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/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check that the argument to __builtin_function_start is a function. 199 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) { 200 if (checkArgCount(S, TheCall, 1)) 201 return true; 202 203 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 204 if (Arg.isInvalid()) 205 return true; 206 207 TheCall->setArg(0, Arg.get()); 208 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>( 209 Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext())); 210 211 if (!FD) { 212 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type) 213 << TheCall->getSourceRange(); 214 return true; 215 } 216 217 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 218 TheCall->getBeginLoc()); 219 } 220 221 /// Check the number of arguments and set the result type to 222 /// the argument type. 223 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 224 if (checkArgCount(S, TheCall, 1)) 225 return true; 226 227 TheCall->setType(TheCall->getArg(0)->getType()); 228 return false; 229 } 230 231 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 232 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 233 /// type (but not a function pointer) and that the alignment is a power-of-two. 234 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 235 if (checkArgCount(S, TheCall, 2)) 236 return true; 237 238 clang::Expr *Source = TheCall->getArg(0); 239 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 240 241 auto IsValidIntegerType = [](QualType Ty) { 242 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 243 }; 244 QualType SrcTy = Source->getType(); 245 // We should also be able to use it with arrays (but not functions!). 246 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 247 SrcTy = S.Context.getDecayedType(SrcTy); 248 } 249 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 250 SrcTy->isFunctionPointerType()) { 251 // FIXME: this is not quite the right error message since we don't allow 252 // floating point types, or member pointers. 253 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 254 << SrcTy; 255 return true; 256 } 257 258 clang::Expr *AlignOp = TheCall->getArg(1); 259 if (!IsValidIntegerType(AlignOp->getType())) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 261 << AlignOp->getType(); 262 return true; 263 } 264 Expr::EvalResult AlignResult; 265 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 266 // We can't check validity of alignment if it is value dependent. 267 if (!AlignOp->isValueDependent() && 268 AlignOp->EvaluateAsInt(AlignResult, S.Context, 269 Expr::SE_AllowSideEffects)) { 270 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 271 llvm::APSInt MaxValue( 272 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 273 if (AlignValue < 1) { 274 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 275 return true; 276 } 277 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 278 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 279 << toString(MaxValue, 10); 280 return true; 281 } 282 if (!AlignValue.isPowerOf2()) { 283 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 284 return true; 285 } 286 if (AlignValue == 1) { 287 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 288 << IsBooleanAlignBuiltin; 289 } 290 } 291 292 ExprResult SrcArg = S.PerformCopyInitialization( 293 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 294 SourceLocation(), Source); 295 if (SrcArg.isInvalid()) 296 return true; 297 TheCall->setArg(0, SrcArg.get()); 298 ExprResult AlignArg = 299 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 300 S.Context, AlignOp->getType(), false), 301 SourceLocation(), AlignOp); 302 if (AlignArg.isInvalid()) 303 return true; 304 TheCall->setArg(1, AlignArg.get()); 305 // For align_up/align_down, the return type is the same as the (potentially 306 // decayed) argument type including qualifiers. For is_aligned(), the result 307 // is always bool. 308 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 309 return false; 310 } 311 312 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 313 unsigned BuiltinID) { 314 if (checkArgCount(S, TheCall, 3)) 315 return true; 316 317 // First two arguments should be integers. 318 for (unsigned I = 0; I < 2; ++I) { 319 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 320 if (Arg.isInvalid()) return true; 321 TheCall->setArg(I, Arg.get()); 322 323 QualType Ty = Arg.get()->getType(); 324 if (!Ty->isIntegerType()) { 325 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 326 << Ty << Arg.get()->getSourceRange(); 327 return true; 328 } 329 } 330 331 // Third argument should be a pointer to a non-const integer. 332 // IRGen correctly handles volatile, restrict, and address spaces, and 333 // the other qualifiers aren't possible. 334 { 335 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 336 if (Arg.isInvalid()) return true; 337 TheCall->setArg(2, Arg.get()); 338 339 QualType Ty = Arg.get()->getType(); 340 const auto *PtrTy = Ty->getAs<PointerType>(); 341 if (!PtrTy || 342 !PtrTy->getPointeeType()->isIntegerType() || 343 PtrTy->getPointeeType().isConstQualified()) { 344 S.Diag(Arg.get()->getBeginLoc(), 345 diag::err_overflow_builtin_must_be_ptr_int) 346 << Ty << Arg.get()->getSourceRange(); 347 return true; 348 } 349 } 350 351 // Disallow signed bit-precise integer args larger than 128 bits to mul 352 // function until we improve backend support. 353 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 354 for (unsigned I = 0; I < 3; ++I) { 355 const auto Arg = TheCall->getArg(I); 356 // Third argument will be a pointer. 357 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 358 if (Ty->isBitIntType() && Ty->isSignedIntegerType() && 359 S.getASTContext().getIntWidth(Ty) > 128) 360 return S.Diag(Arg->getBeginLoc(), 361 diag::err_overflow_builtin_bit_int_max_size) 362 << 128; 363 } 364 } 365 366 return false; 367 } 368 369 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 370 if (checkArgCount(S, BuiltinCall, 2)) 371 return true; 372 373 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 374 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 375 Expr *Call = BuiltinCall->getArg(0); 376 Expr *Chain = BuiltinCall->getArg(1); 377 378 if (Call->getStmtClass() != Stmt::CallExprClass) { 379 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 380 << Call->getSourceRange(); 381 return true; 382 } 383 384 auto CE = cast<CallExpr>(Call); 385 if (CE->getCallee()->getType()->isBlockPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 387 << Call->getSourceRange(); 388 return true; 389 } 390 391 const Decl *TargetDecl = CE->getCalleeDecl(); 392 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 393 if (FD->getBuiltinID()) { 394 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 395 << Call->getSourceRange(); 396 return true; 397 } 398 399 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 400 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 401 << Call->getSourceRange(); 402 return true; 403 } 404 405 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 406 if (ChainResult.isInvalid()) 407 return true; 408 if (!ChainResult.get()->getType()->isPointerType()) { 409 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 410 << Chain->getSourceRange(); 411 return true; 412 } 413 414 QualType ReturnTy = CE->getCallReturnType(S.Context); 415 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 416 QualType BuiltinTy = S.Context.getFunctionType( 417 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 418 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 419 420 Builtin = 421 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 422 423 BuiltinCall->setType(CE->getType()); 424 BuiltinCall->setValueKind(CE->getValueKind()); 425 BuiltinCall->setObjectKind(CE->getObjectKind()); 426 BuiltinCall->setCallee(Builtin); 427 BuiltinCall->setArg(1, ChainResult.get()); 428 429 return false; 430 } 431 432 namespace { 433 434 class ScanfDiagnosticFormatHandler 435 : public analyze_format_string::FormatStringHandler { 436 // Accepts the argument index (relative to the first destination index) of the 437 // argument whose size we want. 438 using ComputeSizeFunction = 439 llvm::function_ref<Optional<llvm::APSInt>(unsigned)>; 440 441 // Accepts the argument index (relative to the first destination index), the 442 // destination size, and the source size). 443 using DiagnoseFunction = 444 llvm::function_ref<void(unsigned, unsigned, unsigned)>; 445 446 ComputeSizeFunction ComputeSizeArgument; 447 DiagnoseFunction Diagnose; 448 449 public: 450 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument, 451 DiagnoseFunction Diagnose) 452 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {} 453 454 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 455 const char *StartSpecifier, 456 unsigned specifierLen) override { 457 if (!FS.consumesDataArgument()) 458 return true; 459 460 unsigned NulByte = 0; 461 switch ((FS.getConversionSpecifier().getKind())) { 462 default: 463 return true; 464 case analyze_format_string::ConversionSpecifier::sArg: 465 case analyze_format_string::ConversionSpecifier::ScanListArg: 466 NulByte = 1; 467 break; 468 case analyze_format_string::ConversionSpecifier::cArg: 469 break; 470 } 471 472 analyze_format_string::OptionalAmount FW = FS.getFieldWidth(); 473 if (FW.getHowSpecified() != 474 analyze_format_string::OptionalAmount::HowSpecified::Constant) 475 return true; 476 477 unsigned SourceSize = FW.getConstantAmount() + NulByte; 478 479 Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex()); 480 if (!DestSizeAPS) 481 return true; 482 483 unsigned DestSize = DestSizeAPS->getZExtValue(); 484 485 if (DestSize < SourceSize) 486 Diagnose(FS.getArgIndex(), DestSize, SourceSize); 487 488 return true; 489 } 490 }; 491 492 class EstimateSizeFormatHandler 493 : public analyze_format_string::FormatStringHandler { 494 size_t Size; 495 496 public: 497 EstimateSizeFormatHandler(StringRef Format) 498 : Size(std::min(Format.find(0), Format.size()) + 499 1 /* null byte always written by sprintf */) {} 500 501 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 502 const char *, unsigned SpecifierLen, 503 const TargetInfo &) override { 504 505 const size_t FieldWidth = computeFieldWidth(FS); 506 const size_t Precision = computePrecision(FS); 507 508 // The actual format. 509 switch (FS.getConversionSpecifier().getKind()) { 510 // Just a char. 511 case analyze_format_string::ConversionSpecifier::cArg: 512 case analyze_format_string::ConversionSpecifier::CArg: 513 Size += std::max(FieldWidth, (size_t)1); 514 break; 515 // Just an integer. 516 case analyze_format_string::ConversionSpecifier::dArg: 517 case analyze_format_string::ConversionSpecifier::DArg: 518 case analyze_format_string::ConversionSpecifier::iArg: 519 case analyze_format_string::ConversionSpecifier::oArg: 520 case analyze_format_string::ConversionSpecifier::OArg: 521 case analyze_format_string::ConversionSpecifier::uArg: 522 case analyze_format_string::ConversionSpecifier::UArg: 523 case analyze_format_string::ConversionSpecifier::xArg: 524 case analyze_format_string::ConversionSpecifier::XArg: 525 Size += std::max(FieldWidth, Precision); 526 break; 527 528 // %g style conversion switches between %f or %e style dynamically. 529 // %f always takes less space, so default to it. 530 case analyze_format_string::ConversionSpecifier::gArg: 531 case analyze_format_string::ConversionSpecifier::GArg: 532 533 // Floating point number in the form '[+]ddd.ddd'. 534 case analyze_format_string::ConversionSpecifier::fArg: 535 case analyze_format_string::ConversionSpecifier::FArg: 536 Size += std::max(FieldWidth, 1 /* integer part */ + 537 (Precision ? 1 + Precision 538 : 0) /* period + decimal */); 539 break; 540 541 // Floating point number in the form '[-]d.ddde[+-]dd'. 542 case analyze_format_string::ConversionSpecifier::eArg: 543 case analyze_format_string::ConversionSpecifier::EArg: 544 Size += 545 std::max(FieldWidth, 546 1 /* integer part */ + 547 (Precision ? 1 + Precision : 0) /* period + decimal */ + 548 1 /* e or E letter */ + 2 /* exponent */); 549 break; 550 551 // Floating point number in the form '[-]0xh.hhhhp±dd'. 552 case analyze_format_string::ConversionSpecifier::aArg: 553 case analyze_format_string::ConversionSpecifier::AArg: 554 Size += 555 std::max(FieldWidth, 556 2 /* 0x */ + 1 /* integer part */ + 557 (Precision ? 1 + Precision : 0) /* period + decimal */ + 558 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 559 break; 560 561 // Just a string. 562 case analyze_format_string::ConversionSpecifier::sArg: 563 case analyze_format_string::ConversionSpecifier::SArg: 564 Size += FieldWidth; 565 break; 566 567 // Just a pointer in the form '0xddd'. 568 case analyze_format_string::ConversionSpecifier::pArg: 569 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 570 break; 571 572 // A plain percent. 573 case analyze_format_string::ConversionSpecifier::PercentArg: 574 Size += 1; 575 break; 576 577 default: 578 break; 579 } 580 581 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 582 583 if (FS.hasAlternativeForm()) { 584 switch (FS.getConversionSpecifier().getKind()) { 585 default: 586 break; 587 // Force a leading '0'. 588 case analyze_format_string::ConversionSpecifier::oArg: 589 Size += 1; 590 break; 591 // Force a leading '0x'. 592 case analyze_format_string::ConversionSpecifier::xArg: 593 case analyze_format_string::ConversionSpecifier::XArg: 594 Size += 2; 595 break; 596 // Force a period '.' before decimal, even if precision is 0. 597 case analyze_format_string::ConversionSpecifier::aArg: 598 case analyze_format_string::ConversionSpecifier::AArg: 599 case analyze_format_string::ConversionSpecifier::eArg: 600 case analyze_format_string::ConversionSpecifier::EArg: 601 case analyze_format_string::ConversionSpecifier::fArg: 602 case analyze_format_string::ConversionSpecifier::FArg: 603 case analyze_format_string::ConversionSpecifier::gArg: 604 case analyze_format_string::ConversionSpecifier::GArg: 605 Size += (Precision ? 0 : 1); 606 break; 607 } 608 } 609 assert(SpecifierLen <= Size && "no underflow"); 610 Size -= SpecifierLen; 611 return true; 612 } 613 614 size_t getSizeLowerBound() const { return Size; } 615 616 private: 617 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 618 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 619 size_t FieldWidth = 0; 620 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 621 FieldWidth = FW.getConstantAmount(); 622 return FieldWidth; 623 } 624 625 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 626 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 627 size_t Precision = 0; 628 629 // See man 3 printf for default precision value based on the specifier. 630 switch (FW.getHowSpecified()) { 631 case analyze_format_string::OptionalAmount::NotSpecified: 632 switch (FS.getConversionSpecifier().getKind()) { 633 default: 634 break; 635 case analyze_format_string::ConversionSpecifier::dArg: // %d 636 case analyze_format_string::ConversionSpecifier::DArg: // %D 637 case analyze_format_string::ConversionSpecifier::iArg: // %i 638 Precision = 1; 639 break; 640 case analyze_format_string::ConversionSpecifier::oArg: // %d 641 case analyze_format_string::ConversionSpecifier::OArg: // %D 642 case analyze_format_string::ConversionSpecifier::uArg: // %d 643 case analyze_format_string::ConversionSpecifier::UArg: // %D 644 case analyze_format_string::ConversionSpecifier::xArg: // %d 645 case analyze_format_string::ConversionSpecifier::XArg: // %D 646 Precision = 1; 647 break; 648 case analyze_format_string::ConversionSpecifier::fArg: // %f 649 case analyze_format_string::ConversionSpecifier::FArg: // %F 650 case analyze_format_string::ConversionSpecifier::eArg: // %e 651 case analyze_format_string::ConversionSpecifier::EArg: // %E 652 case analyze_format_string::ConversionSpecifier::gArg: // %g 653 case analyze_format_string::ConversionSpecifier::GArg: // %G 654 Precision = 6; 655 break; 656 case analyze_format_string::ConversionSpecifier::pArg: // %d 657 Precision = 1; 658 break; 659 } 660 break; 661 case analyze_format_string::OptionalAmount::Constant: 662 Precision = FW.getConstantAmount(); 663 break; 664 default: 665 break; 666 } 667 return Precision; 668 } 669 }; 670 671 } // namespace 672 673 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 674 CallExpr *TheCall) { 675 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 676 isConstantEvaluated()) 677 return; 678 679 bool UseDABAttr = false; 680 const FunctionDecl *UseDecl = FD; 681 682 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>(); 683 if (DABAttr) { 684 UseDecl = DABAttr->getFunction(); 685 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!"); 686 UseDABAttr = true; 687 } 688 689 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true); 690 691 if (!BuiltinID) 692 return; 693 694 const TargetInfo &TI = getASTContext().getTargetInfo(); 695 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 696 697 auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> { 698 // If we refer to a diagnose_as_builtin attribute, we need to change the 699 // argument index to refer to the arguments of the called function. Unless 700 // the index is out of bounds, which presumably means it's a variadic 701 // function. 702 if (!UseDABAttr) 703 return Index; 704 unsigned DABIndices = DABAttr->argIndices_size(); 705 unsigned NewIndex = Index < DABIndices 706 ? DABAttr->argIndices_begin()[Index] 707 : Index - DABIndices + FD->getNumParams(); 708 if (NewIndex >= TheCall->getNumArgs()) 709 return llvm::None; 710 return NewIndex; 711 }; 712 713 auto ComputeExplicitObjectSizeArgument = 714 [&](unsigned Index) -> Optional<llvm::APSInt> { 715 Optional<unsigned> IndexOptional = TranslateIndex(Index); 716 if (!IndexOptional) 717 return llvm::None; 718 unsigned NewIndex = IndexOptional.getValue(); 719 Expr::EvalResult Result; 720 Expr *SizeArg = TheCall->getArg(NewIndex); 721 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 722 return llvm::None; 723 llvm::APSInt Integer = Result.Val.getInt(); 724 Integer.setIsUnsigned(true); 725 return Integer; 726 }; 727 728 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 729 // If the parameter has a pass_object_size attribute, then we should use its 730 // (potentially) more strict checking mode. Otherwise, conservatively assume 731 // type 0. 732 int BOSType = 0; 733 // This check can fail for variadic functions. 734 if (Index < FD->getNumParams()) { 735 if (const auto *POS = 736 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 737 BOSType = POS->getType(); 738 } 739 740 Optional<unsigned> IndexOptional = TranslateIndex(Index); 741 if (!IndexOptional) 742 return llvm::None; 743 unsigned NewIndex = IndexOptional.getValue(); 744 745 const Expr *ObjArg = TheCall->getArg(NewIndex); 746 uint64_t Result; 747 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 748 return llvm::None; 749 750 // Get the object size in the target's size_t width. 751 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 752 }; 753 754 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 755 Optional<unsigned> IndexOptional = TranslateIndex(Index); 756 if (!IndexOptional) 757 return llvm::None; 758 unsigned NewIndex = IndexOptional.getValue(); 759 760 const Expr *ObjArg = TheCall->getArg(NewIndex); 761 uint64_t Result; 762 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 763 return llvm::None; 764 // Add 1 for null byte. 765 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 766 }; 767 768 Optional<llvm::APSInt> SourceSize; 769 Optional<llvm::APSInt> DestinationSize; 770 unsigned DiagID = 0; 771 bool IsChkVariant = false; 772 773 auto GetFunctionName = [&]() { 774 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 775 // Skim off the details of whichever builtin was called to produce a better 776 // diagnostic, as it's unlikely that the user wrote the __builtin 777 // explicitly. 778 if (IsChkVariant) { 779 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 780 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 781 } else if (FunctionName.startswith("__builtin_")) { 782 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 783 } 784 return FunctionName; 785 }; 786 787 switch (BuiltinID) { 788 default: 789 return; 790 case Builtin::BI__builtin_strcpy: 791 case Builtin::BIstrcpy: { 792 DiagID = diag::warn_fortify_strlen_overflow; 793 SourceSize = ComputeStrLenArgument(1); 794 DestinationSize = ComputeSizeArgument(0); 795 break; 796 } 797 798 case Builtin::BI__builtin___strcpy_chk: { 799 DiagID = diag::warn_fortify_strlen_overflow; 800 SourceSize = ComputeStrLenArgument(1); 801 DestinationSize = ComputeExplicitObjectSizeArgument(2); 802 IsChkVariant = true; 803 break; 804 } 805 806 case Builtin::BIscanf: 807 case Builtin::BIfscanf: 808 case Builtin::BIsscanf: { 809 unsigned FormatIndex = 1; 810 unsigned DataIndex = 2; 811 if (BuiltinID == Builtin::BIscanf) { 812 FormatIndex = 0; 813 DataIndex = 1; 814 } 815 816 const auto *FormatExpr = 817 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 818 819 const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 820 if (!Format) 821 return; 822 823 if (!Format->isAscii() && !Format->isUTF8()) 824 return; 825 826 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 827 unsigned SourceSize) { 828 DiagID = diag::warn_fortify_scanf_overflow; 829 unsigned Index = ArgIndex + DataIndex; 830 StringRef FunctionName = GetFunctionName(); 831 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall, 832 PDiag(DiagID) << FunctionName << (Index + 1) 833 << DestSize << SourceSize); 834 }; 835 836 StringRef FormatStrRef = Format->getString(); 837 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 838 return ComputeSizeArgument(Index + DataIndex); 839 }; 840 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 841 const char *FormatBytes = FormatStrRef.data(); 842 const ConstantArrayType *T = 843 Context.getAsConstantArrayType(Format->getType()); 844 assert(T && "String literal not of constant array type!"); 845 size_t TypeSize = T->getSize().getZExtValue(); 846 847 // In case there's a null byte somewhere. 848 size_t StrLen = 849 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 850 851 analyze_format_string::ParseScanfString(H, FormatBytes, 852 FormatBytes + StrLen, getLangOpts(), 853 Context.getTargetInfo()); 854 855 // Unlike the other cases, in this one we have already issued the diagnostic 856 // here, so no need to continue (because unlike the other cases, here the 857 // diagnostic refers to the argument number). 858 return; 859 } 860 861 case Builtin::BIsprintf: 862 case Builtin::BI__builtin___sprintf_chk: { 863 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 864 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 865 866 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 867 868 if (!Format->isAscii() && !Format->isUTF8()) 869 return; 870 871 StringRef FormatStrRef = Format->getString(); 872 EstimateSizeFormatHandler H(FormatStrRef); 873 const char *FormatBytes = FormatStrRef.data(); 874 const ConstantArrayType *T = 875 Context.getAsConstantArrayType(Format->getType()); 876 assert(T && "String literal not of constant array type!"); 877 size_t TypeSize = T->getSize().getZExtValue(); 878 879 // In case there's a null byte somewhere. 880 size_t StrLen = 881 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 882 if (!analyze_format_string::ParsePrintfString( 883 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 884 Context.getTargetInfo(), false)) { 885 DiagID = diag::warn_fortify_source_format_overflow; 886 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 887 .extOrTrunc(SizeTypeWidth); 888 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 889 DestinationSize = ComputeExplicitObjectSizeArgument(2); 890 IsChkVariant = true; 891 } else { 892 DestinationSize = ComputeSizeArgument(0); 893 } 894 break; 895 } 896 } 897 return; 898 } 899 case Builtin::BI__builtin___memcpy_chk: 900 case Builtin::BI__builtin___memmove_chk: 901 case Builtin::BI__builtin___memset_chk: 902 case Builtin::BI__builtin___strlcat_chk: 903 case Builtin::BI__builtin___strlcpy_chk: 904 case Builtin::BI__builtin___strncat_chk: 905 case Builtin::BI__builtin___strncpy_chk: 906 case Builtin::BI__builtin___stpncpy_chk: 907 case Builtin::BI__builtin___memccpy_chk: 908 case Builtin::BI__builtin___mempcpy_chk: { 909 DiagID = diag::warn_builtin_chk_overflow; 910 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 911 DestinationSize = 912 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 913 IsChkVariant = true; 914 break; 915 } 916 917 case Builtin::BI__builtin___snprintf_chk: 918 case Builtin::BI__builtin___vsnprintf_chk: { 919 DiagID = diag::warn_builtin_chk_overflow; 920 SourceSize = ComputeExplicitObjectSizeArgument(1); 921 DestinationSize = ComputeExplicitObjectSizeArgument(3); 922 IsChkVariant = true; 923 break; 924 } 925 926 case Builtin::BIstrncat: 927 case Builtin::BI__builtin_strncat: 928 case Builtin::BIstrncpy: 929 case Builtin::BI__builtin_strncpy: 930 case Builtin::BIstpncpy: 931 case Builtin::BI__builtin_stpncpy: { 932 // Whether these functions overflow depends on the runtime strlen of the 933 // string, not just the buffer size, so emitting the "always overflow" 934 // diagnostic isn't quite right. We should still diagnose passing a buffer 935 // size larger than the destination buffer though; this is a runtime abort 936 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 937 DiagID = diag::warn_fortify_source_size_mismatch; 938 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 939 DestinationSize = ComputeSizeArgument(0); 940 break; 941 } 942 943 case Builtin::BImemcpy: 944 case Builtin::BI__builtin_memcpy: 945 case Builtin::BImemmove: 946 case Builtin::BI__builtin_memmove: 947 case Builtin::BImemset: 948 case Builtin::BI__builtin_memset: 949 case Builtin::BImempcpy: 950 case Builtin::BI__builtin_mempcpy: { 951 DiagID = diag::warn_fortify_source_overflow; 952 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 953 DestinationSize = ComputeSizeArgument(0); 954 break; 955 } 956 case Builtin::BIsnprintf: 957 case Builtin::BI__builtin_snprintf: 958 case Builtin::BIvsnprintf: 959 case Builtin::BI__builtin_vsnprintf: { 960 DiagID = diag::warn_fortify_source_size_mismatch; 961 SourceSize = ComputeExplicitObjectSizeArgument(1); 962 DestinationSize = ComputeSizeArgument(0); 963 break; 964 } 965 } 966 967 if (!SourceSize || !DestinationSize || 968 llvm::APSInt::compareValues(SourceSize.getValue(), 969 DestinationSize.getValue()) <= 0) 970 return; 971 972 StringRef FunctionName = GetFunctionName(); 973 974 SmallString<16> DestinationStr; 975 SmallString<16> SourceStr; 976 DestinationSize->toString(DestinationStr, /*Radix=*/10); 977 SourceSize->toString(SourceStr, /*Radix=*/10); 978 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 979 PDiag(DiagID) 980 << FunctionName << DestinationStr << SourceStr); 981 } 982 983 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 984 Scope::ScopeFlags NeededScopeFlags, 985 unsigned DiagID) { 986 // Scopes aren't available during instantiation. Fortunately, builtin 987 // functions cannot be template args so they cannot be formed through template 988 // instantiation. Therefore checking once during the parse is sufficient. 989 if (SemaRef.inTemplateInstantiation()) 990 return false; 991 992 Scope *S = SemaRef.getCurScope(); 993 while (S && !S->isSEHExceptScope()) 994 S = S->getParent(); 995 if (!S || !(S->getFlags() & NeededScopeFlags)) { 996 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 997 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 998 << DRE->getDecl()->getIdentifier(); 999 return true; 1000 } 1001 1002 return false; 1003 } 1004 1005 static inline bool isBlockPointer(Expr *Arg) { 1006 return Arg->getType()->isBlockPointerType(); 1007 } 1008 1009 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 1010 /// void*, which is a requirement of device side enqueue. 1011 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 1012 const BlockPointerType *BPT = 1013 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1014 ArrayRef<QualType> Params = 1015 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 1016 unsigned ArgCounter = 0; 1017 bool IllegalParams = false; 1018 // Iterate through the block parameters until either one is found that is not 1019 // a local void*, or the block is valid. 1020 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 1021 I != E; ++I, ++ArgCounter) { 1022 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 1023 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 1024 LangAS::opencl_local) { 1025 // Get the location of the error. If a block literal has been passed 1026 // (BlockExpr) then we can point straight to the offending argument, 1027 // else we just point to the variable reference. 1028 SourceLocation ErrorLoc; 1029 if (isa<BlockExpr>(BlockArg)) { 1030 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 1031 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 1032 } else if (isa<DeclRefExpr>(BlockArg)) { 1033 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 1034 } 1035 S.Diag(ErrorLoc, 1036 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 1037 IllegalParams = true; 1038 } 1039 } 1040 1041 return IllegalParams; 1042 } 1043 1044 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 1045 // OpenCL device can support extension but not the feature as extension 1046 // requires subgroup independent forward progress, but subgroup independent 1047 // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature. 1048 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) && 1049 !S.getOpenCLOptions().isSupported("__opencl_c_subgroups", 1050 S.getLangOpts())) { 1051 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 1052 << 1 << Call->getDirectCallee() 1053 << "cl_khr_subgroups or __opencl_c_subgroups"; 1054 return true; 1055 } 1056 return false; 1057 } 1058 1059 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 1060 if (checkArgCount(S, TheCall, 2)) 1061 return true; 1062 1063 if (checkOpenCLSubgroupExt(S, TheCall)) 1064 return true; 1065 1066 // First argument is an ndrange_t type. 1067 Expr *NDRangeArg = TheCall->getArg(0); 1068 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1069 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1070 << TheCall->getDirectCallee() << "'ndrange_t'"; 1071 return true; 1072 } 1073 1074 Expr *BlockArg = TheCall->getArg(1); 1075 if (!isBlockPointer(BlockArg)) { 1076 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1077 << TheCall->getDirectCallee() << "block"; 1078 return true; 1079 } 1080 return checkOpenCLBlockArgs(S, BlockArg); 1081 } 1082 1083 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 1084 /// get_kernel_work_group_size 1085 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 1086 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 1087 if (checkArgCount(S, TheCall, 1)) 1088 return true; 1089 1090 Expr *BlockArg = TheCall->getArg(0); 1091 if (!isBlockPointer(BlockArg)) { 1092 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1093 << TheCall->getDirectCallee() << "block"; 1094 return true; 1095 } 1096 return checkOpenCLBlockArgs(S, BlockArg); 1097 } 1098 1099 /// Diagnose integer type and any valid implicit conversion to it. 1100 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 1101 const QualType &IntType); 1102 1103 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 1104 unsigned Start, unsigned End) { 1105 bool IllegalParams = false; 1106 for (unsigned I = Start; I <= End; ++I) 1107 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 1108 S.Context.getSizeType()); 1109 return IllegalParams; 1110 } 1111 1112 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 1113 /// 'local void*' parameter of passed block. 1114 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 1115 Expr *BlockArg, 1116 unsigned NumNonVarArgs) { 1117 const BlockPointerType *BPT = 1118 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1119 unsigned NumBlockParams = 1120 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 1121 unsigned TotalNumArgs = TheCall->getNumArgs(); 1122 1123 // For each argument passed to the block, a corresponding uint needs to 1124 // be passed to describe the size of the local memory. 1125 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 1126 S.Diag(TheCall->getBeginLoc(), 1127 diag::err_opencl_enqueue_kernel_local_size_args); 1128 return true; 1129 } 1130 1131 // Check that the sizes of the local memory are specified by integers. 1132 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 1133 TotalNumArgs - 1); 1134 } 1135 1136 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 1137 /// overload formats specified in Table 6.13.17.1. 1138 /// int enqueue_kernel(queue_t queue, 1139 /// kernel_enqueue_flags_t flags, 1140 /// const ndrange_t ndrange, 1141 /// void (^block)(void)) 1142 /// int enqueue_kernel(queue_t queue, 1143 /// kernel_enqueue_flags_t flags, 1144 /// const ndrange_t ndrange, 1145 /// uint num_events_in_wait_list, 1146 /// clk_event_t *event_wait_list, 1147 /// clk_event_t *event_ret, 1148 /// void (^block)(void)) 1149 /// int enqueue_kernel(queue_t queue, 1150 /// kernel_enqueue_flags_t flags, 1151 /// const ndrange_t ndrange, 1152 /// void (^block)(local void*, ...), 1153 /// uint size0, ...) 1154 /// int enqueue_kernel(queue_t queue, 1155 /// kernel_enqueue_flags_t flags, 1156 /// const ndrange_t ndrange, 1157 /// uint num_events_in_wait_list, 1158 /// clk_event_t *event_wait_list, 1159 /// clk_event_t *event_ret, 1160 /// void (^block)(local void*, ...), 1161 /// uint size0, ...) 1162 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 1163 unsigned NumArgs = TheCall->getNumArgs(); 1164 1165 if (NumArgs < 4) { 1166 S.Diag(TheCall->getBeginLoc(), 1167 diag::err_typecheck_call_too_few_args_at_least) 1168 << 0 << 4 << NumArgs; 1169 return true; 1170 } 1171 1172 Expr *Arg0 = TheCall->getArg(0); 1173 Expr *Arg1 = TheCall->getArg(1); 1174 Expr *Arg2 = TheCall->getArg(2); 1175 Expr *Arg3 = TheCall->getArg(3); 1176 1177 // First argument always needs to be a queue_t type. 1178 if (!Arg0->getType()->isQueueT()) { 1179 S.Diag(TheCall->getArg(0)->getBeginLoc(), 1180 diag::err_opencl_builtin_expected_type) 1181 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 1182 return true; 1183 } 1184 1185 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 1186 if (!Arg1->getType()->isIntegerType()) { 1187 S.Diag(TheCall->getArg(1)->getBeginLoc(), 1188 diag::err_opencl_builtin_expected_type) 1189 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 1190 return true; 1191 } 1192 1193 // Third argument is always an ndrange_t type. 1194 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1195 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1196 diag::err_opencl_builtin_expected_type) 1197 << TheCall->getDirectCallee() << "'ndrange_t'"; 1198 return true; 1199 } 1200 1201 // With four arguments, there is only one form that the function could be 1202 // called in: no events and no variable arguments. 1203 if (NumArgs == 4) { 1204 // check that the last argument is the right block type. 1205 if (!isBlockPointer(Arg3)) { 1206 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1207 << TheCall->getDirectCallee() << "block"; 1208 return true; 1209 } 1210 // we have a block type, check the prototype 1211 const BlockPointerType *BPT = 1212 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1213 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1214 S.Diag(Arg3->getBeginLoc(), 1215 diag::err_opencl_enqueue_kernel_blocks_no_args); 1216 return true; 1217 } 1218 return false; 1219 } 1220 // we can have block + varargs. 1221 if (isBlockPointer(Arg3)) 1222 return (checkOpenCLBlockArgs(S, Arg3) || 1223 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1224 // last two cases with either exactly 7 args or 7 args and varargs. 1225 if (NumArgs >= 7) { 1226 // check common block argument. 1227 Expr *Arg6 = TheCall->getArg(6); 1228 if (!isBlockPointer(Arg6)) { 1229 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1230 << TheCall->getDirectCallee() << "block"; 1231 return true; 1232 } 1233 if (checkOpenCLBlockArgs(S, Arg6)) 1234 return true; 1235 1236 // Forth argument has to be any integer type. 1237 if (!Arg3->getType()->isIntegerType()) { 1238 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1239 diag::err_opencl_builtin_expected_type) 1240 << TheCall->getDirectCallee() << "integer"; 1241 return true; 1242 } 1243 // check remaining common arguments. 1244 Expr *Arg4 = TheCall->getArg(4); 1245 Expr *Arg5 = TheCall->getArg(5); 1246 1247 // Fifth argument is always passed as a pointer to clk_event_t. 1248 if (!Arg4->isNullPointerConstant(S.Context, 1249 Expr::NPC_ValueDependentIsNotNull) && 1250 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1251 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1252 diag::err_opencl_builtin_expected_type) 1253 << TheCall->getDirectCallee() 1254 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1255 return true; 1256 } 1257 1258 // Sixth argument is always passed as a pointer to clk_event_t. 1259 if (!Arg5->isNullPointerConstant(S.Context, 1260 Expr::NPC_ValueDependentIsNotNull) && 1261 !(Arg5->getType()->isPointerType() && 1262 Arg5->getType()->getPointeeType()->isClkEventT())) { 1263 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1264 diag::err_opencl_builtin_expected_type) 1265 << TheCall->getDirectCallee() 1266 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1267 return true; 1268 } 1269 1270 if (NumArgs == 7) 1271 return false; 1272 1273 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1274 } 1275 1276 // None of the specific case has been detected, give generic error 1277 S.Diag(TheCall->getBeginLoc(), 1278 diag::err_opencl_enqueue_kernel_incorrect_args); 1279 return true; 1280 } 1281 1282 /// Returns OpenCL access qual. 1283 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1284 return D->getAttr<OpenCLAccessAttr>(); 1285 } 1286 1287 /// Returns true if pipe element type is different from the pointer. 1288 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1289 const Expr *Arg0 = Call->getArg(0); 1290 // First argument type should always be pipe. 1291 if (!Arg0->getType()->isPipeType()) { 1292 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1293 << Call->getDirectCallee() << Arg0->getSourceRange(); 1294 return true; 1295 } 1296 OpenCLAccessAttr *AccessQual = 1297 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1298 // Validates the access qualifier is compatible with the call. 1299 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1300 // read_only and write_only, and assumed to be read_only if no qualifier is 1301 // specified. 1302 switch (Call->getDirectCallee()->getBuiltinID()) { 1303 case Builtin::BIread_pipe: 1304 case Builtin::BIreserve_read_pipe: 1305 case Builtin::BIcommit_read_pipe: 1306 case Builtin::BIwork_group_reserve_read_pipe: 1307 case Builtin::BIsub_group_reserve_read_pipe: 1308 case Builtin::BIwork_group_commit_read_pipe: 1309 case Builtin::BIsub_group_commit_read_pipe: 1310 if (!(!AccessQual || AccessQual->isReadOnly())) { 1311 S.Diag(Arg0->getBeginLoc(), 1312 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1313 << "read_only" << Arg0->getSourceRange(); 1314 return true; 1315 } 1316 break; 1317 case Builtin::BIwrite_pipe: 1318 case Builtin::BIreserve_write_pipe: 1319 case Builtin::BIcommit_write_pipe: 1320 case Builtin::BIwork_group_reserve_write_pipe: 1321 case Builtin::BIsub_group_reserve_write_pipe: 1322 case Builtin::BIwork_group_commit_write_pipe: 1323 case Builtin::BIsub_group_commit_write_pipe: 1324 if (!(AccessQual && AccessQual->isWriteOnly())) { 1325 S.Diag(Arg0->getBeginLoc(), 1326 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1327 << "write_only" << Arg0->getSourceRange(); 1328 return true; 1329 } 1330 break; 1331 default: 1332 break; 1333 } 1334 return false; 1335 } 1336 1337 /// Returns true if pipe element type is different from the pointer. 1338 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1339 const Expr *Arg0 = Call->getArg(0); 1340 const Expr *ArgIdx = Call->getArg(Idx); 1341 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1342 const QualType EltTy = PipeTy->getElementType(); 1343 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1344 // The Idx argument should be a pointer and the type of the pointer and 1345 // the type of pipe element should also be the same. 1346 if (!ArgTy || 1347 !S.Context.hasSameType( 1348 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1349 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1350 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1351 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1352 return true; 1353 } 1354 return false; 1355 } 1356 1357 // Performs semantic analysis for the read/write_pipe call. 1358 // \param S Reference to the semantic analyzer. 1359 // \param Call A pointer to the builtin call. 1360 // \return True if a semantic error has been found, false otherwise. 1361 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1362 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1363 // functions have two forms. 1364 switch (Call->getNumArgs()) { 1365 case 2: 1366 if (checkOpenCLPipeArg(S, Call)) 1367 return true; 1368 // The call with 2 arguments should be 1369 // read/write_pipe(pipe T, T*). 1370 // Check packet type T. 1371 if (checkOpenCLPipePacketType(S, Call, 1)) 1372 return true; 1373 break; 1374 1375 case 4: { 1376 if (checkOpenCLPipeArg(S, Call)) 1377 return true; 1378 // The call with 4 arguments should be 1379 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1380 // Check reserve_id_t. 1381 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1382 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1383 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1384 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1385 return true; 1386 } 1387 1388 // Check the index. 1389 const Expr *Arg2 = Call->getArg(2); 1390 if (!Arg2->getType()->isIntegerType() && 1391 !Arg2->getType()->isUnsignedIntegerType()) { 1392 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1393 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1394 << Arg2->getType() << Arg2->getSourceRange(); 1395 return true; 1396 } 1397 1398 // Check packet type T. 1399 if (checkOpenCLPipePacketType(S, Call, 3)) 1400 return true; 1401 } break; 1402 default: 1403 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1404 << Call->getDirectCallee() << Call->getSourceRange(); 1405 return true; 1406 } 1407 1408 return false; 1409 } 1410 1411 // Performs a semantic analysis on the {work_group_/sub_group_ 1412 // /_}reserve_{read/write}_pipe 1413 // \param S Reference to the semantic analyzer. 1414 // \param Call The call to the builtin function to be analyzed. 1415 // \return True if a semantic error was found, false otherwise. 1416 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1417 if (checkArgCount(S, Call, 2)) 1418 return true; 1419 1420 if (checkOpenCLPipeArg(S, Call)) 1421 return true; 1422 1423 // Check the reserve size. 1424 if (!Call->getArg(1)->getType()->isIntegerType() && 1425 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1426 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1427 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1428 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1429 return true; 1430 } 1431 1432 // Since return type of reserve_read/write_pipe built-in function is 1433 // reserve_id_t, which is not defined in the builtin def file , we used int 1434 // as return type and need to override the return type of these functions. 1435 Call->setType(S.Context.OCLReserveIDTy); 1436 1437 return false; 1438 } 1439 1440 // Performs a semantic analysis on {work_group_/sub_group_ 1441 // /_}commit_{read/write}_pipe 1442 // \param S Reference to the semantic analyzer. 1443 // \param Call The call to the builtin function to be analyzed. 1444 // \return True if a semantic error was found, false otherwise. 1445 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1446 if (checkArgCount(S, Call, 2)) 1447 return true; 1448 1449 if (checkOpenCLPipeArg(S, Call)) 1450 return true; 1451 1452 // Check reserve_id_t. 1453 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1454 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1455 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1456 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1457 return true; 1458 } 1459 1460 return false; 1461 } 1462 1463 // Performs a semantic analysis on the call to built-in Pipe 1464 // Query Functions. 1465 // \param S Reference to the semantic analyzer. 1466 // \param Call The call to the builtin function to be analyzed. 1467 // \return True if a semantic error was found, false otherwise. 1468 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1469 if (checkArgCount(S, Call, 1)) 1470 return true; 1471 1472 if (!Call->getArg(0)->getType()->isPipeType()) { 1473 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1474 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1475 return true; 1476 } 1477 1478 return false; 1479 } 1480 1481 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1482 // Performs semantic analysis for the to_global/local/private call. 1483 // \param S Reference to the semantic analyzer. 1484 // \param BuiltinID ID of the builtin function. 1485 // \param Call A pointer to the builtin call. 1486 // \return True if a semantic error has been found, false otherwise. 1487 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1488 CallExpr *Call) { 1489 if (checkArgCount(S, Call, 1)) 1490 return true; 1491 1492 auto RT = Call->getArg(0)->getType(); 1493 if (!RT->isPointerType() || RT->getPointeeType() 1494 .getAddressSpace() == LangAS::opencl_constant) { 1495 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1496 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1497 return true; 1498 } 1499 1500 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1501 S.Diag(Call->getArg(0)->getBeginLoc(), 1502 diag::warn_opencl_generic_address_space_arg) 1503 << Call->getDirectCallee()->getNameInfo().getAsString() 1504 << Call->getArg(0)->getSourceRange(); 1505 } 1506 1507 RT = RT->getPointeeType(); 1508 auto Qual = RT.getQualifiers(); 1509 switch (BuiltinID) { 1510 case Builtin::BIto_global: 1511 Qual.setAddressSpace(LangAS::opencl_global); 1512 break; 1513 case Builtin::BIto_local: 1514 Qual.setAddressSpace(LangAS::opencl_local); 1515 break; 1516 case Builtin::BIto_private: 1517 Qual.setAddressSpace(LangAS::opencl_private); 1518 break; 1519 default: 1520 llvm_unreachable("Invalid builtin function"); 1521 } 1522 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1523 RT.getUnqualifiedType(), Qual))); 1524 1525 return false; 1526 } 1527 1528 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1529 if (checkArgCount(S, TheCall, 1)) 1530 return ExprError(); 1531 1532 // Compute __builtin_launder's parameter type from the argument. 1533 // The parameter type is: 1534 // * The type of the argument if it's not an array or function type, 1535 // Otherwise, 1536 // * The decayed argument type. 1537 QualType ParamTy = [&]() { 1538 QualType ArgTy = TheCall->getArg(0)->getType(); 1539 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1540 return S.Context.getPointerType(Ty->getElementType()); 1541 if (ArgTy->isFunctionType()) { 1542 return S.Context.getPointerType(ArgTy); 1543 } 1544 return ArgTy; 1545 }(); 1546 1547 TheCall->setType(ParamTy); 1548 1549 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1550 if (!ParamTy->isPointerType()) 1551 return 0; 1552 if (ParamTy->isFunctionPointerType()) 1553 return 1; 1554 if (ParamTy->isVoidPointerType()) 1555 return 2; 1556 return llvm::Optional<unsigned>{}; 1557 }(); 1558 if (DiagSelect.hasValue()) { 1559 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1560 << DiagSelect.getValue() << TheCall->getSourceRange(); 1561 return ExprError(); 1562 } 1563 1564 // We either have an incomplete class type, or we have a class template 1565 // whose instantiation has not been forced. Example: 1566 // 1567 // template <class T> struct Foo { T value; }; 1568 // Foo<int> *p = nullptr; 1569 // auto *d = __builtin_launder(p); 1570 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1571 diag::err_incomplete_type)) 1572 return ExprError(); 1573 1574 assert(ParamTy->getPointeeType()->isObjectType() && 1575 "Unhandled non-object pointer case"); 1576 1577 InitializedEntity Entity = 1578 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1579 ExprResult Arg = 1580 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1581 if (Arg.isInvalid()) 1582 return ExprError(); 1583 TheCall->setArg(0, Arg.get()); 1584 1585 return TheCall; 1586 } 1587 1588 // Emit an error and return true if the current object format type is in the 1589 // list of unsupported types. 1590 static bool CheckBuiltinTargetNotInUnsupported( 1591 Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1592 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) { 1593 llvm::Triple::ObjectFormatType CurObjFormat = 1594 S.getASTContext().getTargetInfo().getTriple().getObjectFormat(); 1595 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) { 1596 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1597 << TheCall->getSourceRange(); 1598 return true; 1599 } 1600 return false; 1601 } 1602 1603 // Emit an error and return true if the current architecture is not in the list 1604 // of supported architectures. 1605 static bool 1606 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1607 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1608 llvm::Triple::ArchType CurArch = 1609 S.getASTContext().getTargetInfo().getTriple().getArch(); 1610 if (llvm::is_contained(SupportedArchs, CurArch)) 1611 return false; 1612 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1613 << TheCall->getSourceRange(); 1614 return true; 1615 } 1616 1617 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1618 SourceLocation CallSiteLoc); 1619 1620 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1621 CallExpr *TheCall) { 1622 switch (TI.getTriple().getArch()) { 1623 default: 1624 // Some builtins don't require additional checking, so just consider these 1625 // acceptable. 1626 return false; 1627 case llvm::Triple::arm: 1628 case llvm::Triple::armeb: 1629 case llvm::Triple::thumb: 1630 case llvm::Triple::thumbeb: 1631 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1632 case llvm::Triple::aarch64: 1633 case llvm::Triple::aarch64_32: 1634 case llvm::Triple::aarch64_be: 1635 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1636 case llvm::Triple::bpfeb: 1637 case llvm::Triple::bpfel: 1638 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1639 case llvm::Triple::hexagon: 1640 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1641 case llvm::Triple::mips: 1642 case llvm::Triple::mipsel: 1643 case llvm::Triple::mips64: 1644 case llvm::Triple::mips64el: 1645 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1646 case llvm::Triple::systemz: 1647 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1648 case llvm::Triple::x86: 1649 case llvm::Triple::x86_64: 1650 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1651 case llvm::Triple::ppc: 1652 case llvm::Triple::ppcle: 1653 case llvm::Triple::ppc64: 1654 case llvm::Triple::ppc64le: 1655 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1656 case llvm::Triple::amdgcn: 1657 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1658 case llvm::Triple::riscv32: 1659 case llvm::Triple::riscv64: 1660 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1661 } 1662 } 1663 1664 ExprResult 1665 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1666 CallExpr *TheCall) { 1667 ExprResult TheCallResult(TheCall); 1668 1669 // Find out if any arguments are required to be integer constant expressions. 1670 unsigned ICEArguments = 0; 1671 ASTContext::GetBuiltinTypeError Error; 1672 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1673 if (Error != ASTContext::GE_None) 1674 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1675 1676 // If any arguments are required to be ICE's, check and diagnose. 1677 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1678 // Skip arguments not required to be ICE's. 1679 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1680 1681 llvm::APSInt Result; 1682 // If we don't have enough arguments, continue so we can issue better 1683 // diagnostic in checkArgCount(...) 1684 if (ArgNo < TheCall->getNumArgs() && 1685 SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1686 return true; 1687 ICEArguments &= ~(1 << ArgNo); 1688 } 1689 1690 switch (BuiltinID) { 1691 case Builtin::BI__builtin___CFStringMakeConstantString: 1692 // CFStringMakeConstantString is currently not implemented for GOFF (i.e., 1693 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported 1694 if (CheckBuiltinTargetNotInUnsupported( 1695 *this, BuiltinID, TheCall, 1696 {llvm::Triple::GOFF, llvm::Triple::XCOFF})) 1697 return ExprError(); 1698 assert(TheCall->getNumArgs() == 1 && 1699 "Wrong # arguments to builtin CFStringMakeConstantString"); 1700 if (CheckObjCString(TheCall->getArg(0))) 1701 return ExprError(); 1702 break; 1703 case Builtin::BI__builtin_ms_va_start: 1704 case Builtin::BI__builtin_stdarg_start: 1705 case Builtin::BI__builtin_va_start: 1706 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1707 return ExprError(); 1708 break; 1709 case Builtin::BI__va_start: { 1710 switch (Context.getTargetInfo().getTriple().getArch()) { 1711 case llvm::Triple::aarch64: 1712 case llvm::Triple::arm: 1713 case llvm::Triple::thumb: 1714 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1715 return ExprError(); 1716 break; 1717 default: 1718 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1719 return ExprError(); 1720 break; 1721 } 1722 break; 1723 } 1724 1725 // The acquire, release, and no fence variants are ARM and AArch64 only. 1726 case Builtin::BI_interlockedbittestandset_acq: 1727 case Builtin::BI_interlockedbittestandset_rel: 1728 case Builtin::BI_interlockedbittestandset_nf: 1729 case Builtin::BI_interlockedbittestandreset_acq: 1730 case Builtin::BI_interlockedbittestandreset_rel: 1731 case Builtin::BI_interlockedbittestandreset_nf: 1732 if (CheckBuiltinTargetInSupported( 1733 *this, BuiltinID, TheCall, 1734 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1735 return ExprError(); 1736 break; 1737 1738 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1739 case Builtin::BI_bittest64: 1740 case Builtin::BI_bittestandcomplement64: 1741 case Builtin::BI_bittestandreset64: 1742 case Builtin::BI_bittestandset64: 1743 case Builtin::BI_interlockedbittestandreset64: 1744 case Builtin::BI_interlockedbittestandset64: 1745 if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall, 1746 {llvm::Triple::x86_64, llvm::Triple::arm, 1747 llvm::Triple::thumb, 1748 llvm::Triple::aarch64})) 1749 return ExprError(); 1750 break; 1751 1752 case Builtin::BI__builtin_isgreater: 1753 case Builtin::BI__builtin_isgreaterequal: 1754 case Builtin::BI__builtin_isless: 1755 case Builtin::BI__builtin_islessequal: 1756 case Builtin::BI__builtin_islessgreater: 1757 case Builtin::BI__builtin_isunordered: 1758 if (SemaBuiltinUnorderedCompare(TheCall)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_fpclassify: 1762 if (SemaBuiltinFPClassification(TheCall, 6)) 1763 return ExprError(); 1764 break; 1765 case Builtin::BI__builtin_isfinite: 1766 case Builtin::BI__builtin_isinf: 1767 case Builtin::BI__builtin_isinf_sign: 1768 case Builtin::BI__builtin_isnan: 1769 case Builtin::BI__builtin_isnormal: 1770 case Builtin::BI__builtin_signbit: 1771 case Builtin::BI__builtin_signbitf: 1772 case Builtin::BI__builtin_signbitl: 1773 if (SemaBuiltinFPClassification(TheCall, 1)) 1774 return ExprError(); 1775 break; 1776 case Builtin::BI__builtin_shufflevector: 1777 return SemaBuiltinShuffleVector(TheCall); 1778 // TheCall will be freed by the smart pointer here, but that's fine, since 1779 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1780 case Builtin::BI__builtin_prefetch: 1781 if (SemaBuiltinPrefetch(TheCall)) 1782 return ExprError(); 1783 break; 1784 case Builtin::BI__builtin_alloca_with_align: 1785 case Builtin::BI__builtin_alloca_with_align_uninitialized: 1786 if (SemaBuiltinAllocaWithAlign(TheCall)) 1787 return ExprError(); 1788 LLVM_FALLTHROUGH; 1789 case Builtin::BI__builtin_alloca: 1790 case Builtin::BI__builtin_alloca_uninitialized: 1791 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1792 << TheCall->getDirectCallee(); 1793 break; 1794 case Builtin::BI__arithmetic_fence: 1795 if (SemaBuiltinArithmeticFence(TheCall)) 1796 return ExprError(); 1797 break; 1798 case Builtin::BI__assume: 1799 case Builtin::BI__builtin_assume: 1800 if (SemaBuiltinAssume(TheCall)) 1801 return ExprError(); 1802 break; 1803 case Builtin::BI__builtin_assume_aligned: 1804 if (SemaBuiltinAssumeAligned(TheCall)) 1805 return ExprError(); 1806 break; 1807 case Builtin::BI__builtin_dynamic_object_size: 1808 case Builtin::BI__builtin_object_size: 1809 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1810 return ExprError(); 1811 break; 1812 case Builtin::BI__builtin_longjmp: 1813 if (SemaBuiltinLongjmp(TheCall)) 1814 return ExprError(); 1815 break; 1816 case Builtin::BI__builtin_setjmp: 1817 if (SemaBuiltinSetjmp(TheCall)) 1818 return ExprError(); 1819 break; 1820 case Builtin::BI__builtin_classify_type: 1821 if (checkArgCount(*this, TheCall, 1)) return true; 1822 TheCall->setType(Context.IntTy); 1823 break; 1824 case Builtin::BI__builtin_complex: 1825 if (SemaBuiltinComplex(TheCall)) 1826 return ExprError(); 1827 break; 1828 case Builtin::BI__builtin_constant_p: { 1829 if (checkArgCount(*this, TheCall, 1)) return true; 1830 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1831 if (Arg.isInvalid()) return true; 1832 TheCall->setArg(0, Arg.get()); 1833 TheCall->setType(Context.IntTy); 1834 break; 1835 } 1836 case Builtin::BI__builtin_launder: 1837 return SemaBuiltinLaunder(*this, TheCall); 1838 case Builtin::BI__sync_fetch_and_add: 1839 case Builtin::BI__sync_fetch_and_add_1: 1840 case Builtin::BI__sync_fetch_and_add_2: 1841 case Builtin::BI__sync_fetch_and_add_4: 1842 case Builtin::BI__sync_fetch_and_add_8: 1843 case Builtin::BI__sync_fetch_and_add_16: 1844 case Builtin::BI__sync_fetch_and_sub: 1845 case Builtin::BI__sync_fetch_and_sub_1: 1846 case Builtin::BI__sync_fetch_and_sub_2: 1847 case Builtin::BI__sync_fetch_and_sub_4: 1848 case Builtin::BI__sync_fetch_and_sub_8: 1849 case Builtin::BI__sync_fetch_and_sub_16: 1850 case Builtin::BI__sync_fetch_and_or: 1851 case Builtin::BI__sync_fetch_and_or_1: 1852 case Builtin::BI__sync_fetch_and_or_2: 1853 case Builtin::BI__sync_fetch_and_or_4: 1854 case Builtin::BI__sync_fetch_and_or_8: 1855 case Builtin::BI__sync_fetch_and_or_16: 1856 case Builtin::BI__sync_fetch_and_and: 1857 case Builtin::BI__sync_fetch_and_and_1: 1858 case Builtin::BI__sync_fetch_and_and_2: 1859 case Builtin::BI__sync_fetch_and_and_4: 1860 case Builtin::BI__sync_fetch_and_and_8: 1861 case Builtin::BI__sync_fetch_and_and_16: 1862 case Builtin::BI__sync_fetch_and_xor: 1863 case Builtin::BI__sync_fetch_and_xor_1: 1864 case Builtin::BI__sync_fetch_and_xor_2: 1865 case Builtin::BI__sync_fetch_and_xor_4: 1866 case Builtin::BI__sync_fetch_and_xor_8: 1867 case Builtin::BI__sync_fetch_and_xor_16: 1868 case Builtin::BI__sync_fetch_and_nand: 1869 case Builtin::BI__sync_fetch_and_nand_1: 1870 case Builtin::BI__sync_fetch_and_nand_2: 1871 case Builtin::BI__sync_fetch_and_nand_4: 1872 case Builtin::BI__sync_fetch_and_nand_8: 1873 case Builtin::BI__sync_fetch_and_nand_16: 1874 case Builtin::BI__sync_add_and_fetch: 1875 case Builtin::BI__sync_add_and_fetch_1: 1876 case Builtin::BI__sync_add_and_fetch_2: 1877 case Builtin::BI__sync_add_and_fetch_4: 1878 case Builtin::BI__sync_add_and_fetch_8: 1879 case Builtin::BI__sync_add_and_fetch_16: 1880 case Builtin::BI__sync_sub_and_fetch: 1881 case Builtin::BI__sync_sub_and_fetch_1: 1882 case Builtin::BI__sync_sub_and_fetch_2: 1883 case Builtin::BI__sync_sub_and_fetch_4: 1884 case Builtin::BI__sync_sub_and_fetch_8: 1885 case Builtin::BI__sync_sub_and_fetch_16: 1886 case Builtin::BI__sync_and_and_fetch: 1887 case Builtin::BI__sync_and_and_fetch_1: 1888 case Builtin::BI__sync_and_and_fetch_2: 1889 case Builtin::BI__sync_and_and_fetch_4: 1890 case Builtin::BI__sync_and_and_fetch_8: 1891 case Builtin::BI__sync_and_and_fetch_16: 1892 case Builtin::BI__sync_or_and_fetch: 1893 case Builtin::BI__sync_or_and_fetch_1: 1894 case Builtin::BI__sync_or_and_fetch_2: 1895 case Builtin::BI__sync_or_and_fetch_4: 1896 case Builtin::BI__sync_or_and_fetch_8: 1897 case Builtin::BI__sync_or_and_fetch_16: 1898 case Builtin::BI__sync_xor_and_fetch: 1899 case Builtin::BI__sync_xor_and_fetch_1: 1900 case Builtin::BI__sync_xor_and_fetch_2: 1901 case Builtin::BI__sync_xor_and_fetch_4: 1902 case Builtin::BI__sync_xor_and_fetch_8: 1903 case Builtin::BI__sync_xor_and_fetch_16: 1904 case Builtin::BI__sync_nand_and_fetch: 1905 case Builtin::BI__sync_nand_and_fetch_1: 1906 case Builtin::BI__sync_nand_and_fetch_2: 1907 case Builtin::BI__sync_nand_and_fetch_4: 1908 case Builtin::BI__sync_nand_and_fetch_8: 1909 case Builtin::BI__sync_nand_and_fetch_16: 1910 case Builtin::BI__sync_val_compare_and_swap: 1911 case Builtin::BI__sync_val_compare_and_swap_1: 1912 case Builtin::BI__sync_val_compare_and_swap_2: 1913 case Builtin::BI__sync_val_compare_and_swap_4: 1914 case Builtin::BI__sync_val_compare_and_swap_8: 1915 case Builtin::BI__sync_val_compare_and_swap_16: 1916 case Builtin::BI__sync_bool_compare_and_swap: 1917 case Builtin::BI__sync_bool_compare_and_swap_1: 1918 case Builtin::BI__sync_bool_compare_and_swap_2: 1919 case Builtin::BI__sync_bool_compare_and_swap_4: 1920 case Builtin::BI__sync_bool_compare_and_swap_8: 1921 case Builtin::BI__sync_bool_compare_and_swap_16: 1922 case Builtin::BI__sync_lock_test_and_set: 1923 case Builtin::BI__sync_lock_test_and_set_1: 1924 case Builtin::BI__sync_lock_test_and_set_2: 1925 case Builtin::BI__sync_lock_test_and_set_4: 1926 case Builtin::BI__sync_lock_test_and_set_8: 1927 case Builtin::BI__sync_lock_test_and_set_16: 1928 case Builtin::BI__sync_lock_release: 1929 case Builtin::BI__sync_lock_release_1: 1930 case Builtin::BI__sync_lock_release_2: 1931 case Builtin::BI__sync_lock_release_4: 1932 case Builtin::BI__sync_lock_release_8: 1933 case Builtin::BI__sync_lock_release_16: 1934 case Builtin::BI__sync_swap: 1935 case Builtin::BI__sync_swap_1: 1936 case Builtin::BI__sync_swap_2: 1937 case Builtin::BI__sync_swap_4: 1938 case Builtin::BI__sync_swap_8: 1939 case Builtin::BI__sync_swap_16: 1940 return SemaBuiltinAtomicOverloaded(TheCallResult); 1941 case Builtin::BI__sync_synchronize: 1942 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1943 << TheCall->getCallee()->getSourceRange(); 1944 break; 1945 case Builtin::BI__builtin_nontemporal_load: 1946 case Builtin::BI__builtin_nontemporal_store: 1947 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1948 case Builtin::BI__builtin_memcpy_inline: { 1949 if (checkArgCount(*this, TheCall, 3)) 1950 return ExprError(); 1951 auto ArgArrayConversionFailed = [&](unsigned Arg) { 1952 ExprResult ArgExpr = 1953 DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg)); 1954 if (ArgExpr.isInvalid()) 1955 return true; 1956 TheCall->setArg(Arg, ArgExpr.get()); 1957 return false; 1958 }; 1959 1960 if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1)) 1961 return true; 1962 clang::Expr *SizeOp = TheCall->getArg(2); 1963 // We warn about copying to or from `nullptr` pointers when `size` is 1964 // greater than 0. When `size` is value dependent we cannot evaluate its 1965 // value so we bail out. 1966 if (SizeOp->isValueDependent()) 1967 break; 1968 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1969 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1970 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1971 } 1972 break; 1973 } 1974 #define BUILTIN(ID, TYPE, ATTRS) 1975 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1976 case Builtin::BI##ID: \ 1977 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1978 #include "clang/Basic/Builtins.def" 1979 case Builtin::BI__annotation: 1980 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1981 return ExprError(); 1982 break; 1983 case Builtin::BI__builtin_annotation: 1984 if (SemaBuiltinAnnotation(*this, TheCall)) 1985 return ExprError(); 1986 break; 1987 case Builtin::BI__builtin_addressof: 1988 if (SemaBuiltinAddressof(*this, TheCall)) 1989 return ExprError(); 1990 break; 1991 case Builtin::BI__builtin_function_start: 1992 if (SemaBuiltinFunctionStart(*this, TheCall)) 1993 return ExprError(); 1994 break; 1995 case Builtin::BI__builtin_is_aligned: 1996 case Builtin::BI__builtin_align_up: 1997 case Builtin::BI__builtin_align_down: 1998 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1999 return ExprError(); 2000 break; 2001 case Builtin::BI__builtin_add_overflow: 2002 case Builtin::BI__builtin_sub_overflow: 2003 case Builtin::BI__builtin_mul_overflow: 2004 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 2005 return ExprError(); 2006 break; 2007 case Builtin::BI__builtin_operator_new: 2008 case Builtin::BI__builtin_operator_delete: { 2009 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 2010 ExprResult Res = 2011 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 2012 if (Res.isInvalid()) 2013 CorrectDelayedTyposInExpr(TheCallResult.get()); 2014 return Res; 2015 } 2016 case Builtin::BI__builtin_dump_struct: { 2017 // We first want to ensure we are called with 2 arguments 2018 if (checkArgCount(*this, TheCall, 2)) 2019 return ExprError(); 2020 // Ensure that the first argument is of type 'struct XX *' 2021 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 2022 const QualType PtrArgType = PtrArg->getType(); 2023 if (!PtrArgType->isPointerType() || 2024 !PtrArgType->getPointeeType()->isRecordType()) { 2025 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2026 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 2027 << "structure pointer"; 2028 return ExprError(); 2029 } 2030 2031 // Ensure that the second argument is of type 'FunctionType' 2032 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 2033 const QualType FnPtrArgType = FnPtrArg->getType(); 2034 if (!FnPtrArgType->isPointerType()) { 2035 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2036 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 2037 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2038 return ExprError(); 2039 } 2040 2041 const auto *FuncType = 2042 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 2043 2044 if (!FuncType) { 2045 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2046 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 2047 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2048 return ExprError(); 2049 } 2050 2051 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 2052 if (!FT->getNumParams()) { 2053 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2054 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 2055 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2056 return ExprError(); 2057 } 2058 QualType PT = FT->getParamType(0); 2059 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 2060 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 2061 !PT->getPointeeType().isConstQualified()) { 2062 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2063 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 2064 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2065 return ExprError(); 2066 } 2067 } 2068 2069 TheCall->setType(Context.IntTy); 2070 break; 2071 } 2072 case Builtin::BI__builtin_expect_with_probability: { 2073 // We first want to ensure we are called with 3 arguments 2074 if (checkArgCount(*this, TheCall, 3)) 2075 return ExprError(); 2076 // then check probability is constant float in range [0.0, 1.0] 2077 const Expr *ProbArg = TheCall->getArg(2); 2078 SmallVector<PartialDiagnosticAt, 8> Notes; 2079 Expr::EvalResult Eval; 2080 Eval.Diag = &Notes; 2081 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 2082 !Eval.Val.isFloat()) { 2083 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 2084 << ProbArg->getSourceRange(); 2085 for (const PartialDiagnosticAt &PDiag : Notes) 2086 Diag(PDiag.first, PDiag.second); 2087 return ExprError(); 2088 } 2089 llvm::APFloat Probability = Eval.Val.getFloat(); 2090 bool LoseInfo = false; 2091 Probability.convert(llvm::APFloat::IEEEdouble(), 2092 llvm::RoundingMode::Dynamic, &LoseInfo); 2093 if (!(Probability >= llvm::APFloat(0.0) && 2094 Probability <= llvm::APFloat(1.0))) { 2095 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 2096 << ProbArg->getSourceRange(); 2097 return ExprError(); 2098 } 2099 break; 2100 } 2101 case Builtin::BI__builtin_preserve_access_index: 2102 if (SemaBuiltinPreserveAI(*this, TheCall)) 2103 return ExprError(); 2104 break; 2105 case Builtin::BI__builtin_call_with_static_chain: 2106 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 2107 return ExprError(); 2108 break; 2109 case Builtin::BI__exception_code: 2110 case Builtin::BI_exception_code: 2111 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 2112 diag::err_seh___except_block)) 2113 return ExprError(); 2114 break; 2115 case Builtin::BI__exception_info: 2116 case Builtin::BI_exception_info: 2117 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 2118 diag::err_seh___except_filter)) 2119 return ExprError(); 2120 break; 2121 case Builtin::BI__GetExceptionInfo: 2122 if (checkArgCount(*this, TheCall, 1)) 2123 return ExprError(); 2124 2125 if (CheckCXXThrowOperand( 2126 TheCall->getBeginLoc(), 2127 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 2128 TheCall)) 2129 return ExprError(); 2130 2131 TheCall->setType(Context.VoidPtrTy); 2132 break; 2133 // OpenCL v2.0, s6.13.16 - Pipe functions 2134 case Builtin::BIread_pipe: 2135 case Builtin::BIwrite_pipe: 2136 // Since those two functions are declared with var args, we need a semantic 2137 // check for the argument. 2138 if (SemaBuiltinRWPipe(*this, TheCall)) 2139 return ExprError(); 2140 break; 2141 case Builtin::BIreserve_read_pipe: 2142 case Builtin::BIreserve_write_pipe: 2143 case Builtin::BIwork_group_reserve_read_pipe: 2144 case Builtin::BIwork_group_reserve_write_pipe: 2145 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 2146 return ExprError(); 2147 break; 2148 case Builtin::BIsub_group_reserve_read_pipe: 2149 case Builtin::BIsub_group_reserve_write_pipe: 2150 if (checkOpenCLSubgroupExt(*this, TheCall) || 2151 SemaBuiltinReserveRWPipe(*this, TheCall)) 2152 return ExprError(); 2153 break; 2154 case Builtin::BIcommit_read_pipe: 2155 case Builtin::BIcommit_write_pipe: 2156 case Builtin::BIwork_group_commit_read_pipe: 2157 case Builtin::BIwork_group_commit_write_pipe: 2158 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 2159 return ExprError(); 2160 break; 2161 case Builtin::BIsub_group_commit_read_pipe: 2162 case Builtin::BIsub_group_commit_write_pipe: 2163 if (checkOpenCLSubgroupExt(*this, TheCall) || 2164 SemaBuiltinCommitRWPipe(*this, TheCall)) 2165 return ExprError(); 2166 break; 2167 case Builtin::BIget_pipe_num_packets: 2168 case Builtin::BIget_pipe_max_packets: 2169 if (SemaBuiltinPipePackets(*this, TheCall)) 2170 return ExprError(); 2171 break; 2172 case Builtin::BIto_global: 2173 case Builtin::BIto_local: 2174 case Builtin::BIto_private: 2175 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 2176 return ExprError(); 2177 break; 2178 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2179 case Builtin::BIenqueue_kernel: 2180 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 2181 return ExprError(); 2182 break; 2183 case Builtin::BIget_kernel_work_group_size: 2184 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2185 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 2186 return ExprError(); 2187 break; 2188 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2189 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2190 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 2191 return ExprError(); 2192 break; 2193 case Builtin::BI__builtin_os_log_format: 2194 Cleanup.setExprNeedsCleanups(true); 2195 LLVM_FALLTHROUGH; 2196 case Builtin::BI__builtin_os_log_format_buffer_size: 2197 if (SemaBuiltinOSLogFormat(TheCall)) 2198 return ExprError(); 2199 break; 2200 case Builtin::BI__builtin_frame_address: 2201 case Builtin::BI__builtin_return_address: { 2202 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2203 return ExprError(); 2204 2205 // -Wframe-address warning if non-zero passed to builtin 2206 // return/frame address. 2207 Expr::EvalResult Result; 2208 if (!TheCall->getArg(0)->isValueDependent() && 2209 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2210 Result.Val.getInt() != 0) 2211 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2212 << ((BuiltinID == Builtin::BI__builtin_return_address) 2213 ? "__builtin_return_address" 2214 : "__builtin_frame_address") 2215 << TheCall->getSourceRange(); 2216 break; 2217 } 2218 2219 // __builtin_elementwise_abs restricts the element type to signed integers or 2220 // floating point types only. 2221 case Builtin::BI__builtin_elementwise_abs: { 2222 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2223 return ExprError(); 2224 2225 QualType ArgTy = TheCall->getArg(0)->getType(); 2226 QualType EltTy = ArgTy; 2227 2228 if (auto *VecTy = EltTy->getAs<VectorType>()) 2229 EltTy = VecTy->getElementType(); 2230 if (EltTy->isUnsignedIntegerType()) { 2231 Diag(TheCall->getArg(0)->getBeginLoc(), 2232 diag::err_builtin_invalid_arg_type) 2233 << 1 << /* signed integer or float ty*/ 3 << ArgTy; 2234 return ExprError(); 2235 } 2236 break; 2237 } 2238 2239 // These builtins restrict the element type to floating point 2240 // types only. 2241 case Builtin::BI__builtin_elementwise_ceil: 2242 case Builtin::BI__builtin_elementwise_floor: 2243 case Builtin::BI__builtin_elementwise_roundeven: 2244 case Builtin::BI__builtin_elementwise_trunc: { 2245 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2246 return ExprError(); 2247 2248 QualType ArgTy = TheCall->getArg(0)->getType(); 2249 QualType EltTy = ArgTy; 2250 2251 if (auto *VecTy = EltTy->getAs<VectorType>()) 2252 EltTy = VecTy->getElementType(); 2253 if (!EltTy->isFloatingType()) { 2254 Diag(TheCall->getArg(0)->getBeginLoc(), 2255 diag::err_builtin_invalid_arg_type) 2256 << 1 << /* float ty*/ 5 << ArgTy; 2257 2258 return ExprError(); 2259 } 2260 break; 2261 } 2262 2263 // These builtins restrict the element type to integer 2264 // types only. 2265 case Builtin::BI__builtin_elementwise_add_sat: 2266 case Builtin::BI__builtin_elementwise_sub_sat: { 2267 if (SemaBuiltinElementwiseMath(TheCall)) 2268 return ExprError(); 2269 2270 const Expr *Arg = TheCall->getArg(0); 2271 QualType ArgTy = Arg->getType(); 2272 QualType EltTy = ArgTy; 2273 2274 if (auto *VecTy = EltTy->getAs<VectorType>()) 2275 EltTy = VecTy->getElementType(); 2276 2277 if (!EltTy->isIntegerType()) { 2278 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2279 << 1 << /* integer ty */ 6 << ArgTy; 2280 return ExprError(); 2281 } 2282 break; 2283 } 2284 2285 case Builtin::BI__builtin_elementwise_min: 2286 case Builtin::BI__builtin_elementwise_max: 2287 if (SemaBuiltinElementwiseMath(TheCall)) 2288 return ExprError(); 2289 break; 2290 case Builtin::BI__builtin_reduce_max: 2291 case Builtin::BI__builtin_reduce_min: { 2292 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2293 return ExprError(); 2294 2295 const Expr *Arg = TheCall->getArg(0); 2296 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2297 if (!TyA) { 2298 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2299 << 1 << /* vector ty*/ 4 << Arg->getType(); 2300 return ExprError(); 2301 } 2302 2303 TheCall->setType(TyA->getElementType()); 2304 break; 2305 } 2306 2307 // These builtins support vectors of integers only. 2308 case Builtin::BI__builtin_reduce_xor: 2309 case Builtin::BI__builtin_reduce_or: 2310 case Builtin::BI__builtin_reduce_and: { 2311 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2312 return ExprError(); 2313 2314 const Expr *Arg = TheCall->getArg(0); 2315 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2316 if (!TyA || !TyA->getElementType()->isIntegerType()) { 2317 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2318 << 1 << /* vector of integers */ 6 << Arg->getType(); 2319 return ExprError(); 2320 } 2321 TheCall->setType(TyA->getElementType()); 2322 break; 2323 } 2324 2325 case Builtin::BI__builtin_matrix_transpose: 2326 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 2327 2328 case Builtin::BI__builtin_matrix_column_major_load: 2329 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2330 2331 case Builtin::BI__builtin_matrix_column_major_store: 2332 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2333 2334 case Builtin::BI__builtin_get_device_side_mangled_name: { 2335 auto Check = [](CallExpr *TheCall) { 2336 if (TheCall->getNumArgs() != 1) 2337 return false; 2338 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2339 if (!DRE) 2340 return false; 2341 auto *D = DRE->getDecl(); 2342 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2343 return false; 2344 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2345 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2346 }; 2347 if (!Check(TheCall)) { 2348 Diag(TheCall->getBeginLoc(), 2349 diag::err_hip_invalid_args_builtin_mangled_name); 2350 return ExprError(); 2351 } 2352 } 2353 } 2354 2355 // Since the target specific builtins for each arch overlap, only check those 2356 // of the arch we are compiling for. 2357 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2358 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2359 assert(Context.getAuxTargetInfo() && 2360 "Aux Target Builtin, but not an aux target?"); 2361 2362 if (CheckTSBuiltinFunctionCall( 2363 *Context.getAuxTargetInfo(), 2364 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2365 return ExprError(); 2366 } else { 2367 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2368 TheCall)) 2369 return ExprError(); 2370 } 2371 } 2372 2373 return TheCallResult; 2374 } 2375 2376 // Get the valid immediate range for the specified NEON type code. 2377 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2378 NeonTypeFlags Type(t); 2379 int IsQuad = ForceQuad ? true : Type.isQuad(); 2380 switch (Type.getEltType()) { 2381 case NeonTypeFlags::Int8: 2382 case NeonTypeFlags::Poly8: 2383 return shift ? 7 : (8 << IsQuad) - 1; 2384 case NeonTypeFlags::Int16: 2385 case NeonTypeFlags::Poly16: 2386 return shift ? 15 : (4 << IsQuad) - 1; 2387 case NeonTypeFlags::Int32: 2388 return shift ? 31 : (2 << IsQuad) - 1; 2389 case NeonTypeFlags::Int64: 2390 case NeonTypeFlags::Poly64: 2391 return shift ? 63 : (1 << IsQuad) - 1; 2392 case NeonTypeFlags::Poly128: 2393 return shift ? 127 : (1 << IsQuad) - 1; 2394 case NeonTypeFlags::Float16: 2395 assert(!shift && "cannot shift float types!"); 2396 return (4 << IsQuad) - 1; 2397 case NeonTypeFlags::Float32: 2398 assert(!shift && "cannot shift float types!"); 2399 return (2 << IsQuad) - 1; 2400 case NeonTypeFlags::Float64: 2401 assert(!shift && "cannot shift float types!"); 2402 return (1 << IsQuad) - 1; 2403 case NeonTypeFlags::BFloat16: 2404 assert(!shift && "cannot shift float types!"); 2405 return (4 << IsQuad) - 1; 2406 } 2407 llvm_unreachable("Invalid NeonTypeFlag!"); 2408 } 2409 2410 /// getNeonEltType - Return the QualType corresponding to the elements of 2411 /// the vector type specified by the NeonTypeFlags. This is used to check 2412 /// the pointer arguments for Neon load/store intrinsics. 2413 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2414 bool IsPolyUnsigned, bool IsInt64Long) { 2415 switch (Flags.getEltType()) { 2416 case NeonTypeFlags::Int8: 2417 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2418 case NeonTypeFlags::Int16: 2419 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2420 case NeonTypeFlags::Int32: 2421 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2422 case NeonTypeFlags::Int64: 2423 if (IsInt64Long) 2424 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2425 else 2426 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2427 : Context.LongLongTy; 2428 case NeonTypeFlags::Poly8: 2429 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2430 case NeonTypeFlags::Poly16: 2431 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2432 case NeonTypeFlags::Poly64: 2433 if (IsInt64Long) 2434 return Context.UnsignedLongTy; 2435 else 2436 return Context.UnsignedLongLongTy; 2437 case NeonTypeFlags::Poly128: 2438 break; 2439 case NeonTypeFlags::Float16: 2440 return Context.HalfTy; 2441 case NeonTypeFlags::Float32: 2442 return Context.FloatTy; 2443 case NeonTypeFlags::Float64: 2444 return Context.DoubleTy; 2445 case NeonTypeFlags::BFloat16: 2446 return Context.BFloat16Ty; 2447 } 2448 llvm_unreachable("Invalid NeonTypeFlag!"); 2449 } 2450 2451 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2452 // Range check SVE intrinsics that take immediate values. 2453 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2454 2455 switch (BuiltinID) { 2456 default: 2457 return false; 2458 #define GET_SVE_IMMEDIATE_CHECK 2459 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2460 #undef GET_SVE_IMMEDIATE_CHECK 2461 } 2462 2463 // Perform all the immediate checks for this builtin call. 2464 bool HasError = false; 2465 for (auto &I : ImmChecks) { 2466 int ArgNum, CheckTy, ElementSizeInBits; 2467 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2468 2469 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2470 2471 // Function that checks whether the operand (ArgNum) is an immediate 2472 // that is one of the predefined values. 2473 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2474 int ErrDiag) -> bool { 2475 // We can't check the value of a dependent argument. 2476 Expr *Arg = TheCall->getArg(ArgNum); 2477 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2478 return false; 2479 2480 // Check constant-ness first. 2481 llvm::APSInt Imm; 2482 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2483 return true; 2484 2485 if (!CheckImm(Imm.getSExtValue())) 2486 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2487 return false; 2488 }; 2489 2490 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2491 case SVETypeFlags::ImmCheck0_31: 2492 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2493 HasError = true; 2494 break; 2495 case SVETypeFlags::ImmCheck0_13: 2496 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2497 HasError = true; 2498 break; 2499 case SVETypeFlags::ImmCheck1_16: 2500 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2501 HasError = true; 2502 break; 2503 case SVETypeFlags::ImmCheck0_7: 2504 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2505 HasError = true; 2506 break; 2507 case SVETypeFlags::ImmCheckExtract: 2508 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2509 (2048 / ElementSizeInBits) - 1)) 2510 HasError = true; 2511 break; 2512 case SVETypeFlags::ImmCheckShiftRight: 2513 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2514 HasError = true; 2515 break; 2516 case SVETypeFlags::ImmCheckShiftRightNarrow: 2517 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2518 ElementSizeInBits / 2)) 2519 HasError = true; 2520 break; 2521 case SVETypeFlags::ImmCheckShiftLeft: 2522 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2523 ElementSizeInBits - 1)) 2524 HasError = true; 2525 break; 2526 case SVETypeFlags::ImmCheckLaneIndex: 2527 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2528 (128 / (1 * ElementSizeInBits)) - 1)) 2529 HasError = true; 2530 break; 2531 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2532 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2533 (128 / (2 * ElementSizeInBits)) - 1)) 2534 HasError = true; 2535 break; 2536 case SVETypeFlags::ImmCheckLaneIndexDot: 2537 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2538 (128 / (4 * ElementSizeInBits)) - 1)) 2539 HasError = true; 2540 break; 2541 case SVETypeFlags::ImmCheckComplexRot90_270: 2542 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2543 diag::err_rotation_argument_to_cadd)) 2544 HasError = true; 2545 break; 2546 case SVETypeFlags::ImmCheckComplexRotAll90: 2547 if (CheckImmediateInSet( 2548 [](int64_t V) { 2549 return V == 0 || V == 90 || V == 180 || V == 270; 2550 }, 2551 diag::err_rotation_argument_to_cmla)) 2552 HasError = true; 2553 break; 2554 case SVETypeFlags::ImmCheck0_1: 2555 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2556 HasError = true; 2557 break; 2558 case SVETypeFlags::ImmCheck0_2: 2559 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2560 HasError = true; 2561 break; 2562 case SVETypeFlags::ImmCheck0_3: 2563 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2564 HasError = true; 2565 break; 2566 } 2567 } 2568 2569 return HasError; 2570 } 2571 2572 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2573 unsigned BuiltinID, CallExpr *TheCall) { 2574 llvm::APSInt Result; 2575 uint64_t mask = 0; 2576 unsigned TV = 0; 2577 int PtrArgNum = -1; 2578 bool HasConstPtr = false; 2579 switch (BuiltinID) { 2580 #define GET_NEON_OVERLOAD_CHECK 2581 #include "clang/Basic/arm_neon.inc" 2582 #include "clang/Basic/arm_fp16.inc" 2583 #undef GET_NEON_OVERLOAD_CHECK 2584 } 2585 2586 // For NEON intrinsics which are overloaded on vector element type, validate 2587 // the immediate which specifies which variant to emit. 2588 unsigned ImmArg = TheCall->getNumArgs()-1; 2589 if (mask) { 2590 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2591 return true; 2592 2593 TV = Result.getLimitedValue(64); 2594 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2595 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2596 << TheCall->getArg(ImmArg)->getSourceRange(); 2597 } 2598 2599 if (PtrArgNum >= 0) { 2600 // Check that pointer arguments have the specified type. 2601 Expr *Arg = TheCall->getArg(PtrArgNum); 2602 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2603 Arg = ICE->getSubExpr(); 2604 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2605 QualType RHSTy = RHS.get()->getType(); 2606 2607 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2608 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2609 Arch == llvm::Triple::aarch64_32 || 2610 Arch == llvm::Triple::aarch64_be; 2611 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2612 QualType EltTy = 2613 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2614 if (HasConstPtr) 2615 EltTy = EltTy.withConst(); 2616 QualType LHSTy = Context.getPointerType(EltTy); 2617 AssignConvertType ConvTy; 2618 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2619 if (RHS.isInvalid()) 2620 return true; 2621 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2622 RHS.get(), AA_Assigning)) 2623 return true; 2624 } 2625 2626 // For NEON intrinsics which take an immediate value as part of the 2627 // instruction, range check them here. 2628 unsigned i = 0, l = 0, u = 0; 2629 switch (BuiltinID) { 2630 default: 2631 return false; 2632 #define GET_NEON_IMMEDIATE_CHECK 2633 #include "clang/Basic/arm_neon.inc" 2634 #include "clang/Basic/arm_fp16.inc" 2635 #undef GET_NEON_IMMEDIATE_CHECK 2636 } 2637 2638 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2639 } 2640 2641 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2642 switch (BuiltinID) { 2643 default: 2644 return false; 2645 #include "clang/Basic/arm_mve_builtin_sema.inc" 2646 } 2647 } 2648 2649 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2650 CallExpr *TheCall) { 2651 bool Err = false; 2652 switch (BuiltinID) { 2653 default: 2654 return false; 2655 #include "clang/Basic/arm_cde_builtin_sema.inc" 2656 } 2657 2658 if (Err) 2659 return true; 2660 2661 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2662 } 2663 2664 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2665 const Expr *CoprocArg, bool WantCDE) { 2666 if (isConstantEvaluated()) 2667 return false; 2668 2669 // We can't check the value of a dependent argument. 2670 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2671 return false; 2672 2673 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2674 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2675 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2676 2677 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2678 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2679 2680 if (IsCDECoproc != WantCDE) 2681 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2682 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2683 2684 return false; 2685 } 2686 2687 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2688 unsigned MaxWidth) { 2689 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2690 BuiltinID == ARM::BI__builtin_arm_ldaex || 2691 BuiltinID == ARM::BI__builtin_arm_strex || 2692 BuiltinID == ARM::BI__builtin_arm_stlex || 2693 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2694 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2695 BuiltinID == AArch64::BI__builtin_arm_strex || 2696 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2697 "unexpected ARM builtin"); 2698 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2699 BuiltinID == ARM::BI__builtin_arm_ldaex || 2700 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2701 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2702 2703 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2704 2705 // Ensure that we have the proper number of arguments. 2706 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2707 return true; 2708 2709 // Inspect the pointer argument of the atomic builtin. This should always be 2710 // a pointer type, whose element is an integral scalar or pointer type. 2711 // Because it is a pointer type, we don't have to worry about any implicit 2712 // casts here. 2713 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2714 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2715 if (PointerArgRes.isInvalid()) 2716 return true; 2717 PointerArg = PointerArgRes.get(); 2718 2719 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2720 if (!pointerType) { 2721 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2722 << PointerArg->getType() << PointerArg->getSourceRange(); 2723 return true; 2724 } 2725 2726 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2727 // task is to insert the appropriate casts into the AST. First work out just 2728 // what the appropriate type is. 2729 QualType ValType = pointerType->getPointeeType(); 2730 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2731 if (IsLdrex) 2732 AddrType.addConst(); 2733 2734 // Issue a warning if the cast is dodgy. 2735 CastKind CastNeeded = CK_NoOp; 2736 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2737 CastNeeded = CK_BitCast; 2738 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2739 << PointerArg->getType() << Context.getPointerType(AddrType) 2740 << AA_Passing << PointerArg->getSourceRange(); 2741 } 2742 2743 // Finally, do the cast and replace the argument with the corrected version. 2744 AddrType = Context.getPointerType(AddrType); 2745 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2746 if (PointerArgRes.isInvalid()) 2747 return true; 2748 PointerArg = PointerArgRes.get(); 2749 2750 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2751 2752 // In general, we allow ints, floats and pointers to be loaded and stored. 2753 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2754 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2755 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2756 << PointerArg->getType() << PointerArg->getSourceRange(); 2757 return true; 2758 } 2759 2760 // But ARM doesn't have instructions to deal with 128-bit versions. 2761 if (Context.getTypeSize(ValType) > MaxWidth) { 2762 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2763 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2764 << PointerArg->getType() << PointerArg->getSourceRange(); 2765 return true; 2766 } 2767 2768 switch (ValType.getObjCLifetime()) { 2769 case Qualifiers::OCL_None: 2770 case Qualifiers::OCL_ExplicitNone: 2771 // okay 2772 break; 2773 2774 case Qualifiers::OCL_Weak: 2775 case Qualifiers::OCL_Strong: 2776 case Qualifiers::OCL_Autoreleasing: 2777 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2778 << ValType << PointerArg->getSourceRange(); 2779 return true; 2780 } 2781 2782 if (IsLdrex) { 2783 TheCall->setType(ValType); 2784 return false; 2785 } 2786 2787 // Initialize the argument to be stored. 2788 ExprResult ValArg = TheCall->getArg(0); 2789 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2790 Context, ValType, /*consume*/ false); 2791 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2792 if (ValArg.isInvalid()) 2793 return true; 2794 TheCall->setArg(0, ValArg.get()); 2795 2796 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2797 // but the custom checker bypasses all default analysis. 2798 TheCall->setType(Context.IntTy); 2799 return false; 2800 } 2801 2802 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2803 CallExpr *TheCall) { 2804 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2805 BuiltinID == ARM::BI__builtin_arm_ldaex || 2806 BuiltinID == ARM::BI__builtin_arm_strex || 2807 BuiltinID == ARM::BI__builtin_arm_stlex) { 2808 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2809 } 2810 2811 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2812 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2813 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2814 } 2815 2816 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2817 BuiltinID == ARM::BI__builtin_arm_wsr64) 2818 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2819 2820 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2821 BuiltinID == ARM::BI__builtin_arm_rsrp || 2822 BuiltinID == ARM::BI__builtin_arm_wsr || 2823 BuiltinID == ARM::BI__builtin_arm_wsrp) 2824 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2825 2826 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2827 return true; 2828 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2829 return true; 2830 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2831 return true; 2832 2833 // For intrinsics which take an immediate value as part of the instruction, 2834 // range check them here. 2835 // FIXME: VFP Intrinsics should error if VFP not present. 2836 switch (BuiltinID) { 2837 default: return false; 2838 case ARM::BI__builtin_arm_ssat: 2839 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2840 case ARM::BI__builtin_arm_usat: 2841 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2842 case ARM::BI__builtin_arm_ssat16: 2843 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2844 case ARM::BI__builtin_arm_usat16: 2845 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2846 case ARM::BI__builtin_arm_vcvtr_f: 2847 case ARM::BI__builtin_arm_vcvtr_d: 2848 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2849 case ARM::BI__builtin_arm_dmb: 2850 case ARM::BI__builtin_arm_dsb: 2851 case ARM::BI__builtin_arm_isb: 2852 case ARM::BI__builtin_arm_dbg: 2853 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2854 case ARM::BI__builtin_arm_cdp: 2855 case ARM::BI__builtin_arm_cdp2: 2856 case ARM::BI__builtin_arm_mcr: 2857 case ARM::BI__builtin_arm_mcr2: 2858 case ARM::BI__builtin_arm_mrc: 2859 case ARM::BI__builtin_arm_mrc2: 2860 case ARM::BI__builtin_arm_mcrr: 2861 case ARM::BI__builtin_arm_mcrr2: 2862 case ARM::BI__builtin_arm_mrrc: 2863 case ARM::BI__builtin_arm_mrrc2: 2864 case ARM::BI__builtin_arm_ldc: 2865 case ARM::BI__builtin_arm_ldcl: 2866 case ARM::BI__builtin_arm_ldc2: 2867 case ARM::BI__builtin_arm_ldc2l: 2868 case ARM::BI__builtin_arm_stc: 2869 case ARM::BI__builtin_arm_stcl: 2870 case ARM::BI__builtin_arm_stc2: 2871 case ARM::BI__builtin_arm_stc2l: 2872 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2873 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2874 /*WantCDE*/ false); 2875 } 2876 } 2877 2878 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2879 unsigned BuiltinID, 2880 CallExpr *TheCall) { 2881 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2882 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2883 BuiltinID == AArch64::BI__builtin_arm_strex || 2884 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2885 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2886 } 2887 2888 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2889 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2890 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2891 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2892 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2893 } 2894 2895 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2896 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2897 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2898 2899 // Memory Tagging Extensions (MTE) Intrinsics 2900 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2901 BuiltinID == AArch64::BI__builtin_arm_addg || 2902 BuiltinID == AArch64::BI__builtin_arm_gmi || 2903 BuiltinID == AArch64::BI__builtin_arm_ldg || 2904 BuiltinID == AArch64::BI__builtin_arm_stg || 2905 BuiltinID == AArch64::BI__builtin_arm_subp) { 2906 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2907 } 2908 2909 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2910 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2911 BuiltinID == AArch64::BI__builtin_arm_wsr || 2912 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2913 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2914 2915 // Only check the valid encoding range. Any constant in this range would be 2916 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2917 // an exception for incorrect registers. This matches MSVC behavior. 2918 if (BuiltinID == AArch64::BI_ReadStatusReg || 2919 BuiltinID == AArch64::BI_WriteStatusReg) 2920 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2921 2922 if (BuiltinID == AArch64::BI__getReg) 2923 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2924 2925 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2926 return true; 2927 2928 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2929 return true; 2930 2931 // For intrinsics which take an immediate value as part of the instruction, 2932 // range check them here. 2933 unsigned i = 0, l = 0, u = 0; 2934 switch (BuiltinID) { 2935 default: return false; 2936 case AArch64::BI__builtin_arm_dmb: 2937 case AArch64::BI__builtin_arm_dsb: 2938 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2939 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2940 } 2941 2942 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2943 } 2944 2945 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2946 if (Arg->getType()->getAsPlaceholderType()) 2947 return false; 2948 2949 // The first argument needs to be a record field access. 2950 // If it is an array element access, we delay decision 2951 // to BPF backend to check whether the access is a 2952 // field access or not. 2953 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2954 isa<MemberExpr>(Arg->IgnoreParens()) || 2955 isa<ArraySubscriptExpr>(Arg->IgnoreParens())); 2956 } 2957 2958 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2959 QualType VectorTy, QualType EltTy) { 2960 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2961 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2962 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2963 << Call->getSourceRange() << VectorEltTy << EltTy; 2964 return false; 2965 } 2966 return true; 2967 } 2968 2969 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2970 QualType ArgType = Arg->getType(); 2971 if (ArgType->getAsPlaceholderType()) 2972 return false; 2973 2974 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2975 // format: 2976 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2977 // 2. <type> var; 2978 // __builtin_preserve_type_info(var, flag); 2979 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) && 2980 !isa<UnaryOperator>(Arg->IgnoreParens())) 2981 return false; 2982 2983 // Typedef type. 2984 if (ArgType->getAs<TypedefType>()) 2985 return true; 2986 2987 // Record type or Enum type. 2988 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2989 if (const auto *RT = Ty->getAs<RecordType>()) { 2990 if (!RT->getDecl()->getDeclName().isEmpty()) 2991 return true; 2992 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2993 if (!ET->getDecl()->getDeclName().isEmpty()) 2994 return true; 2995 } 2996 2997 return false; 2998 } 2999 3000 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 3001 QualType ArgType = Arg->getType(); 3002 if (ArgType->getAsPlaceholderType()) 3003 return false; 3004 3005 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 3006 // format: 3007 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 3008 // flag); 3009 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 3010 if (!UO) 3011 return false; 3012 3013 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 3014 if (!CE) 3015 return false; 3016 if (CE->getCastKind() != CK_IntegralToPointer && 3017 CE->getCastKind() != CK_NullToPointer) 3018 return false; 3019 3020 // The integer must be from an EnumConstantDecl. 3021 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 3022 if (!DR) 3023 return false; 3024 3025 const EnumConstantDecl *Enumerator = 3026 dyn_cast<EnumConstantDecl>(DR->getDecl()); 3027 if (!Enumerator) 3028 return false; 3029 3030 // The type must be EnumType. 3031 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 3032 const auto *ET = Ty->getAs<EnumType>(); 3033 if (!ET) 3034 return false; 3035 3036 // The enum value must be supported. 3037 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 3038 } 3039 3040 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 3041 CallExpr *TheCall) { 3042 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 3043 BuiltinID == BPF::BI__builtin_btf_type_id || 3044 BuiltinID == BPF::BI__builtin_preserve_type_info || 3045 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 3046 "unexpected BPF builtin"); 3047 3048 if (checkArgCount(*this, TheCall, 2)) 3049 return true; 3050 3051 // The second argument needs to be a constant int 3052 Expr *Arg = TheCall->getArg(1); 3053 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 3054 diag::kind kind; 3055 if (!Value) { 3056 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 3057 kind = diag::err_preserve_field_info_not_const; 3058 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 3059 kind = diag::err_btf_type_id_not_const; 3060 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 3061 kind = diag::err_preserve_type_info_not_const; 3062 else 3063 kind = diag::err_preserve_enum_value_not_const; 3064 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 3065 return true; 3066 } 3067 3068 // The first argument 3069 Arg = TheCall->getArg(0); 3070 bool InvalidArg = false; 3071 bool ReturnUnsignedInt = true; 3072 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 3073 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 3074 InvalidArg = true; 3075 kind = diag::err_preserve_field_info_not_field; 3076 } 3077 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 3078 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 3079 InvalidArg = true; 3080 kind = diag::err_preserve_type_info_invalid; 3081 } 3082 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 3083 if (!isValidBPFPreserveEnumValueArg(Arg)) { 3084 InvalidArg = true; 3085 kind = diag::err_preserve_enum_value_invalid; 3086 } 3087 ReturnUnsignedInt = false; 3088 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 3089 ReturnUnsignedInt = false; 3090 } 3091 3092 if (InvalidArg) { 3093 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 3094 return true; 3095 } 3096 3097 if (ReturnUnsignedInt) 3098 TheCall->setType(Context.UnsignedIntTy); 3099 else 3100 TheCall->setType(Context.UnsignedLongTy); 3101 return false; 3102 } 3103 3104 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3105 struct ArgInfo { 3106 uint8_t OpNum; 3107 bool IsSigned; 3108 uint8_t BitWidth; 3109 uint8_t Align; 3110 }; 3111 struct BuiltinInfo { 3112 unsigned BuiltinID; 3113 ArgInfo Infos[2]; 3114 }; 3115 3116 static BuiltinInfo Infos[] = { 3117 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 3118 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 3119 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 3120 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 3121 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 3122 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 3123 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 3124 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 3125 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 3126 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 3127 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 3128 3129 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 3130 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 3131 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 3132 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 3133 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 3134 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 3135 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 3136 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 3137 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 3138 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 3139 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 3140 3141 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 3142 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 3143 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 3144 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 3145 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 3146 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 3147 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 3148 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 3149 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 3150 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 3151 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 3152 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 3153 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 3154 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 3155 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 3156 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 3157 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 3158 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 3159 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 3160 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 3161 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 3162 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 3163 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 3164 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 3165 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 3166 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 3167 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 3168 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 3169 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 3170 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 3171 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 3172 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 3173 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 3174 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 3175 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 3176 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 3177 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 3178 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 3179 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 3180 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 3181 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 3182 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 3183 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 3184 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 3185 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 3186 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 3187 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 3188 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 3189 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 3190 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 3191 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 3192 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 3193 {{ 1, false, 6, 0 }} }, 3194 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 3195 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 3196 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 3197 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 3198 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 3199 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 3200 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 3201 {{ 1, false, 5, 0 }} }, 3202 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 3203 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 3204 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 3205 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 3206 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 3207 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 3208 { 2, false, 5, 0 }} }, 3209 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 3210 { 2, false, 6, 0 }} }, 3211 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 3212 { 3, false, 5, 0 }} }, 3213 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 3214 { 3, false, 6, 0 }} }, 3215 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 3216 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 3217 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 3218 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 3219 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 3220 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 3221 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 3222 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 3223 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 3224 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 3225 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 3226 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 3227 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 3228 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3229 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3230 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3231 {{ 2, false, 4, 0 }, 3232 { 3, false, 5, 0 }} }, 3233 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3234 {{ 2, false, 4, 0 }, 3235 { 3, false, 5, 0 }} }, 3236 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3237 {{ 2, false, 4, 0 }, 3238 { 3, false, 5, 0 }} }, 3239 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3240 {{ 2, false, 4, 0 }, 3241 { 3, false, 5, 0 }} }, 3242 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3243 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3244 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3245 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3246 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3247 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3248 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3249 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3250 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3251 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3252 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3253 { 2, false, 5, 0 }} }, 3254 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3255 { 2, false, 6, 0 }} }, 3256 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3257 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3258 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3259 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3260 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3261 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3262 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3263 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3264 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3265 {{ 1, false, 4, 0 }} }, 3266 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3267 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3268 {{ 1, false, 4, 0 }} }, 3269 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3270 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3271 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3272 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3273 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3274 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3275 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3276 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3277 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3278 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3279 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3280 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3281 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3282 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3283 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3284 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3285 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3286 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3287 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3288 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3289 {{ 3, false, 1, 0 }} }, 3290 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3291 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3292 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3293 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3294 {{ 3, false, 1, 0 }} }, 3295 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3296 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3297 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3298 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3299 {{ 3, false, 1, 0 }} }, 3300 }; 3301 3302 // Use a dynamically initialized static to sort the table exactly once on 3303 // first run. 3304 static const bool SortOnce = 3305 (llvm::sort(Infos, 3306 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3307 return LHS.BuiltinID < RHS.BuiltinID; 3308 }), 3309 true); 3310 (void)SortOnce; 3311 3312 const BuiltinInfo *F = llvm::partition_point( 3313 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3314 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3315 return false; 3316 3317 bool Error = false; 3318 3319 for (const ArgInfo &A : F->Infos) { 3320 // Ignore empty ArgInfo elements. 3321 if (A.BitWidth == 0) 3322 continue; 3323 3324 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3325 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3326 if (!A.Align) { 3327 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3328 } else { 3329 unsigned M = 1 << A.Align; 3330 Min *= M; 3331 Max *= M; 3332 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3333 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3334 } 3335 } 3336 return Error; 3337 } 3338 3339 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3340 CallExpr *TheCall) { 3341 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3342 } 3343 3344 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3345 unsigned BuiltinID, CallExpr *TheCall) { 3346 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3347 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3348 } 3349 3350 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3351 CallExpr *TheCall) { 3352 3353 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3354 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3355 if (!TI.hasFeature("dsp")) 3356 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3357 } 3358 3359 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3360 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3361 if (!TI.hasFeature("dspr2")) 3362 return Diag(TheCall->getBeginLoc(), 3363 diag::err_mips_builtin_requires_dspr2); 3364 } 3365 3366 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3367 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3368 if (!TI.hasFeature("msa")) 3369 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3370 } 3371 3372 return false; 3373 } 3374 3375 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3376 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3377 // ordering for DSP is unspecified. MSA is ordered by the data format used 3378 // by the underlying instruction i.e., df/m, df/n and then by size. 3379 // 3380 // FIXME: The size tests here should instead be tablegen'd along with the 3381 // definitions from include/clang/Basic/BuiltinsMips.def. 3382 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3383 // be too. 3384 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3385 unsigned i = 0, l = 0, u = 0, m = 0; 3386 switch (BuiltinID) { 3387 default: return false; 3388 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3389 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3390 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3391 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3392 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3393 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3394 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3395 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3396 // df/m field. 3397 // These intrinsics take an unsigned 3 bit immediate. 3398 case Mips::BI__builtin_msa_bclri_b: 3399 case Mips::BI__builtin_msa_bnegi_b: 3400 case Mips::BI__builtin_msa_bseti_b: 3401 case Mips::BI__builtin_msa_sat_s_b: 3402 case Mips::BI__builtin_msa_sat_u_b: 3403 case Mips::BI__builtin_msa_slli_b: 3404 case Mips::BI__builtin_msa_srai_b: 3405 case Mips::BI__builtin_msa_srari_b: 3406 case Mips::BI__builtin_msa_srli_b: 3407 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3408 case Mips::BI__builtin_msa_binsli_b: 3409 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3410 // These intrinsics take an unsigned 4 bit immediate. 3411 case Mips::BI__builtin_msa_bclri_h: 3412 case Mips::BI__builtin_msa_bnegi_h: 3413 case Mips::BI__builtin_msa_bseti_h: 3414 case Mips::BI__builtin_msa_sat_s_h: 3415 case Mips::BI__builtin_msa_sat_u_h: 3416 case Mips::BI__builtin_msa_slli_h: 3417 case Mips::BI__builtin_msa_srai_h: 3418 case Mips::BI__builtin_msa_srari_h: 3419 case Mips::BI__builtin_msa_srli_h: 3420 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3421 case Mips::BI__builtin_msa_binsli_h: 3422 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3423 // These intrinsics take an unsigned 5 bit immediate. 3424 // The first block of intrinsics actually have an unsigned 5 bit field, 3425 // not a df/n field. 3426 case Mips::BI__builtin_msa_cfcmsa: 3427 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3428 case Mips::BI__builtin_msa_clei_u_b: 3429 case Mips::BI__builtin_msa_clei_u_h: 3430 case Mips::BI__builtin_msa_clei_u_w: 3431 case Mips::BI__builtin_msa_clei_u_d: 3432 case Mips::BI__builtin_msa_clti_u_b: 3433 case Mips::BI__builtin_msa_clti_u_h: 3434 case Mips::BI__builtin_msa_clti_u_w: 3435 case Mips::BI__builtin_msa_clti_u_d: 3436 case Mips::BI__builtin_msa_maxi_u_b: 3437 case Mips::BI__builtin_msa_maxi_u_h: 3438 case Mips::BI__builtin_msa_maxi_u_w: 3439 case Mips::BI__builtin_msa_maxi_u_d: 3440 case Mips::BI__builtin_msa_mini_u_b: 3441 case Mips::BI__builtin_msa_mini_u_h: 3442 case Mips::BI__builtin_msa_mini_u_w: 3443 case Mips::BI__builtin_msa_mini_u_d: 3444 case Mips::BI__builtin_msa_addvi_b: 3445 case Mips::BI__builtin_msa_addvi_h: 3446 case Mips::BI__builtin_msa_addvi_w: 3447 case Mips::BI__builtin_msa_addvi_d: 3448 case Mips::BI__builtin_msa_bclri_w: 3449 case Mips::BI__builtin_msa_bnegi_w: 3450 case Mips::BI__builtin_msa_bseti_w: 3451 case Mips::BI__builtin_msa_sat_s_w: 3452 case Mips::BI__builtin_msa_sat_u_w: 3453 case Mips::BI__builtin_msa_slli_w: 3454 case Mips::BI__builtin_msa_srai_w: 3455 case Mips::BI__builtin_msa_srari_w: 3456 case Mips::BI__builtin_msa_srli_w: 3457 case Mips::BI__builtin_msa_srlri_w: 3458 case Mips::BI__builtin_msa_subvi_b: 3459 case Mips::BI__builtin_msa_subvi_h: 3460 case Mips::BI__builtin_msa_subvi_w: 3461 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3462 case Mips::BI__builtin_msa_binsli_w: 3463 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3464 // These intrinsics take an unsigned 6 bit immediate. 3465 case Mips::BI__builtin_msa_bclri_d: 3466 case Mips::BI__builtin_msa_bnegi_d: 3467 case Mips::BI__builtin_msa_bseti_d: 3468 case Mips::BI__builtin_msa_sat_s_d: 3469 case Mips::BI__builtin_msa_sat_u_d: 3470 case Mips::BI__builtin_msa_slli_d: 3471 case Mips::BI__builtin_msa_srai_d: 3472 case Mips::BI__builtin_msa_srari_d: 3473 case Mips::BI__builtin_msa_srli_d: 3474 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3475 case Mips::BI__builtin_msa_binsli_d: 3476 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3477 // These intrinsics take a signed 5 bit immediate. 3478 case Mips::BI__builtin_msa_ceqi_b: 3479 case Mips::BI__builtin_msa_ceqi_h: 3480 case Mips::BI__builtin_msa_ceqi_w: 3481 case Mips::BI__builtin_msa_ceqi_d: 3482 case Mips::BI__builtin_msa_clti_s_b: 3483 case Mips::BI__builtin_msa_clti_s_h: 3484 case Mips::BI__builtin_msa_clti_s_w: 3485 case Mips::BI__builtin_msa_clti_s_d: 3486 case Mips::BI__builtin_msa_clei_s_b: 3487 case Mips::BI__builtin_msa_clei_s_h: 3488 case Mips::BI__builtin_msa_clei_s_w: 3489 case Mips::BI__builtin_msa_clei_s_d: 3490 case Mips::BI__builtin_msa_maxi_s_b: 3491 case Mips::BI__builtin_msa_maxi_s_h: 3492 case Mips::BI__builtin_msa_maxi_s_w: 3493 case Mips::BI__builtin_msa_maxi_s_d: 3494 case Mips::BI__builtin_msa_mini_s_b: 3495 case Mips::BI__builtin_msa_mini_s_h: 3496 case Mips::BI__builtin_msa_mini_s_w: 3497 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3498 // These intrinsics take an unsigned 8 bit immediate. 3499 case Mips::BI__builtin_msa_andi_b: 3500 case Mips::BI__builtin_msa_nori_b: 3501 case Mips::BI__builtin_msa_ori_b: 3502 case Mips::BI__builtin_msa_shf_b: 3503 case Mips::BI__builtin_msa_shf_h: 3504 case Mips::BI__builtin_msa_shf_w: 3505 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3506 case Mips::BI__builtin_msa_bseli_b: 3507 case Mips::BI__builtin_msa_bmnzi_b: 3508 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3509 // df/n format 3510 // These intrinsics take an unsigned 4 bit immediate. 3511 case Mips::BI__builtin_msa_copy_s_b: 3512 case Mips::BI__builtin_msa_copy_u_b: 3513 case Mips::BI__builtin_msa_insve_b: 3514 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3515 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3516 // These intrinsics take an unsigned 3 bit immediate. 3517 case Mips::BI__builtin_msa_copy_s_h: 3518 case Mips::BI__builtin_msa_copy_u_h: 3519 case Mips::BI__builtin_msa_insve_h: 3520 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3521 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3522 // These intrinsics take an unsigned 2 bit immediate. 3523 case Mips::BI__builtin_msa_copy_s_w: 3524 case Mips::BI__builtin_msa_copy_u_w: 3525 case Mips::BI__builtin_msa_insve_w: 3526 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3527 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3528 // These intrinsics take an unsigned 1 bit immediate. 3529 case Mips::BI__builtin_msa_copy_s_d: 3530 case Mips::BI__builtin_msa_copy_u_d: 3531 case Mips::BI__builtin_msa_insve_d: 3532 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3533 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3534 // Memory offsets and immediate loads. 3535 // These intrinsics take a signed 10 bit immediate. 3536 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3537 case Mips::BI__builtin_msa_ldi_h: 3538 case Mips::BI__builtin_msa_ldi_w: 3539 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3540 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3541 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3542 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3543 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3544 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3545 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3546 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3547 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3548 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3549 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3550 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3551 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3552 } 3553 3554 if (!m) 3555 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3556 3557 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3558 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3559 } 3560 3561 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3562 /// advancing the pointer over the consumed characters. The decoded type is 3563 /// returned. If the decoded type represents a constant integer with a 3564 /// constraint on its value then Mask is set to that value. The type descriptors 3565 /// used in Str are specific to PPC MMA builtins and are documented in the file 3566 /// defining the PPC builtins. 3567 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3568 unsigned &Mask) { 3569 bool RequireICE = false; 3570 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3571 switch (*Str++) { 3572 case 'V': 3573 return Context.getVectorType(Context.UnsignedCharTy, 16, 3574 VectorType::VectorKind::AltiVecVector); 3575 case 'i': { 3576 char *End; 3577 unsigned size = strtoul(Str, &End, 10); 3578 assert(End != Str && "Missing constant parameter constraint"); 3579 Str = End; 3580 Mask = size; 3581 return Context.IntTy; 3582 } 3583 case 'W': { 3584 char *End; 3585 unsigned size = strtoul(Str, &End, 10); 3586 assert(End != Str && "Missing PowerPC MMA type size"); 3587 Str = End; 3588 QualType Type; 3589 switch (size) { 3590 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3591 case size: Type = Context.Id##Ty; break; 3592 #include "clang/Basic/PPCTypes.def" 3593 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3594 } 3595 bool CheckVectorArgs = false; 3596 while (!CheckVectorArgs) { 3597 switch (*Str++) { 3598 case '*': 3599 Type = Context.getPointerType(Type); 3600 break; 3601 case 'C': 3602 Type = Type.withConst(); 3603 break; 3604 default: 3605 CheckVectorArgs = true; 3606 --Str; 3607 break; 3608 } 3609 } 3610 return Type; 3611 } 3612 default: 3613 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3614 } 3615 } 3616 3617 static bool isPPC_64Builtin(unsigned BuiltinID) { 3618 // These builtins only work on PPC 64bit targets. 3619 switch (BuiltinID) { 3620 case PPC::BI__builtin_divde: 3621 case PPC::BI__builtin_divdeu: 3622 case PPC::BI__builtin_bpermd: 3623 case PPC::BI__builtin_pdepd: 3624 case PPC::BI__builtin_pextd: 3625 case PPC::BI__builtin_ppc_ldarx: 3626 case PPC::BI__builtin_ppc_stdcx: 3627 case PPC::BI__builtin_ppc_tdw: 3628 case PPC::BI__builtin_ppc_trapd: 3629 case PPC::BI__builtin_ppc_cmpeqb: 3630 case PPC::BI__builtin_ppc_setb: 3631 case PPC::BI__builtin_ppc_mulhd: 3632 case PPC::BI__builtin_ppc_mulhdu: 3633 case PPC::BI__builtin_ppc_maddhd: 3634 case PPC::BI__builtin_ppc_maddhdu: 3635 case PPC::BI__builtin_ppc_maddld: 3636 case PPC::BI__builtin_ppc_load8r: 3637 case PPC::BI__builtin_ppc_store8r: 3638 case PPC::BI__builtin_ppc_insert_exp: 3639 case PPC::BI__builtin_ppc_extract_sig: 3640 case PPC::BI__builtin_ppc_addex: 3641 case PPC::BI__builtin_darn: 3642 case PPC::BI__builtin_darn_raw: 3643 case PPC::BI__builtin_ppc_compare_and_swaplp: 3644 case PPC::BI__builtin_ppc_fetch_and_addlp: 3645 case PPC::BI__builtin_ppc_fetch_and_andlp: 3646 case PPC::BI__builtin_ppc_fetch_and_orlp: 3647 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3648 return true; 3649 } 3650 return false; 3651 } 3652 3653 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3654 StringRef FeatureToCheck, unsigned DiagID, 3655 StringRef DiagArg = "") { 3656 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3657 return false; 3658 3659 if (DiagArg.empty()) 3660 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3661 else 3662 S.Diag(TheCall->getBeginLoc(), DiagID) 3663 << DiagArg << TheCall->getSourceRange(); 3664 3665 return true; 3666 } 3667 3668 /// Returns true if the argument consists of one contiguous run of 1s with any 3669 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3670 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3671 /// since all 1s are not contiguous. 3672 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3673 llvm::APSInt Result; 3674 // We can't check the value of a dependent argument. 3675 Expr *Arg = TheCall->getArg(ArgNum); 3676 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3677 return false; 3678 3679 // Check constant-ness first. 3680 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3681 return true; 3682 3683 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3684 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3685 return false; 3686 3687 return Diag(TheCall->getBeginLoc(), 3688 diag::err_argument_not_contiguous_bit_field) 3689 << ArgNum << Arg->getSourceRange(); 3690 } 3691 3692 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3693 CallExpr *TheCall) { 3694 unsigned i = 0, l = 0, u = 0; 3695 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3696 llvm::APSInt Result; 3697 3698 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3699 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3700 << TheCall->getSourceRange(); 3701 3702 switch (BuiltinID) { 3703 default: return false; 3704 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3705 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3706 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3707 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3708 case PPC::BI__builtin_altivec_dss: 3709 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3710 case PPC::BI__builtin_tbegin: 3711 case PPC::BI__builtin_tend: 3712 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) || 3713 SemaFeatureCheck(*this, TheCall, "htm", 3714 diag::err_ppc_builtin_requires_htm); 3715 case PPC::BI__builtin_tsr: 3716 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3717 SemaFeatureCheck(*this, TheCall, "htm", 3718 diag::err_ppc_builtin_requires_htm); 3719 case PPC::BI__builtin_tabortwc: 3720 case PPC::BI__builtin_tabortdc: 3721 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3722 SemaFeatureCheck(*this, TheCall, "htm", 3723 diag::err_ppc_builtin_requires_htm); 3724 case PPC::BI__builtin_tabortwci: 3725 case PPC::BI__builtin_tabortdci: 3726 return SemaFeatureCheck(*this, TheCall, "htm", 3727 diag::err_ppc_builtin_requires_htm) || 3728 (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3729 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31)); 3730 case PPC::BI__builtin_tabort: 3731 case PPC::BI__builtin_tcheck: 3732 case PPC::BI__builtin_treclaim: 3733 case PPC::BI__builtin_trechkpt: 3734 case PPC::BI__builtin_tendall: 3735 case PPC::BI__builtin_tresume: 3736 case PPC::BI__builtin_tsuspend: 3737 case PPC::BI__builtin_get_texasr: 3738 case PPC::BI__builtin_get_texasru: 3739 case PPC::BI__builtin_get_tfhar: 3740 case PPC::BI__builtin_get_tfiar: 3741 case PPC::BI__builtin_set_texasr: 3742 case PPC::BI__builtin_set_texasru: 3743 case PPC::BI__builtin_set_tfhar: 3744 case PPC::BI__builtin_set_tfiar: 3745 case PPC::BI__builtin_ttest: 3746 return SemaFeatureCheck(*this, TheCall, "htm", 3747 diag::err_ppc_builtin_requires_htm); 3748 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05', 3749 // __builtin_(un)pack_longdouble are available only if long double uses IBM 3750 // extended double representation. 3751 case PPC::BI__builtin_unpack_longdouble: 3752 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1)) 3753 return true; 3754 LLVM_FALLTHROUGH; 3755 case PPC::BI__builtin_pack_longdouble: 3756 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble()) 3757 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi) 3758 << "ibmlongdouble"; 3759 return false; 3760 case PPC::BI__builtin_altivec_dst: 3761 case PPC::BI__builtin_altivec_dstt: 3762 case PPC::BI__builtin_altivec_dstst: 3763 case PPC::BI__builtin_altivec_dststt: 3764 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3765 case PPC::BI__builtin_vsx_xxpermdi: 3766 case PPC::BI__builtin_vsx_xxsldwi: 3767 return SemaBuiltinVSX(TheCall); 3768 case PPC::BI__builtin_divwe: 3769 case PPC::BI__builtin_divweu: 3770 case PPC::BI__builtin_divde: 3771 case PPC::BI__builtin_divdeu: 3772 return SemaFeatureCheck(*this, TheCall, "extdiv", 3773 diag::err_ppc_builtin_only_on_arch, "7"); 3774 case PPC::BI__builtin_bpermd: 3775 return SemaFeatureCheck(*this, TheCall, "bpermd", 3776 diag::err_ppc_builtin_only_on_arch, "7"); 3777 case PPC::BI__builtin_unpack_vector_int128: 3778 return SemaFeatureCheck(*this, TheCall, "vsx", 3779 diag::err_ppc_builtin_only_on_arch, "7") || 3780 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3781 case PPC::BI__builtin_pack_vector_int128: 3782 return SemaFeatureCheck(*this, TheCall, "vsx", 3783 diag::err_ppc_builtin_only_on_arch, "7"); 3784 case PPC::BI__builtin_pdepd: 3785 case PPC::BI__builtin_pextd: 3786 return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions", 3787 diag::err_ppc_builtin_only_on_arch, "10"); 3788 case PPC::BI__builtin_altivec_vgnb: 3789 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3790 case PPC::BI__builtin_altivec_vec_replace_elt: 3791 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3792 QualType VecTy = TheCall->getArg(0)->getType(); 3793 QualType EltTy = TheCall->getArg(1)->getType(); 3794 unsigned Width = Context.getIntWidth(EltTy); 3795 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3796 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3797 } 3798 case PPC::BI__builtin_vsx_xxeval: 3799 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3800 case PPC::BI__builtin_altivec_vsldbi: 3801 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3802 case PPC::BI__builtin_altivec_vsrdbi: 3803 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3804 case PPC::BI__builtin_vsx_xxpermx: 3805 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3806 case PPC::BI__builtin_ppc_tw: 3807 case PPC::BI__builtin_ppc_tdw: 3808 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3809 case PPC::BI__builtin_ppc_cmpeqb: 3810 case PPC::BI__builtin_ppc_setb: 3811 case PPC::BI__builtin_ppc_maddhd: 3812 case PPC::BI__builtin_ppc_maddhdu: 3813 case PPC::BI__builtin_ppc_maddld: 3814 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3815 diag::err_ppc_builtin_only_on_arch, "9"); 3816 case PPC::BI__builtin_ppc_cmprb: 3817 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3818 diag::err_ppc_builtin_only_on_arch, "9") || 3819 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3820 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3821 // be a constant that represents a contiguous bit field. 3822 case PPC::BI__builtin_ppc_rlwnm: 3823 return SemaValueIsRunOfOnes(TheCall, 2); 3824 case PPC::BI__builtin_ppc_rlwimi: 3825 case PPC::BI__builtin_ppc_rldimi: 3826 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3827 SemaValueIsRunOfOnes(TheCall, 3); 3828 case PPC::BI__builtin_ppc_extract_exp: 3829 case PPC::BI__builtin_ppc_extract_sig: 3830 case PPC::BI__builtin_ppc_insert_exp: 3831 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3832 diag::err_ppc_builtin_only_on_arch, "9"); 3833 case PPC::BI__builtin_ppc_addex: { 3834 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3835 diag::err_ppc_builtin_only_on_arch, "9") || 3836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3837 return true; 3838 // Output warning for reserved values 1 to 3. 3839 int ArgValue = 3840 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3841 if (ArgValue != 0) 3842 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3843 << ArgValue; 3844 return false; 3845 } 3846 case PPC::BI__builtin_ppc_mtfsb0: 3847 case PPC::BI__builtin_ppc_mtfsb1: 3848 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3849 case PPC::BI__builtin_ppc_mtfsf: 3850 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3851 case PPC::BI__builtin_ppc_mtfsfi: 3852 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3853 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3854 case PPC::BI__builtin_ppc_alignx: 3855 return SemaBuiltinConstantArgPower2(TheCall, 0); 3856 case PPC::BI__builtin_ppc_rdlam: 3857 return SemaValueIsRunOfOnes(TheCall, 2); 3858 case PPC::BI__builtin_ppc_icbt: 3859 case PPC::BI__builtin_ppc_sthcx: 3860 case PPC::BI__builtin_ppc_stbcx: 3861 case PPC::BI__builtin_ppc_lharx: 3862 case PPC::BI__builtin_ppc_lbarx: 3863 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3864 diag::err_ppc_builtin_only_on_arch, "8"); 3865 case PPC::BI__builtin_vsx_ldrmb: 3866 case PPC::BI__builtin_vsx_strmb: 3867 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3868 diag::err_ppc_builtin_only_on_arch, "8") || 3869 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3870 case PPC::BI__builtin_altivec_vcntmbb: 3871 case PPC::BI__builtin_altivec_vcntmbh: 3872 case PPC::BI__builtin_altivec_vcntmbw: 3873 case PPC::BI__builtin_altivec_vcntmbd: 3874 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3875 case PPC::BI__builtin_darn: 3876 case PPC::BI__builtin_darn_raw: 3877 case PPC::BI__builtin_darn_32: 3878 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3879 diag::err_ppc_builtin_only_on_arch, "9"); 3880 case PPC::BI__builtin_vsx_xxgenpcvbm: 3881 case PPC::BI__builtin_vsx_xxgenpcvhm: 3882 case PPC::BI__builtin_vsx_xxgenpcvwm: 3883 case PPC::BI__builtin_vsx_xxgenpcvdm: 3884 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3885 case PPC::BI__builtin_ppc_compare_exp_uo: 3886 case PPC::BI__builtin_ppc_compare_exp_lt: 3887 case PPC::BI__builtin_ppc_compare_exp_gt: 3888 case PPC::BI__builtin_ppc_compare_exp_eq: 3889 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3890 diag::err_ppc_builtin_only_on_arch, "9") || 3891 SemaFeatureCheck(*this, TheCall, "vsx", 3892 diag::err_ppc_builtin_requires_vsx); 3893 case PPC::BI__builtin_ppc_test_data_class: { 3894 // Check if the first argument of the __builtin_ppc_test_data_class call is 3895 // valid. The argument must be either a 'float' or a 'double'. 3896 QualType ArgType = TheCall->getArg(0)->getType(); 3897 if (ArgType != QualType(Context.FloatTy) && 3898 ArgType != QualType(Context.DoubleTy)) 3899 return Diag(TheCall->getBeginLoc(), 3900 diag::err_ppc_invalid_test_data_class_type); 3901 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3902 diag::err_ppc_builtin_only_on_arch, "9") || 3903 SemaFeatureCheck(*this, TheCall, "vsx", 3904 diag::err_ppc_builtin_requires_vsx) || 3905 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3906 } 3907 case PPC::BI__builtin_ppc_maxfe: 3908 case PPC::BI__builtin_ppc_minfe: 3909 case PPC::BI__builtin_ppc_maxfl: 3910 case PPC::BI__builtin_ppc_minfl: 3911 case PPC::BI__builtin_ppc_maxfs: 3912 case PPC::BI__builtin_ppc_minfs: { 3913 if (Context.getTargetInfo().getTriple().isOSAIX() && 3914 (BuiltinID == PPC::BI__builtin_ppc_maxfe || 3915 BuiltinID == PPC::BI__builtin_ppc_minfe)) 3916 return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type) 3917 << "builtin" << true << 128 << QualType(Context.LongDoubleTy) 3918 << false << Context.getTargetInfo().getTriple().str(); 3919 // Argument type should be exact. 3920 QualType ArgType = QualType(Context.LongDoubleTy); 3921 if (BuiltinID == PPC::BI__builtin_ppc_maxfl || 3922 BuiltinID == PPC::BI__builtin_ppc_minfl) 3923 ArgType = QualType(Context.DoubleTy); 3924 else if (BuiltinID == PPC::BI__builtin_ppc_maxfs || 3925 BuiltinID == PPC::BI__builtin_ppc_minfs) 3926 ArgType = QualType(Context.FloatTy); 3927 for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I) 3928 if (TheCall->getArg(I)->getType() != ArgType) 3929 return Diag(TheCall->getBeginLoc(), 3930 diag::err_typecheck_convert_incompatible) 3931 << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0; 3932 return false; 3933 } 3934 case PPC::BI__builtin_ppc_load8r: 3935 case PPC::BI__builtin_ppc_store8r: 3936 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3937 diag::err_ppc_builtin_only_on_arch, "7"); 3938 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3939 case PPC::BI__builtin_##Name: \ 3940 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3941 #include "clang/Basic/BuiltinsPPC.def" 3942 } 3943 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3944 } 3945 3946 // Check if the given type is a non-pointer PPC MMA type. This function is used 3947 // in Sema to prevent invalid uses of restricted PPC MMA types. 3948 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3949 if (Type->isPointerType() || Type->isArrayType()) 3950 return false; 3951 3952 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3953 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3954 if (false 3955 #include "clang/Basic/PPCTypes.def" 3956 ) { 3957 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3958 return true; 3959 } 3960 return false; 3961 } 3962 3963 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3964 CallExpr *TheCall) { 3965 // position of memory order and scope arguments in the builtin 3966 unsigned OrderIndex, ScopeIndex; 3967 switch (BuiltinID) { 3968 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3969 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3970 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3971 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3972 OrderIndex = 2; 3973 ScopeIndex = 3; 3974 break; 3975 case AMDGPU::BI__builtin_amdgcn_fence: 3976 OrderIndex = 0; 3977 ScopeIndex = 1; 3978 break; 3979 default: 3980 return false; 3981 } 3982 3983 ExprResult Arg = TheCall->getArg(OrderIndex); 3984 auto ArgExpr = Arg.get(); 3985 Expr::EvalResult ArgResult; 3986 3987 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3988 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3989 << ArgExpr->getType(); 3990 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3991 3992 // Check validity of memory ordering as per C11 / C++11's memody model. 3993 // Only fence needs check. Atomic dec/inc allow all memory orders. 3994 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3995 return Diag(ArgExpr->getBeginLoc(), 3996 diag::warn_atomic_op_has_invalid_memory_order) 3997 << ArgExpr->getSourceRange(); 3998 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3999 case llvm::AtomicOrderingCABI::relaxed: 4000 case llvm::AtomicOrderingCABI::consume: 4001 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 4002 return Diag(ArgExpr->getBeginLoc(), 4003 diag::warn_atomic_op_has_invalid_memory_order) 4004 << ArgExpr->getSourceRange(); 4005 break; 4006 case llvm::AtomicOrderingCABI::acquire: 4007 case llvm::AtomicOrderingCABI::release: 4008 case llvm::AtomicOrderingCABI::acq_rel: 4009 case llvm::AtomicOrderingCABI::seq_cst: 4010 break; 4011 } 4012 4013 Arg = TheCall->getArg(ScopeIndex); 4014 ArgExpr = Arg.get(); 4015 Expr::EvalResult ArgResult1; 4016 // Check that sync scope is a constant literal 4017 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 4018 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 4019 << ArgExpr->getType(); 4020 4021 return false; 4022 } 4023 4024 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 4025 llvm::APSInt Result; 4026 4027 // We can't check the value of a dependent argument. 4028 Expr *Arg = TheCall->getArg(ArgNum); 4029 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4030 return false; 4031 4032 // Check constant-ness first. 4033 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4034 return true; 4035 4036 int64_t Val = Result.getSExtValue(); 4037 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 4038 return false; 4039 4040 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 4041 << Arg->getSourceRange(); 4042 } 4043 4044 static bool isRISCV32Builtin(unsigned BuiltinID) { 4045 // These builtins only work on riscv32 targets. 4046 switch (BuiltinID) { 4047 case RISCV::BI__builtin_riscv_zip_32: 4048 case RISCV::BI__builtin_riscv_unzip_32: 4049 case RISCV::BI__builtin_riscv_aes32dsi_32: 4050 case RISCV::BI__builtin_riscv_aes32dsmi_32: 4051 case RISCV::BI__builtin_riscv_aes32esi_32: 4052 case RISCV::BI__builtin_riscv_aes32esmi_32: 4053 case RISCV::BI__builtin_riscv_sha512sig0h_32: 4054 case RISCV::BI__builtin_riscv_sha512sig0l_32: 4055 case RISCV::BI__builtin_riscv_sha512sig1h_32: 4056 case RISCV::BI__builtin_riscv_sha512sig1l_32: 4057 case RISCV::BI__builtin_riscv_sha512sum0r_32: 4058 case RISCV::BI__builtin_riscv_sha512sum1r_32: 4059 return true; 4060 } 4061 4062 return false; 4063 } 4064 4065 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 4066 unsigned BuiltinID, 4067 CallExpr *TheCall) { 4068 // CodeGenFunction can also detect this, but this gives a better error 4069 // message. 4070 bool FeatureMissing = false; 4071 SmallVector<StringRef> ReqFeatures; 4072 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 4073 Features.split(ReqFeatures, ','); 4074 4075 // Check for 32-bit only builtins on a 64-bit target. 4076 const llvm::Triple &TT = TI.getTriple(); 4077 if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID)) 4078 return Diag(TheCall->getCallee()->getBeginLoc(), 4079 diag::err_32_bit_builtin_64_bit_tgt); 4080 4081 // Check if each required feature is included 4082 for (StringRef F : ReqFeatures) { 4083 SmallVector<StringRef> ReqOpFeatures; 4084 F.split(ReqOpFeatures, '|'); 4085 bool HasFeature = false; 4086 for (StringRef OF : ReqOpFeatures) { 4087 if (TI.hasFeature(OF)) { 4088 HasFeature = true; 4089 continue; 4090 } 4091 } 4092 4093 if (!HasFeature) { 4094 std::string FeatureStrs; 4095 for (StringRef OF : ReqOpFeatures) { 4096 // If the feature is 64bit, alter the string so it will print better in 4097 // the diagnostic. 4098 if (OF == "64bit") 4099 OF = "RV64"; 4100 4101 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 4102 OF.consume_front("experimental-"); 4103 std::string FeatureStr = OF.str(); 4104 FeatureStr[0] = std::toupper(FeatureStr[0]); 4105 // Combine strings. 4106 FeatureStrs += FeatureStrs == "" ? "" : ", "; 4107 FeatureStrs += "'"; 4108 FeatureStrs += FeatureStr; 4109 FeatureStrs += "'"; 4110 } 4111 // Error message 4112 FeatureMissing = true; 4113 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 4114 << TheCall->getSourceRange() << StringRef(FeatureStrs); 4115 } 4116 } 4117 4118 if (FeatureMissing) 4119 return true; 4120 4121 switch (BuiltinID) { 4122 case RISCVVector::BI__builtin_rvv_vsetvli: 4123 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 4124 CheckRISCVLMUL(TheCall, 2); 4125 case RISCVVector::BI__builtin_rvv_vsetvlimax: 4126 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 4127 CheckRISCVLMUL(TheCall, 1); 4128 case RISCVVector::BI__builtin_rvv_vget_v: { 4129 ASTContext::BuiltinVectorTypeInfo ResVecInfo = 4130 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4131 TheCall->getType().getCanonicalType().getTypePtr())); 4132 ASTContext::BuiltinVectorTypeInfo VecInfo = 4133 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4134 TheCall->getArg(0)->getType().getCanonicalType().getTypePtr())); 4135 unsigned MaxIndex = 4136 (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) / 4137 (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors); 4138 return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1); 4139 } 4140 case RISCVVector::BI__builtin_rvv_vset_v: { 4141 ASTContext::BuiltinVectorTypeInfo ResVecInfo = 4142 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4143 TheCall->getType().getCanonicalType().getTypePtr())); 4144 ASTContext::BuiltinVectorTypeInfo VecInfo = 4145 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4146 TheCall->getArg(2)->getType().getCanonicalType().getTypePtr())); 4147 unsigned MaxIndex = 4148 (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) / 4149 (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors); 4150 return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1); 4151 } 4152 // Check if byteselect is in [0, 3] 4153 case RISCV::BI__builtin_riscv_aes32dsi_32: 4154 case RISCV::BI__builtin_riscv_aes32dsmi_32: 4155 case RISCV::BI__builtin_riscv_aes32esi_32: 4156 case RISCV::BI__builtin_riscv_aes32esmi_32: 4157 case RISCV::BI__builtin_riscv_sm4ks: 4158 case RISCV::BI__builtin_riscv_sm4ed: 4159 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 4160 // Check if rnum is in [0, 10] 4161 case RISCV::BI__builtin_riscv_aes64ks1i_64: 4162 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10); 4163 } 4164 4165 return false; 4166 } 4167 4168 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 4169 CallExpr *TheCall) { 4170 if (BuiltinID == SystemZ::BI__builtin_tabort) { 4171 Expr *Arg = TheCall->getArg(0); 4172 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 4173 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 4174 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 4175 << Arg->getSourceRange(); 4176 } 4177 4178 // For intrinsics which take an immediate value as part of the instruction, 4179 // range check them here. 4180 unsigned i = 0, l = 0, u = 0; 4181 switch (BuiltinID) { 4182 default: return false; 4183 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 4184 case SystemZ::BI__builtin_s390_verimb: 4185 case SystemZ::BI__builtin_s390_verimh: 4186 case SystemZ::BI__builtin_s390_verimf: 4187 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 4188 case SystemZ::BI__builtin_s390_vfaeb: 4189 case SystemZ::BI__builtin_s390_vfaeh: 4190 case SystemZ::BI__builtin_s390_vfaef: 4191 case SystemZ::BI__builtin_s390_vfaebs: 4192 case SystemZ::BI__builtin_s390_vfaehs: 4193 case SystemZ::BI__builtin_s390_vfaefs: 4194 case SystemZ::BI__builtin_s390_vfaezb: 4195 case SystemZ::BI__builtin_s390_vfaezh: 4196 case SystemZ::BI__builtin_s390_vfaezf: 4197 case SystemZ::BI__builtin_s390_vfaezbs: 4198 case SystemZ::BI__builtin_s390_vfaezhs: 4199 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 4200 case SystemZ::BI__builtin_s390_vfisb: 4201 case SystemZ::BI__builtin_s390_vfidb: 4202 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 4203 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 4204 case SystemZ::BI__builtin_s390_vftcisb: 4205 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 4206 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 4207 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 4208 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 4209 case SystemZ::BI__builtin_s390_vstrcb: 4210 case SystemZ::BI__builtin_s390_vstrch: 4211 case SystemZ::BI__builtin_s390_vstrcf: 4212 case SystemZ::BI__builtin_s390_vstrczb: 4213 case SystemZ::BI__builtin_s390_vstrczh: 4214 case SystemZ::BI__builtin_s390_vstrczf: 4215 case SystemZ::BI__builtin_s390_vstrcbs: 4216 case SystemZ::BI__builtin_s390_vstrchs: 4217 case SystemZ::BI__builtin_s390_vstrcfs: 4218 case SystemZ::BI__builtin_s390_vstrczbs: 4219 case SystemZ::BI__builtin_s390_vstrczhs: 4220 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 4221 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 4222 case SystemZ::BI__builtin_s390_vfminsb: 4223 case SystemZ::BI__builtin_s390_vfmaxsb: 4224 case SystemZ::BI__builtin_s390_vfmindb: 4225 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 4226 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 4227 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 4228 case SystemZ::BI__builtin_s390_vclfnhs: 4229 case SystemZ::BI__builtin_s390_vclfnls: 4230 case SystemZ::BI__builtin_s390_vcfn: 4231 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 4232 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 4233 } 4234 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 4235 } 4236 4237 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 4238 /// This checks that the target supports __builtin_cpu_supports and 4239 /// that the string argument is constant and valid. 4240 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 4241 CallExpr *TheCall) { 4242 Expr *Arg = TheCall->getArg(0); 4243 4244 // Check if the argument is a string literal. 4245 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4246 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4247 << Arg->getSourceRange(); 4248 4249 // Check the contents of the string. 4250 StringRef Feature = 4251 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4252 if (!TI.validateCpuSupports(Feature)) 4253 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 4254 << Arg->getSourceRange(); 4255 return false; 4256 } 4257 4258 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 4259 /// This checks that the target supports __builtin_cpu_is and 4260 /// that the string argument is constant and valid. 4261 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 4262 Expr *Arg = TheCall->getArg(0); 4263 4264 // Check if the argument is a string literal. 4265 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4266 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4267 << Arg->getSourceRange(); 4268 4269 // Check the contents of the string. 4270 StringRef Feature = 4271 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4272 if (!TI.validateCpuIs(Feature)) 4273 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 4274 << Arg->getSourceRange(); 4275 return false; 4276 } 4277 4278 // Check if the rounding mode is legal. 4279 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 4280 // Indicates if this instruction has rounding control or just SAE. 4281 bool HasRC = false; 4282 4283 unsigned ArgNum = 0; 4284 switch (BuiltinID) { 4285 default: 4286 return false; 4287 case X86::BI__builtin_ia32_vcvttsd2si32: 4288 case X86::BI__builtin_ia32_vcvttsd2si64: 4289 case X86::BI__builtin_ia32_vcvttsd2usi32: 4290 case X86::BI__builtin_ia32_vcvttsd2usi64: 4291 case X86::BI__builtin_ia32_vcvttss2si32: 4292 case X86::BI__builtin_ia32_vcvttss2si64: 4293 case X86::BI__builtin_ia32_vcvttss2usi32: 4294 case X86::BI__builtin_ia32_vcvttss2usi64: 4295 case X86::BI__builtin_ia32_vcvttsh2si32: 4296 case X86::BI__builtin_ia32_vcvttsh2si64: 4297 case X86::BI__builtin_ia32_vcvttsh2usi32: 4298 case X86::BI__builtin_ia32_vcvttsh2usi64: 4299 ArgNum = 1; 4300 break; 4301 case X86::BI__builtin_ia32_maxpd512: 4302 case X86::BI__builtin_ia32_maxps512: 4303 case X86::BI__builtin_ia32_minpd512: 4304 case X86::BI__builtin_ia32_minps512: 4305 case X86::BI__builtin_ia32_maxph512: 4306 case X86::BI__builtin_ia32_minph512: 4307 ArgNum = 2; 4308 break; 4309 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 4310 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 4311 case X86::BI__builtin_ia32_cvtps2pd512_mask: 4312 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 4313 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 4314 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 4315 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 4316 case X86::BI__builtin_ia32_cvttps2dq512_mask: 4317 case X86::BI__builtin_ia32_cvttps2qq512_mask: 4318 case X86::BI__builtin_ia32_cvttps2udq512_mask: 4319 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 4320 case X86::BI__builtin_ia32_vcvttph2w512_mask: 4321 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 4322 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 4323 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 4324 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 4325 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 4326 case X86::BI__builtin_ia32_exp2pd_mask: 4327 case X86::BI__builtin_ia32_exp2ps_mask: 4328 case X86::BI__builtin_ia32_getexppd512_mask: 4329 case X86::BI__builtin_ia32_getexpps512_mask: 4330 case X86::BI__builtin_ia32_getexpph512_mask: 4331 case X86::BI__builtin_ia32_rcp28pd_mask: 4332 case X86::BI__builtin_ia32_rcp28ps_mask: 4333 case X86::BI__builtin_ia32_rsqrt28pd_mask: 4334 case X86::BI__builtin_ia32_rsqrt28ps_mask: 4335 case X86::BI__builtin_ia32_vcomisd: 4336 case X86::BI__builtin_ia32_vcomiss: 4337 case X86::BI__builtin_ia32_vcomish: 4338 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 4339 ArgNum = 3; 4340 break; 4341 case X86::BI__builtin_ia32_cmppd512_mask: 4342 case X86::BI__builtin_ia32_cmpps512_mask: 4343 case X86::BI__builtin_ia32_cmpsd_mask: 4344 case X86::BI__builtin_ia32_cmpss_mask: 4345 case X86::BI__builtin_ia32_cmpsh_mask: 4346 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 4347 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 4348 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 4349 case X86::BI__builtin_ia32_getexpsd128_round_mask: 4350 case X86::BI__builtin_ia32_getexpss128_round_mask: 4351 case X86::BI__builtin_ia32_getexpsh128_round_mask: 4352 case X86::BI__builtin_ia32_getmantpd512_mask: 4353 case X86::BI__builtin_ia32_getmantps512_mask: 4354 case X86::BI__builtin_ia32_getmantph512_mask: 4355 case X86::BI__builtin_ia32_maxsd_round_mask: 4356 case X86::BI__builtin_ia32_maxss_round_mask: 4357 case X86::BI__builtin_ia32_maxsh_round_mask: 4358 case X86::BI__builtin_ia32_minsd_round_mask: 4359 case X86::BI__builtin_ia32_minss_round_mask: 4360 case X86::BI__builtin_ia32_minsh_round_mask: 4361 case X86::BI__builtin_ia32_rcp28sd_round_mask: 4362 case X86::BI__builtin_ia32_rcp28ss_round_mask: 4363 case X86::BI__builtin_ia32_reducepd512_mask: 4364 case X86::BI__builtin_ia32_reduceps512_mask: 4365 case X86::BI__builtin_ia32_reduceph512_mask: 4366 case X86::BI__builtin_ia32_rndscalepd_mask: 4367 case X86::BI__builtin_ia32_rndscaleps_mask: 4368 case X86::BI__builtin_ia32_rndscaleph_mask: 4369 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4370 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4371 ArgNum = 4; 4372 break; 4373 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4374 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4375 case X86::BI__builtin_ia32_fixupimmps512_mask: 4376 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4377 case X86::BI__builtin_ia32_fixupimmsd_mask: 4378 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4379 case X86::BI__builtin_ia32_fixupimmss_mask: 4380 case X86::BI__builtin_ia32_fixupimmss_maskz: 4381 case X86::BI__builtin_ia32_getmantsd_round_mask: 4382 case X86::BI__builtin_ia32_getmantss_round_mask: 4383 case X86::BI__builtin_ia32_getmantsh_round_mask: 4384 case X86::BI__builtin_ia32_rangepd512_mask: 4385 case X86::BI__builtin_ia32_rangeps512_mask: 4386 case X86::BI__builtin_ia32_rangesd128_round_mask: 4387 case X86::BI__builtin_ia32_rangess128_round_mask: 4388 case X86::BI__builtin_ia32_reducesd_mask: 4389 case X86::BI__builtin_ia32_reducess_mask: 4390 case X86::BI__builtin_ia32_reducesh_mask: 4391 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4392 case X86::BI__builtin_ia32_rndscaless_round_mask: 4393 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4394 ArgNum = 5; 4395 break; 4396 case X86::BI__builtin_ia32_vcvtsd2si64: 4397 case X86::BI__builtin_ia32_vcvtsd2si32: 4398 case X86::BI__builtin_ia32_vcvtsd2usi32: 4399 case X86::BI__builtin_ia32_vcvtsd2usi64: 4400 case X86::BI__builtin_ia32_vcvtss2si32: 4401 case X86::BI__builtin_ia32_vcvtss2si64: 4402 case X86::BI__builtin_ia32_vcvtss2usi32: 4403 case X86::BI__builtin_ia32_vcvtss2usi64: 4404 case X86::BI__builtin_ia32_vcvtsh2si32: 4405 case X86::BI__builtin_ia32_vcvtsh2si64: 4406 case X86::BI__builtin_ia32_vcvtsh2usi32: 4407 case X86::BI__builtin_ia32_vcvtsh2usi64: 4408 case X86::BI__builtin_ia32_sqrtpd512: 4409 case X86::BI__builtin_ia32_sqrtps512: 4410 case X86::BI__builtin_ia32_sqrtph512: 4411 ArgNum = 1; 4412 HasRC = true; 4413 break; 4414 case X86::BI__builtin_ia32_addph512: 4415 case X86::BI__builtin_ia32_divph512: 4416 case X86::BI__builtin_ia32_mulph512: 4417 case X86::BI__builtin_ia32_subph512: 4418 case X86::BI__builtin_ia32_addpd512: 4419 case X86::BI__builtin_ia32_addps512: 4420 case X86::BI__builtin_ia32_divpd512: 4421 case X86::BI__builtin_ia32_divps512: 4422 case X86::BI__builtin_ia32_mulpd512: 4423 case X86::BI__builtin_ia32_mulps512: 4424 case X86::BI__builtin_ia32_subpd512: 4425 case X86::BI__builtin_ia32_subps512: 4426 case X86::BI__builtin_ia32_cvtsi2sd64: 4427 case X86::BI__builtin_ia32_cvtsi2ss32: 4428 case X86::BI__builtin_ia32_cvtsi2ss64: 4429 case X86::BI__builtin_ia32_cvtusi2sd64: 4430 case X86::BI__builtin_ia32_cvtusi2ss32: 4431 case X86::BI__builtin_ia32_cvtusi2ss64: 4432 case X86::BI__builtin_ia32_vcvtusi2sh: 4433 case X86::BI__builtin_ia32_vcvtusi642sh: 4434 case X86::BI__builtin_ia32_vcvtsi2sh: 4435 case X86::BI__builtin_ia32_vcvtsi642sh: 4436 ArgNum = 2; 4437 HasRC = true; 4438 break; 4439 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4440 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4441 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4442 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4443 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4444 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4445 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4446 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4447 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4448 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4449 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4450 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4451 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4452 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4453 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4454 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4455 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4456 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4457 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4458 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4459 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4460 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4461 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4462 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4463 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4464 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4465 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4466 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4467 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4468 ArgNum = 3; 4469 HasRC = true; 4470 break; 4471 case X86::BI__builtin_ia32_addsh_round_mask: 4472 case X86::BI__builtin_ia32_addss_round_mask: 4473 case X86::BI__builtin_ia32_addsd_round_mask: 4474 case X86::BI__builtin_ia32_divsh_round_mask: 4475 case X86::BI__builtin_ia32_divss_round_mask: 4476 case X86::BI__builtin_ia32_divsd_round_mask: 4477 case X86::BI__builtin_ia32_mulsh_round_mask: 4478 case X86::BI__builtin_ia32_mulss_round_mask: 4479 case X86::BI__builtin_ia32_mulsd_round_mask: 4480 case X86::BI__builtin_ia32_subsh_round_mask: 4481 case X86::BI__builtin_ia32_subss_round_mask: 4482 case X86::BI__builtin_ia32_subsd_round_mask: 4483 case X86::BI__builtin_ia32_scalefph512_mask: 4484 case X86::BI__builtin_ia32_scalefpd512_mask: 4485 case X86::BI__builtin_ia32_scalefps512_mask: 4486 case X86::BI__builtin_ia32_scalefsd_round_mask: 4487 case X86::BI__builtin_ia32_scalefss_round_mask: 4488 case X86::BI__builtin_ia32_scalefsh_round_mask: 4489 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4490 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4491 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4492 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4493 case X86::BI__builtin_ia32_sqrtss_round_mask: 4494 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4495 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4496 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4497 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4498 case X86::BI__builtin_ia32_vfmaddss3_mask: 4499 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4500 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4501 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4502 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4503 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4504 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4505 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4506 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4507 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4508 case X86::BI__builtin_ia32_vfmaddps512_mask: 4509 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4510 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4511 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4512 case X86::BI__builtin_ia32_vfmaddph512_mask: 4513 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4514 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4515 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4516 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4517 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4518 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4519 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4520 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4521 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4522 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4523 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4524 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4525 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4526 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4527 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4528 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4529 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4530 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4531 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4532 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4533 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4534 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4535 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4536 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4537 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4538 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4539 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4540 case X86::BI__builtin_ia32_vfmulcsh_mask: 4541 case X86::BI__builtin_ia32_vfmulcph512_mask: 4542 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4543 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4544 ArgNum = 4; 4545 HasRC = true; 4546 break; 4547 } 4548 4549 llvm::APSInt Result; 4550 4551 // We can't check the value of a dependent argument. 4552 Expr *Arg = TheCall->getArg(ArgNum); 4553 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4554 return false; 4555 4556 // Check constant-ness first. 4557 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4558 return true; 4559 4560 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4561 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4562 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4563 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4564 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4565 Result == 8/*ROUND_NO_EXC*/ || 4566 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4567 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4568 return false; 4569 4570 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4571 << Arg->getSourceRange(); 4572 } 4573 4574 // Check if the gather/scatter scale is legal. 4575 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4576 CallExpr *TheCall) { 4577 unsigned ArgNum = 0; 4578 switch (BuiltinID) { 4579 default: 4580 return false; 4581 case X86::BI__builtin_ia32_gatherpfdpd: 4582 case X86::BI__builtin_ia32_gatherpfdps: 4583 case X86::BI__builtin_ia32_gatherpfqpd: 4584 case X86::BI__builtin_ia32_gatherpfqps: 4585 case X86::BI__builtin_ia32_scatterpfdpd: 4586 case X86::BI__builtin_ia32_scatterpfdps: 4587 case X86::BI__builtin_ia32_scatterpfqpd: 4588 case X86::BI__builtin_ia32_scatterpfqps: 4589 ArgNum = 3; 4590 break; 4591 case X86::BI__builtin_ia32_gatherd_pd: 4592 case X86::BI__builtin_ia32_gatherd_pd256: 4593 case X86::BI__builtin_ia32_gatherq_pd: 4594 case X86::BI__builtin_ia32_gatherq_pd256: 4595 case X86::BI__builtin_ia32_gatherd_ps: 4596 case X86::BI__builtin_ia32_gatherd_ps256: 4597 case X86::BI__builtin_ia32_gatherq_ps: 4598 case X86::BI__builtin_ia32_gatherq_ps256: 4599 case X86::BI__builtin_ia32_gatherd_q: 4600 case X86::BI__builtin_ia32_gatherd_q256: 4601 case X86::BI__builtin_ia32_gatherq_q: 4602 case X86::BI__builtin_ia32_gatherq_q256: 4603 case X86::BI__builtin_ia32_gatherd_d: 4604 case X86::BI__builtin_ia32_gatherd_d256: 4605 case X86::BI__builtin_ia32_gatherq_d: 4606 case X86::BI__builtin_ia32_gatherq_d256: 4607 case X86::BI__builtin_ia32_gather3div2df: 4608 case X86::BI__builtin_ia32_gather3div2di: 4609 case X86::BI__builtin_ia32_gather3div4df: 4610 case X86::BI__builtin_ia32_gather3div4di: 4611 case X86::BI__builtin_ia32_gather3div4sf: 4612 case X86::BI__builtin_ia32_gather3div4si: 4613 case X86::BI__builtin_ia32_gather3div8sf: 4614 case X86::BI__builtin_ia32_gather3div8si: 4615 case X86::BI__builtin_ia32_gather3siv2df: 4616 case X86::BI__builtin_ia32_gather3siv2di: 4617 case X86::BI__builtin_ia32_gather3siv4df: 4618 case X86::BI__builtin_ia32_gather3siv4di: 4619 case X86::BI__builtin_ia32_gather3siv4sf: 4620 case X86::BI__builtin_ia32_gather3siv4si: 4621 case X86::BI__builtin_ia32_gather3siv8sf: 4622 case X86::BI__builtin_ia32_gather3siv8si: 4623 case X86::BI__builtin_ia32_gathersiv8df: 4624 case X86::BI__builtin_ia32_gathersiv16sf: 4625 case X86::BI__builtin_ia32_gatherdiv8df: 4626 case X86::BI__builtin_ia32_gatherdiv16sf: 4627 case X86::BI__builtin_ia32_gathersiv8di: 4628 case X86::BI__builtin_ia32_gathersiv16si: 4629 case X86::BI__builtin_ia32_gatherdiv8di: 4630 case X86::BI__builtin_ia32_gatherdiv16si: 4631 case X86::BI__builtin_ia32_scatterdiv2df: 4632 case X86::BI__builtin_ia32_scatterdiv2di: 4633 case X86::BI__builtin_ia32_scatterdiv4df: 4634 case X86::BI__builtin_ia32_scatterdiv4di: 4635 case X86::BI__builtin_ia32_scatterdiv4sf: 4636 case X86::BI__builtin_ia32_scatterdiv4si: 4637 case X86::BI__builtin_ia32_scatterdiv8sf: 4638 case X86::BI__builtin_ia32_scatterdiv8si: 4639 case X86::BI__builtin_ia32_scattersiv2df: 4640 case X86::BI__builtin_ia32_scattersiv2di: 4641 case X86::BI__builtin_ia32_scattersiv4df: 4642 case X86::BI__builtin_ia32_scattersiv4di: 4643 case X86::BI__builtin_ia32_scattersiv4sf: 4644 case X86::BI__builtin_ia32_scattersiv4si: 4645 case X86::BI__builtin_ia32_scattersiv8sf: 4646 case X86::BI__builtin_ia32_scattersiv8si: 4647 case X86::BI__builtin_ia32_scattersiv8df: 4648 case X86::BI__builtin_ia32_scattersiv16sf: 4649 case X86::BI__builtin_ia32_scatterdiv8df: 4650 case X86::BI__builtin_ia32_scatterdiv16sf: 4651 case X86::BI__builtin_ia32_scattersiv8di: 4652 case X86::BI__builtin_ia32_scattersiv16si: 4653 case X86::BI__builtin_ia32_scatterdiv8di: 4654 case X86::BI__builtin_ia32_scatterdiv16si: 4655 ArgNum = 4; 4656 break; 4657 } 4658 4659 llvm::APSInt Result; 4660 4661 // We can't check the value of a dependent argument. 4662 Expr *Arg = TheCall->getArg(ArgNum); 4663 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4664 return false; 4665 4666 // Check constant-ness first. 4667 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4668 return true; 4669 4670 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4671 return false; 4672 4673 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4674 << Arg->getSourceRange(); 4675 } 4676 4677 enum { TileRegLow = 0, TileRegHigh = 7 }; 4678 4679 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4680 ArrayRef<int> ArgNums) { 4681 for (int ArgNum : ArgNums) { 4682 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4683 return true; 4684 } 4685 return false; 4686 } 4687 4688 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4689 ArrayRef<int> ArgNums) { 4690 // Because the max number of tile register is TileRegHigh + 1, so here we use 4691 // each bit to represent the usage of them in bitset. 4692 std::bitset<TileRegHigh + 1> ArgValues; 4693 for (int ArgNum : ArgNums) { 4694 Expr *Arg = TheCall->getArg(ArgNum); 4695 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4696 continue; 4697 4698 llvm::APSInt Result; 4699 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4700 return true; 4701 int ArgExtValue = Result.getExtValue(); 4702 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4703 "Incorrect tile register num."); 4704 if (ArgValues.test(ArgExtValue)) 4705 return Diag(TheCall->getBeginLoc(), 4706 diag::err_x86_builtin_tile_arg_duplicate) 4707 << TheCall->getArg(ArgNum)->getSourceRange(); 4708 ArgValues.set(ArgExtValue); 4709 } 4710 return false; 4711 } 4712 4713 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4714 ArrayRef<int> ArgNums) { 4715 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4716 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4717 } 4718 4719 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4720 switch (BuiltinID) { 4721 default: 4722 return false; 4723 case X86::BI__builtin_ia32_tileloadd64: 4724 case X86::BI__builtin_ia32_tileloaddt164: 4725 case X86::BI__builtin_ia32_tilestored64: 4726 case X86::BI__builtin_ia32_tilezero: 4727 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4728 case X86::BI__builtin_ia32_tdpbssd: 4729 case X86::BI__builtin_ia32_tdpbsud: 4730 case X86::BI__builtin_ia32_tdpbusd: 4731 case X86::BI__builtin_ia32_tdpbuud: 4732 case X86::BI__builtin_ia32_tdpbf16ps: 4733 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4734 } 4735 } 4736 static bool isX86_32Builtin(unsigned BuiltinID) { 4737 // These builtins only work on x86-32 targets. 4738 switch (BuiltinID) { 4739 case X86::BI__builtin_ia32_readeflags_u32: 4740 case X86::BI__builtin_ia32_writeeflags_u32: 4741 return true; 4742 } 4743 4744 return false; 4745 } 4746 4747 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4748 CallExpr *TheCall) { 4749 if (BuiltinID == X86::BI__builtin_cpu_supports) 4750 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4751 4752 if (BuiltinID == X86::BI__builtin_cpu_is) 4753 return SemaBuiltinCpuIs(*this, TI, TheCall); 4754 4755 // Check for 32-bit only builtins on a 64-bit target. 4756 const llvm::Triple &TT = TI.getTriple(); 4757 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4758 return Diag(TheCall->getCallee()->getBeginLoc(), 4759 diag::err_32_bit_builtin_64_bit_tgt); 4760 4761 // If the intrinsic has rounding or SAE make sure its valid. 4762 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4763 return true; 4764 4765 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4766 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4767 return true; 4768 4769 // If the intrinsic has a tile arguments, make sure they are valid. 4770 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4771 return true; 4772 4773 // For intrinsics which take an immediate value as part of the instruction, 4774 // range check them here. 4775 int i = 0, l = 0, u = 0; 4776 switch (BuiltinID) { 4777 default: 4778 return false; 4779 case X86::BI__builtin_ia32_vec_ext_v2si: 4780 case X86::BI__builtin_ia32_vec_ext_v2di: 4781 case X86::BI__builtin_ia32_vextractf128_pd256: 4782 case X86::BI__builtin_ia32_vextractf128_ps256: 4783 case X86::BI__builtin_ia32_vextractf128_si256: 4784 case X86::BI__builtin_ia32_extract128i256: 4785 case X86::BI__builtin_ia32_extractf64x4_mask: 4786 case X86::BI__builtin_ia32_extracti64x4_mask: 4787 case X86::BI__builtin_ia32_extractf32x8_mask: 4788 case X86::BI__builtin_ia32_extracti32x8_mask: 4789 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4790 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4791 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4792 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4793 i = 1; l = 0; u = 1; 4794 break; 4795 case X86::BI__builtin_ia32_vec_set_v2di: 4796 case X86::BI__builtin_ia32_vinsertf128_pd256: 4797 case X86::BI__builtin_ia32_vinsertf128_ps256: 4798 case X86::BI__builtin_ia32_vinsertf128_si256: 4799 case X86::BI__builtin_ia32_insert128i256: 4800 case X86::BI__builtin_ia32_insertf32x8: 4801 case X86::BI__builtin_ia32_inserti32x8: 4802 case X86::BI__builtin_ia32_insertf64x4: 4803 case X86::BI__builtin_ia32_inserti64x4: 4804 case X86::BI__builtin_ia32_insertf64x2_256: 4805 case X86::BI__builtin_ia32_inserti64x2_256: 4806 case X86::BI__builtin_ia32_insertf32x4_256: 4807 case X86::BI__builtin_ia32_inserti32x4_256: 4808 i = 2; l = 0; u = 1; 4809 break; 4810 case X86::BI__builtin_ia32_vpermilpd: 4811 case X86::BI__builtin_ia32_vec_ext_v4hi: 4812 case X86::BI__builtin_ia32_vec_ext_v4si: 4813 case X86::BI__builtin_ia32_vec_ext_v4sf: 4814 case X86::BI__builtin_ia32_vec_ext_v4di: 4815 case X86::BI__builtin_ia32_extractf32x4_mask: 4816 case X86::BI__builtin_ia32_extracti32x4_mask: 4817 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4818 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4819 i = 1; l = 0; u = 3; 4820 break; 4821 case X86::BI_mm_prefetch: 4822 case X86::BI__builtin_ia32_vec_ext_v8hi: 4823 case X86::BI__builtin_ia32_vec_ext_v8si: 4824 i = 1; l = 0; u = 7; 4825 break; 4826 case X86::BI__builtin_ia32_sha1rnds4: 4827 case X86::BI__builtin_ia32_blendpd: 4828 case X86::BI__builtin_ia32_shufpd: 4829 case X86::BI__builtin_ia32_vec_set_v4hi: 4830 case X86::BI__builtin_ia32_vec_set_v4si: 4831 case X86::BI__builtin_ia32_vec_set_v4di: 4832 case X86::BI__builtin_ia32_shuf_f32x4_256: 4833 case X86::BI__builtin_ia32_shuf_f64x2_256: 4834 case X86::BI__builtin_ia32_shuf_i32x4_256: 4835 case X86::BI__builtin_ia32_shuf_i64x2_256: 4836 case X86::BI__builtin_ia32_insertf64x2_512: 4837 case X86::BI__builtin_ia32_inserti64x2_512: 4838 case X86::BI__builtin_ia32_insertf32x4: 4839 case X86::BI__builtin_ia32_inserti32x4: 4840 i = 2; l = 0; u = 3; 4841 break; 4842 case X86::BI__builtin_ia32_vpermil2pd: 4843 case X86::BI__builtin_ia32_vpermil2pd256: 4844 case X86::BI__builtin_ia32_vpermil2ps: 4845 case X86::BI__builtin_ia32_vpermil2ps256: 4846 i = 3; l = 0; u = 3; 4847 break; 4848 case X86::BI__builtin_ia32_cmpb128_mask: 4849 case X86::BI__builtin_ia32_cmpw128_mask: 4850 case X86::BI__builtin_ia32_cmpd128_mask: 4851 case X86::BI__builtin_ia32_cmpq128_mask: 4852 case X86::BI__builtin_ia32_cmpb256_mask: 4853 case X86::BI__builtin_ia32_cmpw256_mask: 4854 case X86::BI__builtin_ia32_cmpd256_mask: 4855 case X86::BI__builtin_ia32_cmpq256_mask: 4856 case X86::BI__builtin_ia32_cmpb512_mask: 4857 case X86::BI__builtin_ia32_cmpw512_mask: 4858 case X86::BI__builtin_ia32_cmpd512_mask: 4859 case X86::BI__builtin_ia32_cmpq512_mask: 4860 case X86::BI__builtin_ia32_ucmpb128_mask: 4861 case X86::BI__builtin_ia32_ucmpw128_mask: 4862 case X86::BI__builtin_ia32_ucmpd128_mask: 4863 case X86::BI__builtin_ia32_ucmpq128_mask: 4864 case X86::BI__builtin_ia32_ucmpb256_mask: 4865 case X86::BI__builtin_ia32_ucmpw256_mask: 4866 case X86::BI__builtin_ia32_ucmpd256_mask: 4867 case X86::BI__builtin_ia32_ucmpq256_mask: 4868 case X86::BI__builtin_ia32_ucmpb512_mask: 4869 case X86::BI__builtin_ia32_ucmpw512_mask: 4870 case X86::BI__builtin_ia32_ucmpd512_mask: 4871 case X86::BI__builtin_ia32_ucmpq512_mask: 4872 case X86::BI__builtin_ia32_vpcomub: 4873 case X86::BI__builtin_ia32_vpcomuw: 4874 case X86::BI__builtin_ia32_vpcomud: 4875 case X86::BI__builtin_ia32_vpcomuq: 4876 case X86::BI__builtin_ia32_vpcomb: 4877 case X86::BI__builtin_ia32_vpcomw: 4878 case X86::BI__builtin_ia32_vpcomd: 4879 case X86::BI__builtin_ia32_vpcomq: 4880 case X86::BI__builtin_ia32_vec_set_v8hi: 4881 case X86::BI__builtin_ia32_vec_set_v8si: 4882 i = 2; l = 0; u = 7; 4883 break; 4884 case X86::BI__builtin_ia32_vpermilpd256: 4885 case X86::BI__builtin_ia32_roundps: 4886 case X86::BI__builtin_ia32_roundpd: 4887 case X86::BI__builtin_ia32_roundps256: 4888 case X86::BI__builtin_ia32_roundpd256: 4889 case X86::BI__builtin_ia32_getmantpd128_mask: 4890 case X86::BI__builtin_ia32_getmantpd256_mask: 4891 case X86::BI__builtin_ia32_getmantps128_mask: 4892 case X86::BI__builtin_ia32_getmantps256_mask: 4893 case X86::BI__builtin_ia32_getmantpd512_mask: 4894 case X86::BI__builtin_ia32_getmantps512_mask: 4895 case X86::BI__builtin_ia32_getmantph128_mask: 4896 case X86::BI__builtin_ia32_getmantph256_mask: 4897 case X86::BI__builtin_ia32_getmantph512_mask: 4898 case X86::BI__builtin_ia32_vec_ext_v16qi: 4899 case X86::BI__builtin_ia32_vec_ext_v16hi: 4900 i = 1; l = 0; u = 15; 4901 break; 4902 case X86::BI__builtin_ia32_pblendd128: 4903 case X86::BI__builtin_ia32_blendps: 4904 case X86::BI__builtin_ia32_blendpd256: 4905 case X86::BI__builtin_ia32_shufpd256: 4906 case X86::BI__builtin_ia32_roundss: 4907 case X86::BI__builtin_ia32_roundsd: 4908 case X86::BI__builtin_ia32_rangepd128_mask: 4909 case X86::BI__builtin_ia32_rangepd256_mask: 4910 case X86::BI__builtin_ia32_rangepd512_mask: 4911 case X86::BI__builtin_ia32_rangeps128_mask: 4912 case X86::BI__builtin_ia32_rangeps256_mask: 4913 case X86::BI__builtin_ia32_rangeps512_mask: 4914 case X86::BI__builtin_ia32_getmantsd_round_mask: 4915 case X86::BI__builtin_ia32_getmantss_round_mask: 4916 case X86::BI__builtin_ia32_getmantsh_round_mask: 4917 case X86::BI__builtin_ia32_vec_set_v16qi: 4918 case X86::BI__builtin_ia32_vec_set_v16hi: 4919 i = 2; l = 0; u = 15; 4920 break; 4921 case X86::BI__builtin_ia32_vec_ext_v32qi: 4922 i = 1; l = 0; u = 31; 4923 break; 4924 case X86::BI__builtin_ia32_cmpps: 4925 case X86::BI__builtin_ia32_cmpss: 4926 case X86::BI__builtin_ia32_cmppd: 4927 case X86::BI__builtin_ia32_cmpsd: 4928 case X86::BI__builtin_ia32_cmpps256: 4929 case X86::BI__builtin_ia32_cmppd256: 4930 case X86::BI__builtin_ia32_cmpps128_mask: 4931 case X86::BI__builtin_ia32_cmppd128_mask: 4932 case X86::BI__builtin_ia32_cmpps256_mask: 4933 case X86::BI__builtin_ia32_cmppd256_mask: 4934 case X86::BI__builtin_ia32_cmpps512_mask: 4935 case X86::BI__builtin_ia32_cmppd512_mask: 4936 case X86::BI__builtin_ia32_cmpsd_mask: 4937 case X86::BI__builtin_ia32_cmpss_mask: 4938 case X86::BI__builtin_ia32_vec_set_v32qi: 4939 i = 2; l = 0; u = 31; 4940 break; 4941 case X86::BI__builtin_ia32_permdf256: 4942 case X86::BI__builtin_ia32_permdi256: 4943 case X86::BI__builtin_ia32_permdf512: 4944 case X86::BI__builtin_ia32_permdi512: 4945 case X86::BI__builtin_ia32_vpermilps: 4946 case X86::BI__builtin_ia32_vpermilps256: 4947 case X86::BI__builtin_ia32_vpermilpd512: 4948 case X86::BI__builtin_ia32_vpermilps512: 4949 case X86::BI__builtin_ia32_pshufd: 4950 case X86::BI__builtin_ia32_pshufd256: 4951 case X86::BI__builtin_ia32_pshufd512: 4952 case X86::BI__builtin_ia32_pshufhw: 4953 case X86::BI__builtin_ia32_pshufhw256: 4954 case X86::BI__builtin_ia32_pshufhw512: 4955 case X86::BI__builtin_ia32_pshuflw: 4956 case X86::BI__builtin_ia32_pshuflw256: 4957 case X86::BI__builtin_ia32_pshuflw512: 4958 case X86::BI__builtin_ia32_vcvtps2ph: 4959 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4960 case X86::BI__builtin_ia32_vcvtps2ph256: 4961 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4962 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4963 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4964 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4965 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4966 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4967 case X86::BI__builtin_ia32_rndscaleps_mask: 4968 case X86::BI__builtin_ia32_rndscalepd_mask: 4969 case X86::BI__builtin_ia32_rndscaleph_mask: 4970 case X86::BI__builtin_ia32_reducepd128_mask: 4971 case X86::BI__builtin_ia32_reducepd256_mask: 4972 case X86::BI__builtin_ia32_reducepd512_mask: 4973 case X86::BI__builtin_ia32_reduceps128_mask: 4974 case X86::BI__builtin_ia32_reduceps256_mask: 4975 case X86::BI__builtin_ia32_reduceps512_mask: 4976 case X86::BI__builtin_ia32_reduceph128_mask: 4977 case X86::BI__builtin_ia32_reduceph256_mask: 4978 case X86::BI__builtin_ia32_reduceph512_mask: 4979 case X86::BI__builtin_ia32_prold512: 4980 case X86::BI__builtin_ia32_prolq512: 4981 case X86::BI__builtin_ia32_prold128: 4982 case X86::BI__builtin_ia32_prold256: 4983 case X86::BI__builtin_ia32_prolq128: 4984 case X86::BI__builtin_ia32_prolq256: 4985 case X86::BI__builtin_ia32_prord512: 4986 case X86::BI__builtin_ia32_prorq512: 4987 case X86::BI__builtin_ia32_prord128: 4988 case X86::BI__builtin_ia32_prord256: 4989 case X86::BI__builtin_ia32_prorq128: 4990 case X86::BI__builtin_ia32_prorq256: 4991 case X86::BI__builtin_ia32_fpclasspd128_mask: 4992 case X86::BI__builtin_ia32_fpclasspd256_mask: 4993 case X86::BI__builtin_ia32_fpclassps128_mask: 4994 case X86::BI__builtin_ia32_fpclassps256_mask: 4995 case X86::BI__builtin_ia32_fpclassps512_mask: 4996 case X86::BI__builtin_ia32_fpclasspd512_mask: 4997 case X86::BI__builtin_ia32_fpclassph128_mask: 4998 case X86::BI__builtin_ia32_fpclassph256_mask: 4999 case X86::BI__builtin_ia32_fpclassph512_mask: 5000 case X86::BI__builtin_ia32_fpclasssd_mask: 5001 case X86::BI__builtin_ia32_fpclassss_mask: 5002 case X86::BI__builtin_ia32_fpclasssh_mask: 5003 case X86::BI__builtin_ia32_pslldqi128_byteshift: 5004 case X86::BI__builtin_ia32_pslldqi256_byteshift: 5005 case X86::BI__builtin_ia32_pslldqi512_byteshift: 5006 case X86::BI__builtin_ia32_psrldqi128_byteshift: 5007 case X86::BI__builtin_ia32_psrldqi256_byteshift: 5008 case X86::BI__builtin_ia32_psrldqi512_byteshift: 5009 case X86::BI__builtin_ia32_kshiftliqi: 5010 case X86::BI__builtin_ia32_kshiftlihi: 5011 case X86::BI__builtin_ia32_kshiftlisi: 5012 case X86::BI__builtin_ia32_kshiftlidi: 5013 case X86::BI__builtin_ia32_kshiftriqi: 5014 case X86::BI__builtin_ia32_kshiftrihi: 5015 case X86::BI__builtin_ia32_kshiftrisi: 5016 case X86::BI__builtin_ia32_kshiftridi: 5017 i = 1; l = 0; u = 255; 5018 break; 5019 case X86::BI__builtin_ia32_vperm2f128_pd256: 5020 case X86::BI__builtin_ia32_vperm2f128_ps256: 5021 case X86::BI__builtin_ia32_vperm2f128_si256: 5022 case X86::BI__builtin_ia32_permti256: 5023 case X86::BI__builtin_ia32_pblendw128: 5024 case X86::BI__builtin_ia32_pblendw256: 5025 case X86::BI__builtin_ia32_blendps256: 5026 case X86::BI__builtin_ia32_pblendd256: 5027 case X86::BI__builtin_ia32_palignr128: 5028 case X86::BI__builtin_ia32_palignr256: 5029 case X86::BI__builtin_ia32_palignr512: 5030 case X86::BI__builtin_ia32_alignq512: 5031 case X86::BI__builtin_ia32_alignd512: 5032 case X86::BI__builtin_ia32_alignd128: 5033 case X86::BI__builtin_ia32_alignd256: 5034 case X86::BI__builtin_ia32_alignq128: 5035 case X86::BI__builtin_ia32_alignq256: 5036 case X86::BI__builtin_ia32_vcomisd: 5037 case X86::BI__builtin_ia32_vcomiss: 5038 case X86::BI__builtin_ia32_shuf_f32x4: 5039 case X86::BI__builtin_ia32_shuf_f64x2: 5040 case X86::BI__builtin_ia32_shuf_i32x4: 5041 case X86::BI__builtin_ia32_shuf_i64x2: 5042 case X86::BI__builtin_ia32_shufpd512: 5043 case X86::BI__builtin_ia32_shufps: 5044 case X86::BI__builtin_ia32_shufps256: 5045 case X86::BI__builtin_ia32_shufps512: 5046 case X86::BI__builtin_ia32_dbpsadbw128: 5047 case X86::BI__builtin_ia32_dbpsadbw256: 5048 case X86::BI__builtin_ia32_dbpsadbw512: 5049 case X86::BI__builtin_ia32_vpshldd128: 5050 case X86::BI__builtin_ia32_vpshldd256: 5051 case X86::BI__builtin_ia32_vpshldd512: 5052 case X86::BI__builtin_ia32_vpshldq128: 5053 case X86::BI__builtin_ia32_vpshldq256: 5054 case X86::BI__builtin_ia32_vpshldq512: 5055 case X86::BI__builtin_ia32_vpshldw128: 5056 case X86::BI__builtin_ia32_vpshldw256: 5057 case X86::BI__builtin_ia32_vpshldw512: 5058 case X86::BI__builtin_ia32_vpshrdd128: 5059 case X86::BI__builtin_ia32_vpshrdd256: 5060 case X86::BI__builtin_ia32_vpshrdd512: 5061 case X86::BI__builtin_ia32_vpshrdq128: 5062 case X86::BI__builtin_ia32_vpshrdq256: 5063 case X86::BI__builtin_ia32_vpshrdq512: 5064 case X86::BI__builtin_ia32_vpshrdw128: 5065 case X86::BI__builtin_ia32_vpshrdw256: 5066 case X86::BI__builtin_ia32_vpshrdw512: 5067 i = 2; l = 0; u = 255; 5068 break; 5069 case X86::BI__builtin_ia32_fixupimmpd512_mask: 5070 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 5071 case X86::BI__builtin_ia32_fixupimmps512_mask: 5072 case X86::BI__builtin_ia32_fixupimmps512_maskz: 5073 case X86::BI__builtin_ia32_fixupimmsd_mask: 5074 case X86::BI__builtin_ia32_fixupimmsd_maskz: 5075 case X86::BI__builtin_ia32_fixupimmss_mask: 5076 case X86::BI__builtin_ia32_fixupimmss_maskz: 5077 case X86::BI__builtin_ia32_fixupimmpd128_mask: 5078 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 5079 case X86::BI__builtin_ia32_fixupimmpd256_mask: 5080 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 5081 case X86::BI__builtin_ia32_fixupimmps128_mask: 5082 case X86::BI__builtin_ia32_fixupimmps128_maskz: 5083 case X86::BI__builtin_ia32_fixupimmps256_mask: 5084 case X86::BI__builtin_ia32_fixupimmps256_maskz: 5085 case X86::BI__builtin_ia32_pternlogd512_mask: 5086 case X86::BI__builtin_ia32_pternlogd512_maskz: 5087 case X86::BI__builtin_ia32_pternlogq512_mask: 5088 case X86::BI__builtin_ia32_pternlogq512_maskz: 5089 case X86::BI__builtin_ia32_pternlogd128_mask: 5090 case X86::BI__builtin_ia32_pternlogd128_maskz: 5091 case X86::BI__builtin_ia32_pternlogd256_mask: 5092 case X86::BI__builtin_ia32_pternlogd256_maskz: 5093 case X86::BI__builtin_ia32_pternlogq128_mask: 5094 case X86::BI__builtin_ia32_pternlogq128_maskz: 5095 case X86::BI__builtin_ia32_pternlogq256_mask: 5096 case X86::BI__builtin_ia32_pternlogq256_maskz: 5097 i = 3; l = 0; u = 255; 5098 break; 5099 case X86::BI__builtin_ia32_gatherpfdpd: 5100 case X86::BI__builtin_ia32_gatherpfdps: 5101 case X86::BI__builtin_ia32_gatherpfqpd: 5102 case X86::BI__builtin_ia32_gatherpfqps: 5103 case X86::BI__builtin_ia32_scatterpfdpd: 5104 case X86::BI__builtin_ia32_scatterpfdps: 5105 case X86::BI__builtin_ia32_scatterpfqpd: 5106 case X86::BI__builtin_ia32_scatterpfqps: 5107 i = 4; l = 2; u = 3; 5108 break; 5109 case X86::BI__builtin_ia32_reducesd_mask: 5110 case X86::BI__builtin_ia32_reducess_mask: 5111 case X86::BI__builtin_ia32_rndscalesd_round_mask: 5112 case X86::BI__builtin_ia32_rndscaless_round_mask: 5113 case X86::BI__builtin_ia32_rndscalesh_round_mask: 5114 case X86::BI__builtin_ia32_reducesh_mask: 5115 i = 4; l = 0; u = 255; 5116 break; 5117 } 5118 5119 // Note that we don't force a hard error on the range check here, allowing 5120 // template-generated or macro-generated dead code to potentially have out-of- 5121 // range values. These need to code generate, but don't need to necessarily 5122 // make any sense. We use a warning that defaults to an error. 5123 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 5124 } 5125 5126 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 5127 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 5128 /// Returns true when the format fits the function and the FormatStringInfo has 5129 /// been populated. 5130 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 5131 FormatStringInfo *FSI) { 5132 FSI->HasVAListArg = Format->getFirstArg() == 0; 5133 FSI->FormatIdx = Format->getFormatIdx() - 1; 5134 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 5135 5136 // The way the format attribute works in GCC, the implicit this argument 5137 // of member functions is counted. However, it doesn't appear in our own 5138 // lists, so decrement format_idx in that case. 5139 if (IsCXXMember) { 5140 if(FSI->FormatIdx == 0) 5141 return false; 5142 --FSI->FormatIdx; 5143 if (FSI->FirstDataArg != 0) 5144 --FSI->FirstDataArg; 5145 } 5146 return true; 5147 } 5148 5149 /// Checks if a the given expression evaluates to null. 5150 /// 5151 /// Returns true if the value evaluates to null. 5152 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 5153 // If the expression has non-null type, it doesn't evaluate to null. 5154 if (auto nullability 5155 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 5156 if (*nullability == NullabilityKind::NonNull) 5157 return false; 5158 } 5159 5160 // As a special case, transparent unions initialized with zero are 5161 // considered null for the purposes of the nonnull attribute. 5162 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 5163 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5164 if (const CompoundLiteralExpr *CLE = 5165 dyn_cast<CompoundLiteralExpr>(Expr)) 5166 if (const InitListExpr *ILE = 5167 dyn_cast<InitListExpr>(CLE->getInitializer())) 5168 Expr = ILE->getInit(0); 5169 } 5170 5171 bool Result; 5172 return (!Expr->isValueDependent() && 5173 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 5174 !Result); 5175 } 5176 5177 static void CheckNonNullArgument(Sema &S, 5178 const Expr *ArgExpr, 5179 SourceLocation CallSiteLoc) { 5180 if (CheckNonNullExpr(S, ArgExpr)) 5181 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 5182 S.PDiag(diag::warn_null_arg) 5183 << ArgExpr->getSourceRange()); 5184 } 5185 5186 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 5187 FormatStringInfo FSI; 5188 if ((GetFormatStringType(Format) == FST_NSString) && 5189 getFormatStringInfo(Format, false, &FSI)) { 5190 Idx = FSI.FormatIdx; 5191 return true; 5192 } 5193 return false; 5194 } 5195 5196 /// Diagnose use of %s directive in an NSString which is being passed 5197 /// as formatting string to formatting method. 5198 static void 5199 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 5200 const NamedDecl *FDecl, 5201 Expr **Args, 5202 unsigned NumArgs) { 5203 unsigned Idx = 0; 5204 bool Format = false; 5205 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 5206 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 5207 Idx = 2; 5208 Format = true; 5209 } 5210 else 5211 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5212 if (S.GetFormatNSStringIdx(I, Idx)) { 5213 Format = true; 5214 break; 5215 } 5216 } 5217 if (!Format || NumArgs <= Idx) 5218 return; 5219 const Expr *FormatExpr = Args[Idx]; 5220 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 5221 FormatExpr = CSCE->getSubExpr(); 5222 const StringLiteral *FormatString; 5223 if (const ObjCStringLiteral *OSL = 5224 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 5225 FormatString = OSL->getString(); 5226 else 5227 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 5228 if (!FormatString) 5229 return; 5230 if (S.FormatStringHasSArg(FormatString)) { 5231 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 5232 << "%s" << 1 << 1; 5233 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 5234 << FDecl->getDeclName(); 5235 } 5236 } 5237 5238 /// Determine whether the given type has a non-null nullability annotation. 5239 static bool isNonNullType(ASTContext &ctx, QualType type) { 5240 if (auto nullability = type->getNullability(ctx)) 5241 return *nullability == NullabilityKind::NonNull; 5242 5243 return false; 5244 } 5245 5246 static void CheckNonNullArguments(Sema &S, 5247 const NamedDecl *FDecl, 5248 const FunctionProtoType *Proto, 5249 ArrayRef<const Expr *> Args, 5250 SourceLocation CallSiteLoc) { 5251 assert((FDecl || Proto) && "Need a function declaration or prototype"); 5252 5253 // Already checked by by constant evaluator. 5254 if (S.isConstantEvaluated()) 5255 return; 5256 // Check the attributes attached to the method/function itself. 5257 llvm::SmallBitVector NonNullArgs; 5258 if (FDecl) { 5259 // Handle the nonnull attribute on the function/method declaration itself. 5260 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 5261 if (!NonNull->args_size()) { 5262 // Easy case: all pointer arguments are nonnull. 5263 for (const auto *Arg : Args) 5264 if (S.isValidPointerAttrType(Arg->getType())) 5265 CheckNonNullArgument(S, Arg, CallSiteLoc); 5266 return; 5267 } 5268 5269 for (const ParamIdx &Idx : NonNull->args()) { 5270 unsigned IdxAST = Idx.getASTIndex(); 5271 if (IdxAST >= Args.size()) 5272 continue; 5273 if (NonNullArgs.empty()) 5274 NonNullArgs.resize(Args.size()); 5275 NonNullArgs.set(IdxAST); 5276 } 5277 } 5278 } 5279 5280 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 5281 // Handle the nonnull attribute on the parameters of the 5282 // function/method. 5283 ArrayRef<ParmVarDecl*> parms; 5284 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 5285 parms = FD->parameters(); 5286 else 5287 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 5288 5289 unsigned ParamIndex = 0; 5290 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 5291 I != E; ++I, ++ParamIndex) { 5292 const ParmVarDecl *PVD = *I; 5293 if (PVD->hasAttr<NonNullAttr>() || 5294 isNonNullType(S.Context, PVD->getType())) { 5295 if (NonNullArgs.empty()) 5296 NonNullArgs.resize(Args.size()); 5297 5298 NonNullArgs.set(ParamIndex); 5299 } 5300 } 5301 } else { 5302 // If we have a non-function, non-method declaration but no 5303 // function prototype, try to dig out the function prototype. 5304 if (!Proto) { 5305 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 5306 QualType type = VD->getType().getNonReferenceType(); 5307 if (auto pointerType = type->getAs<PointerType>()) 5308 type = pointerType->getPointeeType(); 5309 else if (auto blockType = type->getAs<BlockPointerType>()) 5310 type = blockType->getPointeeType(); 5311 // FIXME: data member pointers? 5312 5313 // Dig out the function prototype, if there is one. 5314 Proto = type->getAs<FunctionProtoType>(); 5315 } 5316 } 5317 5318 // Fill in non-null argument information from the nullability 5319 // information on the parameter types (if we have them). 5320 if (Proto) { 5321 unsigned Index = 0; 5322 for (auto paramType : Proto->getParamTypes()) { 5323 if (isNonNullType(S.Context, paramType)) { 5324 if (NonNullArgs.empty()) 5325 NonNullArgs.resize(Args.size()); 5326 5327 NonNullArgs.set(Index); 5328 } 5329 5330 ++Index; 5331 } 5332 } 5333 } 5334 5335 // Check for non-null arguments. 5336 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 5337 ArgIndex != ArgIndexEnd; ++ArgIndex) { 5338 if (NonNullArgs[ArgIndex]) 5339 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 5340 } 5341 } 5342 5343 /// Warn if a pointer or reference argument passed to a function points to an 5344 /// object that is less aligned than the parameter. This can happen when 5345 /// creating a typedef with a lower alignment than the original type and then 5346 /// calling functions defined in terms of the original type. 5347 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 5348 StringRef ParamName, QualType ArgTy, 5349 QualType ParamTy) { 5350 5351 // If a function accepts a pointer or reference type 5352 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 5353 return; 5354 5355 // If the parameter is a pointer type, get the pointee type for the 5356 // argument too. If the parameter is a reference type, don't try to get 5357 // the pointee type for the argument. 5358 if (ParamTy->isPointerType()) 5359 ArgTy = ArgTy->getPointeeType(); 5360 5361 // Remove reference or pointer 5362 ParamTy = ParamTy->getPointeeType(); 5363 5364 // Find expected alignment, and the actual alignment of the passed object. 5365 // getTypeAlignInChars requires complete types 5366 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5367 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5368 ArgTy->isUndeducedType()) 5369 return; 5370 5371 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5372 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5373 5374 // If the argument is less aligned than the parameter, there is a 5375 // potential alignment issue. 5376 if (ArgAlign < ParamAlign) 5377 Diag(Loc, diag::warn_param_mismatched_alignment) 5378 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5379 << ParamName << (FDecl != nullptr) << FDecl; 5380 } 5381 5382 /// Handles the checks for format strings, non-POD arguments to vararg 5383 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5384 /// attributes. 5385 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5386 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5387 bool IsMemberFunction, SourceLocation Loc, 5388 SourceRange Range, VariadicCallType CallType) { 5389 // FIXME: We should check as much as we can in the template definition. 5390 if (CurContext->isDependentContext()) 5391 return; 5392 5393 // Printf and scanf checking. 5394 llvm::SmallBitVector CheckedVarArgs; 5395 if (FDecl) { 5396 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5397 // Only create vector if there are format attributes. 5398 CheckedVarArgs.resize(Args.size()); 5399 5400 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5401 CheckedVarArgs); 5402 } 5403 } 5404 5405 // Refuse POD arguments that weren't caught by the format string 5406 // checks above. 5407 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5408 if (CallType != VariadicDoesNotApply && 5409 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5410 unsigned NumParams = Proto ? Proto->getNumParams() 5411 : FDecl && isa<FunctionDecl>(FDecl) 5412 ? cast<FunctionDecl>(FDecl)->getNumParams() 5413 : FDecl && isa<ObjCMethodDecl>(FDecl) 5414 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5415 : 0; 5416 5417 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5418 // Args[ArgIdx] can be null in malformed code. 5419 if (const Expr *Arg = Args[ArgIdx]) { 5420 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5421 checkVariadicArgument(Arg, CallType); 5422 } 5423 } 5424 } 5425 5426 if (FDecl || Proto) { 5427 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5428 5429 // Type safety checking. 5430 if (FDecl) { 5431 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5432 CheckArgumentWithTypeTag(I, Args, Loc); 5433 } 5434 } 5435 5436 // Check that passed arguments match the alignment of original arguments. 5437 // Try to get the missing prototype from the declaration. 5438 if (!Proto && FDecl) { 5439 const auto *FT = FDecl->getFunctionType(); 5440 if (isa_and_nonnull<FunctionProtoType>(FT)) 5441 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5442 } 5443 if (Proto) { 5444 // For variadic functions, we may have more args than parameters. 5445 // For some K&R functions, we may have less args than parameters. 5446 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5447 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5448 // Args[ArgIdx] can be null in malformed code. 5449 if (const Expr *Arg = Args[ArgIdx]) { 5450 if (Arg->containsErrors()) 5451 continue; 5452 5453 QualType ParamTy = Proto->getParamType(ArgIdx); 5454 QualType ArgTy = Arg->getType(); 5455 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5456 ArgTy, ParamTy); 5457 } 5458 } 5459 } 5460 5461 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5462 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5463 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5464 if (!Arg->isValueDependent()) { 5465 Expr::EvalResult Align; 5466 if (Arg->EvaluateAsInt(Align, Context)) { 5467 const llvm::APSInt &I = Align.Val.getInt(); 5468 if (!I.isPowerOf2()) 5469 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5470 << Arg->getSourceRange(); 5471 5472 if (I > Sema::MaximumAlignment) 5473 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5474 << Arg->getSourceRange() << Sema::MaximumAlignment; 5475 } 5476 } 5477 } 5478 5479 if (FD) 5480 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5481 } 5482 5483 /// CheckConstructorCall - Check a constructor call for correctness and safety 5484 /// properties not enforced by the C type system. 5485 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5486 ArrayRef<const Expr *> Args, 5487 const FunctionProtoType *Proto, 5488 SourceLocation Loc) { 5489 VariadicCallType CallType = 5490 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5491 5492 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5493 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5494 Context.getPointerType(Ctor->getThisObjectType())); 5495 5496 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5497 Loc, SourceRange(), CallType); 5498 } 5499 5500 /// CheckFunctionCall - Check a direct function call for various correctness 5501 /// and safety properties not strictly enforced by the C type system. 5502 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5503 const FunctionProtoType *Proto) { 5504 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5505 isa<CXXMethodDecl>(FDecl); 5506 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5507 IsMemberOperatorCall; 5508 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5509 TheCall->getCallee()); 5510 Expr** Args = TheCall->getArgs(); 5511 unsigned NumArgs = TheCall->getNumArgs(); 5512 5513 Expr *ImplicitThis = nullptr; 5514 if (IsMemberOperatorCall) { 5515 // If this is a call to a member operator, hide the first argument 5516 // from checkCall. 5517 // FIXME: Our choice of AST representation here is less than ideal. 5518 ImplicitThis = Args[0]; 5519 ++Args; 5520 --NumArgs; 5521 } else if (IsMemberFunction) 5522 ImplicitThis = 5523 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5524 5525 if (ImplicitThis) { 5526 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5527 // used. 5528 QualType ThisType = ImplicitThis->getType(); 5529 if (!ThisType->isPointerType()) { 5530 assert(!ThisType->isReferenceType()); 5531 ThisType = Context.getPointerType(ThisType); 5532 } 5533 5534 QualType ThisTypeFromDecl = 5535 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5536 5537 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5538 ThisTypeFromDecl); 5539 } 5540 5541 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5542 IsMemberFunction, TheCall->getRParenLoc(), 5543 TheCall->getCallee()->getSourceRange(), CallType); 5544 5545 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5546 // None of the checks below are needed for functions that don't have 5547 // simple names (e.g., C++ conversion functions). 5548 if (!FnInfo) 5549 return false; 5550 5551 // Enforce TCB except for builtin calls, which are always allowed. 5552 if (FDecl->getBuiltinID() == 0) 5553 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl); 5554 5555 CheckAbsoluteValueFunction(TheCall, FDecl); 5556 CheckMaxUnsignedZero(TheCall, FDecl); 5557 5558 if (getLangOpts().ObjC) 5559 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5560 5561 unsigned CMId = FDecl->getMemoryFunctionKind(); 5562 5563 // Handle memory setting and copying functions. 5564 switch (CMId) { 5565 case 0: 5566 return false; 5567 case Builtin::BIstrlcpy: // fallthrough 5568 case Builtin::BIstrlcat: 5569 CheckStrlcpycatArguments(TheCall, FnInfo); 5570 break; 5571 case Builtin::BIstrncat: 5572 CheckStrncatArguments(TheCall, FnInfo); 5573 break; 5574 case Builtin::BIfree: 5575 CheckFreeArguments(TheCall); 5576 break; 5577 default: 5578 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5579 } 5580 5581 return false; 5582 } 5583 5584 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5585 ArrayRef<const Expr *> Args) { 5586 VariadicCallType CallType = 5587 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5588 5589 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5590 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5591 CallType); 5592 5593 CheckTCBEnforcement(lbrac, Method); 5594 5595 return false; 5596 } 5597 5598 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5599 const FunctionProtoType *Proto) { 5600 QualType Ty; 5601 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5602 Ty = V->getType().getNonReferenceType(); 5603 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5604 Ty = F->getType().getNonReferenceType(); 5605 else 5606 return false; 5607 5608 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5609 !Ty->isFunctionProtoType()) 5610 return false; 5611 5612 VariadicCallType CallType; 5613 if (!Proto || !Proto->isVariadic()) { 5614 CallType = VariadicDoesNotApply; 5615 } else if (Ty->isBlockPointerType()) { 5616 CallType = VariadicBlock; 5617 } else { // Ty->isFunctionPointerType() 5618 CallType = VariadicFunction; 5619 } 5620 5621 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5622 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5623 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5624 TheCall->getCallee()->getSourceRange(), CallType); 5625 5626 return false; 5627 } 5628 5629 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5630 /// such as function pointers returned from functions. 5631 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5632 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5633 TheCall->getCallee()); 5634 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5635 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5636 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5637 TheCall->getCallee()->getSourceRange(), CallType); 5638 5639 return false; 5640 } 5641 5642 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5643 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5644 return false; 5645 5646 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5647 switch (Op) { 5648 case AtomicExpr::AO__c11_atomic_init: 5649 case AtomicExpr::AO__opencl_atomic_init: 5650 llvm_unreachable("There is no ordering argument for an init"); 5651 5652 case AtomicExpr::AO__c11_atomic_load: 5653 case AtomicExpr::AO__opencl_atomic_load: 5654 case AtomicExpr::AO__hip_atomic_load: 5655 case AtomicExpr::AO__atomic_load_n: 5656 case AtomicExpr::AO__atomic_load: 5657 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5658 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5659 5660 case AtomicExpr::AO__c11_atomic_store: 5661 case AtomicExpr::AO__opencl_atomic_store: 5662 case AtomicExpr::AO__hip_atomic_store: 5663 case AtomicExpr::AO__atomic_store: 5664 case AtomicExpr::AO__atomic_store_n: 5665 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5666 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5667 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5668 5669 default: 5670 return true; 5671 } 5672 } 5673 5674 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5675 AtomicExpr::AtomicOp Op) { 5676 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5677 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5678 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5679 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5680 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5681 Op); 5682 } 5683 5684 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5685 SourceLocation RParenLoc, MultiExprArg Args, 5686 AtomicExpr::AtomicOp Op, 5687 AtomicArgumentOrder ArgOrder) { 5688 // All the non-OpenCL operations take one of the following forms. 5689 // The OpenCL operations take the __c11 forms with one extra argument for 5690 // synchronization scope. 5691 enum { 5692 // C __c11_atomic_init(A *, C) 5693 Init, 5694 5695 // C __c11_atomic_load(A *, int) 5696 Load, 5697 5698 // void __atomic_load(A *, CP, int) 5699 LoadCopy, 5700 5701 // void __atomic_store(A *, CP, int) 5702 Copy, 5703 5704 // C __c11_atomic_add(A *, M, int) 5705 Arithmetic, 5706 5707 // C __atomic_exchange_n(A *, CP, int) 5708 Xchg, 5709 5710 // void __atomic_exchange(A *, C *, CP, int) 5711 GNUXchg, 5712 5713 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5714 C11CmpXchg, 5715 5716 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5717 GNUCmpXchg 5718 } Form = Init; 5719 5720 const unsigned NumForm = GNUCmpXchg + 1; 5721 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5722 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5723 // where: 5724 // C is an appropriate type, 5725 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5726 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5727 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5728 // the int parameters are for orderings. 5729 5730 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5731 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5732 "need to update code for modified forms"); 5733 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5734 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5735 AtomicExpr::AO__atomic_load, 5736 "need to update code for modified C11 atomics"); 5737 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5738 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5739 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load && 5740 Op <= AtomicExpr::AO__hip_atomic_fetch_max; 5741 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5742 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5743 IsOpenCL; 5744 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5745 Op == AtomicExpr::AO__atomic_store_n || 5746 Op == AtomicExpr::AO__atomic_exchange_n || 5747 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5748 bool IsAddSub = false; 5749 5750 switch (Op) { 5751 case AtomicExpr::AO__c11_atomic_init: 5752 case AtomicExpr::AO__opencl_atomic_init: 5753 Form = Init; 5754 break; 5755 5756 case AtomicExpr::AO__c11_atomic_load: 5757 case AtomicExpr::AO__opencl_atomic_load: 5758 case AtomicExpr::AO__hip_atomic_load: 5759 case AtomicExpr::AO__atomic_load_n: 5760 Form = Load; 5761 break; 5762 5763 case AtomicExpr::AO__atomic_load: 5764 Form = LoadCopy; 5765 break; 5766 5767 case AtomicExpr::AO__c11_atomic_store: 5768 case AtomicExpr::AO__opencl_atomic_store: 5769 case AtomicExpr::AO__hip_atomic_store: 5770 case AtomicExpr::AO__atomic_store: 5771 case AtomicExpr::AO__atomic_store_n: 5772 Form = Copy; 5773 break; 5774 case AtomicExpr::AO__hip_atomic_fetch_add: 5775 case AtomicExpr::AO__hip_atomic_fetch_min: 5776 case AtomicExpr::AO__hip_atomic_fetch_max: 5777 case AtomicExpr::AO__c11_atomic_fetch_add: 5778 case AtomicExpr::AO__c11_atomic_fetch_sub: 5779 case AtomicExpr::AO__opencl_atomic_fetch_add: 5780 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5781 case AtomicExpr::AO__atomic_fetch_add: 5782 case AtomicExpr::AO__atomic_fetch_sub: 5783 case AtomicExpr::AO__atomic_add_fetch: 5784 case AtomicExpr::AO__atomic_sub_fetch: 5785 IsAddSub = true; 5786 Form = Arithmetic; 5787 break; 5788 case AtomicExpr::AO__c11_atomic_fetch_and: 5789 case AtomicExpr::AO__c11_atomic_fetch_or: 5790 case AtomicExpr::AO__c11_atomic_fetch_xor: 5791 case AtomicExpr::AO__hip_atomic_fetch_and: 5792 case AtomicExpr::AO__hip_atomic_fetch_or: 5793 case AtomicExpr::AO__hip_atomic_fetch_xor: 5794 case AtomicExpr::AO__c11_atomic_fetch_nand: 5795 case AtomicExpr::AO__opencl_atomic_fetch_and: 5796 case AtomicExpr::AO__opencl_atomic_fetch_or: 5797 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5798 case AtomicExpr::AO__atomic_fetch_and: 5799 case AtomicExpr::AO__atomic_fetch_or: 5800 case AtomicExpr::AO__atomic_fetch_xor: 5801 case AtomicExpr::AO__atomic_fetch_nand: 5802 case AtomicExpr::AO__atomic_and_fetch: 5803 case AtomicExpr::AO__atomic_or_fetch: 5804 case AtomicExpr::AO__atomic_xor_fetch: 5805 case AtomicExpr::AO__atomic_nand_fetch: 5806 Form = Arithmetic; 5807 break; 5808 case AtomicExpr::AO__c11_atomic_fetch_min: 5809 case AtomicExpr::AO__c11_atomic_fetch_max: 5810 case AtomicExpr::AO__opencl_atomic_fetch_min: 5811 case AtomicExpr::AO__opencl_atomic_fetch_max: 5812 case AtomicExpr::AO__atomic_min_fetch: 5813 case AtomicExpr::AO__atomic_max_fetch: 5814 case AtomicExpr::AO__atomic_fetch_min: 5815 case AtomicExpr::AO__atomic_fetch_max: 5816 Form = Arithmetic; 5817 break; 5818 5819 case AtomicExpr::AO__c11_atomic_exchange: 5820 case AtomicExpr::AO__hip_atomic_exchange: 5821 case AtomicExpr::AO__opencl_atomic_exchange: 5822 case AtomicExpr::AO__atomic_exchange_n: 5823 Form = Xchg; 5824 break; 5825 5826 case AtomicExpr::AO__atomic_exchange: 5827 Form = GNUXchg; 5828 break; 5829 5830 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5831 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5832 case AtomicExpr::AO__hip_atomic_compare_exchange_strong: 5833 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5834 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5835 case AtomicExpr::AO__hip_atomic_compare_exchange_weak: 5836 Form = C11CmpXchg; 5837 break; 5838 5839 case AtomicExpr::AO__atomic_compare_exchange: 5840 case AtomicExpr::AO__atomic_compare_exchange_n: 5841 Form = GNUCmpXchg; 5842 break; 5843 } 5844 5845 unsigned AdjustedNumArgs = NumArgs[Form]; 5846 if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init) 5847 ++AdjustedNumArgs; 5848 // Check we have the right number of arguments. 5849 if (Args.size() < AdjustedNumArgs) { 5850 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5851 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5852 << ExprRange; 5853 return ExprError(); 5854 } else if (Args.size() > AdjustedNumArgs) { 5855 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5856 diag::err_typecheck_call_too_many_args) 5857 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5858 << ExprRange; 5859 return ExprError(); 5860 } 5861 5862 // Inspect the first argument of the atomic operation. 5863 Expr *Ptr = Args[0]; 5864 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5865 if (ConvertedPtr.isInvalid()) 5866 return ExprError(); 5867 5868 Ptr = ConvertedPtr.get(); 5869 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5870 if (!pointerType) { 5871 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5872 << Ptr->getType() << Ptr->getSourceRange(); 5873 return ExprError(); 5874 } 5875 5876 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5877 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5878 QualType ValType = AtomTy; // 'C' 5879 if (IsC11) { 5880 if (!AtomTy->isAtomicType()) { 5881 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5882 << Ptr->getType() << Ptr->getSourceRange(); 5883 return ExprError(); 5884 } 5885 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5886 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5887 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5888 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5889 << Ptr->getSourceRange(); 5890 return ExprError(); 5891 } 5892 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5893 } else if (Form != Load && Form != LoadCopy) { 5894 if (ValType.isConstQualified()) { 5895 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5896 << Ptr->getType() << Ptr->getSourceRange(); 5897 return ExprError(); 5898 } 5899 } 5900 5901 // For an arithmetic operation, the implied arithmetic must be well-formed. 5902 if (Form == Arithmetic) { 5903 // GCC does not enforce these rules for GNU atomics, but we do to help catch 5904 // trivial type errors. 5905 auto IsAllowedValueType = [&](QualType ValType) { 5906 if (ValType->isIntegerType()) 5907 return true; 5908 if (ValType->isPointerType()) 5909 return true; 5910 if (!ValType->isFloatingType()) 5911 return false; 5912 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5913 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5914 &Context.getTargetInfo().getLongDoubleFormat() == 5915 &llvm::APFloat::x87DoubleExtended()) 5916 return false; 5917 return true; 5918 }; 5919 if (IsAddSub && !IsAllowedValueType(ValType)) { 5920 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5921 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5922 return ExprError(); 5923 } 5924 if (!IsAddSub && !ValType->isIntegerType()) { 5925 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5926 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5927 return ExprError(); 5928 } 5929 if (IsC11 && ValType->isPointerType() && 5930 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5931 diag::err_incomplete_type)) { 5932 return ExprError(); 5933 } 5934 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5935 // For __atomic_*_n operations, the value type must be a scalar integral or 5936 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5937 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5938 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5939 return ExprError(); 5940 } 5941 5942 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5943 !AtomTy->isScalarType()) { 5944 // For GNU atomics, require a trivially-copyable type. This is not part of 5945 // the GNU atomics specification but we enforce it for consistency with 5946 // other atomics which generally all require a trivially-copyable type. This 5947 // is because atomics just copy bits. 5948 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5949 << Ptr->getType() << Ptr->getSourceRange(); 5950 return ExprError(); 5951 } 5952 5953 switch (ValType.getObjCLifetime()) { 5954 case Qualifiers::OCL_None: 5955 case Qualifiers::OCL_ExplicitNone: 5956 // okay 5957 break; 5958 5959 case Qualifiers::OCL_Weak: 5960 case Qualifiers::OCL_Strong: 5961 case Qualifiers::OCL_Autoreleasing: 5962 // FIXME: Can this happen? By this point, ValType should be known 5963 // to be trivially copyable. 5964 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5965 << ValType << Ptr->getSourceRange(); 5966 return ExprError(); 5967 } 5968 5969 // All atomic operations have an overload which takes a pointer to a volatile 5970 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5971 // into the result or the other operands. Similarly atomic_load takes a 5972 // pointer to a const 'A'. 5973 ValType.removeLocalVolatile(); 5974 ValType.removeLocalConst(); 5975 QualType ResultType = ValType; 5976 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5977 Form == Init) 5978 ResultType = Context.VoidTy; 5979 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5980 ResultType = Context.BoolTy; 5981 5982 // The type of a parameter passed 'by value'. In the GNU atomics, such 5983 // arguments are actually passed as pointers. 5984 QualType ByValType = ValType; // 'CP' 5985 bool IsPassedByAddress = false; 5986 if (!IsC11 && !IsHIP && !IsN) { 5987 ByValType = Ptr->getType(); 5988 IsPassedByAddress = true; 5989 } 5990 5991 SmallVector<Expr *, 5> APIOrderedArgs; 5992 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5993 APIOrderedArgs.push_back(Args[0]); 5994 switch (Form) { 5995 case Init: 5996 case Load: 5997 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5998 break; 5999 case LoadCopy: 6000 case Copy: 6001 case Arithmetic: 6002 case Xchg: 6003 APIOrderedArgs.push_back(Args[2]); // Val1 6004 APIOrderedArgs.push_back(Args[1]); // Order 6005 break; 6006 case GNUXchg: 6007 APIOrderedArgs.push_back(Args[2]); // Val1 6008 APIOrderedArgs.push_back(Args[3]); // Val2 6009 APIOrderedArgs.push_back(Args[1]); // Order 6010 break; 6011 case C11CmpXchg: 6012 APIOrderedArgs.push_back(Args[2]); // Val1 6013 APIOrderedArgs.push_back(Args[4]); // Val2 6014 APIOrderedArgs.push_back(Args[1]); // Order 6015 APIOrderedArgs.push_back(Args[3]); // OrderFail 6016 break; 6017 case GNUCmpXchg: 6018 APIOrderedArgs.push_back(Args[2]); // Val1 6019 APIOrderedArgs.push_back(Args[4]); // Val2 6020 APIOrderedArgs.push_back(Args[5]); // Weak 6021 APIOrderedArgs.push_back(Args[1]); // Order 6022 APIOrderedArgs.push_back(Args[3]); // OrderFail 6023 break; 6024 } 6025 } else 6026 APIOrderedArgs.append(Args.begin(), Args.end()); 6027 6028 // The first argument's non-CV pointer type is used to deduce the type of 6029 // subsequent arguments, except for: 6030 // - weak flag (always converted to bool) 6031 // - memory order (always converted to int) 6032 // - scope (always converted to int) 6033 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 6034 QualType Ty; 6035 if (i < NumVals[Form] + 1) { 6036 switch (i) { 6037 case 0: 6038 // The first argument is always a pointer. It has a fixed type. 6039 // It is always dereferenced, a nullptr is undefined. 6040 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 6041 // Nothing else to do: we already know all we want about this pointer. 6042 continue; 6043 case 1: 6044 // The second argument is the non-atomic operand. For arithmetic, this 6045 // is always passed by value, and for a compare_exchange it is always 6046 // passed by address. For the rest, GNU uses by-address and C11 uses 6047 // by-value. 6048 assert(Form != Load); 6049 if (Form == Arithmetic && ValType->isPointerType()) 6050 Ty = Context.getPointerDiffType(); 6051 else if (Form == Init || Form == Arithmetic) 6052 Ty = ValType; 6053 else if (Form == Copy || Form == Xchg) { 6054 if (IsPassedByAddress) { 6055 // The value pointer is always dereferenced, a nullptr is undefined. 6056 CheckNonNullArgument(*this, APIOrderedArgs[i], 6057 ExprRange.getBegin()); 6058 } 6059 Ty = ByValType; 6060 } else { 6061 Expr *ValArg = APIOrderedArgs[i]; 6062 // The value pointer is always dereferenced, a nullptr is undefined. 6063 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 6064 LangAS AS = LangAS::Default; 6065 // Keep address space of non-atomic pointer type. 6066 if (const PointerType *PtrTy = 6067 ValArg->getType()->getAs<PointerType>()) { 6068 AS = PtrTy->getPointeeType().getAddressSpace(); 6069 } 6070 Ty = Context.getPointerType( 6071 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 6072 } 6073 break; 6074 case 2: 6075 // The third argument to compare_exchange / GNU exchange is the desired 6076 // value, either by-value (for the C11 and *_n variant) or as a pointer. 6077 if (IsPassedByAddress) 6078 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 6079 Ty = ByValType; 6080 break; 6081 case 3: 6082 // The fourth argument to GNU compare_exchange is a 'weak' flag. 6083 Ty = Context.BoolTy; 6084 break; 6085 } 6086 } else { 6087 // The order(s) and scope are always converted to int. 6088 Ty = Context.IntTy; 6089 } 6090 6091 InitializedEntity Entity = 6092 InitializedEntity::InitializeParameter(Context, Ty, false); 6093 ExprResult Arg = APIOrderedArgs[i]; 6094 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6095 if (Arg.isInvalid()) 6096 return true; 6097 APIOrderedArgs[i] = Arg.get(); 6098 } 6099 6100 // Permute the arguments into a 'consistent' order. 6101 SmallVector<Expr*, 5> SubExprs; 6102 SubExprs.push_back(Ptr); 6103 switch (Form) { 6104 case Init: 6105 // Note, AtomicExpr::getVal1() has a special case for this atomic. 6106 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6107 break; 6108 case Load: 6109 SubExprs.push_back(APIOrderedArgs[1]); // Order 6110 break; 6111 case LoadCopy: 6112 case Copy: 6113 case Arithmetic: 6114 case Xchg: 6115 SubExprs.push_back(APIOrderedArgs[2]); // Order 6116 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6117 break; 6118 case GNUXchg: 6119 // Note, AtomicExpr::getVal2() has a special case for this atomic. 6120 SubExprs.push_back(APIOrderedArgs[3]); // Order 6121 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6122 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6123 break; 6124 case C11CmpXchg: 6125 SubExprs.push_back(APIOrderedArgs[3]); // Order 6126 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6127 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 6128 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6129 break; 6130 case GNUCmpXchg: 6131 SubExprs.push_back(APIOrderedArgs[4]); // Order 6132 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6133 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 6134 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6135 SubExprs.push_back(APIOrderedArgs[3]); // Weak 6136 break; 6137 } 6138 6139 if (SubExprs.size() >= 2 && Form != Init) { 6140 if (Optional<llvm::APSInt> Result = 6141 SubExprs[1]->getIntegerConstantExpr(Context)) 6142 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 6143 Diag(SubExprs[1]->getBeginLoc(), 6144 diag::warn_atomic_op_has_invalid_memory_order) 6145 << SubExprs[1]->getSourceRange(); 6146 } 6147 6148 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 6149 auto *Scope = Args[Args.size() - 1]; 6150 if (Optional<llvm::APSInt> Result = 6151 Scope->getIntegerConstantExpr(Context)) { 6152 if (!ScopeModel->isValid(Result->getZExtValue())) 6153 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 6154 << Scope->getSourceRange(); 6155 } 6156 SubExprs.push_back(Scope); 6157 } 6158 6159 AtomicExpr *AE = new (Context) 6160 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 6161 6162 if ((Op == AtomicExpr::AO__c11_atomic_load || 6163 Op == AtomicExpr::AO__c11_atomic_store || 6164 Op == AtomicExpr::AO__opencl_atomic_load || 6165 Op == AtomicExpr::AO__hip_atomic_load || 6166 Op == AtomicExpr::AO__opencl_atomic_store || 6167 Op == AtomicExpr::AO__hip_atomic_store) && 6168 Context.AtomicUsesUnsupportedLibcall(AE)) 6169 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 6170 << ((Op == AtomicExpr::AO__c11_atomic_load || 6171 Op == AtomicExpr::AO__opencl_atomic_load || 6172 Op == AtomicExpr::AO__hip_atomic_load) 6173 ? 0 6174 : 1); 6175 6176 if (ValType->isBitIntType()) { 6177 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit); 6178 return ExprError(); 6179 } 6180 6181 return AE; 6182 } 6183 6184 /// checkBuiltinArgument - Given a call to a builtin function, perform 6185 /// normal type-checking on the given argument, updating the call in 6186 /// place. This is useful when a builtin function requires custom 6187 /// type-checking for some of its arguments but not necessarily all of 6188 /// them. 6189 /// 6190 /// Returns true on error. 6191 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 6192 FunctionDecl *Fn = E->getDirectCallee(); 6193 assert(Fn && "builtin call without direct callee!"); 6194 6195 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 6196 InitializedEntity Entity = 6197 InitializedEntity::InitializeParameter(S.Context, Param); 6198 6199 ExprResult Arg = E->getArg(0); 6200 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 6201 if (Arg.isInvalid()) 6202 return true; 6203 6204 E->setArg(ArgIndex, Arg.get()); 6205 return false; 6206 } 6207 6208 /// We have a call to a function like __sync_fetch_and_add, which is an 6209 /// overloaded function based on the pointer type of its first argument. 6210 /// The main BuildCallExpr routines have already promoted the types of 6211 /// arguments because all of these calls are prototyped as void(...). 6212 /// 6213 /// This function goes through and does final semantic checking for these 6214 /// builtins, as well as generating any warnings. 6215 ExprResult 6216 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 6217 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 6218 Expr *Callee = TheCall->getCallee(); 6219 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 6220 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6221 6222 // Ensure that we have at least one argument to do type inference from. 6223 if (TheCall->getNumArgs() < 1) { 6224 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6225 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 6226 return ExprError(); 6227 } 6228 6229 // Inspect the first argument of the atomic builtin. This should always be 6230 // a pointer type, whose element is an integral scalar or pointer type. 6231 // Because it is a pointer type, we don't have to worry about any implicit 6232 // casts here. 6233 // FIXME: We don't allow floating point scalars as input. 6234 Expr *FirstArg = TheCall->getArg(0); 6235 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 6236 if (FirstArgResult.isInvalid()) 6237 return ExprError(); 6238 FirstArg = FirstArgResult.get(); 6239 TheCall->setArg(0, FirstArg); 6240 6241 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 6242 if (!pointerType) { 6243 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 6244 << FirstArg->getType() << FirstArg->getSourceRange(); 6245 return ExprError(); 6246 } 6247 6248 QualType ValType = pointerType->getPointeeType(); 6249 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6250 !ValType->isBlockPointerType()) { 6251 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 6252 << FirstArg->getType() << FirstArg->getSourceRange(); 6253 return ExprError(); 6254 } 6255 6256 if (ValType.isConstQualified()) { 6257 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 6258 << FirstArg->getType() << FirstArg->getSourceRange(); 6259 return ExprError(); 6260 } 6261 6262 switch (ValType.getObjCLifetime()) { 6263 case Qualifiers::OCL_None: 6264 case Qualifiers::OCL_ExplicitNone: 6265 // okay 6266 break; 6267 6268 case Qualifiers::OCL_Weak: 6269 case Qualifiers::OCL_Strong: 6270 case Qualifiers::OCL_Autoreleasing: 6271 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 6272 << ValType << FirstArg->getSourceRange(); 6273 return ExprError(); 6274 } 6275 6276 // Strip any qualifiers off ValType. 6277 ValType = ValType.getUnqualifiedType(); 6278 6279 // The majority of builtins return a value, but a few have special return 6280 // types, so allow them to override appropriately below. 6281 QualType ResultType = ValType; 6282 6283 // We need to figure out which concrete builtin this maps onto. For example, 6284 // __sync_fetch_and_add with a 2 byte object turns into 6285 // __sync_fetch_and_add_2. 6286 #define BUILTIN_ROW(x) \ 6287 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 6288 Builtin::BI##x##_8, Builtin::BI##x##_16 } 6289 6290 static const unsigned BuiltinIndices[][5] = { 6291 BUILTIN_ROW(__sync_fetch_and_add), 6292 BUILTIN_ROW(__sync_fetch_and_sub), 6293 BUILTIN_ROW(__sync_fetch_and_or), 6294 BUILTIN_ROW(__sync_fetch_and_and), 6295 BUILTIN_ROW(__sync_fetch_and_xor), 6296 BUILTIN_ROW(__sync_fetch_and_nand), 6297 6298 BUILTIN_ROW(__sync_add_and_fetch), 6299 BUILTIN_ROW(__sync_sub_and_fetch), 6300 BUILTIN_ROW(__sync_and_and_fetch), 6301 BUILTIN_ROW(__sync_or_and_fetch), 6302 BUILTIN_ROW(__sync_xor_and_fetch), 6303 BUILTIN_ROW(__sync_nand_and_fetch), 6304 6305 BUILTIN_ROW(__sync_val_compare_and_swap), 6306 BUILTIN_ROW(__sync_bool_compare_and_swap), 6307 BUILTIN_ROW(__sync_lock_test_and_set), 6308 BUILTIN_ROW(__sync_lock_release), 6309 BUILTIN_ROW(__sync_swap) 6310 }; 6311 #undef BUILTIN_ROW 6312 6313 // Determine the index of the size. 6314 unsigned SizeIndex; 6315 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 6316 case 1: SizeIndex = 0; break; 6317 case 2: SizeIndex = 1; break; 6318 case 4: SizeIndex = 2; break; 6319 case 8: SizeIndex = 3; break; 6320 case 16: SizeIndex = 4; break; 6321 default: 6322 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 6323 << FirstArg->getType() << FirstArg->getSourceRange(); 6324 return ExprError(); 6325 } 6326 6327 // Each of these builtins has one pointer argument, followed by some number of 6328 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 6329 // that we ignore. Find out which row of BuiltinIndices to read from as well 6330 // as the number of fixed args. 6331 unsigned BuiltinID = FDecl->getBuiltinID(); 6332 unsigned BuiltinIndex, NumFixed = 1; 6333 bool WarnAboutSemanticsChange = false; 6334 switch (BuiltinID) { 6335 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 6336 case Builtin::BI__sync_fetch_and_add: 6337 case Builtin::BI__sync_fetch_and_add_1: 6338 case Builtin::BI__sync_fetch_and_add_2: 6339 case Builtin::BI__sync_fetch_and_add_4: 6340 case Builtin::BI__sync_fetch_and_add_8: 6341 case Builtin::BI__sync_fetch_and_add_16: 6342 BuiltinIndex = 0; 6343 break; 6344 6345 case Builtin::BI__sync_fetch_and_sub: 6346 case Builtin::BI__sync_fetch_and_sub_1: 6347 case Builtin::BI__sync_fetch_and_sub_2: 6348 case Builtin::BI__sync_fetch_and_sub_4: 6349 case Builtin::BI__sync_fetch_and_sub_8: 6350 case Builtin::BI__sync_fetch_and_sub_16: 6351 BuiltinIndex = 1; 6352 break; 6353 6354 case Builtin::BI__sync_fetch_and_or: 6355 case Builtin::BI__sync_fetch_and_or_1: 6356 case Builtin::BI__sync_fetch_and_or_2: 6357 case Builtin::BI__sync_fetch_and_or_4: 6358 case Builtin::BI__sync_fetch_and_or_8: 6359 case Builtin::BI__sync_fetch_and_or_16: 6360 BuiltinIndex = 2; 6361 break; 6362 6363 case Builtin::BI__sync_fetch_and_and: 6364 case Builtin::BI__sync_fetch_and_and_1: 6365 case Builtin::BI__sync_fetch_and_and_2: 6366 case Builtin::BI__sync_fetch_and_and_4: 6367 case Builtin::BI__sync_fetch_and_and_8: 6368 case Builtin::BI__sync_fetch_and_and_16: 6369 BuiltinIndex = 3; 6370 break; 6371 6372 case Builtin::BI__sync_fetch_and_xor: 6373 case Builtin::BI__sync_fetch_and_xor_1: 6374 case Builtin::BI__sync_fetch_and_xor_2: 6375 case Builtin::BI__sync_fetch_and_xor_4: 6376 case Builtin::BI__sync_fetch_and_xor_8: 6377 case Builtin::BI__sync_fetch_and_xor_16: 6378 BuiltinIndex = 4; 6379 break; 6380 6381 case Builtin::BI__sync_fetch_and_nand: 6382 case Builtin::BI__sync_fetch_and_nand_1: 6383 case Builtin::BI__sync_fetch_and_nand_2: 6384 case Builtin::BI__sync_fetch_and_nand_4: 6385 case Builtin::BI__sync_fetch_and_nand_8: 6386 case Builtin::BI__sync_fetch_and_nand_16: 6387 BuiltinIndex = 5; 6388 WarnAboutSemanticsChange = true; 6389 break; 6390 6391 case Builtin::BI__sync_add_and_fetch: 6392 case Builtin::BI__sync_add_and_fetch_1: 6393 case Builtin::BI__sync_add_and_fetch_2: 6394 case Builtin::BI__sync_add_and_fetch_4: 6395 case Builtin::BI__sync_add_and_fetch_8: 6396 case Builtin::BI__sync_add_and_fetch_16: 6397 BuiltinIndex = 6; 6398 break; 6399 6400 case Builtin::BI__sync_sub_and_fetch: 6401 case Builtin::BI__sync_sub_and_fetch_1: 6402 case Builtin::BI__sync_sub_and_fetch_2: 6403 case Builtin::BI__sync_sub_and_fetch_4: 6404 case Builtin::BI__sync_sub_and_fetch_8: 6405 case Builtin::BI__sync_sub_and_fetch_16: 6406 BuiltinIndex = 7; 6407 break; 6408 6409 case Builtin::BI__sync_and_and_fetch: 6410 case Builtin::BI__sync_and_and_fetch_1: 6411 case Builtin::BI__sync_and_and_fetch_2: 6412 case Builtin::BI__sync_and_and_fetch_4: 6413 case Builtin::BI__sync_and_and_fetch_8: 6414 case Builtin::BI__sync_and_and_fetch_16: 6415 BuiltinIndex = 8; 6416 break; 6417 6418 case Builtin::BI__sync_or_and_fetch: 6419 case Builtin::BI__sync_or_and_fetch_1: 6420 case Builtin::BI__sync_or_and_fetch_2: 6421 case Builtin::BI__sync_or_and_fetch_4: 6422 case Builtin::BI__sync_or_and_fetch_8: 6423 case Builtin::BI__sync_or_and_fetch_16: 6424 BuiltinIndex = 9; 6425 break; 6426 6427 case Builtin::BI__sync_xor_and_fetch: 6428 case Builtin::BI__sync_xor_and_fetch_1: 6429 case Builtin::BI__sync_xor_and_fetch_2: 6430 case Builtin::BI__sync_xor_and_fetch_4: 6431 case Builtin::BI__sync_xor_and_fetch_8: 6432 case Builtin::BI__sync_xor_and_fetch_16: 6433 BuiltinIndex = 10; 6434 break; 6435 6436 case Builtin::BI__sync_nand_and_fetch: 6437 case Builtin::BI__sync_nand_and_fetch_1: 6438 case Builtin::BI__sync_nand_and_fetch_2: 6439 case Builtin::BI__sync_nand_and_fetch_4: 6440 case Builtin::BI__sync_nand_and_fetch_8: 6441 case Builtin::BI__sync_nand_and_fetch_16: 6442 BuiltinIndex = 11; 6443 WarnAboutSemanticsChange = true; 6444 break; 6445 6446 case Builtin::BI__sync_val_compare_and_swap: 6447 case Builtin::BI__sync_val_compare_and_swap_1: 6448 case Builtin::BI__sync_val_compare_and_swap_2: 6449 case Builtin::BI__sync_val_compare_and_swap_4: 6450 case Builtin::BI__sync_val_compare_and_swap_8: 6451 case Builtin::BI__sync_val_compare_and_swap_16: 6452 BuiltinIndex = 12; 6453 NumFixed = 2; 6454 break; 6455 6456 case Builtin::BI__sync_bool_compare_and_swap: 6457 case Builtin::BI__sync_bool_compare_and_swap_1: 6458 case Builtin::BI__sync_bool_compare_and_swap_2: 6459 case Builtin::BI__sync_bool_compare_and_swap_4: 6460 case Builtin::BI__sync_bool_compare_and_swap_8: 6461 case Builtin::BI__sync_bool_compare_and_swap_16: 6462 BuiltinIndex = 13; 6463 NumFixed = 2; 6464 ResultType = Context.BoolTy; 6465 break; 6466 6467 case Builtin::BI__sync_lock_test_and_set: 6468 case Builtin::BI__sync_lock_test_and_set_1: 6469 case Builtin::BI__sync_lock_test_and_set_2: 6470 case Builtin::BI__sync_lock_test_and_set_4: 6471 case Builtin::BI__sync_lock_test_and_set_8: 6472 case Builtin::BI__sync_lock_test_and_set_16: 6473 BuiltinIndex = 14; 6474 break; 6475 6476 case Builtin::BI__sync_lock_release: 6477 case Builtin::BI__sync_lock_release_1: 6478 case Builtin::BI__sync_lock_release_2: 6479 case Builtin::BI__sync_lock_release_4: 6480 case Builtin::BI__sync_lock_release_8: 6481 case Builtin::BI__sync_lock_release_16: 6482 BuiltinIndex = 15; 6483 NumFixed = 0; 6484 ResultType = Context.VoidTy; 6485 break; 6486 6487 case Builtin::BI__sync_swap: 6488 case Builtin::BI__sync_swap_1: 6489 case Builtin::BI__sync_swap_2: 6490 case Builtin::BI__sync_swap_4: 6491 case Builtin::BI__sync_swap_8: 6492 case Builtin::BI__sync_swap_16: 6493 BuiltinIndex = 16; 6494 break; 6495 } 6496 6497 // Now that we know how many fixed arguments we expect, first check that we 6498 // have at least that many. 6499 if (TheCall->getNumArgs() < 1+NumFixed) { 6500 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6501 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6502 << Callee->getSourceRange(); 6503 return ExprError(); 6504 } 6505 6506 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6507 << Callee->getSourceRange(); 6508 6509 if (WarnAboutSemanticsChange) { 6510 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6511 << Callee->getSourceRange(); 6512 } 6513 6514 // Get the decl for the concrete builtin from this, we can tell what the 6515 // concrete integer type we should convert to is. 6516 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6517 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6518 FunctionDecl *NewBuiltinDecl; 6519 if (NewBuiltinID == BuiltinID) 6520 NewBuiltinDecl = FDecl; 6521 else { 6522 // Perform builtin lookup to avoid redeclaring it. 6523 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6524 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6525 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6526 assert(Res.getFoundDecl()); 6527 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6528 if (!NewBuiltinDecl) 6529 return ExprError(); 6530 } 6531 6532 // The first argument --- the pointer --- has a fixed type; we 6533 // deduce the types of the rest of the arguments accordingly. Walk 6534 // the remaining arguments, converting them to the deduced value type. 6535 for (unsigned i = 0; i != NumFixed; ++i) { 6536 ExprResult Arg = TheCall->getArg(i+1); 6537 6538 // GCC does an implicit conversion to the pointer or integer ValType. This 6539 // can fail in some cases (1i -> int**), check for this error case now. 6540 // Initialize the argument. 6541 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6542 ValType, /*consume*/ false); 6543 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6544 if (Arg.isInvalid()) 6545 return ExprError(); 6546 6547 // Okay, we have something that *can* be converted to the right type. Check 6548 // to see if there is a potentially weird extension going on here. This can 6549 // happen when you do an atomic operation on something like an char* and 6550 // pass in 42. The 42 gets converted to char. This is even more strange 6551 // for things like 45.123 -> char, etc. 6552 // FIXME: Do this check. 6553 TheCall->setArg(i+1, Arg.get()); 6554 } 6555 6556 // Create a new DeclRefExpr to refer to the new decl. 6557 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6558 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6559 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6560 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6561 6562 // Set the callee in the CallExpr. 6563 // FIXME: This loses syntactic information. 6564 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6565 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6566 CK_BuiltinFnToFnPtr); 6567 TheCall->setCallee(PromotedCall.get()); 6568 6569 // Change the result type of the call to match the original value type. This 6570 // is arbitrary, but the codegen for these builtins ins design to handle it 6571 // gracefully. 6572 TheCall->setType(ResultType); 6573 6574 // Prohibit problematic uses of bit-precise integer types with atomic 6575 // builtins. The arguments would have already been converted to the first 6576 // argument's type, so only need to check the first argument. 6577 const auto *BitIntValType = ValType->getAs<BitIntType>(); 6578 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) { 6579 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6580 return ExprError(); 6581 } 6582 6583 return TheCallResult; 6584 } 6585 6586 /// SemaBuiltinNontemporalOverloaded - We have a call to 6587 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6588 /// overloaded function based on the pointer type of its last argument. 6589 /// 6590 /// This function goes through and does final semantic checking for these 6591 /// builtins. 6592 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6593 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6594 DeclRefExpr *DRE = 6595 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6596 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6597 unsigned BuiltinID = FDecl->getBuiltinID(); 6598 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6599 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6600 "Unexpected nontemporal load/store builtin!"); 6601 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6602 unsigned numArgs = isStore ? 2 : 1; 6603 6604 // Ensure that we have the proper number of arguments. 6605 if (checkArgCount(*this, TheCall, numArgs)) 6606 return ExprError(); 6607 6608 // Inspect the last argument of the nontemporal builtin. This should always 6609 // be a pointer type, from which we imply the type of the memory access. 6610 // Because it is a pointer type, we don't have to worry about any implicit 6611 // casts here. 6612 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6613 ExprResult PointerArgResult = 6614 DefaultFunctionArrayLvalueConversion(PointerArg); 6615 6616 if (PointerArgResult.isInvalid()) 6617 return ExprError(); 6618 PointerArg = PointerArgResult.get(); 6619 TheCall->setArg(numArgs - 1, PointerArg); 6620 6621 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6622 if (!pointerType) { 6623 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6624 << PointerArg->getType() << PointerArg->getSourceRange(); 6625 return ExprError(); 6626 } 6627 6628 QualType ValType = pointerType->getPointeeType(); 6629 6630 // Strip any qualifiers off ValType. 6631 ValType = ValType.getUnqualifiedType(); 6632 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6633 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6634 !ValType->isVectorType()) { 6635 Diag(DRE->getBeginLoc(), 6636 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6637 << PointerArg->getType() << PointerArg->getSourceRange(); 6638 return ExprError(); 6639 } 6640 6641 if (!isStore) { 6642 TheCall->setType(ValType); 6643 return TheCallResult; 6644 } 6645 6646 ExprResult ValArg = TheCall->getArg(0); 6647 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6648 Context, ValType, /*consume*/ false); 6649 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6650 if (ValArg.isInvalid()) 6651 return ExprError(); 6652 6653 TheCall->setArg(0, ValArg.get()); 6654 TheCall->setType(Context.VoidTy); 6655 return TheCallResult; 6656 } 6657 6658 /// CheckObjCString - Checks that the argument to the builtin 6659 /// CFString constructor is correct 6660 /// Note: It might also make sense to do the UTF-16 conversion here (would 6661 /// simplify the backend). 6662 bool Sema::CheckObjCString(Expr *Arg) { 6663 Arg = Arg->IgnoreParenCasts(); 6664 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6665 6666 if (!Literal || !Literal->isAscii()) { 6667 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6668 << Arg->getSourceRange(); 6669 return true; 6670 } 6671 6672 if (Literal->containsNonAsciiOrNull()) { 6673 StringRef String = Literal->getString(); 6674 unsigned NumBytes = String.size(); 6675 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6676 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6677 llvm::UTF16 *ToPtr = &ToBuf[0]; 6678 6679 llvm::ConversionResult Result = 6680 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6681 ToPtr + NumBytes, llvm::strictConversion); 6682 // Check for conversion failure. 6683 if (Result != llvm::conversionOK) 6684 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6685 << Arg->getSourceRange(); 6686 } 6687 return false; 6688 } 6689 6690 /// CheckObjCString - Checks that the format string argument to the os_log() 6691 /// and os_trace() functions is correct, and converts it to const char *. 6692 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6693 Arg = Arg->IgnoreParenCasts(); 6694 auto *Literal = dyn_cast<StringLiteral>(Arg); 6695 if (!Literal) { 6696 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6697 Literal = ObjcLiteral->getString(); 6698 } 6699 } 6700 6701 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6702 return ExprError( 6703 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6704 << Arg->getSourceRange()); 6705 } 6706 6707 ExprResult Result(Literal); 6708 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6709 InitializedEntity Entity = 6710 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6711 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6712 return Result; 6713 } 6714 6715 /// Check that the user is calling the appropriate va_start builtin for the 6716 /// target and calling convention. 6717 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6718 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6719 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6720 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6721 TT.getArch() == llvm::Triple::aarch64_32); 6722 bool IsWindows = TT.isOSWindows(); 6723 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6724 if (IsX64 || IsAArch64) { 6725 CallingConv CC = CC_C; 6726 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6727 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6728 if (IsMSVAStart) { 6729 // Don't allow this in System V ABI functions. 6730 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6731 return S.Diag(Fn->getBeginLoc(), 6732 diag::err_ms_va_start_used_in_sysv_function); 6733 } else { 6734 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6735 // On x64 Windows, don't allow this in System V ABI functions. 6736 // (Yes, that means there's no corresponding way to support variadic 6737 // System V ABI functions on Windows.) 6738 if ((IsWindows && CC == CC_X86_64SysV) || 6739 (!IsWindows && CC == CC_Win64)) 6740 return S.Diag(Fn->getBeginLoc(), 6741 diag::err_va_start_used_in_wrong_abi_function) 6742 << !IsWindows; 6743 } 6744 return false; 6745 } 6746 6747 if (IsMSVAStart) 6748 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6749 return false; 6750 } 6751 6752 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6753 ParmVarDecl **LastParam = nullptr) { 6754 // Determine whether the current function, block, or obj-c method is variadic 6755 // and get its parameter list. 6756 bool IsVariadic = false; 6757 ArrayRef<ParmVarDecl *> Params; 6758 DeclContext *Caller = S.CurContext; 6759 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6760 IsVariadic = Block->isVariadic(); 6761 Params = Block->parameters(); 6762 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6763 IsVariadic = FD->isVariadic(); 6764 Params = FD->parameters(); 6765 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6766 IsVariadic = MD->isVariadic(); 6767 // FIXME: This isn't correct for methods (results in bogus warning). 6768 Params = MD->parameters(); 6769 } else if (isa<CapturedDecl>(Caller)) { 6770 // We don't support va_start in a CapturedDecl. 6771 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6772 return true; 6773 } else { 6774 // This must be some other declcontext that parses exprs. 6775 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6776 return true; 6777 } 6778 6779 if (!IsVariadic) { 6780 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6781 return true; 6782 } 6783 6784 if (LastParam) 6785 *LastParam = Params.empty() ? nullptr : Params.back(); 6786 6787 return false; 6788 } 6789 6790 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6791 /// for validity. Emit an error and return true on failure; return false 6792 /// on success. 6793 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6794 Expr *Fn = TheCall->getCallee(); 6795 6796 if (checkVAStartABI(*this, BuiltinID, Fn)) 6797 return true; 6798 6799 if (checkArgCount(*this, TheCall, 2)) 6800 return true; 6801 6802 // Type-check the first argument normally. 6803 if (checkBuiltinArgument(*this, TheCall, 0)) 6804 return true; 6805 6806 // Check that the current function is variadic, and get its last parameter. 6807 ParmVarDecl *LastParam; 6808 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6809 return true; 6810 6811 // Verify that the second argument to the builtin is the last argument of the 6812 // current function or method. 6813 bool SecondArgIsLastNamedArgument = false; 6814 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6815 6816 // These are valid if SecondArgIsLastNamedArgument is false after the next 6817 // block. 6818 QualType Type; 6819 SourceLocation ParamLoc; 6820 bool IsCRegister = false; 6821 6822 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6823 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6824 SecondArgIsLastNamedArgument = PV == LastParam; 6825 6826 Type = PV->getType(); 6827 ParamLoc = PV->getLocation(); 6828 IsCRegister = 6829 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6830 } 6831 } 6832 6833 if (!SecondArgIsLastNamedArgument) 6834 Diag(TheCall->getArg(1)->getBeginLoc(), 6835 diag::warn_second_arg_of_va_start_not_last_named_param); 6836 else if (IsCRegister || Type->isReferenceType() || 6837 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6838 // Promotable integers are UB, but enumerations need a bit of 6839 // extra checking to see what their promotable type actually is. 6840 if (!Type->isPromotableIntegerType()) 6841 return false; 6842 if (!Type->isEnumeralType()) 6843 return true; 6844 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6845 return !(ED && 6846 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6847 }()) { 6848 unsigned Reason = 0; 6849 if (Type->isReferenceType()) Reason = 1; 6850 else if (IsCRegister) Reason = 2; 6851 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6852 Diag(ParamLoc, diag::note_parameter_type) << Type; 6853 } 6854 6855 TheCall->setType(Context.VoidTy); 6856 return false; 6857 } 6858 6859 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6860 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6861 const LangOptions &LO = getLangOpts(); 6862 6863 if (LO.CPlusPlus) 6864 return Arg->getType() 6865 .getCanonicalType() 6866 .getTypePtr() 6867 ->getPointeeType() 6868 .withoutLocalFastQualifiers() == Context.CharTy; 6869 6870 // In C, allow aliasing through `char *`, this is required for AArch64 at 6871 // least. 6872 return true; 6873 }; 6874 6875 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6876 // const char *named_addr); 6877 6878 Expr *Func = Call->getCallee(); 6879 6880 if (Call->getNumArgs() < 3) 6881 return Diag(Call->getEndLoc(), 6882 diag::err_typecheck_call_too_few_args_at_least) 6883 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6884 6885 // Type-check the first argument normally. 6886 if (checkBuiltinArgument(*this, Call, 0)) 6887 return true; 6888 6889 // Check that the current function is variadic. 6890 if (checkVAStartIsInVariadicFunction(*this, Func)) 6891 return true; 6892 6893 // __va_start on Windows does not validate the parameter qualifiers 6894 6895 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6896 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6897 6898 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6899 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6900 6901 const QualType &ConstCharPtrTy = 6902 Context.getPointerType(Context.CharTy.withConst()); 6903 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6904 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6905 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6906 << 0 /* qualifier difference */ 6907 << 3 /* parameter mismatch */ 6908 << 2 << Arg1->getType() << ConstCharPtrTy; 6909 6910 const QualType SizeTy = Context.getSizeType(); 6911 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6912 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6913 << Arg2->getType() << SizeTy << 1 /* different class */ 6914 << 0 /* qualifier difference */ 6915 << 3 /* parameter mismatch */ 6916 << 3 << Arg2->getType() << SizeTy; 6917 6918 return false; 6919 } 6920 6921 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6922 /// friends. This is declared to take (...), so we have to check everything. 6923 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6924 if (checkArgCount(*this, TheCall, 2)) 6925 return true; 6926 6927 ExprResult OrigArg0 = TheCall->getArg(0); 6928 ExprResult OrigArg1 = TheCall->getArg(1); 6929 6930 // Do standard promotions between the two arguments, returning their common 6931 // type. 6932 QualType Res = UsualArithmeticConversions( 6933 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6934 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6935 return true; 6936 6937 // Make sure any conversions are pushed back into the call; this is 6938 // type safe since unordered compare builtins are declared as "_Bool 6939 // foo(...)". 6940 TheCall->setArg(0, OrigArg0.get()); 6941 TheCall->setArg(1, OrigArg1.get()); 6942 6943 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6944 return false; 6945 6946 // If the common type isn't a real floating type, then the arguments were 6947 // invalid for this operation. 6948 if (Res.isNull() || !Res->isRealFloatingType()) 6949 return Diag(OrigArg0.get()->getBeginLoc(), 6950 diag::err_typecheck_call_invalid_ordered_compare) 6951 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6952 << SourceRange(OrigArg0.get()->getBeginLoc(), 6953 OrigArg1.get()->getEndLoc()); 6954 6955 return false; 6956 } 6957 6958 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6959 /// __builtin_isnan and friends. This is declared to take (...), so we have 6960 /// to check everything. We expect the last argument to be a floating point 6961 /// value. 6962 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6963 if (checkArgCount(*this, TheCall, NumArgs)) 6964 return true; 6965 6966 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6967 // on all preceding parameters just being int. Try all of those. 6968 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6969 Expr *Arg = TheCall->getArg(i); 6970 6971 if (Arg->isTypeDependent()) 6972 return false; 6973 6974 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6975 6976 if (Res.isInvalid()) 6977 return true; 6978 TheCall->setArg(i, Res.get()); 6979 } 6980 6981 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6982 6983 if (OrigArg->isTypeDependent()) 6984 return false; 6985 6986 // Usual Unary Conversions will convert half to float, which we want for 6987 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6988 // type how it is, but do normal L->Rvalue conversions. 6989 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6990 OrigArg = UsualUnaryConversions(OrigArg).get(); 6991 else 6992 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6993 TheCall->setArg(NumArgs - 1, OrigArg); 6994 6995 // This operation requires a non-_Complex floating-point number. 6996 if (!OrigArg->getType()->isRealFloatingType()) 6997 return Diag(OrigArg->getBeginLoc(), 6998 diag::err_typecheck_call_invalid_unary_fp) 6999 << OrigArg->getType() << OrigArg->getSourceRange(); 7000 7001 return false; 7002 } 7003 7004 /// Perform semantic analysis for a call to __builtin_complex. 7005 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 7006 if (checkArgCount(*this, TheCall, 2)) 7007 return true; 7008 7009 bool Dependent = false; 7010 for (unsigned I = 0; I != 2; ++I) { 7011 Expr *Arg = TheCall->getArg(I); 7012 QualType T = Arg->getType(); 7013 if (T->isDependentType()) { 7014 Dependent = true; 7015 continue; 7016 } 7017 7018 // Despite supporting _Complex int, GCC requires a real floating point type 7019 // for the operands of __builtin_complex. 7020 if (!T->isRealFloatingType()) { 7021 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 7022 << Arg->getType() << Arg->getSourceRange(); 7023 } 7024 7025 ExprResult Converted = DefaultLvalueConversion(Arg); 7026 if (Converted.isInvalid()) 7027 return true; 7028 TheCall->setArg(I, Converted.get()); 7029 } 7030 7031 if (Dependent) { 7032 TheCall->setType(Context.DependentTy); 7033 return false; 7034 } 7035 7036 Expr *Real = TheCall->getArg(0); 7037 Expr *Imag = TheCall->getArg(1); 7038 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 7039 return Diag(Real->getBeginLoc(), 7040 diag::err_typecheck_call_different_arg_types) 7041 << Real->getType() << Imag->getType() 7042 << Real->getSourceRange() << Imag->getSourceRange(); 7043 } 7044 7045 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 7046 // don't allow this builtin to form those types either. 7047 // FIXME: Should we allow these types? 7048 if (Real->getType()->isFloat16Type()) 7049 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 7050 << "_Float16"; 7051 if (Real->getType()->isHalfType()) 7052 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 7053 << "half"; 7054 7055 TheCall->setType(Context.getComplexType(Real->getType())); 7056 return false; 7057 } 7058 7059 // Customized Sema Checking for VSX builtins that have the following signature: 7060 // vector [...] builtinName(vector [...], vector [...], const int); 7061 // Which takes the same type of vectors (any legal vector type) for the first 7062 // two arguments and takes compile time constant for the third argument. 7063 // Example builtins are : 7064 // vector double vec_xxpermdi(vector double, vector double, int); 7065 // vector short vec_xxsldwi(vector short, vector short, int); 7066 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 7067 unsigned ExpectedNumArgs = 3; 7068 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 7069 return true; 7070 7071 // Check the third argument is a compile time constant 7072 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 7073 return Diag(TheCall->getBeginLoc(), 7074 diag::err_vsx_builtin_nonconstant_argument) 7075 << 3 /* argument index */ << TheCall->getDirectCallee() 7076 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 7077 TheCall->getArg(2)->getEndLoc()); 7078 7079 QualType Arg1Ty = TheCall->getArg(0)->getType(); 7080 QualType Arg2Ty = TheCall->getArg(1)->getType(); 7081 7082 // Check the type of argument 1 and argument 2 are vectors. 7083 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 7084 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 7085 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 7086 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 7087 << TheCall->getDirectCallee() 7088 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7089 TheCall->getArg(1)->getEndLoc()); 7090 } 7091 7092 // Check the first two arguments are the same type. 7093 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 7094 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 7095 << TheCall->getDirectCallee() 7096 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7097 TheCall->getArg(1)->getEndLoc()); 7098 } 7099 7100 // When default clang type checking is turned off and the customized type 7101 // checking is used, the returning type of the function must be explicitly 7102 // set. Otherwise it is _Bool by default. 7103 TheCall->setType(Arg1Ty); 7104 7105 return false; 7106 } 7107 7108 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 7109 // This is declared to take (...), so we have to check everything. 7110 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 7111 if (TheCall->getNumArgs() < 2) 7112 return ExprError(Diag(TheCall->getEndLoc(), 7113 diag::err_typecheck_call_too_few_args_at_least) 7114 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 7115 << TheCall->getSourceRange()); 7116 7117 // Determine which of the following types of shufflevector we're checking: 7118 // 1) unary, vector mask: (lhs, mask) 7119 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 7120 QualType resType = TheCall->getArg(0)->getType(); 7121 unsigned numElements = 0; 7122 7123 if (!TheCall->getArg(0)->isTypeDependent() && 7124 !TheCall->getArg(1)->isTypeDependent()) { 7125 QualType LHSType = TheCall->getArg(0)->getType(); 7126 QualType RHSType = TheCall->getArg(1)->getType(); 7127 7128 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 7129 return ExprError( 7130 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 7131 << TheCall->getDirectCallee() 7132 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7133 TheCall->getArg(1)->getEndLoc())); 7134 7135 numElements = LHSType->castAs<VectorType>()->getNumElements(); 7136 unsigned numResElements = TheCall->getNumArgs() - 2; 7137 7138 // Check to see if we have a call with 2 vector arguments, the unary shuffle 7139 // with mask. If so, verify that RHS is an integer vector type with the 7140 // same number of elts as lhs. 7141 if (TheCall->getNumArgs() == 2) { 7142 if (!RHSType->hasIntegerRepresentation() || 7143 RHSType->castAs<VectorType>()->getNumElements() != numElements) 7144 return ExprError(Diag(TheCall->getBeginLoc(), 7145 diag::err_vec_builtin_incompatible_vector) 7146 << TheCall->getDirectCallee() 7147 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 7148 TheCall->getArg(1)->getEndLoc())); 7149 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 7150 return ExprError(Diag(TheCall->getBeginLoc(), 7151 diag::err_vec_builtin_incompatible_vector) 7152 << TheCall->getDirectCallee() 7153 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7154 TheCall->getArg(1)->getEndLoc())); 7155 } else if (numElements != numResElements) { 7156 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 7157 resType = Context.getVectorType(eltType, numResElements, 7158 VectorType::GenericVector); 7159 } 7160 } 7161 7162 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 7163 if (TheCall->getArg(i)->isTypeDependent() || 7164 TheCall->getArg(i)->isValueDependent()) 7165 continue; 7166 7167 Optional<llvm::APSInt> Result; 7168 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 7169 return ExprError(Diag(TheCall->getBeginLoc(), 7170 diag::err_shufflevector_nonconstant_argument) 7171 << TheCall->getArg(i)->getSourceRange()); 7172 7173 // Allow -1 which will be translated to undef in the IR. 7174 if (Result->isSigned() && Result->isAllOnes()) 7175 continue; 7176 7177 if (Result->getActiveBits() > 64 || 7178 Result->getZExtValue() >= numElements * 2) 7179 return ExprError(Diag(TheCall->getBeginLoc(), 7180 diag::err_shufflevector_argument_too_large) 7181 << TheCall->getArg(i)->getSourceRange()); 7182 } 7183 7184 SmallVector<Expr*, 32> exprs; 7185 7186 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 7187 exprs.push_back(TheCall->getArg(i)); 7188 TheCall->setArg(i, nullptr); 7189 } 7190 7191 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 7192 TheCall->getCallee()->getBeginLoc(), 7193 TheCall->getRParenLoc()); 7194 } 7195 7196 /// SemaConvertVectorExpr - Handle __builtin_convertvector 7197 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 7198 SourceLocation BuiltinLoc, 7199 SourceLocation RParenLoc) { 7200 ExprValueKind VK = VK_PRValue; 7201 ExprObjectKind OK = OK_Ordinary; 7202 QualType DstTy = TInfo->getType(); 7203 QualType SrcTy = E->getType(); 7204 7205 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 7206 return ExprError(Diag(BuiltinLoc, 7207 diag::err_convertvector_non_vector) 7208 << E->getSourceRange()); 7209 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 7210 return ExprError(Diag(BuiltinLoc, 7211 diag::err_convertvector_non_vector_type)); 7212 7213 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 7214 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 7215 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 7216 if (SrcElts != DstElts) 7217 return ExprError(Diag(BuiltinLoc, 7218 diag::err_convertvector_incompatible_vector) 7219 << E->getSourceRange()); 7220 } 7221 7222 return new (Context) 7223 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 7224 } 7225 7226 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 7227 // This is declared to take (const void*, ...) and can take two 7228 // optional constant int args. 7229 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 7230 unsigned NumArgs = TheCall->getNumArgs(); 7231 7232 if (NumArgs > 3) 7233 return Diag(TheCall->getEndLoc(), 7234 diag::err_typecheck_call_too_many_args_at_most) 7235 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7236 7237 // Argument 0 is checked for us and the remaining arguments must be 7238 // constant integers. 7239 for (unsigned i = 1; i != NumArgs; ++i) 7240 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 7241 return true; 7242 7243 return false; 7244 } 7245 7246 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 7247 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 7248 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 7249 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 7250 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7251 if (checkArgCount(*this, TheCall, 1)) 7252 return true; 7253 Expr *Arg = TheCall->getArg(0); 7254 if (Arg->isInstantiationDependent()) 7255 return false; 7256 7257 QualType ArgTy = Arg->getType(); 7258 if (!ArgTy->hasFloatingRepresentation()) 7259 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 7260 << ArgTy; 7261 if (Arg->isLValue()) { 7262 ExprResult FirstArg = DefaultLvalueConversion(Arg); 7263 TheCall->setArg(0, FirstArg.get()); 7264 } 7265 TheCall->setType(TheCall->getArg(0)->getType()); 7266 return false; 7267 } 7268 7269 /// SemaBuiltinAssume - Handle __assume (MS Extension). 7270 // __assume does not evaluate its arguments, and should warn if its argument 7271 // has side effects. 7272 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 7273 Expr *Arg = TheCall->getArg(0); 7274 if (Arg->isInstantiationDependent()) return false; 7275 7276 if (Arg->HasSideEffects(Context)) 7277 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 7278 << Arg->getSourceRange() 7279 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 7280 7281 return false; 7282 } 7283 7284 /// Handle __builtin_alloca_with_align. This is declared 7285 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 7286 /// than 8. 7287 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 7288 // The alignment must be a constant integer. 7289 Expr *Arg = TheCall->getArg(1); 7290 7291 // We can't check the value of a dependent argument. 7292 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7293 if (const auto *UE = 7294 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 7295 if (UE->getKind() == UETT_AlignOf || 7296 UE->getKind() == UETT_PreferredAlignOf) 7297 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 7298 << Arg->getSourceRange(); 7299 7300 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 7301 7302 if (!Result.isPowerOf2()) 7303 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7304 << Arg->getSourceRange(); 7305 7306 if (Result < Context.getCharWidth()) 7307 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 7308 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 7309 7310 if (Result > std::numeric_limits<int32_t>::max()) 7311 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 7312 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 7313 } 7314 7315 return false; 7316 } 7317 7318 /// Handle __builtin_assume_aligned. This is declared 7319 /// as (const void*, size_t, ...) and can take one optional constant int arg. 7320 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 7321 unsigned NumArgs = TheCall->getNumArgs(); 7322 7323 if (NumArgs > 3) 7324 return Diag(TheCall->getEndLoc(), 7325 diag::err_typecheck_call_too_many_args_at_most) 7326 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7327 7328 // The alignment must be a constant integer. 7329 Expr *Arg = TheCall->getArg(1); 7330 7331 // We can't check the value of a dependent argument. 7332 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7333 llvm::APSInt Result; 7334 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7335 return true; 7336 7337 if (!Result.isPowerOf2()) 7338 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7339 << Arg->getSourceRange(); 7340 7341 if (Result > Sema::MaximumAlignment) 7342 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 7343 << Arg->getSourceRange() << Sema::MaximumAlignment; 7344 } 7345 7346 if (NumArgs > 2) { 7347 ExprResult Arg(TheCall->getArg(2)); 7348 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 7349 Context.getSizeType(), false); 7350 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7351 if (Arg.isInvalid()) return true; 7352 TheCall->setArg(2, Arg.get()); 7353 } 7354 7355 return false; 7356 } 7357 7358 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 7359 unsigned BuiltinID = 7360 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 7361 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 7362 7363 unsigned NumArgs = TheCall->getNumArgs(); 7364 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 7365 if (NumArgs < NumRequiredArgs) { 7366 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 7367 << 0 /* function call */ << NumRequiredArgs << NumArgs 7368 << TheCall->getSourceRange(); 7369 } 7370 if (NumArgs >= NumRequiredArgs + 0x100) { 7371 return Diag(TheCall->getEndLoc(), 7372 diag::err_typecheck_call_too_many_args_at_most) 7373 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 7374 << TheCall->getSourceRange(); 7375 } 7376 unsigned i = 0; 7377 7378 // For formatting call, check buffer arg. 7379 if (!IsSizeCall) { 7380 ExprResult Arg(TheCall->getArg(i)); 7381 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7382 Context, Context.VoidPtrTy, false); 7383 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7384 if (Arg.isInvalid()) 7385 return true; 7386 TheCall->setArg(i, Arg.get()); 7387 i++; 7388 } 7389 7390 // Check string literal arg. 7391 unsigned FormatIdx = i; 7392 { 7393 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7394 if (Arg.isInvalid()) 7395 return true; 7396 TheCall->setArg(i, Arg.get()); 7397 i++; 7398 } 7399 7400 // Make sure variadic args are scalar. 7401 unsigned FirstDataArg = i; 7402 while (i < NumArgs) { 7403 ExprResult Arg = DefaultVariadicArgumentPromotion( 7404 TheCall->getArg(i), VariadicFunction, nullptr); 7405 if (Arg.isInvalid()) 7406 return true; 7407 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7408 if (ArgSize.getQuantity() >= 0x100) { 7409 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7410 << i << (int)ArgSize.getQuantity() << 0xff 7411 << TheCall->getSourceRange(); 7412 } 7413 TheCall->setArg(i, Arg.get()); 7414 i++; 7415 } 7416 7417 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7418 // call to avoid duplicate diagnostics. 7419 if (!IsSizeCall) { 7420 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7421 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7422 bool Success = CheckFormatArguments( 7423 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7424 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7425 CheckedVarArgs); 7426 if (!Success) 7427 return true; 7428 } 7429 7430 if (IsSizeCall) { 7431 TheCall->setType(Context.getSizeType()); 7432 } else { 7433 TheCall->setType(Context.VoidPtrTy); 7434 } 7435 return false; 7436 } 7437 7438 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7439 /// TheCall is a constant expression. 7440 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7441 llvm::APSInt &Result) { 7442 Expr *Arg = TheCall->getArg(ArgNum); 7443 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7444 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7445 7446 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7447 7448 Optional<llvm::APSInt> R; 7449 if (!(R = Arg->getIntegerConstantExpr(Context))) 7450 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7451 << FDecl->getDeclName() << Arg->getSourceRange(); 7452 Result = *R; 7453 return false; 7454 } 7455 7456 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7457 /// TheCall is a constant expression in the range [Low, High]. 7458 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7459 int Low, int High, bool RangeIsError) { 7460 if (isConstantEvaluated()) 7461 return false; 7462 llvm::APSInt Result; 7463 7464 // We can't check the value of a dependent argument. 7465 Expr *Arg = TheCall->getArg(ArgNum); 7466 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7467 return false; 7468 7469 // Check constant-ness first. 7470 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7471 return true; 7472 7473 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7474 if (RangeIsError) 7475 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7476 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7477 else 7478 // Defer the warning until we know if the code will be emitted so that 7479 // dead code can ignore this. 7480 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7481 PDiag(diag::warn_argument_invalid_range) 7482 << toString(Result, 10) << Low << High 7483 << Arg->getSourceRange()); 7484 } 7485 7486 return false; 7487 } 7488 7489 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7490 /// TheCall is a constant expression is a multiple of Num.. 7491 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7492 unsigned Num) { 7493 llvm::APSInt Result; 7494 7495 // We can't check the value of a dependent argument. 7496 Expr *Arg = TheCall->getArg(ArgNum); 7497 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7498 return false; 7499 7500 // Check constant-ness first. 7501 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7502 return true; 7503 7504 if (Result.getSExtValue() % Num != 0) 7505 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7506 << Num << Arg->getSourceRange(); 7507 7508 return false; 7509 } 7510 7511 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7512 /// constant expression representing a power of 2. 7513 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7514 llvm::APSInt Result; 7515 7516 // We can't check the value of a dependent argument. 7517 Expr *Arg = TheCall->getArg(ArgNum); 7518 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7519 return false; 7520 7521 // Check constant-ness first. 7522 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7523 return true; 7524 7525 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7526 // and only if x is a power of 2. 7527 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7528 return false; 7529 7530 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7531 << Arg->getSourceRange(); 7532 } 7533 7534 static bool IsShiftedByte(llvm::APSInt Value) { 7535 if (Value.isNegative()) 7536 return false; 7537 7538 // Check if it's a shifted byte, by shifting it down 7539 while (true) { 7540 // If the value fits in the bottom byte, the check passes. 7541 if (Value < 0x100) 7542 return true; 7543 7544 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7545 // fails. 7546 if ((Value & 0xFF) != 0) 7547 return false; 7548 7549 // If the bottom 8 bits are all 0, but something above that is nonzero, 7550 // then shifting the value right by 8 bits won't affect whether it's a 7551 // shifted byte or not. So do that, and go round again. 7552 Value >>= 8; 7553 } 7554 } 7555 7556 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7557 /// a constant expression representing an arbitrary byte value shifted left by 7558 /// a multiple of 8 bits. 7559 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7560 unsigned ArgBits) { 7561 llvm::APSInt Result; 7562 7563 // We can't check the value of a dependent argument. 7564 Expr *Arg = TheCall->getArg(ArgNum); 7565 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7566 return false; 7567 7568 // Check constant-ness first. 7569 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7570 return true; 7571 7572 // Truncate to the given size. 7573 Result = Result.getLoBits(ArgBits); 7574 Result.setIsUnsigned(true); 7575 7576 if (IsShiftedByte(Result)) 7577 return false; 7578 7579 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7580 << Arg->getSourceRange(); 7581 } 7582 7583 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7584 /// TheCall is a constant expression representing either a shifted byte value, 7585 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7586 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7587 /// Arm MVE intrinsics. 7588 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7589 int ArgNum, 7590 unsigned ArgBits) { 7591 llvm::APSInt Result; 7592 7593 // We can't check the value of a dependent argument. 7594 Expr *Arg = TheCall->getArg(ArgNum); 7595 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7596 return false; 7597 7598 // Check constant-ness first. 7599 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7600 return true; 7601 7602 // Truncate to the given size. 7603 Result = Result.getLoBits(ArgBits); 7604 Result.setIsUnsigned(true); 7605 7606 // Check to see if it's in either of the required forms. 7607 if (IsShiftedByte(Result) || 7608 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7609 return false; 7610 7611 return Diag(TheCall->getBeginLoc(), 7612 diag::err_argument_not_shifted_byte_or_xxff) 7613 << Arg->getSourceRange(); 7614 } 7615 7616 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7617 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7618 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7619 if (checkArgCount(*this, TheCall, 2)) 7620 return true; 7621 Expr *Arg0 = TheCall->getArg(0); 7622 Expr *Arg1 = TheCall->getArg(1); 7623 7624 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7625 if (FirstArg.isInvalid()) 7626 return true; 7627 QualType FirstArgType = FirstArg.get()->getType(); 7628 if (!FirstArgType->isAnyPointerType()) 7629 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7630 << "first" << FirstArgType << Arg0->getSourceRange(); 7631 TheCall->setArg(0, FirstArg.get()); 7632 7633 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7634 if (SecArg.isInvalid()) 7635 return true; 7636 QualType SecArgType = SecArg.get()->getType(); 7637 if (!SecArgType->isIntegerType()) 7638 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7639 << "second" << SecArgType << Arg1->getSourceRange(); 7640 7641 // Derive the return type from the pointer argument. 7642 TheCall->setType(FirstArgType); 7643 return false; 7644 } 7645 7646 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7647 if (checkArgCount(*this, TheCall, 2)) 7648 return true; 7649 7650 Expr *Arg0 = TheCall->getArg(0); 7651 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7652 if (FirstArg.isInvalid()) 7653 return true; 7654 QualType FirstArgType = FirstArg.get()->getType(); 7655 if (!FirstArgType->isAnyPointerType()) 7656 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7657 << "first" << FirstArgType << Arg0->getSourceRange(); 7658 TheCall->setArg(0, FirstArg.get()); 7659 7660 // Derive the return type from the pointer argument. 7661 TheCall->setType(FirstArgType); 7662 7663 // Second arg must be an constant in range [0,15] 7664 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7665 } 7666 7667 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7668 if (checkArgCount(*this, TheCall, 2)) 7669 return true; 7670 Expr *Arg0 = TheCall->getArg(0); 7671 Expr *Arg1 = TheCall->getArg(1); 7672 7673 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7674 if (FirstArg.isInvalid()) 7675 return true; 7676 QualType FirstArgType = FirstArg.get()->getType(); 7677 if (!FirstArgType->isAnyPointerType()) 7678 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7679 << "first" << FirstArgType << Arg0->getSourceRange(); 7680 7681 QualType SecArgType = Arg1->getType(); 7682 if (!SecArgType->isIntegerType()) 7683 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7684 << "second" << SecArgType << Arg1->getSourceRange(); 7685 TheCall->setType(Context.IntTy); 7686 return false; 7687 } 7688 7689 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7690 BuiltinID == AArch64::BI__builtin_arm_stg) { 7691 if (checkArgCount(*this, TheCall, 1)) 7692 return true; 7693 Expr *Arg0 = TheCall->getArg(0); 7694 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7695 if (FirstArg.isInvalid()) 7696 return true; 7697 7698 QualType FirstArgType = FirstArg.get()->getType(); 7699 if (!FirstArgType->isAnyPointerType()) 7700 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7701 << "first" << FirstArgType << Arg0->getSourceRange(); 7702 TheCall->setArg(0, FirstArg.get()); 7703 7704 // Derive the return type from the pointer argument. 7705 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7706 TheCall->setType(FirstArgType); 7707 return false; 7708 } 7709 7710 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7711 Expr *ArgA = TheCall->getArg(0); 7712 Expr *ArgB = TheCall->getArg(1); 7713 7714 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7715 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7716 7717 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7718 return true; 7719 7720 QualType ArgTypeA = ArgExprA.get()->getType(); 7721 QualType ArgTypeB = ArgExprB.get()->getType(); 7722 7723 auto isNull = [&] (Expr *E) -> bool { 7724 return E->isNullPointerConstant( 7725 Context, Expr::NPC_ValueDependentIsNotNull); }; 7726 7727 // argument should be either a pointer or null 7728 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7729 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7730 << "first" << ArgTypeA << ArgA->getSourceRange(); 7731 7732 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7733 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7734 << "second" << ArgTypeB << ArgB->getSourceRange(); 7735 7736 // Ensure Pointee types are compatible 7737 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7738 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7739 QualType pointeeA = ArgTypeA->getPointeeType(); 7740 QualType pointeeB = ArgTypeB->getPointeeType(); 7741 if (!Context.typesAreCompatible( 7742 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7743 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7744 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7745 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7746 << ArgB->getSourceRange(); 7747 } 7748 } 7749 7750 // at least one argument should be pointer type 7751 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7752 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7753 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7754 7755 if (isNull(ArgA)) // adopt type of the other pointer 7756 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7757 7758 if (isNull(ArgB)) 7759 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7760 7761 TheCall->setArg(0, ArgExprA.get()); 7762 TheCall->setArg(1, ArgExprB.get()); 7763 TheCall->setType(Context.LongLongTy); 7764 return false; 7765 } 7766 assert(false && "Unhandled ARM MTE intrinsic"); 7767 return true; 7768 } 7769 7770 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7771 /// TheCall is an ARM/AArch64 special register string literal. 7772 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7773 int ArgNum, unsigned ExpectedFieldNum, 7774 bool AllowName) { 7775 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7776 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7777 BuiltinID == ARM::BI__builtin_arm_rsr || 7778 BuiltinID == ARM::BI__builtin_arm_rsrp || 7779 BuiltinID == ARM::BI__builtin_arm_wsr || 7780 BuiltinID == ARM::BI__builtin_arm_wsrp; 7781 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7782 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7783 BuiltinID == AArch64::BI__builtin_arm_rsr || 7784 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7785 BuiltinID == AArch64::BI__builtin_arm_wsr || 7786 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7787 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7788 7789 // We can't check the value of a dependent argument. 7790 Expr *Arg = TheCall->getArg(ArgNum); 7791 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7792 return false; 7793 7794 // Check if the argument is a string literal. 7795 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7796 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7797 << Arg->getSourceRange(); 7798 7799 // Check the type of special register given. 7800 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7801 SmallVector<StringRef, 6> Fields; 7802 Reg.split(Fields, ":"); 7803 7804 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7805 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7806 << Arg->getSourceRange(); 7807 7808 // If the string is the name of a register then we cannot check that it is 7809 // valid here but if the string is of one the forms described in ACLE then we 7810 // can check that the supplied fields are integers and within the valid 7811 // ranges. 7812 if (Fields.size() > 1) { 7813 bool FiveFields = Fields.size() == 5; 7814 7815 bool ValidString = true; 7816 if (IsARMBuiltin) { 7817 ValidString &= Fields[0].startswith_insensitive("cp") || 7818 Fields[0].startswith_insensitive("p"); 7819 if (ValidString) 7820 Fields[0] = Fields[0].drop_front( 7821 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7822 7823 ValidString &= Fields[2].startswith_insensitive("c"); 7824 if (ValidString) 7825 Fields[2] = Fields[2].drop_front(1); 7826 7827 if (FiveFields) { 7828 ValidString &= Fields[3].startswith_insensitive("c"); 7829 if (ValidString) 7830 Fields[3] = Fields[3].drop_front(1); 7831 } 7832 } 7833 7834 SmallVector<int, 5> Ranges; 7835 if (FiveFields) 7836 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7837 else 7838 Ranges.append({15, 7, 15}); 7839 7840 for (unsigned i=0; i<Fields.size(); ++i) { 7841 int IntField; 7842 ValidString &= !Fields[i].getAsInteger(10, IntField); 7843 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7844 } 7845 7846 if (!ValidString) 7847 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7848 << Arg->getSourceRange(); 7849 } else if (IsAArch64Builtin && Fields.size() == 1) { 7850 // If the register name is one of those that appear in the condition below 7851 // and the special register builtin being used is one of the write builtins, 7852 // then we require that the argument provided for writing to the register 7853 // is an integer constant expression. This is because it will be lowered to 7854 // an MSR (immediate) instruction, so we need to know the immediate at 7855 // compile time. 7856 if (TheCall->getNumArgs() != 2) 7857 return false; 7858 7859 std::string RegLower = Reg.lower(); 7860 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7861 RegLower != "pan" && RegLower != "uao") 7862 return false; 7863 7864 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7865 } 7866 7867 return false; 7868 } 7869 7870 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7871 /// Emit an error and return true on failure; return false on success. 7872 /// TypeStr is a string containing the type descriptor of the value returned by 7873 /// the builtin and the descriptors of the expected type of the arguments. 7874 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7875 const char *TypeStr) { 7876 7877 assert((TypeStr[0] != '\0') && 7878 "Invalid types in PPC MMA builtin declaration"); 7879 7880 switch (BuiltinID) { 7881 default: 7882 // This function is called in CheckPPCBuiltinFunctionCall where the 7883 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7884 // we are isolating the pair vector memop builtins that can be used with mma 7885 // off so the default case is every builtin that requires mma and paired 7886 // vector memops. 7887 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7888 diag::err_ppc_builtin_only_on_arch, "10") || 7889 SemaFeatureCheck(*this, TheCall, "mma", 7890 diag::err_ppc_builtin_only_on_arch, "10")) 7891 return true; 7892 break; 7893 case PPC::BI__builtin_vsx_lxvp: 7894 case PPC::BI__builtin_vsx_stxvp: 7895 case PPC::BI__builtin_vsx_assemble_pair: 7896 case PPC::BI__builtin_vsx_disassemble_pair: 7897 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7898 diag::err_ppc_builtin_only_on_arch, "10")) 7899 return true; 7900 break; 7901 } 7902 7903 unsigned Mask = 0; 7904 unsigned ArgNum = 0; 7905 7906 // The first type in TypeStr is the type of the value returned by the 7907 // builtin. So we first read that type and change the type of TheCall. 7908 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7909 TheCall->setType(type); 7910 7911 while (*TypeStr != '\0') { 7912 Mask = 0; 7913 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7914 if (ArgNum >= TheCall->getNumArgs()) { 7915 ArgNum++; 7916 break; 7917 } 7918 7919 Expr *Arg = TheCall->getArg(ArgNum); 7920 QualType PassedType = Arg->getType(); 7921 QualType StrippedRVType = PassedType.getCanonicalType(); 7922 7923 // Strip Restrict/Volatile qualifiers. 7924 if (StrippedRVType.isRestrictQualified() || 7925 StrippedRVType.isVolatileQualified()) 7926 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7927 7928 // The only case where the argument type and expected type are allowed to 7929 // mismatch is if the argument type is a non-void pointer (or array) and 7930 // expected type is a void pointer. 7931 if (StrippedRVType != ExpectedType) 7932 if (!(ExpectedType->isVoidPointerType() && 7933 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType()))) 7934 return Diag(Arg->getBeginLoc(), 7935 diag::err_typecheck_convert_incompatible) 7936 << PassedType << ExpectedType << 1 << 0 << 0; 7937 7938 // If the value of the Mask is not 0, we have a constraint in the size of 7939 // the integer argument so here we ensure the argument is a constant that 7940 // is in the valid range. 7941 if (Mask != 0 && 7942 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7943 return true; 7944 7945 ArgNum++; 7946 } 7947 7948 // In case we exited early from the previous loop, there are other types to 7949 // read from TypeStr. So we need to read them all to ensure we have the right 7950 // number of arguments in TheCall and if it is not the case, to display a 7951 // better error message. 7952 while (*TypeStr != '\0') { 7953 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7954 ArgNum++; 7955 } 7956 if (checkArgCount(*this, TheCall, ArgNum)) 7957 return true; 7958 7959 return false; 7960 } 7961 7962 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7963 /// This checks that the target supports __builtin_longjmp and 7964 /// that val is a constant 1. 7965 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7966 if (!Context.getTargetInfo().hasSjLjLowering()) 7967 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7968 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7969 7970 Expr *Arg = TheCall->getArg(1); 7971 llvm::APSInt Result; 7972 7973 // TODO: This is less than ideal. Overload this to take a value. 7974 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7975 return true; 7976 7977 if (Result != 1) 7978 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7979 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7980 7981 return false; 7982 } 7983 7984 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7985 /// This checks that the target supports __builtin_setjmp. 7986 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7987 if (!Context.getTargetInfo().hasSjLjLowering()) 7988 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7989 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7990 return false; 7991 } 7992 7993 namespace { 7994 7995 class UncoveredArgHandler { 7996 enum { Unknown = -1, AllCovered = -2 }; 7997 7998 signed FirstUncoveredArg = Unknown; 7999 SmallVector<const Expr *, 4> DiagnosticExprs; 8000 8001 public: 8002 UncoveredArgHandler() = default; 8003 8004 bool hasUncoveredArg() const { 8005 return (FirstUncoveredArg >= 0); 8006 } 8007 8008 unsigned getUncoveredArg() const { 8009 assert(hasUncoveredArg() && "no uncovered argument"); 8010 return FirstUncoveredArg; 8011 } 8012 8013 void setAllCovered() { 8014 // A string has been found with all arguments covered, so clear out 8015 // the diagnostics. 8016 DiagnosticExprs.clear(); 8017 FirstUncoveredArg = AllCovered; 8018 } 8019 8020 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 8021 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 8022 8023 // Don't update if a previous string covers all arguments. 8024 if (FirstUncoveredArg == AllCovered) 8025 return; 8026 8027 // UncoveredArgHandler tracks the highest uncovered argument index 8028 // and with it all the strings that match this index. 8029 if (NewFirstUncoveredArg == FirstUncoveredArg) 8030 DiagnosticExprs.push_back(StrExpr); 8031 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 8032 DiagnosticExprs.clear(); 8033 DiagnosticExprs.push_back(StrExpr); 8034 FirstUncoveredArg = NewFirstUncoveredArg; 8035 } 8036 } 8037 8038 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 8039 }; 8040 8041 enum StringLiteralCheckType { 8042 SLCT_NotALiteral, 8043 SLCT_UncheckedLiteral, 8044 SLCT_CheckedLiteral 8045 }; 8046 8047 } // namespace 8048 8049 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 8050 BinaryOperatorKind BinOpKind, 8051 bool AddendIsRight) { 8052 unsigned BitWidth = Offset.getBitWidth(); 8053 unsigned AddendBitWidth = Addend.getBitWidth(); 8054 // There might be negative interim results. 8055 if (Addend.isUnsigned()) { 8056 Addend = Addend.zext(++AddendBitWidth); 8057 Addend.setIsSigned(true); 8058 } 8059 // Adjust the bit width of the APSInts. 8060 if (AddendBitWidth > BitWidth) { 8061 Offset = Offset.sext(AddendBitWidth); 8062 BitWidth = AddendBitWidth; 8063 } else if (BitWidth > AddendBitWidth) { 8064 Addend = Addend.sext(BitWidth); 8065 } 8066 8067 bool Ov = false; 8068 llvm::APSInt ResOffset = Offset; 8069 if (BinOpKind == BO_Add) 8070 ResOffset = Offset.sadd_ov(Addend, Ov); 8071 else { 8072 assert(AddendIsRight && BinOpKind == BO_Sub && 8073 "operator must be add or sub with addend on the right"); 8074 ResOffset = Offset.ssub_ov(Addend, Ov); 8075 } 8076 8077 // We add an offset to a pointer here so we should support an offset as big as 8078 // possible. 8079 if (Ov) { 8080 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 8081 "index (intermediate) result too big"); 8082 Offset = Offset.sext(2 * BitWidth); 8083 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 8084 return; 8085 } 8086 8087 Offset = ResOffset; 8088 } 8089 8090 namespace { 8091 8092 // This is a wrapper class around StringLiteral to support offsetted string 8093 // literals as format strings. It takes the offset into account when returning 8094 // the string and its length or the source locations to display notes correctly. 8095 class FormatStringLiteral { 8096 const StringLiteral *FExpr; 8097 int64_t Offset; 8098 8099 public: 8100 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 8101 : FExpr(fexpr), Offset(Offset) {} 8102 8103 StringRef getString() const { 8104 return FExpr->getString().drop_front(Offset); 8105 } 8106 8107 unsigned getByteLength() const { 8108 return FExpr->getByteLength() - getCharByteWidth() * Offset; 8109 } 8110 8111 unsigned getLength() const { return FExpr->getLength() - Offset; } 8112 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 8113 8114 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 8115 8116 QualType getType() const { return FExpr->getType(); } 8117 8118 bool isAscii() const { return FExpr->isAscii(); } 8119 bool isWide() const { return FExpr->isWide(); } 8120 bool isUTF8() const { return FExpr->isUTF8(); } 8121 bool isUTF16() const { return FExpr->isUTF16(); } 8122 bool isUTF32() const { return FExpr->isUTF32(); } 8123 bool isPascal() const { return FExpr->isPascal(); } 8124 8125 SourceLocation getLocationOfByte( 8126 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 8127 const TargetInfo &Target, unsigned *StartToken = nullptr, 8128 unsigned *StartTokenByteOffset = nullptr) const { 8129 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 8130 StartToken, StartTokenByteOffset); 8131 } 8132 8133 SourceLocation getBeginLoc() const LLVM_READONLY { 8134 return FExpr->getBeginLoc().getLocWithOffset(Offset); 8135 } 8136 8137 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 8138 }; 8139 8140 } // namespace 8141 8142 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8143 const Expr *OrigFormatExpr, 8144 ArrayRef<const Expr *> Args, 8145 bool HasVAListArg, unsigned format_idx, 8146 unsigned firstDataArg, 8147 Sema::FormatStringType Type, 8148 bool inFunctionCall, 8149 Sema::VariadicCallType CallType, 8150 llvm::SmallBitVector &CheckedVarArgs, 8151 UncoveredArgHandler &UncoveredArg, 8152 bool IgnoreStringsWithoutSpecifiers); 8153 8154 // Determine if an expression is a string literal or constant string. 8155 // If this function returns false on the arguments to a function expecting a 8156 // format string, we will usually need to emit a warning. 8157 // True string literals are then checked by CheckFormatString. 8158 static StringLiteralCheckType 8159 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 8160 bool HasVAListArg, unsigned format_idx, 8161 unsigned firstDataArg, Sema::FormatStringType Type, 8162 Sema::VariadicCallType CallType, bool InFunctionCall, 8163 llvm::SmallBitVector &CheckedVarArgs, 8164 UncoveredArgHandler &UncoveredArg, 8165 llvm::APSInt Offset, 8166 bool IgnoreStringsWithoutSpecifiers = false) { 8167 if (S.isConstantEvaluated()) 8168 return SLCT_NotALiteral; 8169 tryAgain: 8170 assert(Offset.isSigned() && "invalid offset"); 8171 8172 if (E->isTypeDependent() || E->isValueDependent()) 8173 return SLCT_NotALiteral; 8174 8175 E = E->IgnoreParenCasts(); 8176 8177 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 8178 // Technically -Wformat-nonliteral does not warn about this case. 8179 // The behavior of printf and friends in this case is implementation 8180 // dependent. Ideally if the format string cannot be null then 8181 // it should have a 'nonnull' attribute in the function prototype. 8182 return SLCT_UncheckedLiteral; 8183 8184 switch (E->getStmtClass()) { 8185 case Stmt::BinaryConditionalOperatorClass: 8186 case Stmt::ConditionalOperatorClass: { 8187 // The expression is a literal if both sub-expressions were, and it was 8188 // completely checked only if both sub-expressions were checked. 8189 const AbstractConditionalOperator *C = 8190 cast<AbstractConditionalOperator>(E); 8191 8192 // Determine whether it is necessary to check both sub-expressions, for 8193 // example, because the condition expression is a constant that can be 8194 // evaluated at compile time. 8195 bool CheckLeft = true, CheckRight = true; 8196 8197 bool Cond; 8198 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 8199 S.isConstantEvaluated())) { 8200 if (Cond) 8201 CheckRight = false; 8202 else 8203 CheckLeft = false; 8204 } 8205 8206 // We need to maintain the offsets for the right and the left hand side 8207 // separately to check if every possible indexed expression is a valid 8208 // string literal. They might have different offsets for different string 8209 // literals in the end. 8210 StringLiteralCheckType Left; 8211 if (!CheckLeft) 8212 Left = SLCT_UncheckedLiteral; 8213 else { 8214 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 8215 HasVAListArg, format_idx, firstDataArg, 8216 Type, CallType, InFunctionCall, 8217 CheckedVarArgs, UncoveredArg, Offset, 8218 IgnoreStringsWithoutSpecifiers); 8219 if (Left == SLCT_NotALiteral || !CheckRight) { 8220 return Left; 8221 } 8222 } 8223 8224 StringLiteralCheckType Right = checkFormatStringExpr( 8225 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 8226 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8227 IgnoreStringsWithoutSpecifiers); 8228 8229 return (CheckLeft && Left < Right) ? Left : Right; 8230 } 8231 8232 case Stmt::ImplicitCastExprClass: 8233 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 8234 goto tryAgain; 8235 8236 case Stmt::OpaqueValueExprClass: 8237 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 8238 E = src; 8239 goto tryAgain; 8240 } 8241 return SLCT_NotALiteral; 8242 8243 case Stmt::PredefinedExprClass: 8244 // While __func__, etc., are technically not string literals, they 8245 // cannot contain format specifiers and thus are not a security 8246 // liability. 8247 return SLCT_UncheckedLiteral; 8248 8249 case Stmt::DeclRefExprClass: { 8250 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8251 8252 // As an exception, do not flag errors for variables binding to 8253 // const string literals. 8254 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 8255 bool isConstant = false; 8256 QualType T = DR->getType(); 8257 8258 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 8259 isConstant = AT->getElementType().isConstant(S.Context); 8260 } else if (const PointerType *PT = T->getAs<PointerType>()) { 8261 isConstant = T.isConstant(S.Context) && 8262 PT->getPointeeType().isConstant(S.Context); 8263 } else if (T->isObjCObjectPointerType()) { 8264 // In ObjC, there is usually no "const ObjectPointer" type, 8265 // so don't check if the pointee type is constant. 8266 isConstant = T.isConstant(S.Context); 8267 } 8268 8269 if (isConstant) { 8270 if (const Expr *Init = VD->getAnyInitializer()) { 8271 // Look through initializers like const char c[] = { "foo" } 8272 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 8273 if (InitList->isStringLiteralInit()) 8274 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 8275 } 8276 return checkFormatStringExpr(S, Init, Args, 8277 HasVAListArg, format_idx, 8278 firstDataArg, Type, CallType, 8279 /*InFunctionCall*/ false, CheckedVarArgs, 8280 UncoveredArg, Offset); 8281 } 8282 } 8283 8284 // For vprintf* functions (i.e., HasVAListArg==true), we add a 8285 // special check to see if the format string is a function parameter 8286 // of the function calling the printf function. If the function 8287 // has an attribute indicating it is a printf-like function, then we 8288 // should suppress warnings concerning non-literals being used in a call 8289 // to a vprintf function. For example: 8290 // 8291 // void 8292 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 8293 // va_list ap; 8294 // va_start(ap, fmt); 8295 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 8296 // ... 8297 // } 8298 if (HasVAListArg) { 8299 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 8300 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 8301 int PVIndex = PV->getFunctionScopeIndex() + 1; 8302 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 8303 // adjust for implicit parameter 8304 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 8305 if (MD->isInstance()) 8306 ++PVIndex; 8307 // We also check if the formats are compatible. 8308 // We can't pass a 'scanf' string to a 'printf' function. 8309 if (PVIndex == PVFormat->getFormatIdx() && 8310 Type == S.GetFormatStringType(PVFormat)) 8311 return SLCT_UncheckedLiteral; 8312 } 8313 } 8314 } 8315 } 8316 } 8317 8318 return SLCT_NotALiteral; 8319 } 8320 8321 case Stmt::CallExprClass: 8322 case Stmt::CXXMemberCallExprClass: { 8323 const CallExpr *CE = cast<CallExpr>(E); 8324 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 8325 bool IsFirst = true; 8326 StringLiteralCheckType CommonResult; 8327 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 8328 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 8329 StringLiteralCheckType Result = checkFormatStringExpr( 8330 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8331 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8332 IgnoreStringsWithoutSpecifiers); 8333 if (IsFirst) { 8334 CommonResult = Result; 8335 IsFirst = false; 8336 } 8337 } 8338 if (!IsFirst) 8339 return CommonResult; 8340 8341 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 8342 unsigned BuiltinID = FD->getBuiltinID(); 8343 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 8344 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 8345 const Expr *Arg = CE->getArg(0); 8346 return checkFormatStringExpr(S, Arg, Args, 8347 HasVAListArg, format_idx, 8348 firstDataArg, Type, CallType, 8349 InFunctionCall, CheckedVarArgs, 8350 UncoveredArg, Offset, 8351 IgnoreStringsWithoutSpecifiers); 8352 } 8353 } 8354 } 8355 8356 return SLCT_NotALiteral; 8357 } 8358 case Stmt::ObjCMessageExprClass: { 8359 const auto *ME = cast<ObjCMessageExpr>(E); 8360 if (const auto *MD = ME->getMethodDecl()) { 8361 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 8362 // As a special case heuristic, if we're using the method -[NSBundle 8363 // localizedStringForKey:value:table:], ignore any key strings that lack 8364 // format specifiers. The idea is that if the key doesn't have any 8365 // format specifiers then its probably just a key to map to the 8366 // localized strings. If it does have format specifiers though, then its 8367 // likely that the text of the key is the format string in the 8368 // programmer's language, and should be checked. 8369 const ObjCInterfaceDecl *IFace; 8370 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 8371 IFace->getIdentifier()->isStr("NSBundle") && 8372 MD->getSelector().isKeywordSelector( 8373 {"localizedStringForKey", "value", "table"})) { 8374 IgnoreStringsWithoutSpecifiers = true; 8375 } 8376 8377 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 8378 return checkFormatStringExpr( 8379 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8380 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8381 IgnoreStringsWithoutSpecifiers); 8382 } 8383 } 8384 8385 return SLCT_NotALiteral; 8386 } 8387 case Stmt::ObjCStringLiteralClass: 8388 case Stmt::StringLiteralClass: { 8389 const StringLiteral *StrE = nullptr; 8390 8391 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8392 StrE = ObjCFExpr->getString(); 8393 else 8394 StrE = cast<StringLiteral>(E); 8395 8396 if (StrE) { 8397 if (Offset.isNegative() || Offset > StrE->getLength()) { 8398 // TODO: It would be better to have an explicit warning for out of 8399 // bounds literals. 8400 return SLCT_NotALiteral; 8401 } 8402 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8403 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8404 firstDataArg, Type, InFunctionCall, CallType, 8405 CheckedVarArgs, UncoveredArg, 8406 IgnoreStringsWithoutSpecifiers); 8407 return SLCT_CheckedLiteral; 8408 } 8409 8410 return SLCT_NotALiteral; 8411 } 8412 case Stmt::BinaryOperatorClass: { 8413 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8414 8415 // A string literal + an int offset is still a string literal. 8416 if (BinOp->isAdditiveOp()) { 8417 Expr::EvalResult LResult, RResult; 8418 8419 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8420 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8421 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8422 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8423 8424 if (LIsInt != RIsInt) { 8425 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8426 8427 if (LIsInt) { 8428 if (BinOpKind == BO_Add) { 8429 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8430 E = BinOp->getRHS(); 8431 goto tryAgain; 8432 } 8433 } else { 8434 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8435 E = BinOp->getLHS(); 8436 goto tryAgain; 8437 } 8438 } 8439 } 8440 8441 return SLCT_NotALiteral; 8442 } 8443 case Stmt::UnaryOperatorClass: { 8444 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8445 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8446 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8447 Expr::EvalResult IndexResult; 8448 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8449 Expr::SE_NoSideEffects, 8450 S.isConstantEvaluated())) { 8451 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8452 /*RHS is int*/ true); 8453 E = ASE->getBase(); 8454 goto tryAgain; 8455 } 8456 } 8457 8458 return SLCT_NotALiteral; 8459 } 8460 8461 default: 8462 return SLCT_NotALiteral; 8463 } 8464 } 8465 8466 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8467 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8468 .Case("scanf", FST_Scanf) 8469 .Cases("printf", "printf0", FST_Printf) 8470 .Cases("NSString", "CFString", FST_NSString) 8471 .Case("strftime", FST_Strftime) 8472 .Case("strfmon", FST_Strfmon) 8473 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8474 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8475 .Case("os_trace", FST_OSLog) 8476 .Case("os_log", FST_OSLog) 8477 .Default(FST_Unknown); 8478 } 8479 8480 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8481 /// functions) for correct use of format strings. 8482 /// Returns true if a format string has been fully checked. 8483 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8484 ArrayRef<const Expr *> Args, 8485 bool IsCXXMember, 8486 VariadicCallType CallType, 8487 SourceLocation Loc, SourceRange Range, 8488 llvm::SmallBitVector &CheckedVarArgs) { 8489 FormatStringInfo FSI; 8490 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8491 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8492 FSI.FirstDataArg, GetFormatStringType(Format), 8493 CallType, Loc, Range, CheckedVarArgs); 8494 return false; 8495 } 8496 8497 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8498 bool HasVAListArg, unsigned format_idx, 8499 unsigned firstDataArg, FormatStringType Type, 8500 VariadicCallType CallType, 8501 SourceLocation Loc, SourceRange Range, 8502 llvm::SmallBitVector &CheckedVarArgs) { 8503 // CHECK: printf/scanf-like function is called with no format string. 8504 if (format_idx >= Args.size()) { 8505 Diag(Loc, diag::warn_missing_format_string) << Range; 8506 return false; 8507 } 8508 8509 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8510 8511 // CHECK: format string is not a string literal. 8512 // 8513 // Dynamically generated format strings are difficult to 8514 // automatically vet at compile time. Requiring that format strings 8515 // are string literals: (1) permits the checking of format strings by 8516 // the compiler and thereby (2) can practically remove the source of 8517 // many format string exploits. 8518 8519 // Format string can be either ObjC string (e.g. @"%d") or 8520 // C string (e.g. "%d") 8521 // ObjC string uses the same format specifiers as C string, so we can use 8522 // the same format string checking logic for both ObjC and C strings. 8523 UncoveredArgHandler UncoveredArg; 8524 StringLiteralCheckType CT = 8525 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8526 format_idx, firstDataArg, Type, CallType, 8527 /*IsFunctionCall*/ true, CheckedVarArgs, 8528 UncoveredArg, 8529 /*no string offset*/ llvm::APSInt(64, false) = 0); 8530 8531 // Generate a diagnostic where an uncovered argument is detected. 8532 if (UncoveredArg.hasUncoveredArg()) { 8533 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8534 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8535 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8536 } 8537 8538 if (CT != SLCT_NotALiteral) 8539 // Literal format string found, check done! 8540 return CT == SLCT_CheckedLiteral; 8541 8542 // Strftime is particular as it always uses a single 'time' argument, 8543 // so it is safe to pass a non-literal string. 8544 if (Type == FST_Strftime) 8545 return false; 8546 8547 // Do not emit diag when the string param is a macro expansion and the 8548 // format is either NSString or CFString. This is a hack to prevent 8549 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8550 // which are usually used in place of NS and CF string literals. 8551 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8552 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8553 return false; 8554 8555 // If there are no arguments specified, warn with -Wformat-security, otherwise 8556 // warn only with -Wformat-nonliteral. 8557 if (Args.size() == firstDataArg) { 8558 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8559 << OrigFormatExpr->getSourceRange(); 8560 switch (Type) { 8561 default: 8562 break; 8563 case FST_Kprintf: 8564 case FST_FreeBSDKPrintf: 8565 case FST_Printf: 8566 Diag(FormatLoc, diag::note_format_security_fixit) 8567 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8568 break; 8569 case FST_NSString: 8570 Diag(FormatLoc, diag::note_format_security_fixit) 8571 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8572 break; 8573 } 8574 } else { 8575 Diag(FormatLoc, diag::warn_format_nonliteral) 8576 << OrigFormatExpr->getSourceRange(); 8577 } 8578 return false; 8579 } 8580 8581 namespace { 8582 8583 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8584 protected: 8585 Sema &S; 8586 const FormatStringLiteral *FExpr; 8587 const Expr *OrigFormatExpr; 8588 const Sema::FormatStringType FSType; 8589 const unsigned FirstDataArg; 8590 const unsigned NumDataArgs; 8591 const char *Beg; // Start of format string. 8592 const bool HasVAListArg; 8593 ArrayRef<const Expr *> Args; 8594 unsigned FormatIdx; 8595 llvm::SmallBitVector CoveredArgs; 8596 bool usesPositionalArgs = false; 8597 bool atFirstArg = true; 8598 bool inFunctionCall; 8599 Sema::VariadicCallType CallType; 8600 llvm::SmallBitVector &CheckedVarArgs; 8601 UncoveredArgHandler &UncoveredArg; 8602 8603 public: 8604 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8605 const Expr *origFormatExpr, 8606 const Sema::FormatStringType type, unsigned firstDataArg, 8607 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8608 ArrayRef<const Expr *> Args, unsigned formatIdx, 8609 bool inFunctionCall, Sema::VariadicCallType callType, 8610 llvm::SmallBitVector &CheckedVarArgs, 8611 UncoveredArgHandler &UncoveredArg) 8612 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8613 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8614 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8615 inFunctionCall(inFunctionCall), CallType(callType), 8616 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8617 CoveredArgs.resize(numDataArgs); 8618 CoveredArgs.reset(); 8619 } 8620 8621 void DoneProcessing(); 8622 8623 void HandleIncompleteSpecifier(const char *startSpecifier, 8624 unsigned specifierLen) override; 8625 8626 void HandleInvalidLengthModifier( 8627 const analyze_format_string::FormatSpecifier &FS, 8628 const analyze_format_string::ConversionSpecifier &CS, 8629 const char *startSpecifier, unsigned specifierLen, 8630 unsigned DiagID); 8631 8632 void HandleNonStandardLengthModifier( 8633 const analyze_format_string::FormatSpecifier &FS, 8634 const char *startSpecifier, unsigned specifierLen); 8635 8636 void HandleNonStandardConversionSpecifier( 8637 const analyze_format_string::ConversionSpecifier &CS, 8638 const char *startSpecifier, unsigned specifierLen); 8639 8640 void HandlePosition(const char *startPos, unsigned posLen) override; 8641 8642 void HandleInvalidPosition(const char *startSpecifier, 8643 unsigned specifierLen, 8644 analyze_format_string::PositionContext p) override; 8645 8646 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8647 8648 void HandleNullChar(const char *nullCharacter) override; 8649 8650 template <typename Range> 8651 static void 8652 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8653 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8654 bool IsStringLocation, Range StringRange, 8655 ArrayRef<FixItHint> Fixit = None); 8656 8657 protected: 8658 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8659 const char *startSpec, 8660 unsigned specifierLen, 8661 const char *csStart, unsigned csLen); 8662 8663 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8664 const char *startSpec, 8665 unsigned specifierLen); 8666 8667 SourceRange getFormatStringRange(); 8668 CharSourceRange getSpecifierRange(const char *startSpecifier, 8669 unsigned specifierLen); 8670 SourceLocation getLocationOfByte(const char *x); 8671 8672 const Expr *getDataArg(unsigned i) const; 8673 8674 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8675 const analyze_format_string::ConversionSpecifier &CS, 8676 const char *startSpecifier, unsigned specifierLen, 8677 unsigned argIndex); 8678 8679 template <typename Range> 8680 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8681 bool IsStringLocation, Range StringRange, 8682 ArrayRef<FixItHint> Fixit = None); 8683 }; 8684 8685 } // namespace 8686 8687 SourceRange CheckFormatHandler::getFormatStringRange() { 8688 return OrigFormatExpr->getSourceRange(); 8689 } 8690 8691 CharSourceRange CheckFormatHandler:: 8692 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8693 SourceLocation Start = getLocationOfByte(startSpecifier); 8694 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8695 8696 // Advance the end SourceLocation by one due to half-open ranges. 8697 End = End.getLocWithOffset(1); 8698 8699 return CharSourceRange::getCharRange(Start, End); 8700 } 8701 8702 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8703 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8704 S.getLangOpts(), S.Context.getTargetInfo()); 8705 } 8706 8707 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8708 unsigned specifierLen){ 8709 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8710 getLocationOfByte(startSpecifier), 8711 /*IsStringLocation*/true, 8712 getSpecifierRange(startSpecifier, specifierLen)); 8713 } 8714 8715 void CheckFormatHandler::HandleInvalidLengthModifier( 8716 const analyze_format_string::FormatSpecifier &FS, 8717 const analyze_format_string::ConversionSpecifier &CS, 8718 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8719 using namespace analyze_format_string; 8720 8721 const LengthModifier &LM = FS.getLengthModifier(); 8722 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8723 8724 // See if we know how to fix this length modifier. 8725 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8726 if (FixedLM) { 8727 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8728 getLocationOfByte(LM.getStart()), 8729 /*IsStringLocation*/true, 8730 getSpecifierRange(startSpecifier, specifierLen)); 8731 8732 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8733 << FixedLM->toString() 8734 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8735 8736 } else { 8737 FixItHint Hint; 8738 if (DiagID == diag::warn_format_nonsensical_length) 8739 Hint = FixItHint::CreateRemoval(LMRange); 8740 8741 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8742 getLocationOfByte(LM.getStart()), 8743 /*IsStringLocation*/true, 8744 getSpecifierRange(startSpecifier, specifierLen), 8745 Hint); 8746 } 8747 } 8748 8749 void CheckFormatHandler::HandleNonStandardLengthModifier( 8750 const analyze_format_string::FormatSpecifier &FS, 8751 const char *startSpecifier, unsigned specifierLen) { 8752 using namespace analyze_format_string; 8753 8754 const LengthModifier &LM = FS.getLengthModifier(); 8755 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8756 8757 // See if we know how to fix this length modifier. 8758 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8759 if (FixedLM) { 8760 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8761 << LM.toString() << 0, 8762 getLocationOfByte(LM.getStart()), 8763 /*IsStringLocation*/true, 8764 getSpecifierRange(startSpecifier, specifierLen)); 8765 8766 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8767 << FixedLM->toString() 8768 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8769 8770 } else { 8771 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8772 << LM.toString() << 0, 8773 getLocationOfByte(LM.getStart()), 8774 /*IsStringLocation*/true, 8775 getSpecifierRange(startSpecifier, specifierLen)); 8776 } 8777 } 8778 8779 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8780 const analyze_format_string::ConversionSpecifier &CS, 8781 const char *startSpecifier, unsigned specifierLen) { 8782 using namespace analyze_format_string; 8783 8784 // See if we know how to fix this conversion specifier. 8785 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8786 if (FixedCS) { 8787 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8788 << CS.toString() << /*conversion specifier*/1, 8789 getLocationOfByte(CS.getStart()), 8790 /*IsStringLocation*/true, 8791 getSpecifierRange(startSpecifier, specifierLen)); 8792 8793 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8794 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8795 << FixedCS->toString() 8796 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8797 } else { 8798 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8799 << CS.toString() << /*conversion specifier*/1, 8800 getLocationOfByte(CS.getStart()), 8801 /*IsStringLocation*/true, 8802 getSpecifierRange(startSpecifier, specifierLen)); 8803 } 8804 } 8805 8806 void CheckFormatHandler::HandlePosition(const char *startPos, 8807 unsigned posLen) { 8808 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8809 getLocationOfByte(startPos), 8810 /*IsStringLocation*/true, 8811 getSpecifierRange(startPos, posLen)); 8812 } 8813 8814 void 8815 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8816 analyze_format_string::PositionContext p) { 8817 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8818 << (unsigned) p, 8819 getLocationOfByte(startPos), /*IsStringLocation*/true, 8820 getSpecifierRange(startPos, posLen)); 8821 } 8822 8823 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8824 unsigned posLen) { 8825 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8826 getLocationOfByte(startPos), 8827 /*IsStringLocation*/true, 8828 getSpecifierRange(startPos, posLen)); 8829 } 8830 8831 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8832 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8833 // The presence of a null character is likely an error. 8834 EmitFormatDiagnostic( 8835 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8836 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8837 getFormatStringRange()); 8838 } 8839 } 8840 8841 // Note that this may return NULL if there was an error parsing or building 8842 // one of the argument expressions. 8843 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8844 return Args[FirstDataArg + i]; 8845 } 8846 8847 void CheckFormatHandler::DoneProcessing() { 8848 // Does the number of data arguments exceed the number of 8849 // format conversions in the format string? 8850 if (!HasVAListArg) { 8851 // Find any arguments that weren't covered. 8852 CoveredArgs.flip(); 8853 signed notCoveredArg = CoveredArgs.find_first(); 8854 if (notCoveredArg >= 0) { 8855 assert((unsigned)notCoveredArg < NumDataArgs); 8856 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8857 } else { 8858 UncoveredArg.setAllCovered(); 8859 } 8860 } 8861 } 8862 8863 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8864 const Expr *ArgExpr) { 8865 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8866 "Invalid state"); 8867 8868 if (!ArgExpr) 8869 return; 8870 8871 SourceLocation Loc = ArgExpr->getBeginLoc(); 8872 8873 if (S.getSourceManager().isInSystemMacro(Loc)) 8874 return; 8875 8876 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8877 for (auto E : DiagnosticExprs) 8878 PDiag << E->getSourceRange(); 8879 8880 CheckFormatHandler::EmitFormatDiagnostic( 8881 S, IsFunctionCall, DiagnosticExprs[0], 8882 PDiag, Loc, /*IsStringLocation*/false, 8883 DiagnosticExprs[0]->getSourceRange()); 8884 } 8885 8886 bool 8887 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8888 SourceLocation Loc, 8889 const char *startSpec, 8890 unsigned specifierLen, 8891 const char *csStart, 8892 unsigned csLen) { 8893 bool keepGoing = true; 8894 if (argIndex < NumDataArgs) { 8895 // Consider the argument coverered, even though the specifier doesn't 8896 // make sense. 8897 CoveredArgs.set(argIndex); 8898 } 8899 else { 8900 // If argIndex exceeds the number of data arguments we 8901 // don't issue a warning because that is just a cascade of warnings (and 8902 // they may have intended '%%' anyway). We don't want to continue processing 8903 // the format string after this point, however, as we will like just get 8904 // gibberish when trying to match arguments. 8905 keepGoing = false; 8906 } 8907 8908 StringRef Specifier(csStart, csLen); 8909 8910 // If the specifier in non-printable, it could be the first byte of a UTF-8 8911 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8912 // hex value. 8913 std::string CodePointStr; 8914 if (!llvm::sys::locale::isPrint(*csStart)) { 8915 llvm::UTF32 CodePoint; 8916 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8917 const llvm::UTF8 *E = 8918 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8919 llvm::ConversionResult Result = 8920 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8921 8922 if (Result != llvm::conversionOK) { 8923 unsigned char FirstChar = *csStart; 8924 CodePoint = (llvm::UTF32)FirstChar; 8925 } 8926 8927 llvm::raw_string_ostream OS(CodePointStr); 8928 if (CodePoint < 256) 8929 OS << "\\x" << llvm::format("%02x", CodePoint); 8930 else if (CodePoint <= 0xFFFF) 8931 OS << "\\u" << llvm::format("%04x", CodePoint); 8932 else 8933 OS << "\\U" << llvm::format("%08x", CodePoint); 8934 OS.flush(); 8935 Specifier = CodePointStr; 8936 } 8937 8938 EmitFormatDiagnostic( 8939 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8940 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8941 8942 return keepGoing; 8943 } 8944 8945 void 8946 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8947 const char *startSpec, 8948 unsigned specifierLen) { 8949 EmitFormatDiagnostic( 8950 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8951 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8952 } 8953 8954 bool 8955 CheckFormatHandler::CheckNumArgs( 8956 const analyze_format_string::FormatSpecifier &FS, 8957 const analyze_format_string::ConversionSpecifier &CS, 8958 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8959 8960 if (argIndex >= NumDataArgs) { 8961 PartialDiagnostic PDiag = FS.usesPositionalArg() 8962 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8963 << (argIndex+1) << NumDataArgs) 8964 : S.PDiag(diag::warn_printf_insufficient_data_args); 8965 EmitFormatDiagnostic( 8966 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8967 getSpecifierRange(startSpecifier, specifierLen)); 8968 8969 // Since more arguments than conversion tokens are given, by extension 8970 // all arguments are covered, so mark this as so. 8971 UncoveredArg.setAllCovered(); 8972 return false; 8973 } 8974 return true; 8975 } 8976 8977 template<typename Range> 8978 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8979 SourceLocation Loc, 8980 bool IsStringLocation, 8981 Range StringRange, 8982 ArrayRef<FixItHint> FixIt) { 8983 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8984 Loc, IsStringLocation, StringRange, FixIt); 8985 } 8986 8987 /// If the format string is not within the function call, emit a note 8988 /// so that the function call and string are in diagnostic messages. 8989 /// 8990 /// \param InFunctionCall if true, the format string is within the function 8991 /// call and only one diagnostic message will be produced. Otherwise, an 8992 /// extra note will be emitted pointing to location of the format string. 8993 /// 8994 /// \param ArgumentExpr the expression that is passed as the format string 8995 /// argument in the function call. Used for getting locations when two 8996 /// diagnostics are emitted. 8997 /// 8998 /// \param PDiag the callee should already have provided any strings for the 8999 /// diagnostic message. This function only adds locations and fixits 9000 /// to diagnostics. 9001 /// 9002 /// \param Loc primary location for diagnostic. If two diagnostics are 9003 /// required, one will be at Loc and a new SourceLocation will be created for 9004 /// the other one. 9005 /// 9006 /// \param IsStringLocation if true, Loc points to the format string should be 9007 /// used for the note. Otherwise, Loc points to the argument list and will 9008 /// be used with PDiag. 9009 /// 9010 /// \param StringRange some or all of the string to highlight. This is 9011 /// templated so it can accept either a CharSourceRange or a SourceRange. 9012 /// 9013 /// \param FixIt optional fix it hint for the format string. 9014 template <typename Range> 9015 void CheckFormatHandler::EmitFormatDiagnostic( 9016 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 9017 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 9018 Range StringRange, ArrayRef<FixItHint> FixIt) { 9019 if (InFunctionCall) { 9020 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 9021 D << StringRange; 9022 D << FixIt; 9023 } else { 9024 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 9025 << ArgumentExpr->getSourceRange(); 9026 9027 const Sema::SemaDiagnosticBuilder &Note = 9028 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 9029 diag::note_format_string_defined); 9030 9031 Note << StringRange; 9032 Note << FixIt; 9033 } 9034 } 9035 9036 //===--- CHECK: Printf format string checking ------------------------------===// 9037 9038 namespace { 9039 9040 class CheckPrintfHandler : public CheckFormatHandler { 9041 public: 9042 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 9043 const Expr *origFormatExpr, 9044 const Sema::FormatStringType type, unsigned firstDataArg, 9045 unsigned numDataArgs, bool isObjC, const char *beg, 9046 bool hasVAListArg, ArrayRef<const Expr *> Args, 9047 unsigned formatIdx, bool inFunctionCall, 9048 Sema::VariadicCallType CallType, 9049 llvm::SmallBitVector &CheckedVarArgs, 9050 UncoveredArgHandler &UncoveredArg) 9051 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9052 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9053 inFunctionCall, CallType, CheckedVarArgs, 9054 UncoveredArg) {} 9055 9056 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 9057 9058 /// Returns true if '%@' specifiers are allowed in the format string. 9059 bool allowsObjCArg() const { 9060 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 9061 FSType == Sema::FST_OSTrace; 9062 } 9063 9064 bool HandleInvalidPrintfConversionSpecifier( 9065 const analyze_printf::PrintfSpecifier &FS, 9066 const char *startSpecifier, 9067 unsigned specifierLen) override; 9068 9069 void handleInvalidMaskType(StringRef MaskType) override; 9070 9071 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 9072 const char *startSpecifier, unsigned specifierLen, 9073 const TargetInfo &Target) override; 9074 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9075 const char *StartSpecifier, 9076 unsigned SpecifierLen, 9077 const Expr *E); 9078 9079 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 9080 const char *startSpecifier, unsigned specifierLen); 9081 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 9082 const analyze_printf::OptionalAmount &Amt, 9083 unsigned type, 9084 const char *startSpecifier, unsigned specifierLen); 9085 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9086 const analyze_printf::OptionalFlag &flag, 9087 const char *startSpecifier, unsigned specifierLen); 9088 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 9089 const analyze_printf::OptionalFlag &ignoredFlag, 9090 const analyze_printf::OptionalFlag &flag, 9091 const char *startSpecifier, unsigned specifierLen); 9092 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 9093 const Expr *E); 9094 9095 void HandleEmptyObjCModifierFlag(const char *startFlag, 9096 unsigned flagLen) override; 9097 9098 void HandleInvalidObjCModifierFlag(const char *startFlag, 9099 unsigned flagLen) override; 9100 9101 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 9102 const char *flagsEnd, 9103 const char *conversionPosition) 9104 override; 9105 }; 9106 9107 } // namespace 9108 9109 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 9110 const analyze_printf::PrintfSpecifier &FS, 9111 const char *startSpecifier, 9112 unsigned specifierLen) { 9113 const analyze_printf::PrintfConversionSpecifier &CS = 9114 FS.getConversionSpecifier(); 9115 9116 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9117 getLocationOfByte(CS.getStart()), 9118 startSpecifier, specifierLen, 9119 CS.getStart(), CS.getLength()); 9120 } 9121 9122 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 9123 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 9124 } 9125 9126 bool CheckPrintfHandler::HandleAmount( 9127 const analyze_format_string::OptionalAmount &Amt, 9128 unsigned k, const char *startSpecifier, 9129 unsigned specifierLen) { 9130 if (Amt.hasDataArgument()) { 9131 if (!HasVAListArg) { 9132 unsigned argIndex = Amt.getArgIndex(); 9133 if (argIndex >= NumDataArgs) { 9134 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 9135 << k, 9136 getLocationOfByte(Amt.getStart()), 9137 /*IsStringLocation*/true, 9138 getSpecifierRange(startSpecifier, specifierLen)); 9139 // Don't do any more checking. We will just emit 9140 // spurious errors. 9141 return false; 9142 } 9143 9144 // Type check the data argument. It should be an 'int'. 9145 // Although not in conformance with C99, we also allow the argument to be 9146 // an 'unsigned int' as that is a reasonably safe case. GCC also 9147 // doesn't emit a warning for that case. 9148 CoveredArgs.set(argIndex); 9149 const Expr *Arg = getDataArg(argIndex); 9150 if (!Arg) 9151 return false; 9152 9153 QualType T = Arg->getType(); 9154 9155 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 9156 assert(AT.isValid()); 9157 9158 if (!AT.matchesType(S.Context, T)) { 9159 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 9160 << k << AT.getRepresentativeTypeName(S.Context) 9161 << T << Arg->getSourceRange(), 9162 getLocationOfByte(Amt.getStart()), 9163 /*IsStringLocation*/true, 9164 getSpecifierRange(startSpecifier, specifierLen)); 9165 // Don't do any more checking. We will just emit 9166 // spurious errors. 9167 return false; 9168 } 9169 } 9170 } 9171 return true; 9172 } 9173 9174 void CheckPrintfHandler::HandleInvalidAmount( 9175 const analyze_printf::PrintfSpecifier &FS, 9176 const analyze_printf::OptionalAmount &Amt, 9177 unsigned type, 9178 const char *startSpecifier, 9179 unsigned specifierLen) { 9180 const analyze_printf::PrintfConversionSpecifier &CS = 9181 FS.getConversionSpecifier(); 9182 9183 FixItHint fixit = 9184 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 9185 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 9186 Amt.getConstantLength())) 9187 : FixItHint(); 9188 9189 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 9190 << type << CS.toString(), 9191 getLocationOfByte(Amt.getStart()), 9192 /*IsStringLocation*/true, 9193 getSpecifierRange(startSpecifier, specifierLen), 9194 fixit); 9195 } 9196 9197 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9198 const analyze_printf::OptionalFlag &flag, 9199 const char *startSpecifier, 9200 unsigned specifierLen) { 9201 // Warn about pointless flag with a fixit removal. 9202 const analyze_printf::PrintfConversionSpecifier &CS = 9203 FS.getConversionSpecifier(); 9204 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 9205 << flag.toString() << CS.toString(), 9206 getLocationOfByte(flag.getPosition()), 9207 /*IsStringLocation*/true, 9208 getSpecifierRange(startSpecifier, specifierLen), 9209 FixItHint::CreateRemoval( 9210 getSpecifierRange(flag.getPosition(), 1))); 9211 } 9212 9213 void CheckPrintfHandler::HandleIgnoredFlag( 9214 const analyze_printf::PrintfSpecifier &FS, 9215 const analyze_printf::OptionalFlag &ignoredFlag, 9216 const analyze_printf::OptionalFlag &flag, 9217 const char *startSpecifier, 9218 unsigned specifierLen) { 9219 // Warn about ignored flag with a fixit removal. 9220 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 9221 << ignoredFlag.toString() << flag.toString(), 9222 getLocationOfByte(ignoredFlag.getPosition()), 9223 /*IsStringLocation*/true, 9224 getSpecifierRange(startSpecifier, specifierLen), 9225 FixItHint::CreateRemoval( 9226 getSpecifierRange(ignoredFlag.getPosition(), 1))); 9227 } 9228 9229 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 9230 unsigned flagLen) { 9231 // Warn about an empty flag. 9232 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 9233 getLocationOfByte(startFlag), 9234 /*IsStringLocation*/true, 9235 getSpecifierRange(startFlag, flagLen)); 9236 } 9237 9238 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 9239 unsigned flagLen) { 9240 // Warn about an invalid flag. 9241 auto Range = getSpecifierRange(startFlag, flagLen); 9242 StringRef flag(startFlag, flagLen); 9243 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 9244 getLocationOfByte(startFlag), 9245 /*IsStringLocation*/true, 9246 Range, FixItHint::CreateRemoval(Range)); 9247 } 9248 9249 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 9250 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 9251 // Warn about using '[...]' without a '@' conversion. 9252 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 9253 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 9254 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 9255 getLocationOfByte(conversionPosition), 9256 /*IsStringLocation*/true, 9257 Range, FixItHint::CreateRemoval(Range)); 9258 } 9259 9260 // Determines if the specified is a C++ class or struct containing 9261 // a member with the specified name and kind (e.g. a CXXMethodDecl named 9262 // "c_str()"). 9263 template<typename MemberKind> 9264 static llvm::SmallPtrSet<MemberKind*, 1> 9265 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 9266 const RecordType *RT = Ty->getAs<RecordType>(); 9267 llvm::SmallPtrSet<MemberKind*, 1> Results; 9268 9269 if (!RT) 9270 return Results; 9271 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 9272 if (!RD || !RD->getDefinition()) 9273 return Results; 9274 9275 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 9276 Sema::LookupMemberName); 9277 R.suppressDiagnostics(); 9278 9279 // We just need to include all members of the right kind turned up by the 9280 // filter, at this point. 9281 if (S.LookupQualifiedName(R, RT->getDecl())) 9282 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9283 NamedDecl *decl = (*I)->getUnderlyingDecl(); 9284 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 9285 Results.insert(FK); 9286 } 9287 return Results; 9288 } 9289 9290 /// Check if we could call '.c_str()' on an object. 9291 /// 9292 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 9293 /// allow the call, or if it would be ambiguous). 9294 bool Sema::hasCStrMethod(const Expr *E) { 9295 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9296 9297 MethodSet Results = 9298 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 9299 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9300 MI != ME; ++MI) 9301 if ((*MI)->getMinRequiredArguments() == 0) 9302 return true; 9303 return false; 9304 } 9305 9306 // Check if a (w)string was passed when a (w)char* was needed, and offer a 9307 // better diagnostic if so. AT is assumed to be valid. 9308 // Returns true when a c_str() conversion method is found. 9309 bool CheckPrintfHandler::checkForCStrMembers( 9310 const analyze_printf::ArgType &AT, const Expr *E) { 9311 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9312 9313 MethodSet Results = 9314 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 9315 9316 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9317 MI != ME; ++MI) { 9318 const CXXMethodDecl *Method = *MI; 9319 if (Method->getMinRequiredArguments() == 0 && 9320 AT.matchesType(S.Context, Method->getReturnType())) { 9321 // FIXME: Suggest parens if the expression needs them. 9322 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 9323 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 9324 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 9325 return true; 9326 } 9327 } 9328 9329 return false; 9330 } 9331 9332 bool CheckPrintfHandler::HandlePrintfSpecifier( 9333 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier, 9334 unsigned specifierLen, const TargetInfo &Target) { 9335 using namespace analyze_format_string; 9336 using namespace analyze_printf; 9337 9338 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 9339 9340 if (FS.consumesDataArgument()) { 9341 if (atFirstArg) { 9342 atFirstArg = false; 9343 usesPositionalArgs = FS.usesPositionalArg(); 9344 } 9345 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9346 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9347 startSpecifier, specifierLen); 9348 return false; 9349 } 9350 } 9351 9352 // First check if the field width, precision, and conversion specifier 9353 // have matching data arguments. 9354 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 9355 startSpecifier, specifierLen)) { 9356 return false; 9357 } 9358 9359 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 9360 startSpecifier, specifierLen)) { 9361 return false; 9362 } 9363 9364 if (!CS.consumesDataArgument()) { 9365 // FIXME: Technically specifying a precision or field width here 9366 // makes no sense. Worth issuing a warning at some point. 9367 return true; 9368 } 9369 9370 // Consume the argument. 9371 unsigned argIndex = FS.getArgIndex(); 9372 if (argIndex < NumDataArgs) { 9373 // The check to see if the argIndex is valid will come later. 9374 // We set the bit here because we may exit early from this 9375 // function if we encounter some other error. 9376 CoveredArgs.set(argIndex); 9377 } 9378 9379 // FreeBSD kernel extensions. 9380 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 9381 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 9382 // We need at least two arguments. 9383 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 9384 return false; 9385 9386 // Claim the second argument. 9387 CoveredArgs.set(argIndex + 1); 9388 9389 // Type check the first argument (int for %b, pointer for %D) 9390 const Expr *Ex = getDataArg(argIndex); 9391 const analyze_printf::ArgType &AT = 9392 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9393 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9394 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9395 EmitFormatDiagnostic( 9396 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9397 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9398 << false << Ex->getSourceRange(), 9399 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9400 getSpecifierRange(startSpecifier, specifierLen)); 9401 9402 // Type check the second argument (char * for both %b and %D) 9403 Ex = getDataArg(argIndex + 1); 9404 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9405 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9406 EmitFormatDiagnostic( 9407 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9408 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9409 << false << Ex->getSourceRange(), 9410 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9411 getSpecifierRange(startSpecifier, specifierLen)); 9412 9413 return true; 9414 } 9415 9416 // Check for using an Objective-C specific conversion specifier 9417 // in a non-ObjC literal. 9418 if (!allowsObjCArg() && CS.isObjCArg()) { 9419 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9420 specifierLen); 9421 } 9422 9423 // %P can only be used with os_log. 9424 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9425 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9426 specifierLen); 9427 } 9428 9429 // %n is not allowed with os_log. 9430 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9431 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9432 getLocationOfByte(CS.getStart()), 9433 /*IsStringLocation*/ false, 9434 getSpecifierRange(startSpecifier, specifierLen)); 9435 9436 return true; 9437 } 9438 9439 // Only scalars are allowed for os_trace. 9440 if (FSType == Sema::FST_OSTrace && 9441 (CS.getKind() == ConversionSpecifier::PArg || 9442 CS.getKind() == ConversionSpecifier::sArg || 9443 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9444 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9445 specifierLen); 9446 } 9447 9448 // Check for use of public/private annotation outside of os_log(). 9449 if (FSType != Sema::FST_OSLog) { 9450 if (FS.isPublic().isSet()) { 9451 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9452 << "public", 9453 getLocationOfByte(FS.isPublic().getPosition()), 9454 /*IsStringLocation*/ false, 9455 getSpecifierRange(startSpecifier, specifierLen)); 9456 } 9457 if (FS.isPrivate().isSet()) { 9458 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9459 << "private", 9460 getLocationOfByte(FS.isPrivate().getPosition()), 9461 /*IsStringLocation*/ false, 9462 getSpecifierRange(startSpecifier, specifierLen)); 9463 } 9464 } 9465 9466 const llvm::Triple &Triple = Target.getTriple(); 9467 if (CS.getKind() == ConversionSpecifier::nArg && 9468 (Triple.isAndroid() || Triple.isOSFuchsia())) { 9469 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported), 9470 getLocationOfByte(CS.getStart()), 9471 /*IsStringLocation*/ false, 9472 getSpecifierRange(startSpecifier, specifierLen)); 9473 } 9474 9475 // Check for invalid use of field width 9476 if (!FS.hasValidFieldWidth()) { 9477 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9478 startSpecifier, specifierLen); 9479 } 9480 9481 // Check for invalid use of precision 9482 if (!FS.hasValidPrecision()) { 9483 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9484 startSpecifier, specifierLen); 9485 } 9486 9487 // Precision is mandatory for %P specifier. 9488 if (CS.getKind() == ConversionSpecifier::PArg && 9489 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9490 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9491 getLocationOfByte(startSpecifier), 9492 /*IsStringLocation*/ false, 9493 getSpecifierRange(startSpecifier, specifierLen)); 9494 } 9495 9496 // Check each flag does not conflict with any other component. 9497 if (!FS.hasValidThousandsGroupingPrefix()) 9498 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9499 if (!FS.hasValidLeadingZeros()) 9500 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9501 if (!FS.hasValidPlusPrefix()) 9502 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9503 if (!FS.hasValidSpacePrefix()) 9504 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9505 if (!FS.hasValidAlternativeForm()) 9506 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9507 if (!FS.hasValidLeftJustified()) 9508 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9509 9510 // Check that flags are not ignored by another flag 9511 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9512 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9513 startSpecifier, specifierLen); 9514 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9515 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9516 startSpecifier, specifierLen); 9517 9518 // Check the length modifier is valid with the given conversion specifier. 9519 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9520 S.getLangOpts())) 9521 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9522 diag::warn_format_nonsensical_length); 9523 else if (!FS.hasStandardLengthModifier()) 9524 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9525 else if (!FS.hasStandardLengthConversionCombination()) 9526 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9527 diag::warn_format_non_standard_conversion_spec); 9528 9529 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9530 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9531 9532 // The remaining checks depend on the data arguments. 9533 if (HasVAListArg) 9534 return true; 9535 9536 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9537 return false; 9538 9539 const Expr *Arg = getDataArg(argIndex); 9540 if (!Arg) 9541 return true; 9542 9543 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9544 } 9545 9546 static bool requiresParensToAddCast(const Expr *E) { 9547 // FIXME: We should have a general way to reason about operator 9548 // precedence and whether parens are actually needed here. 9549 // Take care of a few common cases where they aren't. 9550 const Expr *Inside = E->IgnoreImpCasts(); 9551 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9552 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9553 9554 switch (Inside->getStmtClass()) { 9555 case Stmt::ArraySubscriptExprClass: 9556 case Stmt::CallExprClass: 9557 case Stmt::CharacterLiteralClass: 9558 case Stmt::CXXBoolLiteralExprClass: 9559 case Stmt::DeclRefExprClass: 9560 case Stmt::FloatingLiteralClass: 9561 case Stmt::IntegerLiteralClass: 9562 case Stmt::MemberExprClass: 9563 case Stmt::ObjCArrayLiteralClass: 9564 case Stmt::ObjCBoolLiteralExprClass: 9565 case Stmt::ObjCBoxedExprClass: 9566 case Stmt::ObjCDictionaryLiteralClass: 9567 case Stmt::ObjCEncodeExprClass: 9568 case Stmt::ObjCIvarRefExprClass: 9569 case Stmt::ObjCMessageExprClass: 9570 case Stmt::ObjCPropertyRefExprClass: 9571 case Stmt::ObjCStringLiteralClass: 9572 case Stmt::ObjCSubscriptRefExprClass: 9573 case Stmt::ParenExprClass: 9574 case Stmt::StringLiteralClass: 9575 case Stmt::UnaryOperatorClass: 9576 return false; 9577 default: 9578 return true; 9579 } 9580 } 9581 9582 static std::pair<QualType, StringRef> 9583 shouldNotPrintDirectly(const ASTContext &Context, 9584 QualType IntendedTy, 9585 const Expr *E) { 9586 // Use a 'while' to peel off layers of typedefs. 9587 QualType TyTy = IntendedTy; 9588 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9589 StringRef Name = UserTy->getDecl()->getName(); 9590 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9591 .Case("CFIndex", Context.getNSIntegerType()) 9592 .Case("NSInteger", Context.getNSIntegerType()) 9593 .Case("NSUInteger", Context.getNSUIntegerType()) 9594 .Case("SInt32", Context.IntTy) 9595 .Case("UInt32", Context.UnsignedIntTy) 9596 .Default(QualType()); 9597 9598 if (!CastTy.isNull()) 9599 return std::make_pair(CastTy, Name); 9600 9601 TyTy = UserTy->desugar(); 9602 } 9603 9604 // Strip parens if necessary. 9605 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9606 return shouldNotPrintDirectly(Context, 9607 PE->getSubExpr()->getType(), 9608 PE->getSubExpr()); 9609 9610 // If this is a conditional expression, then its result type is constructed 9611 // via usual arithmetic conversions and thus there might be no necessary 9612 // typedef sugar there. Recurse to operands to check for NSInteger & 9613 // Co. usage condition. 9614 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9615 QualType TrueTy, FalseTy; 9616 StringRef TrueName, FalseName; 9617 9618 std::tie(TrueTy, TrueName) = 9619 shouldNotPrintDirectly(Context, 9620 CO->getTrueExpr()->getType(), 9621 CO->getTrueExpr()); 9622 std::tie(FalseTy, FalseName) = 9623 shouldNotPrintDirectly(Context, 9624 CO->getFalseExpr()->getType(), 9625 CO->getFalseExpr()); 9626 9627 if (TrueTy == FalseTy) 9628 return std::make_pair(TrueTy, TrueName); 9629 else if (TrueTy.isNull()) 9630 return std::make_pair(FalseTy, FalseName); 9631 else if (FalseTy.isNull()) 9632 return std::make_pair(TrueTy, TrueName); 9633 } 9634 9635 return std::make_pair(QualType(), StringRef()); 9636 } 9637 9638 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9639 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9640 /// type do not count. 9641 static bool 9642 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9643 QualType From = ICE->getSubExpr()->getType(); 9644 QualType To = ICE->getType(); 9645 // It's an integer promotion if the destination type is the promoted 9646 // source type. 9647 if (ICE->getCastKind() == CK_IntegralCast && 9648 From->isPromotableIntegerType() && 9649 S.Context.getPromotedIntegerType(From) == To) 9650 return true; 9651 // Look through vector types, since we do default argument promotion for 9652 // those in OpenCL. 9653 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9654 From = VecTy->getElementType(); 9655 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9656 To = VecTy->getElementType(); 9657 // It's a floating promotion if the source type is a lower rank. 9658 return ICE->getCastKind() == CK_FloatingCast && 9659 S.Context.getFloatingTypeOrder(From, To) < 0; 9660 } 9661 9662 bool 9663 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9664 const char *StartSpecifier, 9665 unsigned SpecifierLen, 9666 const Expr *E) { 9667 using namespace analyze_format_string; 9668 using namespace analyze_printf; 9669 9670 // Now type check the data expression that matches the 9671 // format specifier. 9672 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9673 if (!AT.isValid()) 9674 return true; 9675 9676 QualType ExprTy = E->getType(); 9677 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9678 ExprTy = TET->getUnderlyingExpr()->getType(); 9679 } 9680 9681 // Diagnose attempts to print a boolean value as a character. Unlike other 9682 // -Wformat diagnostics, this is fine from a type perspective, but it still 9683 // doesn't make sense. 9684 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9685 E->isKnownToHaveBooleanValue()) { 9686 const CharSourceRange &CSR = 9687 getSpecifierRange(StartSpecifier, SpecifierLen); 9688 SmallString<4> FSString; 9689 llvm::raw_svector_ostream os(FSString); 9690 FS.toString(os); 9691 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9692 << FSString, 9693 E->getExprLoc(), false, CSR); 9694 return true; 9695 } 9696 9697 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9698 if (Match == analyze_printf::ArgType::Match) 9699 return true; 9700 9701 // Look through argument promotions for our error message's reported type. 9702 // This includes the integral and floating promotions, but excludes array 9703 // and function pointer decay (seeing that an argument intended to be a 9704 // string has type 'char [6]' is probably more confusing than 'char *') and 9705 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9706 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9707 if (isArithmeticArgumentPromotion(S, ICE)) { 9708 E = ICE->getSubExpr(); 9709 ExprTy = E->getType(); 9710 9711 // Check if we didn't match because of an implicit cast from a 'char' 9712 // or 'short' to an 'int'. This is done because printf is a varargs 9713 // function. 9714 if (ICE->getType() == S.Context.IntTy || 9715 ICE->getType() == S.Context.UnsignedIntTy) { 9716 // All further checking is done on the subexpression 9717 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9718 AT.matchesType(S.Context, ExprTy); 9719 if (ImplicitMatch == analyze_printf::ArgType::Match) 9720 return true; 9721 if (ImplicitMatch == ArgType::NoMatchPedantic || 9722 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9723 Match = ImplicitMatch; 9724 } 9725 } 9726 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9727 // Special case for 'a', which has type 'int' in C. 9728 // Note, however, that we do /not/ want to treat multibyte constants like 9729 // 'MooV' as characters! This form is deprecated but still exists. In 9730 // addition, don't treat expressions as of type 'char' if one byte length 9731 // modifier is provided. 9732 if (ExprTy == S.Context.IntTy && 9733 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9734 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9735 ExprTy = S.Context.CharTy; 9736 } 9737 9738 // Look through enums to their underlying type. 9739 bool IsEnum = false; 9740 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9741 ExprTy = EnumTy->getDecl()->getIntegerType(); 9742 IsEnum = true; 9743 } 9744 9745 // %C in an Objective-C context prints a unichar, not a wchar_t. 9746 // If the argument is an integer of some kind, believe the %C and suggest 9747 // a cast instead of changing the conversion specifier. 9748 QualType IntendedTy = ExprTy; 9749 if (isObjCContext() && 9750 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9751 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9752 !ExprTy->isCharType()) { 9753 // 'unichar' is defined as a typedef of unsigned short, but we should 9754 // prefer using the typedef if it is visible. 9755 IntendedTy = S.Context.UnsignedShortTy; 9756 9757 // While we are here, check if the value is an IntegerLiteral that happens 9758 // to be within the valid range. 9759 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9760 const llvm::APInt &V = IL->getValue(); 9761 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9762 return true; 9763 } 9764 9765 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9766 Sema::LookupOrdinaryName); 9767 if (S.LookupName(Result, S.getCurScope())) { 9768 NamedDecl *ND = Result.getFoundDecl(); 9769 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9770 if (TD->getUnderlyingType() == IntendedTy) 9771 IntendedTy = S.Context.getTypedefType(TD); 9772 } 9773 } 9774 } 9775 9776 // Special-case some of Darwin's platform-independence types by suggesting 9777 // casts to primitive types that are known to be large enough. 9778 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9779 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9780 QualType CastTy; 9781 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9782 if (!CastTy.isNull()) { 9783 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9784 // (long in ASTContext). Only complain to pedants. 9785 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9786 (AT.isSizeT() || AT.isPtrdiffT()) && 9787 AT.matchesType(S.Context, CastTy)) 9788 Match = ArgType::NoMatchPedantic; 9789 IntendedTy = CastTy; 9790 ShouldNotPrintDirectly = true; 9791 } 9792 } 9793 9794 // We may be able to offer a FixItHint if it is a supported type. 9795 PrintfSpecifier fixedFS = FS; 9796 bool Success = 9797 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9798 9799 if (Success) { 9800 // Get the fix string from the fixed format specifier 9801 SmallString<16> buf; 9802 llvm::raw_svector_ostream os(buf); 9803 fixedFS.toString(os); 9804 9805 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9806 9807 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9808 unsigned Diag; 9809 switch (Match) { 9810 case ArgType::Match: llvm_unreachable("expected non-matching"); 9811 case ArgType::NoMatchPedantic: 9812 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9813 break; 9814 case ArgType::NoMatchTypeConfusion: 9815 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9816 break; 9817 case ArgType::NoMatch: 9818 Diag = diag::warn_format_conversion_argument_type_mismatch; 9819 break; 9820 } 9821 9822 // In this case, the specifier is wrong and should be changed to match 9823 // the argument. 9824 EmitFormatDiagnostic(S.PDiag(Diag) 9825 << AT.getRepresentativeTypeName(S.Context) 9826 << IntendedTy << IsEnum << E->getSourceRange(), 9827 E->getBeginLoc(), 9828 /*IsStringLocation*/ false, SpecRange, 9829 FixItHint::CreateReplacement(SpecRange, os.str())); 9830 } else { 9831 // The canonical type for formatting this value is different from the 9832 // actual type of the expression. (This occurs, for example, with Darwin's 9833 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9834 // should be printed as 'long' for 64-bit compatibility.) 9835 // Rather than emitting a normal format/argument mismatch, we want to 9836 // add a cast to the recommended type (and correct the format string 9837 // if necessary). 9838 SmallString<16> CastBuf; 9839 llvm::raw_svector_ostream CastFix(CastBuf); 9840 CastFix << "("; 9841 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9842 CastFix << ")"; 9843 9844 SmallVector<FixItHint,4> Hints; 9845 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9846 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9847 9848 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9849 // If there's already a cast present, just replace it. 9850 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9851 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9852 9853 } else if (!requiresParensToAddCast(E)) { 9854 // If the expression has high enough precedence, 9855 // just write the C-style cast. 9856 Hints.push_back( 9857 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9858 } else { 9859 // Otherwise, add parens around the expression as well as the cast. 9860 CastFix << "("; 9861 Hints.push_back( 9862 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9863 9864 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9865 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9866 } 9867 9868 if (ShouldNotPrintDirectly) { 9869 // The expression has a type that should not be printed directly. 9870 // We extract the name from the typedef because we don't want to show 9871 // the underlying type in the diagnostic. 9872 StringRef Name; 9873 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9874 Name = TypedefTy->getDecl()->getName(); 9875 else 9876 Name = CastTyName; 9877 unsigned Diag = Match == ArgType::NoMatchPedantic 9878 ? diag::warn_format_argument_needs_cast_pedantic 9879 : diag::warn_format_argument_needs_cast; 9880 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9881 << E->getSourceRange(), 9882 E->getBeginLoc(), /*IsStringLocation=*/false, 9883 SpecRange, Hints); 9884 } else { 9885 // In this case, the expression could be printed using a different 9886 // specifier, but we've decided that the specifier is probably correct 9887 // and we should cast instead. Just use the normal warning message. 9888 EmitFormatDiagnostic( 9889 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9890 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9891 << E->getSourceRange(), 9892 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9893 } 9894 } 9895 } else { 9896 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9897 SpecifierLen); 9898 // Since the warning for passing non-POD types to variadic functions 9899 // was deferred until now, we emit a warning for non-POD 9900 // arguments here. 9901 switch (S.isValidVarArgType(ExprTy)) { 9902 case Sema::VAK_Valid: 9903 case Sema::VAK_ValidInCXX11: { 9904 unsigned Diag; 9905 switch (Match) { 9906 case ArgType::Match: llvm_unreachable("expected non-matching"); 9907 case ArgType::NoMatchPedantic: 9908 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9909 break; 9910 case ArgType::NoMatchTypeConfusion: 9911 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9912 break; 9913 case ArgType::NoMatch: 9914 Diag = diag::warn_format_conversion_argument_type_mismatch; 9915 break; 9916 } 9917 9918 EmitFormatDiagnostic( 9919 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9920 << IsEnum << CSR << E->getSourceRange(), 9921 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9922 break; 9923 } 9924 case Sema::VAK_Undefined: 9925 case Sema::VAK_MSVCUndefined: 9926 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9927 << S.getLangOpts().CPlusPlus11 << ExprTy 9928 << CallType 9929 << AT.getRepresentativeTypeName(S.Context) << CSR 9930 << E->getSourceRange(), 9931 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9932 checkForCStrMembers(AT, E); 9933 break; 9934 9935 case Sema::VAK_Invalid: 9936 if (ExprTy->isObjCObjectType()) 9937 EmitFormatDiagnostic( 9938 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9939 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9940 << AT.getRepresentativeTypeName(S.Context) << CSR 9941 << E->getSourceRange(), 9942 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9943 else 9944 // FIXME: If this is an initializer list, suggest removing the braces 9945 // or inserting a cast to the target type. 9946 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9947 << isa<InitListExpr>(E) << ExprTy << CallType 9948 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9949 break; 9950 } 9951 9952 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9953 "format string specifier index out of range"); 9954 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9955 } 9956 9957 return true; 9958 } 9959 9960 //===--- CHECK: Scanf format string checking ------------------------------===// 9961 9962 namespace { 9963 9964 class CheckScanfHandler : public CheckFormatHandler { 9965 public: 9966 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9967 const Expr *origFormatExpr, Sema::FormatStringType type, 9968 unsigned firstDataArg, unsigned numDataArgs, 9969 const char *beg, bool hasVAListArg, 9970 ArrayRef<const Expr *> Args, unsigned formatIdx, 9971 bool inFunctionCall, Sema::VariadicCallType CallType, 9972 llvm::SmallBitVector &CheckedVarArgs, 9973 UncoveredArgHandler &UncoveredArg) 9974 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9975 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9976 inFunctionCall, CallType, CheckedVarArgs, 9977 UncoveredArg) {} 9978 9979 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9980 const char *startSpecifier, 9981 unsigned specifierLen) override; 9982 9983 bool HandleInvalidScanfConversionSpecifier( 9984 const analyze_scanf::ScanfSpecifier &FS, 9985 const char *startSpecifier, 9986 unsigned specifierLen) override; 9987 9988 void HandleIncompleteScanList(const char *start, const char *end) override; 9989 }; 9990 9991 } // namespace 9992 9993 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9994 const char *end) { 9995 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9996 getLocationOfByte(end), /*IsStringLocation*/true, 9997 getSpecifierRange(start, end - start)); 9998 } 9999 10000 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 10001 const analyze_scanf::ScanfSpecifier &FS, 10002 const char *startSpecifier, 10003 unsigned specifierLen) { 10004 const analyze_scanf::ScanfConversionSpecifier &CS = 10005 FS.getConversionSpecifier(); 10006 10007 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 10008 getLocationOfByte(CS.getStart()), 10009 startSpecifier, specifierLen, 10010 CS.getStart(), CS.getLength()); 10011 } 10012 10013 bool CheckScanfHandler::HandleScanfSpecifier( 10014 const analyze_scanf::ScanfSpecifier &FS, 10015 const char *startSpecifier, 10016 unsigned specifierLen) { 10017 using namespace analyze_scanf; 10018 using namespace analyze_format_string; 10019 10020 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 10021 10022 // Handle case where '%' and '*' don't consume an argument. These shouldn't 10023 // be used to decide if we are using positional arguments consistently. 10024 if (FS.consumesDataArgument()) { 10025 if (atFirstArg) { 10026 atFirstArg = false; 10027 usesPositionalArgs = FS.usesPositionalArg(); 10028 } 10029 else if (usesPositionalArgs != FS.usesPositionalArg()) { 10030 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 10031 startSpecifier, specifierLen); 10032 return false; 10033 } 10034 } 10035 10036 // Check if the field with is non-zero. 10037 const OptionalAmount &Amt = FS.getFieldWidth(); 10038 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 10039 if (Amt.getConstantAmount() == 0) { 10040 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 10041 Amt.getConstantLength()); 10042 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 10043 getLocationOfByte(Amt.getStart()), 10044 /*IsStringLocation*/true, R, 10045 FixItHint::CreateRemoval(R)); 10046 } 10047 } 10048 10049 if (!FS.consumesDataArgument()) { 10050 // FIXME: Technically specifying a precision or field width here 10051 // makes no sense. Worth issuing a warning at some point. 10052 return true; 10053 } 10054 10055 // Consume the argument. 10056 unsigned argIndex = FS.getArgIndex(); 10057 if (argIndex < NumDataArgs) { 10058 // The check to see if the argIndex is valid will come later. 10059 // We set the bit here because we may exit early from this 10060 // function if we encounter some other error. 10061 CoveredArgs.set(argIndex); 10062 } 10063 10064 // Check the length modifier is valid with the given conversion specifier. 10065 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 10066 S.getLangOpts())) 10067 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 10068 diag::warn_format_nonsensical_length); 10069 else if (!FS.hasStandardLengthModifier()) 10070 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 10071 else if (!FS.hasStandardLengthConversionCombination()) 10072 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 10073 diag::warn_format_non_standard_conversion_spec); 10074 10075 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 10076 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 10077 10078 // The remaining checks depend on the data arguments. 10079 if (HasVAListArg) 10080 return true; 10081 10082 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 10083 return false; 10084 10085 // Check that the argument type matches the format specifier. 10086 const Expr *Ex = getDataArg(argIndex); 10087 if (!Ex) 10088 return true; 10089 10090 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 10091 10092 if (!AT.isValid()) { 10093 return true; 10094 } 10095 10096 analyze_format_string::ArgType::MatchKind Match = 10097 AT.matchesType(S.Context, Ex->getType()); 10098 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 10099 if (Match == analyze_format_string::ArgType::Match) 10100 return true; 10101 10102 ScanfSpecifier fixedFS = FS; 10103 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 10104 S.getLangOpts(), S.Context); 10105 10106 unsigned Diag = 10107 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 10108 : diag::warn_format_conversion_argument_type_mismatch; 10109 10110 if (Success) { 10111 // Get the fix string from the fixed format specifier. 10112 SmallString<128> buf; 10113 llvm::raw_svector_ostream os(buf); 10114 fixedFS.toString(os); 10115 10116 EmitFormatDiagnostic( 10117 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 10118 << Ex->getType() << false << Ex->getSourceRange(), 10119 Ex->getBeginLoc(), 10120 /*IsStringLocation*/ false, 10121 getSpecifierRange(startSpecifier, specifierLen), 10122 FixItHint::CreateReplacement( 10123 getSpecifierRange(startSpecifier, specifierLen), os.str())); 10124 } else { 10125 EmitFormatDiagnostic(S.PDiag(Diag) 10126 << AT.getRepresentativeTypeName(S.Context) 10127 << Ex->getType() << false << Ex->getSourceRange(), 10128 Ex->getBeginLoc(), 10129 /*IsStringLocation*/ false, 10130 getSpecifierRange(startSpecifier, specifierLen)); 10131 } 10132 10133 return true; 10134 } 10135 10136 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 10137 const Expr *OrigFormatExpr, 10138 ArrayRef<const Expr *> Args, 10139 bool HasVAListArg, unsigned format_idx, 10140 unsigned firstDataArg, 10141 Sema::FormatStringType Type, 10142 bool inFunctionCall, 10143 Sema::VariadicCallType CallType, 10144 llvm::SmallBitVector &CheckedVarArgs, 10145 UncoveredArgHandler &UncoveredArg, 10146 bool IgnoreStringsWithoutSpecifiers) { 10147 // CHECK: is the format string a wide literal? 10148 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 10149 CheckFormatHandler::EmitFormatDiagnostic( 10150 S, inFunctionCall, Args[format_idx], 10151 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 10152 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 10153 return; 10154 } 10155 10156 // Str - The format string. NOTE: this is NOT null-terminated! 10157 StringRef StrRef = FExpr->getString(); 10158 const char *Str = StrRef.data(); 10159 // Account for cases where the string literal is truncated in a declaration. 10160 const ConstantArrayType *T = 10161 S.Context.getAsConstantArrayType(FExpr->getType()); 10162 assert(T && "String literal not of constant array type!"); 10163 size_t TypeSize = T->getSize().getZExtValue(); 10164 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10165 const unsigned numDataArgs = Args.size() - firstDataArg; 10166 10167 if (IgnoreStringsWithoutSpecifiers && 10168 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 10169 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 10170 return; 10171 10172 // Emit a warning if the string literal is truncated and does not contain an 10173 // embedded null character. 10174 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 10175 CheckFormatHandler::EmitFormatDiagnostic( 10176 S, inFunctionCall, Args[format_idx], 10177 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 10178 FExpr->getBeginLoc(), 10179 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 10180 return; 10181 } 10182 10183 // CHECK: empty format string? 10184 if (StrLen == 0 && numDataArgs > 0) { 10185 CheckFormatHandler::EmitFormatDiagnostic( 10186 S, inFunctionCall, Args[format_idx], 10187 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 10188 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 10189 return; 10190 } 10191 10192 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 10193 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 10194 Type == Sema::FST_OSTrace) { 10195 CheckPrintfHandler H( 10196 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 10197 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 10198 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 10199 CheckedVarArgs, UncoveredArg); 10200 10201 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 10202 S.getLangOpts(), 10203 S.Context.getTargetInfo(), 10204 Type == Sema::FST_FreeBSDKPrintf)) 10205 H.DoneProcessing(); 10206 } else if (Type == Sema::FST_Scanf) { 10207 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 10208 numDataArgs, Str, HasVAListArg, Args, format_idx, 10209 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 10210 10211 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 10212 S.getLangOpts(), 10213 S.Context.getTargetInfo())) 10214 H.DoneProcessing(); 10215 } // TODO: handle other formats 10216 } 10217 10218 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 10219 // Str - The format string. NOTE: this is NOT null-terminated! 10220 StringRef StrRef = FExpr->getString(); 10221 const char *Str = StrRef.data(); 10222 // Account for cases where the string literal is truncated in a declaration. 10223 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 10224 assert(T && "String literal not of constant array type!"); 10225 size_t TypeSize = T->getSize().getZExtValue(); 10226 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10227 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 10228 getLangOpts(), 10229 Context.getTargetInfo()); 10230 } 10231 10232 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 10233 10234 // Returns the related absolute value function that is larger, of 0 if one 10235 // does not exist. 10236 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 10237 switch (AbsFunction) { 10238 default: 10239 return 0; 10240 10241 case Builtin::BI__builtin_abs: 10242 return Builtin::BI__builtin_labs; 10243 case Builtin::BI__builtin_labs: 10244 return Builtin::BI__builtin_llabs; 10245 case Builtin::BI__builtin_llabs: 10246 return 0; 10247 10248 case Builtin::BI__builtin_fabsf: 10249 return Builtin::BI__builtin_fabs; 10250 case Builtin::BI__builtin_fabs: 10251 return Builtin::BI__builtin_fabsl; 10252 case Builtin::BI__builtin_fabsl: 10253 return 0; 10254 10255 case Builtin::BI__builtin_cabsf: 10256 return Builtin::BI__builtin_cabs; 10257 case Builtin::BI__builtin_cabs: 10258 return Builtin::BI__builtin_cabsl; 10259 case Builtin::BI__builtin_cabsl: 10260 return 0; 10261 10262 case Builtin::BIabs: 10263 return Builtin::BIlabs; 10264 case Builtin::BIlabs: 10265 return Builtin::BIllabs; 10266 case Builtin::BIllabs: 10267 return 0; 10268 10269 case Builtin::BIfabsf: 10270 return Builtin::BIfabs; 10271 case Builtin::BIfabs: 10272 return Builtin::BIfabsl; 10273 case Builtin::BIfabsl: 10274 return 0; 10275 10276 case Builtin::BIcabsf: 10277 return Builtin::BIcabs; 10278 case Builtin::BIcabs: 10279 return Builtin::BIcabsl; 10280 case Builtin::BIcabsl: 10281 return 0; 10282 } 10283 } 10284 10285 // Returns the argument type of the absolute value function. 10286 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 10287 unsigned AbsType) { 10288 if (AbsType == 0) 10289 return QualType(); 10290 10291 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 10292 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 10293 if (Error != ASTContext::GE_None) 10294 return QualType(); 10295 10296 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 10297 if (!FT) 10298 return QualType(); 10299 10300 if (FT->getNumParams() != 1) 10301 return QualType(); 10302 10303 return FT->getParamType(0); 10304 } 10305 10306 // Returns the best absolute value function, or zero, based on type and 10307 // current absolute value function. 10308 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 10309 unsigned AbsFunctionKind) { 10310 unsigned BestKind = 0; 10311 uint64_t ArgSize = Context.getTypeSize(ArgType); 10312 for (unsigned Kind = AbsFunctionKind; Kind != 0; 10313 Kind = getLargerAbsoluteValueFunction(Kind)) { 10314 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 10315 if (Context.getTypeSize(ParamType) >= ArgSize) { 10316 if (BestKind == 0) 10317 BestKind = Kind; 10318 else if (Context.hasSameType(ParamType, ArgType)) { 10319 BestKind = Kind; 10320 break; 10321 } 10322 } 10323 } 10324 return BestKind; 10325 } 10326 10327 enum AbsoluteValueKind { 10328 AVK_Integer, 10329 AVK_Floating, 10330 AVK_Complex 10331 }; 10332 10333 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 10334 if (T->isIntegralOrEnumerationType()) 10335 return AVK_Integer; 10336 if (T->isRealFloatingType()) 10337 return AVK_Floating; 10338 if (T->isAnyComplexType()) 10339 return AVK_Complex; 10340 10341 llvm_unreachable("Type not integer, floating, or complex"); 10342 } 10343 10344 // Changes the absolute value function to a different type. Preserves whether 10345 // the function is a builtin. 10346 static unsigned changeAbsFunction(unsigned AbsKind, 10347 AbsoluteValueKind ValueKind) { 10348 switch (ValueKind) { 10349 case AVK_Integer: 10350 switch (AbsKind) { 10351 default: 10352 return 0; 10353 case Builtin::BI__builtin_fabsf: 10354 case Builtin::BI__builtin_fabs: 10355 case Builtin::BI__builtin_fabsl: 10356 case Builtin::BI__builtin_cabsf: 10357 case Builtin::BI__builtin_cabs: 10358 case Builtin::BI__builtin_cabsl: 10359 return Builtin::BI__builtin_abs; 10360 case Builtin::BIfabsf: 10361 case Builtin::BIfabs: 10362 case Builtin::BIfabsl: 10363 case Builtin::BIcabsf: 10364 case Builtin::BIcabs: 10365 case Builtin::BIcabsl: 10366 return Builtin::BIabs; 10367 } 10368 case AVK_Floating: 10369 switch (AbsKind) { 10370 default: 10371 return 0; 10372 case Builtin::BI__builtin_abs: 10373 case Builtin::BI__builtin_labs: 10374 case Builtin::BI__builtin_llabs: 10375 case Builtin::BI__builtin_cabsf: 10376 case Builtin::BI__builtin_cabs: 10377 case Builtin::BI__builtin_cabsl: 10378 return Builtin::BI__builtin_fabsf; 10379 case Builtin::BIabs: 10380 case Builtin::BIlabs: 10381 case Builtin::BIllabs: 10382 case Builtin::BIcabsf: 10383 case Builtin::BIcabs: 10384 case Builtin::BIcabsl: 10385 return Builtin::BIfabsf; 10386 } 10387 case AVK_Complex: 10388 switch (AbsKind) { 10389 default: 10390 return 0; 10391 case Builtin::BI__builtin_abs: 10392 case Builtin::BI__builtin_labs: 10393 case Builtin::BI__builtin_llabs: 10394 case Builtin::BI__builtin_fabsf: 10395 case Builtin::BI__builtin_fabs: 10396 case Builtin::BI__builtin_fabsl: 10397 return Builtin::BI__builtin_cabsf; 10398 case Builtin::BIabs: 10399 case Builtin::BIlabs: 10400 case Builtin::BIllabs: 10401 case Builtin::BIfabsf: 10402 case Builtin::BIfabs: 10403 case Builtin::BIfabsl: 10404 return Builtin::BIcabsf; 10405 } 10406 } 10407 llvm_unreachable("Unable to convert function"); 10408 } 10409 10410 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10411 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10412 if (!FnInfo) 10413 return 0; 10414 10415 switch (FDecl->getBuiltinID()) { 10416 default: 10417 return 0; 10418 case Builtin::BI__builtin_abs: 10419 case Builtin::BI__builtin_fabs: 10420 case Builtin::BI__builtin_fabsf: 10421 case Builtin::BI__builtin_fabsl: 10422 case Builtin::BI__builtin_labs: 10423 case Builtin::BI__builtin_llabs: 10424 case Builtin::BI__builtin_cabs: 10425 case Builtin::BI__builtin_cabsf: 10426 case Builtin::BI__builtin_cabsl: 10427 case Builtin::BIabs: 10428 case Builtin::BIlabs: 10429 case Builtin::BIllabs: 10430 case Builtin::BIfabs: 10431 case Builtin::BIfabsf: 10432 case Builtin::BIfabsl: 10433 case Builtin::BIcabs: 10434 case Builtin::BIcabsf: 10435 case Builtin::BIcabsl: 10436 return FDecl->getBuiltinID(); 10437 } 10438 llvm_unreachable("Unknown Builtin type"); 10439 } 10440 10441 // If the replacement is valid, emit a note with replacement function. 10442 // Additionally, suggest including the proper header if not already included. 10443 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10444 unsigned AbsKind, QualType ArgType) { 10445 bool EmitHeaderHint = true; 10446 const char *HeaderName = nullptr; 10447 const char *FunctionName = nullptr; 10448 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10449 FunctionName = "std::abs"; 10450 if (ArgType->isIntegralOrEnumerationType()) { 10451 HeaderName = "cstdlib"; 10452 } else if (ArgType->isRealFloatingType()) { 10453 HeaderName = "cmath"; 10454 } else { 10455 llvm_unreachable("Invalid Type"); 10456 } 10457 10458 // Lookup all std::abs 10459 if (NamespaceDecl *Std = S.getStdNamespace()) { 10460 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10461 R.suppressDiagnostics(); 10462 S.LookupQualifiedName(R, Std); 10463 10464 for (const auto *I : R) { 10465 const FunctionDecl *FDecl = nullptr; 10466 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10467 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10468 } else { 10469 FDecl = dyn_cast<FunctionDecl>(I); 10470 } 10471 if (!FDecl) 10472 continue; 10473 10474 // Found std::abs(), check that they are the right ones. 10475 if (FDecl->getNumParams() != 1) 10476 continue; 10477 10478 // Check that the parameter type can handle the argument. 10479 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10480 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10481 S.Context.getTypeSize(ArgType) <= 10482 S.Context.getTypeSize(ParamType)) { 10483 // Found a function, don't need the header hint. 10484 EmitHeaderHint = false; 10485 break; 10486 } 10487 } 10488 } 10489 } else { 10490 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10491 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10492 10493 if (HeaderName) { 10494 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10495 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10496 R.suppressDiagnostics(); 10497 S.LookupName(R, S.getCurScope()); 10498 10499 if (R.isSingleResult()) { 10500 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10501 if (FD && FD->getBuiltinID() == AbsKind) { 10502 EmitHeaderHint = false; 10503 } else { 10504 return; 10505 } 10506 } else if (!R.empty()) { 10507 return; 10508 } 10509 } 10510 } 10511 10512 S.Diag(Loc, diag::note_replace_abs_function) 10513 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10514 10515 if (!HeaderName) 10516 return; 10517 10518 if (!EmitHeaderHint) 10519 return; 10520 10521 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10522 << FunctionName; 10523 } 10524 10525 template <std::size_t StrLen> 10526 static bool IsStdFunction(const FunctionDecl *FDecl, 10527 const char (&Str)[StrLen]) { 10528 if (!FDecl) 10529 return false; 10530 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10531 return false; 10532 if (!FDecl->isInStdNamespace()) 10533 return false; 10534 10535 return true; 10536 } 10537 10538 // Warn when using the wrong abs() function. 10539 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10540 const FunctionDecl *FDecl) { 10541 if (Call->getNumArgs() != 1) 10542 return; 10543 10544 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10545 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10546 if (AbsKind == 0 && !IsStdAbs) 10547 return; 10548 10549 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10550 QualType ParamType = Call->getArg(0)->getType(); 10551 10552 // Unsigned types cannot be negative. Suggest removing the absolute value 10553 // function call. 10554 if (ArgType->isUnsignedIntegerType()) { 10555 const char *FunctionName = 10556 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10557 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10558 Diag(Call->getExprLoc(), diag::note_remove_abs) 10559 << FunctionName 10560 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10561 return; 10562 } 10563 10564 // Taking the absolute value of a pointer is very suspicious, they probably 10565 // wanted to index into an array, dereference a pointer, call a function, etc. 10566 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10567 unsigned DiagType = 0; 10568 if (ArgType->isFunctionType()) 10569 DiagType = 1; 10570 else if (ArgType->isArrayType()) 10571 DiagType = 2; 10572 10573 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10574 return; 10575 } 10576 10577 // std::abs has overloads which prevent most of the absolute value problems 10578 // from occurring. 10579 if (IsStdAbs) 10580 return; 10581 10582 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10583 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10584 10585 // The argument and parameter are the same kind. Check if they are the right 10586 // size. 10587 if (ArgValueKind == ParamValueKind) { 10588 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10589 return; 10590 10591 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10592 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10593 << FDecl << ArgType << ParamType; 10594 10595 if (NewAbsKind == 0) 10596 return; 10597 10598 emitReplacement(*this, Call->getExprLoc(), 10599 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10600 return; 10601 } 10602 10603 // ArgValueKind != ParamValueKind 10604 // The wrong type of absolute value function was used. Attempt to find the 10605 // proper one. 10606 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10607 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10608 if (NewAbsKind == 0) 10609 return; 10610 10611 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10612 << FDecl << ParamValueKind << ArgValueKind; 10613 10614 emitReplacement(*this, Call->getExprLoc(), 10615 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10616 } 10617 10618 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10619 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10620 const FunctionDecl *FDecl) { 10621 if (!Call || !FDecl) return; 10622 10623 // Ignore template specializations and macros. 10624 if (inTemplateInstantiation()) return; 10625 if (Call->getExprLoc().isMacroID()) return; 10626 10627 // Only care about the one template argument, two function parameter std::max 10628 if (Call->getNumArgs() != 2) return; 10629 if (!IsStdFunction(FDecl, "max")) return; 10630 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10631 if (!ArgList) return; 10632 if (ArgList->size() != 1) return; 10633 10634 // Check that template type argument is unsigned integer. 10635 const auto& TA = ArgList->get(0); 10636 if (TA.getKind() != TemplateArgument::Type) return; 10637 QualType ArgType = TA.getAsType(); 10638 if (!ArgType->isUnsignedIntegerType()) return; 10639 10640 // See if either argument is a literal zero. 10641 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10642 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10643 if (!MTE) return false; 10644 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10645 if (!Num) return false; 10646 if (Num->getValue() != 0) return false; 10647 return true; 10648 }; 10649 10650 const Expr *FirstArg = Call->getArg(0); 10651 const Expr *SecondArg = Call->getArg(1); 10652 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10653 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10654 10655 // Only warn when exactly one argument is zero. 10656 if (IsFirstArgZero == IsSecondArgZero) return; 10657 10658 SourceRange FirstRange = FirstArg->getSourceRange(); 10659 SourceRange SecondRange = SecondArg->getSourceRange(); 10660 10661 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10662 10663 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10664 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10665 10666 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10667 SourceRange RemovalRange; 10668 if (IsFirstArgZero) { 10669 RemovalRange = SourceRange(FirstRange.getBegin(), 10670 SecondRange.getBegin().getLocWithOffset(-1)); 10671 } else { 10672 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10673 SecondRange.getEnd()); 10674 } 10675 10676 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10677 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10678 << FixItHint::CreateRemoval(RemovalRange); 10679 } 10680 10681 //===--- CHECK: Standard memory functions ---------------------------------===// 10682 10683 /// Takes the expression passed to the size_t parameter of functions 10684 /// such as memcmp, strncat, etc and warns if it's a comparison. 10685 /// 10686 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10687 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10688 IdentifierInfo *FnName, 10689 SourceLocation FnLoc, 10690 SourceLocation RParenLoc) { 10691 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10692 if (!Size) 10693 return false; 10694 10695 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10696 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10697 return false; 10698 10699 SourceRange SizeRange = Size->getSourceRange(); 10700 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10701 << SizeRange << FnName; 10702 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10703 << FnName 10704 << FixItHint::CreateInsertion( 10705 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10706 << FixItHint::CreateRemoval(RParenLoc); 10707 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10708 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10709 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10710 ")"); 10711 10712 return true; 10713 } 10714 10715 /// Determine whether the given type is or contains a dynamic class type 10716 /// (e.g., whether it has a vtable). 10717 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10718 bool &IsContained) { 10719 // Look through array types while ignoring qualifiers. 10720 const Type *Ty = T->getBaseElementTypeUnsafe(); 10721 IsContained = false; 10722 10723 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10724 RD = RD ? RD->getDefinition() : nullptr; 10725 if (!RD || RD->isInvalidDecl()) 10726 return nullptr; 10727 10728 if (RD->isDynamicClass()) 10729 return RD; 10730 10731 // Check all the fields. If any bases were dynamic, the class is dynamic. 10732 // It's impossible for a class to transitively contain itself by value, so 10733 // infinite recursion is impossible. 10734 for (auto *FD : RD->fields()) { 10735 bool SubContained; 10736 if (const CXXRecordDecl *ContainedRD = 10737 getContainedDynamicClass(FD->getType(), SubContained)) { 10738 IsContained = true; 10739 return ContainedRD; 10740 } 10741 } 10742 10743 return nullptr; 10744 } 10745 10746 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10747 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10748 if (Unary->getKind() == UETT_SizeOf) 10749 return Unary; 10750 return nullptr; 10751 } 10752 10753 /// If E is a sizeof expression, returns its argument expression, 10754 /// otherwise returns NULL. 10755 static const Expr *getSizeOfExprArg(const Expr *E) { 10756 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10757 if (!SizeOf->isArgumentType()) 10758 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10759 return nullptr; 10760 } 10761 10762 /// If E is a sizeof expression, returns its argument type. 10763 static QualType getSizeOfArgType(const Expr *E) { 10764 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10765 return SizeOf->getTypeOfArgument(); 10766 return QualType(); 10767 } 10768 10769 namespace { 10770 10771 struct SearchNonTrivialToInitializeField 10772 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10773 using Super = 10774 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10775 10776 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10777 10778 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10779 SourceLocation SL) { 10780 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10781 asDerived().visitArray(PDIK, AT, SL); 10782 return; 10783 } 10784 10785 Super::visitWithKind(PDIK, FT, SL); 10786 } 10787 10788 void visitARCStrong(QualType FT, SourceLocation SL) { 10789 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10790 } 10791 void visitARCWeak(QualType FT, SourceLocation SL) { 10792 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10793 } 10794 void visitStruct(QualType FT, SourceLocation SL) { 10795 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10796 visit(FD->getType(), FD->getLocation()); 10797 } 10798 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10799 const ArrayType *AT, SourceLocation SL) { 10800 visit(getContext().getBaseElementType(AT), SL); 10801 } 10802 void visitTrivial(QualType FT, SourceLocation SL) {} 10803 10804 static void diag(QualType RT, const Expr *E, Sema &S) { 10805 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10806 } 10807 10808 ASTContext &getContext() { return S.getASTContext(); } 10809 10810 const Expr *E; 10811 Sema &S; 10812 }; 10813 10814 struct SearchNonTrivialToCopyField 10815 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10816 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10817 10818 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10819 10820 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10821 SourceLocation SL) { 10822 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10823 asDerived().visitArray(PCK, AT, SL); 10824 return; 10825 } 10826 10827 Super::visitWithKind(PCK, FT, SL); 10828 } 10829 10830 void visitARCStrong(QualType FT, SourceLocation SL) { 10831 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10832 } 10833 void visitARCWeak(QualType FT, SourceLocation SL) { 10834 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10835 } 10836 void visitStruct(QualType FT, SourceLocation SL) { 10837 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10838 visit(FD->getType(), FD->getLocation()); 10839 } 10840 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10841 SourceLocation SL) { 10842 visit(getContext().getBaseElementType(AT), SL); 10843 } 10844 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10845 SourceLocation SL) {} 10846 void visitTrivial(QualType FT, SourceLocation SL) {} 10847 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10848 10849 static void diag(QualType RT, const Expr *E, Sema &S) { 10850 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10851 } 10852 10853 ASTContext &getContext() { return S.getASTContext(); } 10854 10855 const Expr *E; 10856 Sema &S; 10857 }; 10858 10859 } 10860 10861 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10862 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10863 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10864 10865 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10866 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10867 return false; 10868 10869 return doesExprLikelyComputeSize(BO->getLHS()) || 10870 doesExprLikelyComputeSize(BO->getRHS()); 10871 } 10872 10873 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10874 } 10875 10876 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10877 /// 10878 /// \code 10879 /// #define MACRO 0 10880 /// foo(MACRO); 10881 /// foo(0); 10882 /// \endcode 10883 /// 10884 /// This should return true for the first call to foo, but not for the second 10885 /// (regardless of whether foo is a macro or function). 10886 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10887 SourceLocation CallLoc, 10888 SourceLocation ArgLoc) { 10889 if (!CallLoc.isMacroID()) 10890 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10891 10892 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10893 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10894 } 10895 10896 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10897 /// last two arguments transposed. 10898 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10899 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10900 return; 10901 10902 const Expr *SizeArg = 10903 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10904 10905 auto isLiteralZero = [](const Expr *E) { 10906 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10907 }; 10908 10909 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10910 SourceLocation CallLoc = Call->getRParenLoc(); 10911 SourceManager &SM = S.getSourceManager(); 10912 if (isLiteralZero(SizeArg) && 10913 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10914 10915 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10916 10917 // Some platforms #define bzero to __builtin_memset. See if this is the 10918 // case, and if so, emit a better diagnostic. 10919 if (BId == Builtin::BIbzero || 10920 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10921 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10922 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10923 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10924 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10925 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10926 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10927 } 10928 return; 10929 } 10930 10931 // If the second argument to a memset is a sizeof expression and the third 10932 // isn't, this is also likely an error. This should catch 10933 // 'memset(buf, sizeof(buf), 0xff)'. 10934 if (BId == Builtin::BImemset && 10935 doesExprLikelyComputeSize(Call->getArg(1)) && 10936 !doesExprLikelyComputeSize(Call->getArg(2))) { 10937 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10938 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10939 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10940 return; 10941 } 10942 } 10943 10944 /// Check for dangerous or invalid arguments to memset(). 10945 /// 10946 /// This issues warnings on known problematic, dangerous or unspecified 10947 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10948 /// function calls. 10949 /// 10950 /// \param Call The call expression to diagnose. 10951 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10952 unsigned BId, 10953 IdentifierInfo *FnName) { 10954 assert(BId != 0); 10955 10956 // It is possible to have a non-standard definition of memset. Validate 10957 // we have enough arguments, and if not, abort further checking. 10958 unsigned ExpectedNumArgs = 10959 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10960 if (Call->getNumArgs() < ExpectedNumArgs) 10961 return; 10962 10963 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10964 BId == Builtin::BIstrndup ? 1 : 2); 10965 unsigned LenArg = 10966 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10967 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10968 10969 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10970 Call->getBeginLoc(), Call->getRParenLoc())) 10971 return; 10972 10973 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10974 CheckMemaccessSize(*this, BId, Call); 10975 10976 // We have special checking when the length is a sizeof expression. 10977 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10978 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10979 llvm::FoldingSetNodeID SizeOfArgID; 10980 10981 // Although widely used, 'bzero' is not a standard function. Be more strict 10982 // with the argument types before allowing diagnostics and only allow the 10983 // form bzero(ptr, sizeof(...)). 10984 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10985 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10986 return; 10987 10988 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10989 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10990 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10991 10992 QualType DestTy = Dest->getType(); 10993 QualType PointeeTy; 10994 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10995 PointeeTy = DestPtrTy->getPointeeType(); 10996 10997 // Never warn about void type pointers. This can be used to suppress 10998 // false positives. 10999 if (PointeeTy->isVoidType()) 11000 continue; 11001 11002 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 11003 // actually comparing the expressions for equality. Because computing the 11004 // expression IDs can be expensive, we only do this if the diagnostic is 11005 // enabled. 11006 if (SizeOfArg && 11007 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 11008 SizeOfArg->getExprLoc())) { 11009 // We only compute IDs for expressions if the warning is enabled, and 11010 // cache the sizeof arg's ID. 11011 if (SizeOfArgID == llvm::FoldingSetNodeID()) 11012 SizeOfArg->Profile(SizeOfArgID, Context, true); 11013 llvm::FoldingSetNodeID DestID; 11014 Dest->Profile(DestID, Context, true); 11015 if (DestID == SizeOfArgID) { 11016 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 11017 // over sizeof(src) as well. 11018 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 11019 StringRef ReadableName = FnName->getName(); 11020 11021 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 11022 if (UnaryOp->getOpcode() == UO_AddrOf) 11023 ActionIdx = 1; // If its an address-of operator, just remove it. 11024 if (!PointeeTy->isIncompleteType() && 11025 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 11026 ActionIdx = 2; // If the pointee's size is sizeof(char), 11027 // suggest an explicit length. 11028 11029 // If the function is defined as a builtin macro, do not show macro 11030 // expansion. 11031 SourceLocation SL = SizeOfArg->getExprLoc(); 11032 SourceRange DSR = Dest->getSourceRange(); 11033 SourceRange SSR = SizeOfArg->getSourceRange(); 11034 SourceManager &SM = getSourceManager(); 11035 11036 if (SM.isMacroArgExpansion(SL)) { 11037 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 11038 SL = SM.getSpellingLoc(SL); 11039 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 11040 SM.getSpellingLoc(DSR.getEnd())); 11041 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 11042 SM.getSpellingLoc(SSR.getEnd())); 11043 } 11044 11045 DiagRuntimeBehavior(SL, SizeOfArg, 11046 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 11047 << ReadableName 11048 << PointeeTy 11049 << DestTy 11050 << DSR 11051 << SSR); 11052 DiagRuntimeBehavior(SL, SizeOfArg, 11053 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 11054 << ActionIdx 11055 << SSR); 11056 11057 break; 11058 } 11059 } 11060 11061 // Also check for cases where the sizeof argument is the exact same 11062 // type as the memory argument, and where it points to a user-defined 11063 // record type. 11064 if (SizeOfArgTy != QualType()) { 11065 if (PointeeTy->isRecordType() && 11066 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 11067 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 11068 PDiag(diag::warn_sizeof_pointer_type_memaccess) 11069 << FnName << SizeOfArgTy << ArgIdx 11070 << PointeeTy << Dest->getSourceRange() 11071 << LenExpr->getSourceRange()); 11072 break; 11073 } 11074 } 11075 } else if (DestTy->isArrayType()) { 11076 PointeeTy = DestTy; 11077 } 11078 11079 if (PointeeTy == QualType()) 11080 continue; 11081 11082 // Always complain about dynamic classes. 11083 bool IsContained; 11084 if (const CXXRecordDecl *ContainedRD = 11085 getContainedDynamicClass(PointeeTy, IsContained)) { 11086 11087 unsigned OperationType = 0; 11088 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 11089 // "overwritten" if we're warning about the destination for any call 11090 // but memcmp; otherwise a verb appropriate to the call. 11091 if (ArgIdx != 0 || IsCmp) { 11092 if (BId == Builtin::BImemcpy) 11093 OperationType = 1; 11094 else if(BId == Builtin::BImemmove) 11095 OperationType = 2; 11096 else if (IsCmp) 11097 OperationType = 3; 11098 } 11099 11100 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11101 PDiag(diag::warn_dyn_class_memaccess) 11102 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 11103 << IsContained << ContainedRD << OperationType 11104 << Call->getCallee()->getSourceRange()); 11105 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 11106 BId != Builtin::BImemset) 11107 DiagRuntimeBehavior( 11108 Dest->getExprLoc(), Dest, 11109 PDiag(diag::warn_arc_object_memaccess) 11110 << ArgIdx << FnName << PointeeTy 11111 << Call->getCallee()->getSourceRange()); 11112 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 11113 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 11114 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 11115 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11116 PDiag(diag::warn_cstruct_memaccess) 11117 << ArgIdx << FnName << PointeeTy << 0); 11118 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 11119 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 11120 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 11121 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11122 PDiag(diag::warn_cstruct_memaccess) 11123 << ArgIdx << FnName << PointeeTy << 1); 11124 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 11125 } else { 11126 continue; 11127 } 11128 } else 11129 continue; 11130 11131 DiagRuntimeBehavior( 11132 Dest->getExprLoc(), Dest, 11133 PDiag(diag::note_bad_memaccess_silence) 11134 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 11135 break; 11136 } 11137 } 11138 11139 // A little helper routine: ignore addition and subtraction of integer literals. 11140 // This intentionally does not ignore all integer constant expressions because 11141 // we don't want to remove sizeof(). 11142 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 11143 Ex = Ex->IgnoreParenCasts(); 11144 11145 while (true) { 11146 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 11147 if (!BO || !BO->isAdditiveOp()) 11148 break; 11149 11150 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 11151 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 11152 11153 if (isa<IntegerLiteral>(RHS)) 11154 Ex = LHS; 11155 else if (isa<IntegerLiteral>(LHS)) 11156 Ex = RHS; 11157 else 11158 break; 11159 } 11160 11161 return Ex; 11162 } 11163 11164 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 11165 ASTContext &Context) { 11166 // Only handle constant-sized or VLAs, but not flexible members. 11167 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 11168 // Only issue the FIXIT for arrays of size > 1. 11169 if (CAT->getSize().getSExtValue() <= 1) 11170 return false; 11171 } else if (!Ty->isVariableArrayType()) { 11172 return false; 11173 } 11174 return true; 11175 } 11176 11177 // Warn if the user has made the 'size' argument to strlcpy or strlcat 11178 // be the size of the source, instead of the destination. 11179 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 11180 IdentifierInfo *FnName) { 11181 11182 // Don't crash if the user has the wrong number of arguments 11183 unsigned NumArgs = Call->getNumArgs(); 11184 if ((NumArgs != 3) && (NumArgs != 4)) 11185 return; 11186 11187 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 11188 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 11189 const Expr *CompareWithSrc = nullptr; 11190 11191 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 11192 Call->getBeginLoc(), Call->getRParenLoc())) 11193 return; 11194 11195 // Look for 'strlcpy(dst, x, sizeof(x))' 11196 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 11197 CompareWithSrc = Ex; 11198 else { 11199 // Look for 'strlcpy(dst, x, strlen(x))' 11200 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 11201 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 11202 SizeCall->getNumArgs() == 1) 11203 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 11204 } 11205 } 11206 11207 if (!CompareWithSrc) 11208 return; 11209 11210 // Determine if the argument to sizeof/strlen is equal to the source 11211 // argument. In principle there's all kinds of things you could do 11212 // here, for instance creating an == expression and evaluating it with 11213 // EvaluateAsBooleanCondition, but this uses a more direct technique: 11214 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 11215 if (!SrcArgDRE) 11216 return; 11217 11218 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 11219 if (!CompareWithSrcDRE || 11220 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 11221 return; 11222 11223 const Expr *OriginalSizeArg = Call->getArg(2); 11224 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 11225 << OriginalSizeArg->getSourceRange() << FnName; 11226 11227 // Output a FIXIT hint if the destination is an array (rather than a 11228 // pointer to an array). This could be enhanced to handle some 11229 // pointers if we know the actual size, like if DstArg is 'array+2' 11230 // we could say 'sizeof(array)-2'. 11231 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 11232 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 11233 return; 11234 11235 SmallString<128> sizeString; 11236 llvm::raw_svector_ostream OS(sizeString); 11237 OS << "sizeof("; 11238 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11239 OS << ")"; 11240 11241 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 11242 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 11243 OS.str()); 11244 } 11245 11246 /// Check if two expressions refer to the same declaration. 11247 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 11248 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 11249 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 11250 return D1->getDecl() == D2->getDecl(); 11251 return false; 11252 } 11253 11254 static const Expr *getStrlenExprArg(const Expr *E) { 11255 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11256 const FunctionDecl *FD = CE->getDirectCallee(); 11257 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 11258 return nullptr; 11259 return CE->getArg(0)->IgnoreParenCasts(); 11260 } 11261 return nullptr; 11262 } 11263 11264 // Warn on anti-patterns as the 'size' argument to strncat. 11265 // The correct size argument should look like following: 11266 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 11267 void Sema::CheckStrncatArguments(const CallExpr *CE, 11268 IdentifierInfo *FnName) { 11269 // Don't crash if the user has the wrong number of arguments. 11270 if (CE->getNumArgs() < 3) 11271 return; 11272 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 11273 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 11274 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 11275 11276 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 11277 CE->getRParenLoc())) 11278 return; 11279 11280 // Identify common expressions, which are wrongly used as the size argument 11281 // to strncat and may lead to buffer overflows. 11282 unsigned PatternType = 0; 11283 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 11284 // - sizeof(dst) 11285 if (referToTheSameDecl(SizeOfArg, DstArg)) 11286 PatternType = 1; 11287 // - sizeof(src) 11288 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 11289 PatternType = 2; 11290 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 11291 if (BE->getOpcode() == BO_Sub) { 11292 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 11293 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 11294 // - sizeof(dst) - strlen(dst) 11295 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 11296 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 11297 PatternType = 1; 11298 // - sizeof(src) - (anything) 11299 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 11300 PatternType = 2; 11301 } 11302 } 11303 11304 if (PatternType == 0) 11305 return; 11306 11307 // Generate the diagnostic. 11308 SourceLocation SL = LenArg->getBeginLoc(); 11309 SourceRange SR = LenArg->getSourceRange(); 11310 SourceManager &SM = getSourceManager(); 11311 11312 // If the function is defined as a builtin macro, do not show macro expansion. 11313 if (SM.isMacroArgExpansion(SL)) { 11314 SL = SM.getSpellingLoc(SL); 11315 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 11316 SM.getSpellingLoc(SR.getEnd())); 11317 } 11318 11319 // Check if the destination is an array (rather than a pointer to an array). 11320 QualType DstTy = DstArg->getType(); 11321 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 11322 Context); 11323 if (!isKnownSizeArray) { 11324 if (PatternType == 1) 11325 Diag(SL, diag::warn_strncat_wrong_size) << SR; 11326 else 11327 Diag(SL, diag::warn_strncat_src_size) << SR; 11328 return; 11329 } 11330 11331 if (PatternType == 1) 11332 Diag(SL, diag::warn_strncat_large_size) << SR; 11333 else 11334 Diag(SL, diag::warn_strncat_src_size) << SR; 11335 11336 SmallString<128> sizeString; 11337 llvm::raw_svector_ostream OS(sizeString); 11338 OS << "sizeof("; 11339 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11340 OS << ") - "; 11341 OS << "strlen("; 11342 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11343 OS << ") - 1"; 11344 11345 Diag(SL, diag::note_strncat_wrong_size) 11346 << FixItHint::CreateReplacement(SR, OS.str()); 11347 } 11348 11349 namespace { 11350 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 11351 const UnaryOperator *UnaryExpr, const Decl *D) { 11352 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 11353 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 11354 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 11355 return; 11356 } 11357 } 11358 11359 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 11360 const UnaryOperator *UnaryExpr) { 11361 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 11362 const Decl *D = Lvalue->getDecl(); 11363 if (isa<DeclaratorDecl>(D)) 11364 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 11365 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 11366 } 11367 11368 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 11369 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 11370 Lvalue->getMemberDecl()); 11371 } 11372 11373 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 11374 const UnaryOperator *UnaryExpr) { 11375 const auto *Lambda = dyn_cast<LambdaExpr>( 11376 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 11377 if (!Lambda) 11378 return; 11379 11380 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 11381 << CalleeName << 2 /*object: lambda expression*/; 11382 } 11383 11384 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 11385 const DeclRefExpr *Lvalue) { 11386 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 11387 if (Var == nullptr) 11388 return; 11389 11390 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 11391 << CalleeName << 0 /*object: */ << Var; 11392 } 11393 11394 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 11395 const CastExpr *Cast) { 11396 SmallString<128> SizeString; 11397 llvm::raw_svector_ostream OS(SizeString); 11398 11399 clang::CastKind Kind = Cast->getCastKind(); 11400 if (Kind == clang::CK_BitCast && 11401 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11402 return; 11403 if (Kind == clang::CK_IntegralToPointer && 11404 !isa<IntegerLiteral>( 11405 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11406 return; 11407 11408 switch (Cast->getCastKind()) { 11409 case clang::CK_BitCast: 11410 case clang::CK_IntegralToPointer: 11411 case clang::CK_FunctionToPointerDecay: 11412 OS << '\''; 11413 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11414 OS << '\''; 11415 break; 11416 default: 11417 return; 11418 } 11419 11420 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11421 << CalleeName << 0 /*object: */ << OS.str(); 11422 } 11423 } // namespace 11424 11425 /// Alerts the user that they are attempting to free a non-malloc'd object. 11426 void Sema::CheckFreeArguments(const CallExpr *E) { 11427 const std::string CalleeName = 11428 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11429 11430 { // Prefer something that doesn't involve a cast to make things simpler. 11431 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11432 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11433 switch (UnaryExpr->getOpcode()) { 11434 case UnaryOperator::Opcode::UO_AddrOf: 11435 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11436 case UnaryOperator::Opcode::UO_Plus: 11437 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11438 default: 11439 break; 11440 } 11441 11442 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11443 if (Lvalue->getType()->isArrayType()) 11444 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11445 11446 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11447 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11448 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11449 return; 11450 } 11451 11452 if (isa<BlockExpr>(Arg)) { 11453 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11454 << CalleeName << 1 /*object: block*/; 11455 return; 11456 } 11457 } 11458 // Maybe the cast was important, check after the other cases. 11459 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11460 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11461 } 11462 11463 void 11464 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11465 SourceLocation ReturnLoc, 11466 bool isObjCMethod, 11467 const AttrVec *Attrs, 11468 const FunctionDecl *FD) { 11469 // Check if the return value is null but should not be. 11470 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11471 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11472 CheckNonNullExpr(*this, RetValExp)) 11473 Diag(ReturnLoc, diag::warn_null_ret) 11474 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11475 11476 // C++11 [basic.stc.dynamic.allocation]p4: 11477 // If an allocation function declared with a non-throwing 11478 // exception-specification fails to allocate storage, it shall return 11479 // a null pointer. Any other allocation function that fails to allocate 11480 // storage shall indicate failure only by throwing an exception [...] 11481 if (FD) { 11482 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11483 if (Op == OO_New || Op == OO_Array_New) { 11484 const FunctionProtoType *Proto 11485 = FD->getType()->castAs<FunctionProtoType>(); 11486 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11487 CheckNonNullExpr(*this, RetValExp)) 11488 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11489 << FD << getLangOpts().CPlusPlus11; 11490 } 11491 } 11492 11493 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11494 // here prevent the user from using a PPC MMA type as trailing return type. 11495 if (Context.getTargetInfo().getTriple().isPPC64()) 11496 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11497 } 11498 11499 /// Check for comparisons of floating-point values using == and !=. Issue a 11500 /// warning if the comparison is not likely to do what the programmer intended. 11501 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, 11502 BinaryOperatorKind Opcode) { 11503 // Match and capture subexpressions such as "(float) X == 0.1". 11504 FloatingLiteral *FPLiteral; 11505 CastExpr *FPCast; 11506 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) { 11507 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens()); 11508 FPCast = dyn_cast<CastExpr>(R->IgnoreParens()); 11509 return FPLiteral && FPCast; 11510 }; 11511 11512 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) { 11513 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>(); 11514 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>(); 11515 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() && 11516 TargetTy->isFloatingPoint()) { 11517 bool Lossy; 11518 llvm::APFloat TargetC = FPLiteral->getValue(); 11519 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)), 11520 llvm::APFloat::rmNearestTiesToEven, &Lossy); 11521 if (Lossy) { 11522 // If the literal cannot be represented in the source type, then a 11523 // check for == is always false and check for != is always true. 11524 Diag(Loc, diag::warn_float_compare_literal) 11525 << (Opcode == BO_EQ) << QualType(SourceTy, 0) 11526 << LHS->getSourceRange() << RHS->getSourceRange(); 11527 return; 11528 } 11529 } 11530 } 11531 11532 // Match a more general floating-point equality comparison (-Wfloat-equal). 11533 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11534 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11535 11536 // Special case: check for x == x (which is OK). 11537 // Do not emit warnings for such cases. 11538 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11539 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11540 if (DRL->getDecl() == DRR->getDecl()) 11541 return; 11542 11543 // Special case: check for comparisons against literals that can be exactly 11544 // represented by APFloat. In such cases, do not emit a warning. This 11545 // is a heuristic: often comparison against such literals are used to 11546 // detect if a value in a variable has not changed. This clearly can 11547 // lead to false negatives. 11548 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11549 if (FLL->isExact()) 11550 return; 11551 } else 11552 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11553 if (FLR->isExact()) 11554 return; 11555 11556 // Check for comparisons with builtin types. 11557 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11558 if (CL->getBuiltinCallee()) 11559 return; 11560 11561 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11562 if (CR->getBuiltinCallee()) 11563 return; 11564 11565 // Emit the diagnostic. 11566 Diag(Loc, diag::warn_floatingpoint_eq) 11567 << LHS->getSourceRange() << RHS->getSourceRange(); 11568 } 11569 11570 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11571 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11572 11573 namespace { 11574 11575 /// Structure recording the 'active' range of an integer-valued 11576 /// expression. 11577 struct IntRange { 11578 /// The number of bits active in the int. Note that this includes exactly one 11579 /// sign bit if !NonNegative. 11580 unsigned Width; 11581 11582 /// True if the int is known not to have negative values. If so, all leading 11583 /// bits before Width are known zero, otherwise they are known to be the 11584 /// same as the MSB within Width. 11585 bool NonNegative; 11586 11587 IntRange(unsigned Width, bool NonNegative) 11588 : Width(Width), NonNegative(NonNegative) {} 11589 11590 /// Number of bits excluding the sign bit. 11591 unsigned valueBits() const { 11592 return NonNegative ? Width : Width - 1; 11593 } 11594 11595 /// Returns the range of the bool type. 11596 static IntRange forBoolType() { 11597 return IntRange(1, true); 11598 } 11599 11600 /// Returns the range of an opaque value of the given integral type. 11601 static IntRange forValueOfType(ASTContext &C, QualType T) { 11602 return forValueOfCanonicalType(C, 11603 T->getCanonicalTypeInternal().getTypePtr()); 11604 } 11605 11606 /// Returns the range of an opaque value of a canonical integral type. 11607 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11608 assert(T->isCanonicalUnqualified()); 11609 11610 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11611 T = VT->getElementType().getTypePtr(); 11612 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11613 T = CT->getElementType().getTypePtr(); 11614 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11615 T = AT->getValueType().getTypePtr(); 11616 11617 if (!C.getLangOpts().CPlusPlus) { 11618 // For enum types in C code, use the underlying datatype. 11619 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11620 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11621 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11622 // For enum types in C++, use the known bit width of the enumerators. 11623 EnumDecl *Enum = ET->getDecl(); 11624 // In C++11, enums can have a fixed underlying type. Use this type to 11625 // compute the range. 11626 if (Enum->isFixed()) { 11627 return IntRange(C.getIntWidth(QualType(T, 0)), 11628 !ET->isSignedIntegerOrEnumerationType()); 11629 } 11630 11631 unsigned NumPositive = Enum->getNumPositiveBits(); 11632 unsigned NumNegative = Enum->getNumNegativeBits(); 11633 11634 if (NumNegative == 0) 11635 return IntRange(NumPositive, true/*NonNegative*/); 11636 else 11637 return IntRange(std::max(NumPositive + 1, NumNegative), 11638 false/*NonNegative*/); 11639 } 11640 11641 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11642 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11643 11644 const BuiltinType *BT = cast<BuiltinType>(T); 11645 assert(BT->isInteger()); 11646 11647 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11648 } 11649 11650 /// Returns the "target" range of a canonical integral type, i.e. 11651 /// the range of values expressible in the type. 11652 /// 11653 /// This matches forValueOfCanonicalType except that enums have the 11654 /// full range of their type, not the range of their enumerators. 11655 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11656 assert(T->isCanonicalUnqualified()); 11657 11658 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11659 T = VT->getElementType().getTypePtr(); 11660 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11661 T = CT->getElementType().getTypePtr(); 11662 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11663 T = AT->getValueType().getTypePtr(); 11664 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11665 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11666 11667 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11668 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11669 11670 const BuiltinType *BT = cast<BuiltinType>(T); 11671 assert(BT->isInteger()); 11672 11673 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11674 } 11675 11676 /// Returns the supremum of two ranges: i.e. their conservative merge. 11677 static IntRange join(IntRange L, IntRange R) { 11678 bool Unsigned = L.NonNegative && R.NonNegative; 11679 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11680 L.NonNegative && R.NonNegative); 11681 } 11682 11683 /// Return the range of a bitwise-AND of the two ranges. 11684 static IntRange bit_and(IntRange L, IntRange R) { 11685 unsigned Bits = std::max(L.Width, R.Width); 11686 bool NonNegative = false; 11687 if (L.NonNegative) { 11688 Bits = std::min(Bits, L.Width); 11689 NonNegative = true; 11690 } 11691 if (R.NonNegative) { 11692 Bits = std::min(Bits, R.Width); 11693 NonNegative = true; 11694 } 11695 return IntRange(Bits, NonNegative); 11696 } 11697 11698 /// Return the range of a sum of the two ranges. 11699 static IntRange sum(IntRange L, IntRange R) { 11700 bool Unsigned = L.NonNegative && R.NonNegative; 11701 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11702 Unsigned); 11703 } 11704 11705 /// Return the range of a difference of the two ranges. 11706 static IntRange difference(IntRange L, IntRange R) { 11707 // We need a 1-bit-wider range if: 11708 // 1) LHS can be negative: least value can be reduced. 11709 // 2) RHS can be negative: greatest value can be increased. 11710 bool CanWiden = !L.NonNegative || !R.NonNegative; 11711 bool Unsigned = L.NonNegative && R.Width == 0; 11712 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11713 !Unsigned, 11714 Unsigned); 11715 } 11716 11717 /// Return the range of a product of the two ranges. 11718 static IntRange product(IntRange L, IntRange R) { 11719 // If both LHS and RHS can be negative, we can form 11720 // -2^L * -2^R = 2^(L + R) 11721 // which requires L + R + 1 value bits to represent. 11722 bool CanWiden = !L.NonNegative && !R.NonNegative; 11723 bool Unsigned = L.NonNegative && R.NonNegative; 11724 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11725 Unsigned); 11726 } 11727 11728 /// Return the range of a remainder operation between the two ranges. 11729 static IntRange rem(IntRange L, IntRange R) { 11730 // The result of a remainder can't be larger than the result of 11731 // either side. The sign of the result is the sign of the LHS. 11732 bool Unsigned = L.NonNegative; 11733 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11734 Unsigned); 11735 } 11736 }; 11737 11738 } // namespace 11739 11740 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11741 unsigned MaxWidth) { 11742 if (value.isSigned() && value.isNegative()) 11743 return IntRange(value.getMinSignedBits(), false); 11744 11745 if (value.getBitWidth() > MaxWidth) 11746 value = value.trunc(MaxWidth); 11747 11748 // isNonNegative() just checks the sign bit without considering 11749 // signedness. 11750 return IntRange(value.getActiveBits(), true); 11751 } 11752 11753 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11754 unsigned MaxWidth) { 11755 if (result.isInt()) 11756 return GetValueRange(C, result.getInt(), MaxWidth); 11757 11758 if (result.isVector()) { 11759 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11760 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11761 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11762 R = IntRange::join(R, El); 11763 } 11764 return R; 11765 } 11766 11767 if (result.isComplexInt()) { 11768 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11769 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11770 return IntRange::join(R, I); 11771 } 11772 11773 // This can happen with lossless casts to intptr_t of "based" lvalues. 11774 // Assume it might use arbitrary bits. 11775 // FIXME: The only reason we need to pass the type in here is to get 11776 // the sign right on this one case. It would be nice if APValue 11777 // preserved this. 11778 assert(result.isLValue() || result.isAddrLabelDiff()); 11779 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11780 } 11781 11782 static QualType GetExprType(const Expr *E) { 11783 QualType Ty = E->getType(); 11784 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11785 Ty = AtomicRHS->getValueType(); 11786 return Ty; 11787 } 11788 11789 /// Pseudo-evaluate the given integer expression, estimating the 11790 /// range of values it might take. 11791 /// 11792 /// \param MaxWidth The width to which the value will be truncated. 11793 /// \param Approximate If \c true, return a likely range for the result: in 11794 /// particular, assume that arithmetic on narrower types doesn't leave 11795 /// those types. If \c false, return a range including all possible 11796 /// result values. 11797 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11798 bool InConstantContext, bool Approximate) { 11799 E = E->IgnoreParens(); 11800 11801 // Try a full evaluation first. 11802 Expr::EvalResult result; 11803 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11804 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11805 11806 // I think we only want to look through implicit casts here; if the 11807 // user has an explicit widening cast, we should treat the value as 11808 // being of the new, wider type. 11809 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11810 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11811 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11812 Approximate); 11813 11814 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11815 11816 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11817 CE->getCastKind() == CK_BooleanToSignedIntegral; 11818 11819 // Assume that non-integer casts can span the full range of the type. 11820 if (!isIntegerCast) 11821 return OutputTypeRange; 11822 11823 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11824 std::min(MaxWidth, OutputTypeRange.Width), 11825 InConstantContext, Approximate); 11826 11827 // Bail out if the subexpr's range is as wide as the cast type. 11828 if (SubRange.Width >= OutputTypeRange.Width) 11829 return OutputTypeRange; 11830 11831 // Otherwise, we take the smaller width, and we're non-negative if 11832 // either the output type or the subexpr is. 11833 return IntRange(SubRange.Width, 11834 SubRange.NonNegative || OutputTypeRange.NonNegative); 11835 } 11836 11837 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11838 // If we can fold the condition, just take that operand. 11839 bool CondResult; 11840 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11841 return GetExprRange(C, 11842 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11843 MaxWidth, InConstantContext, Approximate); 11844 11845 // Otherwise, conservatively merge. 11846 // GetExprRange requires an integer expression, but a throw expression 11847 // results in a void type. 11848 Expr *E = CO->getTrueExpr(); 11849 IntRange L = E->getType()->isVoidType() 11850 ? IntRange{0, true} 11851 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11852 E = CO->getFalseExpr(); 11853 IntRange R = E->getType()->isVoidType() 11854 ? IntRange{0, true} 11855 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11856 return IntRange::join(L, R); 11857 } 11858 11859 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11860 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11861 11862 switch (BO->getOpcode()) { 11863 case BO_Cmp: 11864 llvm_unreachable("builtin <=> should have class type"); 11865 11866 // Boolean-valued operations are single-bit and positive. 11867 case BO_LAnd: 11868 case BO_LOr: 11869 case BO_LT: 11870 case BO_GT: 11871 case BO_LE: 11872 case BO_GE: 11873 case BO_EQ: 11874 case BO_NE: 11875 return IntRange::forBoolType(); 11876 11877 // The type of the assignments is the type of the LHS, so the RHS 11878 // is not necessarily the same type. 11879 case BO_MulAssign: 11880 case BO_DivAssign: 11881 case BO_RemAssign: 11882 case BO_AddAssign: 11883 case BO_SubAssign: 11884 case BO_XorAssign: 11885 case BO_OrAssign: 11886 // TODO: bitfields? 11887 return IntRange::forValueOfType(C, GetExprType(E)); 11888 11889 // Simple assignments just pass through the RHS, which will have 11890 // been coerced to the LHS type. 11891 case BO_Assign: 11892 // TODO: bitfields? 11893 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11894 Approximate); 11895 11896 // Operations with opaque sources are black-listed. 11897 case BO_PtrMemD: 11898 case BO_PtrMemI: 11899 return IntRange::forValueOfType(C, GetExprType(E)); 11900 11901 // Bitwise-and uses the *infinum* of the two source ranges. 11902 case BO_And: 11903 case BO_AndAssign: 11904 Combine = IntRange::bit_and; 11905 break; 11906 11907 // Left shift gets black-listed based on a judgement call. 11908 case BO_Shl: 11909 // ...except that we want to treat '1 << (blah)' as logically 11910 // positive. It's an important idiom. 11911 if (IntegerLiteral *I 11912 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11913 if (I->getValue() == 1) { 11914 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11915 return IntRange(R.Width, /*NonNegative*/ true); 11916 } 11917 } 11918 LLVM_FALLTHROUGH; 11919 11920 case BO_ShlAssign: 11921 return IntRange::forValueOfType(C, GetExprType(E)); 11922 11923 // Right shift by a constant can narrow its left argument. 11924 case BO_Shr: 11925 case BO_ShrAssign: { 11926 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11927 Approximate); 11928 11929 // If the shift amount is a positive constant, drop the width by 11930 // that much. 11931 if (Optional<llvm::APSInt> shift = 11932 BO->getRHS()->getIntegerConstantExpr(C)) { 11933 if (shift->isNonNegative()) { 11934 unsigned zext = shift->getZExtValue(); 11935 if (zext >= L.Width) 11936 L.Width = (L.NonNegative ? 0 : 1); 11937 else 11938 L.Width -= zext; 11939 } 11940 } 11941 11942 return L; 11943 } 11944 11945 // Comma acts as its right operand. 11946 case BO_Comma: 11947 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11948 Approximate); 11949 11950 case BO_Add: 11951 if (!Approximate) 11952 Combine = IntRange::sum; 11953 break; 11954 11955 case BO_Sub: 11956 if (BO->getLHS()->getType()->isPointerType()) 11957 return IntRange::forValueOfType(C, GetExprType(E)); 11958 if (!Approximate) 11959 Combine = IntRange::difference; 11960 break; 11961 11962 case BO_Mul: 11963 if (!Approximate) 11964 Combine = IntRange::product; 11965 break; 11966 11967 // The width of a division result is mostly determined by the size 11968 // of the LHS. 11969 case BO_Div: { 11970 // Don't 'pre-truncate' the operands. 11971 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11972 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11973 Approximate); 11974 11975 // If the divisor is constant, use that. 11976 if (Optional<llvm::APSInt> divisor = 11977 BO->getRHS()->getIntegerConstantExpr(C)) { 11978 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11979 if (log2 >= L.Width) 11980 L.Width = (L.NonNegative ? 0 : 1); 11981 else 11982 L.Width = std::min(L.Width - log2, MaxWidth); 11983 return L; 11984 } 11985 11986 // Otherwise, just use the LHS's width. 11987 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11988 // could be -1. 11989 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11990 Approximate); 11991 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11992 } 11993 11994 case BO_Rem: 11995 Combine = IntRange::rem; 11996 break; 11997 11998 // The default behavior is okay for these. 11999 case BO_Xor: 12000 case BO_Or: 12001 break; 12002 } 12003 12004 // Combine the two ranges, but limit the result to the type in which we 12005 // performed the computation. 12006 QualType T = GetExprType(E); 12007 unsigned opWidth = C.getIntWidth(T); 12008 IntRange L = 12009 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 12010 IntRange R = 12011 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 12012 IntRange C = Combine(L, R); 12013 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 12014 C.Width = std::min(C.Width, MaxWidth); 12015 return C; 12016 } 12017 12018 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 12019 switch (UO->getOpcode()) { 12020 // Boolean-valued operations are white-listed. 12021 case UO_LNot: 12022 return IntRange::forBoolType(); 12023 12024 // Operations with opaque sources are black-listed. 12025 case UO_Deref: 12026 case UO_AddrOf: // should be impossible 12027 return IntRange::forValueOfType(C, GetExprType(E)); 12028 12029 default: 12030 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 12031 Approximate); 12032 } 12033 } 12034 12035 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12036 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 12037 Approximate); 12038 12039 if (const auto *BitField = E->getSourceBitField()) 12040 return IntRange(BitField->getBitWidthValue(C), 12041 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 12042 12043 return IntRange::forValueOfType(C, GetExprType(E)); 12044 } 12045 12046 static IntRange GetExprRange(ASTContext &C, const Expr *E, 12047 bool InConstantContext, bool Approximate) { 12048 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 12049 Approximate); 12050 } 12051 12052 /// Checks whether the given value, which currently has the given 12053 /// source semantics, has the same value when coerced through the 12054 /// target semantics. 12055 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 12056 const llvm::fltSemantics &Src, 12057 const llvm::fltSemantics &Tgt) { 12058 llvm::APFloat truncated = value; 12059 12060 bool ignored; 12061 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 12062 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 12063 12064 return truncated.bitwiseIsEqual(value); 12065 } 12066 12067 /// Checks whether the given value, which currently has the given 12068 /// source semantics, has the same value when coerced through the 12069 /// target semantics. 12070 /// 12071 /// The value might be a vector of floats (or a complex number). 12072 static bool IsSameFloatAfterCast(const APValue &value, 12073 const llvm::fltSemantics &Src, 12074 const llvm::fltSemantics &Tgt) { 12075 if (value.isFloat()) 12076 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 12077 12078 if (value.isVector()) { 12079 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 12080 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 12081 return false; 12082 return true; 12083 } 12084 12085 assert(value.isComplexFloat()); 12086 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 12087 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 12088 } 12089 12090 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 12091 bool IsListInit = false); 12092 12093 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 12094 // Suppress cases where we are comparing against an enum constant. 12095 if (const DeclRefExpr *DR = 12096 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 12097 if (isa<EnumConstantDecl>(DR->getDecl())) 12098 return true; 12099 12100 // Suppress cases where the value is expanded from a macro, unless that macro 12101 // is how a language represents a boolean literal. This is the case in both C 12102 // and Objective-C. 12103 SourceLocation BeginLoc = E->getBeginLoc(); 12104 if (BeginLoc.isMacroID()) { 12105 StringRef MacroName = Lexer::getImmediateMacroName( 12106 BeginLoc, S.getSourceManager(), S.getLangOpts()); 12107 return MacroName != "YES" && MacroName != "NO" && 12108 MacroName != "true" && MacroName != "false"; 12109 } 12110 12111 return false; 12112 } 12113 12114 static bool isKnownToHaveUnsignedValue(Expr *E) { 12115 return E->getType()->isIntegerType() && 12116 (!E->getType()->isSignedIntegerType() || 12117 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 12118 } 12119 12120 namespace { 12121 /// The promoted range of values of a type. In general this has the 12122 /// following structure: 12123 /// 12124 /// |-----------| . . . |-----------| 12125 /// ^ ^ ^ ^ 12126 /// Min HoleMin HoleMax Max 12127 /// 12128 /// ... where there is only a hole if a signed type is promoted to unsigned 12129 /// (in which case Min and Max are the smallest and largest representable 12130 /// values). 12131 struct PromotedRange { 12132 // Min, or HoleMax if there is a hole. 12133 llvm::APSInt PromotedMin; 12134 // Max, or HoleMin if there is a hole. 12135 llvm::APSInt PromotedMax; 12136 12137 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 12138 if (R.Width == 0) 12139 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 12140 else if (R.Width >= BitWidth && !Unsigned) { 12141 // Promotion made the type *narrower*. This happens when promoting 12142 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 12143 // Treat all values of 'signed int' as being in range for now. 12144 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 12145 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 12146 } else { 12147 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 12148 .extOrTrunc(BitWidth); 12149 PromotedMin.setIsUnsigned(Unsigned); 12150 12151 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 12152 .extOrTrunc(BitWidth); 12153 PromotedMax.setIsUnsigned(Unsigned); 12154 } 12155 } 12156 12157 // Determine whether this range is contiguous (has no hole). 12158 bool isContiguous() const { return PromotedMin <= PromotedMax; } 12159 12160 // Where a constant value is within the range. 12161 enum ComparisonResult { 12162 LT = 0x1, 12163 LE = 0x2, 12164 GT = 0x4, 12165 GE = 0x8, 12166 EQ = 0x10, 12167 NE = 0x20, 12168 InRangeFlag = 0x40, 12169 12170 Less = LE | LT | NE, 12171 Min = LE | InRangeFlag, 12172 InRange = InRangeFlag, 12173 Max = GE | InRangeFlag, 12174 Greater = GE | GT | NE, 12175 12176 OnlyValue = LE | GE | EQ | InRangeFlag, 12177 InHole = NE 12178 }; 12179 12180 ComparisonResult compare(const llvm::APSInt &Value) const { 12181 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 12182 Value.isUnsigned() == PromotedMin.isUnsigned()); 12183 if (!isContiguous()) { 12184 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 12185 if (Value.isMinValue()) return Min; 12186 if (Value.isMaxValue()) return Max; 12187 if (Value >= PromotedMin) return InRange; 12188 if (Value <= PromotedMax) return InRange; 12189 return InHole; 12190 } 12191 12192 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 12193 case -1: return Less; 12194 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 12195 case 1: 12196 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 12197 case -1: return InRange; 12198 case 0: return Max; 12199 case 1: return Greater; 12200 } 12201 } 12202 12203 llvm_unreachable("impossible compare result"); 12204 } 12205 12206 static llvm::Optional<StringRef> 12207 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 12208 if (Op == BO_Cmp) { 12209 ComparisonResult LTFlag = LT, GTFlag = GT; 12210 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 12211 12212 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 12213 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 12214 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 12215 return llvm::None; 12216 } 12217 12218 ComparisonResult TrueFlag, FalseFlag; 12219 if (Op == BO_EQ) { 12220 TrueFlag = EQ; 12221 FalseFlag = NE; 12222 } else if (Op == BO_NE) { 12223 TrueFlag = NE; 12224 FalseFlag = EQ; 12225 } else { 12226 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 12227 TrueFlag = LT; 12228 FalseFlag = GE; 12229 } else { 12230 TrueFlag = GT; 12231 FalseFlag = LE; 12232 } 12233 if (Op == BO_GE || Op == BO_LE) 12234 std::swap(TrueFlag, FalseFlag); 12235 } 12236 if (R & TrueFlag) 12237 return StringRef("true"); 12238 if (R & FalseFlag) 12239 return StringRef("false"); 12240 return llvm::None; 12241 } 12242 }; 12243 } 12244 12245 static bool HasEnumType(Expr *E) { 12246 // Strip off implicit integral promotions. 12247 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12248 if (ICE->getCastKind() != CK_IntegralCast && 12249 ICE->getCastKind() != CK_NoOp) 12250 break; 12251 E = ICE->getSubExpr(); 12252 } 12253 12254 return E->getType()->isEnumeralType(); 12255 } 12256 12257 static int classifyConstantValue(Expr *Constant) { 12258 // The values of this enumeration are used in the diagnostics 12259 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 12260 enum ConstantValueKind { 12261 Miscellaneous = 0, 12262 LiteralTrue, 12263 LiteralFalse 12264 }; 12265 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 12266 return BL->getValue() ? ConstantValueKind::LiteralTrue 12267 : ConstantValueKind::LiteralFalse; 12268 return ConstantValueKind::Miscellaneous; 12269 } 12270 12271 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 12272 Expr *Constant, Expr *Other, 12273 const llvm::APSInt &Value, 12274 bool RhsConstant) { 12275 if (S.inTemplateInstantiation()) 12276 return false; 12277 12278 Expr *OriginalOther = Other; 12279 12280 Constant = Constant->IgnoreParenImpCasts(); 12281 Other = Other->IgnoreParenImpCasts(); 12282 12283 // Suppress warnings on tautological comparisons between values of the same 12284 // enumeration type. There are only two ways we could warn on this: 12285 // - If the constant is outside the range of representable values of 12286 // the enumeration. In such a case, we should warn about the cast 12287 // to enumeration type, not about the comparison. 12288 // - If the constant is the maximum / minimum in-range value. For an 12289 // enumeratin type, such comparisons can be meaningful and useful. 12290 if (Constant->getType()->isEnumeralType() && 12291 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 12292 return false; 12293 12294 IntRange OtherValueRange = GetExprRange( 12295 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 12296 12297 QualType OtherT = Other->getType(); 12298 if (const auto *AT = OtherT->getAs<AtomicType>()) 12299 OtherT = AT->getValueType(); 12300 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 12301 12302 // Special case for ObjC BOOL on targets where its a typedef for a signed char 12303 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 12304 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 12305 S.NSAPIObj->isObjCBOOLType(OtherT) && 12306 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 12307 12308 // Whether we're treating Other as being a bool because of the form of 12309 // expression despite it having another type (typically 'int' in C). 12310 bool OtherIsBooleanDespiteType = 12311 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 12312 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 12313 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 12314 12315 // Check if all values in the range of possible values of this expression 12316 // lead to the same comparison outcome. 12317 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 12318 Value.isUnsigned()); 12319 auto Cmp = OtherPromotedValueRange.compare(Value); 12320 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 12321 if (!Result) 12322 return false; 12323 12324 // Also consider the range determined by the type alone. This allows us to 12325 // classify the warning under the proper diagnostic group. 12326 bool TautologicalTypeCompare = false; 12327 { 12328 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 12329 Value.isUnsigned()); 12330 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 12331 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 12332 RhsConstant)) { 12333 TautologicalTypeCompare = true; 12334 Cmp = TypeCmp; 12335 Result = TypeResult; 12336 } 12337 } 12338 12339 // Don't warn if the non-constant operand actually always evaluates to the 12340 // same value. 12341 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 12342 return false; 12343 12344 // Suppress the diagnostic for an in-range comparison if the constant comes 12345 // from a macro or enumerator. We don't want to diagnose 12346 // 12347 // some_long_value <= INT_MAX 12348 // 12349 // when sizeof(int) == sizeof(long). 12350 bool InRange = Cmp & PromotedRange::InRangeFlag; 12351 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 12352 return false; 12353 12354 // A comparison of an unsigned bit-field against 0 is really a type problem, 12355 // even though at the type level the bit-field might promote to 'signed int'. 12356 if (Other->refersToBitField() && InRange && Value == 0 && 12357 Other->getType()->isUnsignedIntegerOrEnumerationType()) 12358 TautologicalTypeCompare = true; 12359 12360 // If this is a comparison to an enum constant, include that 12361 // constant in the diagnostic. 12362 const EnumConstantDecl *ED = nullptr; 12363 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 12364 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 12365 12366 // Should be enough for uint128 (39 decimal digits) 12367 SmallString<64> PrettySourceValue; 12368 llvm::raw_svector_ostream OS(PrettySourceValue); 12369 if (ED) { 12370 OS << '\'' << *ED << "' (" << Value << ")"; 12371 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 12372 Constant->IgnoreParenImpCasts())) { 12373 OS << (BL->getValue() ? "YES" : "NO"); 12374 } else { 12375 OS << Value; 12376 } 12377 12378 if (!TautologicalTypeCompare) { 12379 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 12380 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 12381 << E->getOpcodeStr() << OS.str() << *Result 12382 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12383 return true; 12384 } 12385 12386 if (IsObjCSignedCharBool) { 12387 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12388 S.PDiag(diag::warn_tautological_compare_objc_bool) 12389 << OS.str() << *Result); 12390 return true; 12391 } 12392 12393 // FIXME: We use a somewhat different formatting for the in-range cases and 12394 // cases involving boolean values for historical reasons. We should pick a 12395 // consistent way of presenting these diagnostics. 12396 if (!InRange || Other->isKnownToHaveBooleanValue()) { 12397 12398 S.DiagRuntimeBehavior( 12399 E->getOperatorLoc(), E, 12400 S.PDiag(!InRange ? diag::warn_out_of_range_compare 12401 : diag::warn_tautological_bool_compare) 12402 << OS.str() << classifyConstantValue(Constant) << OtherT 12403 << OtherIsBooleanDespiteType << *Result 12404 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 12405 } else { 12406 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 12407 unsigned Diag = 12408 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 12409 ? (HasEnumType(OriginalOther) 12410 ? diag::warn_unsigned_enum_always_true_comparison 12411 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 12412 : diag::warn_unsigned_always_true_comparison) 12413 : diag::warn_tautological_constant_compare; 12414 12415 S.Diag(E->getOperatorLoc(), Diag) 12416 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 12417 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12418 } 12419 12420 return true; 12421 } 12422 12423 /// Analyze the operands of the given comparison. Implements the 12424 /// fallback case from AnalyzeComparison. 12425 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12426 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12427 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12428 } 12429 12430 /// Implements -Wsign-compare. 12431 /// 12432 /// \param E the binary operator to check for warnings 12433 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12434 // The type the comparison is being performed in. 12435 QualType T = E->getLHS()->getType(); 12436 12437 // Only analyze comparison operators where both sides have been converted to 12438 // the same type. 12439 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12440 return AnalyzeImpConvsInComparison(S, E); 12441 12442 // Don't analyze value-dependent comparisons directly. 12443 if (E->isValueDependent()) 12444 return AnalyzeImpConvsInComparison(S, E); 12445 12446 Expr *LHS = E->getLHS(); 12447 Expr *RHS = E->getRHS(); 12448 12449 if (T->isIntegralType(S.Context)) { 12450 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12451 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12452 12453 // We don't care about expressions whose result is a constant. 12454 if (RHSValue && LHSValue) 12455 return AnalyzeImpConvsInComparison(S, E); 12456 12457 // We only care about expressions where just one side is literal 12458 if ((bool)RHSValue ^ (bool)LHSValue) { 12459 // Is the constant on the RHS or LHS? 12460 const bool RhsConstant = (bool)RHSValue; 12461 Expr *Const = RhsConstant ? RHS : LHS; 12462 Expr *Other = RhsConstant ? LHS : RHS; 12463 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12464 12465 // Check whether an integer constant comparison results in a value 12466 // of 'true' or 'false'. 12467 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12468 return AnalyzeImpConvsInComparison(S, E); 12469 } 12470 } 12471 12472 if (!T->hasUnsignedIntegerRepresentation()) { 12473 // We don't do anything special if this isn't an unsigned integral 12474 // comparison: we're only interested in integral comparisons, and 12475 // signed comparisons only happen in cases we don't care to warn about. 12476 return AnalyzeImpConvsInComparison(S, E); 12477 } 12478 12479 LHS = LHS->IgnoreParenImpCasts(); 12480 RHS = RHS->IgnoreParenImpCasts(); 12481 12482 if (!S.getLangOpts().CPlusPlus) { 12483 // Avoid warning about comparison of integers with different signs when 12484 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12485 // the type of `E`. 12486 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12487 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12488 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12489 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12490 } 12491 12492 // Check to see if one of the (unmodified) operands is of different 12493 // signedness. 12494 Expr *signedOperand, *unsignedOperand; 12495 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12496 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12497 "unsigned comparison between two signed integer expressions?"); 12498 signedOperand = LHS; 12499 unsignedOperand = RHS; 12500 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12501 signedOperand = RHS; 12502 unsignedOperand = LHS; 12503 } else { 12504 return AnalyzeImpConvsInComparison(S, E); 12505 } 12506 12507 // Otherwise, calculate the effective range of the signed operand. 12508 IntRange signedRange = GetExprRange( 12509 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12510 12511 // Go ahead and analyze implicit conversions in the operands. Note 12512 // that we skip the implicit conversions on both sides. 12513 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12514 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12515 12516 // If the signed range is non-negative, -Wsign-compare won't fire. 12517 if (signedRange.NonNegative) 12518 return; 12519 12520 // For (in)equality comparisons, if the unsigned operand is a 12521 // constant which cannot collide with a overflowed signed operand, 12522 // then reinterpreting the signed operand as unsigned will not 12523 // change the result of the comparison. 12524 if (E->isEqualityOp()) { 12525 unsigned comparisonWidth = S.Context.getIntWidth(T); 12526 IntRange unsignedRange = 12527 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12528 /*Approximate*/ true); 12529 12530 // We should never be unable to prove that the unsigned operand is 12531 // non-negative. 12532 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12533 12534 if (unsignedRange.Width < comparisonWidth) 12535 return; 12536 } 12537 12538 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12539 S.PDiag(diag::warn_mixed_sign_comparison) 12540 << LHS->getType() << RHS->getType() 12541 << LHS->getSourceRange() << RHS->getSourceRange()); 12542 } 12543 12544 /// Analyzes an attempt to assign the given value to a bitfield. 12545 /// 12546 /// Returns true if there was something fishy about the attempt. 12547 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12548 SourceLocation InitLoc) { 12549 assert(Bitfield->isBitField()); 12550 if (Bitfield->isInvalidDecl()) 12551 return false; 12552 12553 // White-list bool bitfields. 12554 QualType BitfieldType = Bitfield->getType(); 12555 if (BitfieldType->isBooleanType()) 12556 return false; 12557 12558 if (BitfieldType->isEnumeralType()) { 12559 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12560 // If the underlying enum type was not explicitly specified as an unsigned 12561 // type and the enum contain only positive values, MSVC++ will cause an 12562 // inconsistency by storing this as a signed type. 12563 if (S.getLangOpts().CPlusPlus11 && 12564 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12565 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12566 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12567 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12568 << BitfieldEnumDecl; 12569 } 12570 } 12571 12572 if (Bitfield->getType()->isBooleanType()) 12573 return false; 12574 12575 // Ignore value- or type-dependent expressions. 12576 if (Bitfield->getBitWidth()->isValueDependent() || 12577 Bitfield->getBitWidth()->isTypeDependent() || 12578 Init->isValueDependent() || 12579 Init->isTypeDependent()) 12580 return false; 12581 12582 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12583 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12584 12585 Expr::EvalResult Result; 12586 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12587 Expr::SE_AllowSideEffects)) { 12588 // The RHS is not constant. If the RHS has an enum type, make sure the 12589 // bitfield is wide enough to hold all the values of the enum without 12590 // truncation. 12591 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12592 EnumDecl *ED = EnumTy->getDecl(); 12593 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12594 12595 // Enum types are implicitly signed on Windows, so check if there are any 12596 // negative enumerators to see if the enum was intended to be signed or 12597 // not. 12598 bool SignedEnum = ED->getNumNegativeBits() > 0; 12599 12600 // Check for surprising sign changes when assigning enum values to a 12601 // bitfield of different signedness. If the bitfield is signed and we 12602 // have exactly the right number of bits to store this unsigned enum, 12603 // suggest changing the enum to an unsigned type. This typically happens 12604 // on Windows where unfixed enums always use an underlying type of 'int'. 12605 unsigned DiagID = 0; 12606 if (SignedEnum && !SignedBitfield) { 12607 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12608 } else if (SignedBitfield && !SignedEnum && 12609 ED->getNumPositiveBits() == FieldWidth) { 12610 DiagID = diag::warn_signed_bitfield_enum_conversion; 12611 } 12612 12613 if (DiagID) { 12614 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12615 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12616 SourceRange TypeRange = 12617 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12618 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12619 << SignedEnum << TypeRange; 12620 } 12621 12622 // Compute the required bitwidth. If the enum has negative values, we need 12623 // one more bit than the normal number of positive bits to represent the 12624 // sign bit. 12625 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12626 ED->getNumNegativeBits()) 12627 : ED->getNumPositiveBits(); 12628 12629 // Check the bitwidth. 12630 if (BitsNeeded > FieldWidth) { 12631 Expr *WidthExpr = Bitfield->getBitWidth(); 12632 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12633 << Bitfield << ED; 12634 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12635 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12636 } 12637 } 12638 12639 return false; 12640 } 12641 12642 llvm::APSInt Value = Result.Val.getInt(); 12643 12644 unsigned OriginalWidth = Value.getBitWidth(); 12645 12646 if (!Value.isSigned() || Value.isNegative()) 12647 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12648 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12649 OriginalWidth = Value.getMinSignedBits(); 12650 12651 if (OriginalWidth <= FieldWidth) 12652 return false; 12653 12654 // Compute the value which the bitfield will contain. 12655 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12656 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12657 12658 // Check whether the stored value is equal to the original value. 12659 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12660 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12661 return false; 12662 12663 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12664 // therefore don't strictly fit into a signed bitfield of width 1. 12665 if (FieldWidth == 1 && Value == 1) 12666 return false; 12667 12668 std::string PrettyValue = toString(Value, 10); 12669 std::string PrettyTrunc = toString(TruncatedValue, 10); 12670 12671 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12672 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12673 << Init->getSourceRange(); 12674 12675 return true; 12676 } 12677 12678 /// Analyze the given simple or compound assignment for warning-worthy 12679 /// operations. 12680 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12681 // Just recurse on the LHS. 12682 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12683 12684 // We want to recurse on the RHS as normal unless we're assigning to 12685 // a bitfield. 12686 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12687 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12688 E->getOperatorLoc())) { 12689 // Recurse, ignoring any implicit conversions on the RHS. 12690 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12691 E->getOperatorLoc()); 12692 } 12693 } 12694 12695 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12696 12697 // Diagnose implicitly sequentially-consistent atomic assignment. 12698 if (E->getLHS()->getType()->isAtomicType()) 12699 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12700 } 12701 12702 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12703 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12704 SourceLocation CContext, unsigned diag, 12705 bool pruneControlFlow = false) { 12706 if (pruneControlFlow) { 12707 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12708 S.PDiag(diag) 12709 << SourceType << T << E->getSourceRange() 12710 << SourceRange(CContext)); 12711 return; 12712 } 12713 S.Diag(E->getExprLoc(), diag) 12714 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12715 } 12716 12717 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12718 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12719 SourceLocation CContext, 12720 unsigned diag, bool pruneControlFlow = false) { 12721 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12722 } 12723 12724 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12725 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12726 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12727 } 12728 12729 static void adornObjCBoolConversionDiagWithTernaryFixit( 12730 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12731 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12732 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12733 Ignored = OVE->getSourceExpr(); 12734 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12735 isa<BinaryOperator>(Ignored) || 12736 isa<CXXOperatorCallExpr>(Ignored); 12737 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12738 if (NeedsParens) 12739 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12740 << FixItHint::CreateInsertion(EndLoc, ")"); 12741 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12742 } 12743 12744 /// Diagnose an implicit cast from a floating point value to an integer value. 12745 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12746 SourceLocation CContext) { 12747 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12748 const bool PruneWarnings = S.inTemplateInstantiation(); 12749 12750 Expr *InnerE = E->IgnoreParenImpCasts(); 12751 // We also want to warn on, e.g., "int i = -1.234" 12752 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12753 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12754 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12755 12756 const bool IsLiteral = 12757 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12758 12759 llvm::APFloat Value(0.0); 12760 bool IsConstant = 12761 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12762 if (!IsConstant) { 12763 if (isObjCSignedCharBool(S, T)) { 12764 return adornObjCBoolConversionDiagWithTernaryFixit( 12765 S, E, 12766 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12767 << E->getType()); 12768 } 12769 12770 return DiagnoseImpCast(S, E, T, CContext, 12771 diag::warn_impcast_float_integer, PruneWarnings); 12772 } 12773 12774 bool isExact = false; 12775 12776 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12777 T->hasUnsignedIntegerRepresentation()); 12778 llvm::APFloat::opStatus Result = Value.convertToInteger( 12779 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12780 12781 // FIXME: Force the precision of the source value down so we don't print 12782 // digits which are usually useless (we don't really care here if we 12783 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12784 // would automatically print the shortest representation, but it's a bit 12785 // tricky to implement. 12786 SmallString<16> PrettySourceValue; 12787 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12788 precision = (precision * 59 + 195) / 196; 12789 Value.toString(PrettySourceValue, precision); 12790 12791 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12792 return adornObjCBoolConversionDiagWithTernaryFixit( 12793 S, E, 12794 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12795 << PrettySourceValue); 12796 } 12797 12798 if (Result == llvm::APFloat::opOK && isExact) { 12799 if (IsLiteral) return; 12800 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12801 PruneWarnings); 12802 } 12803 12804 // Conversion of a floating-point value to a non-bool integer where the 12805 // integral part cannot be represented by the integer type is undefined. 12806 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12807 return DiagnoseImpCast( 12808 S, E, T, CContext, 12809 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12810 : diag::warn_impcast_float_to_integer_out_of_range, 12811 PruneWarnings); 12812 12813 unsigned DiagID = 0; 12814 if (IsLiteral) { 12815 // Warn on floating point literal to integer. 12816 DiagID = diag::warn_impcast_literal_float_to_integer; 12817 } else if (IntegerValue == 0) { 12818 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12819 return DiagnoseImpCast(S, E, T, CContext, 12820 diag::warn_impcast_float_integer, PruneWarnings); 12821 } 12822 // Warn on non-zero to zero conversion. 12823 DiagID = diag::warn_impcast_float_to_integer_zero; 12824 } else { 12825 if (IntegerValue.isUnsigned()) { 12826 if (!IntegerValue.isMaxValue()) { 12827 return DiagnoseImpCast(S, E, T, CContext, 12828 diag::warn_impcast_float_integer, PruneWarnings); 12829 } 12830 } else { // IntegerValue.isSigned() 12831 if (!IntegerValue.isMaxSignedValue() && 12832 !IntegerValue.isMinSignedValue()) { 12833 return DiagnoseImpCast(S, E, T, CContext, 12834 diag::warn_impcast_float_integer, PruneWarnings); 12835 } 12836 } 12837 // Warn on evaluatable floating point expression to integer conversion. 12838 DiagID = diag::warn_impcast_float_to_integer; 12839 } 12840 12841 SmallString<16> PrettyTargetValue; 12842 if (IsBool) 12843 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12844 else 12845 IntegerValue.toString(PrettyTargetValue); 12846 12847 if (PruneWarnings) { 12848 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12849 S.PDiag(DiagID) 12850 << E->getType() << T.getUnqualifiedType() 12851 << PrettySourceValue << PrettyTargetValue 12852 << E->getSourceRange() << SourceRange(CContext)); 12853 } else { 12854 S.Diag(E->getExprLoc(), DiagID) 12855 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12856 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12857 } 12858 } 12859 12860 /// Analyze the given compound assignment for the possible losing of 12861 /// floating-point precision. 12862 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12863 assert(isa<CompoundAssignOperator>(E) && 12864 "Must be compound assignment operation"); 12865 // Recurse on the LHS and RHS in here 12866 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12867 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12868 12869 if (E->getLHS()->getType()->isAtomicType()) 12870 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12871 12872 // Now check the outermost expression 12873 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12874 const auto *RBT = cast<CompoundAssignOperator>(E) 12875 ->getComputationResultType() 12876 ->getAs<BuiltinType>(); 12877 12878 // The below checks assume source is floating point. 12879 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12880 12881 // If source is floating point but target is an integer. 12882 if (ResultBT->isInteger()) 12883 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12884 E->getExprLoc(), diag::warn_impcast_float_integer); 12885 12886 if (!ResultBT->isFloatingPoint()) 12887 return; 12888 12889 // If both source and target are floating points, warn about losing precision. 12890 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12891 QualType(ResultBT, 0), QualType(RBT, 0)); 12892 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12893 // warn about dropping FP rank. 12894 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12895 diag::warn_impcast_float_result_precision); 12896 } 12897 12898 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12899 IntRange Range) { 12900 if (!Range.Width) return "0"; 12901 12902 llvm::APSInt ValueInRange = Value; 12903 ValueInRange.setIsSigned(!Range.NonNegative); 12904 ValueInRange = ValueInRange.trunc(Range.Width); 12905 return toString(ValueInRange, 10); 12906 } 12907 12908 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12909 if (!isa<ImplicitCastExpr>(Ex)) 12910 return false; 12911 12912 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12913 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12914 const Type *Source = 12915 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12916 if (Target->isDependentType()) 12917 return false; 12918 12919 const BuiltinType *FloatCandidateBT = 12920 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12921 const Type *BoolCandidateType = ToBool ? Target : Source; 12922 12923 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12924 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12925 } 12926 12927 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12928 SourceLocation CC) { 12929 unsigned NumArgs = TheCall->getNumArgs(); 12930 for (unsigned i = 0; i < NumArgs; ++i) { 12931 Expr *CurrA = TheCall->getArg(i); 12932 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12933 continue; 12934 12935 bool IsSwapped = ((i > 0) && 12936 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12937 IsSwapped |= ((i < (NumArgs - 1)) && 12938 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12939 if (IsSwapped) { 12940 // Warn on this floating-point to bool conversion. 12941 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12942 CurrA->getType(), CC, 12943 diag::warn_impcast_floating_point_to_bool); 12944 } 12945 } 12946 } 12947 12948 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12949 SourceLocation CC) { 12950 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12951 E->getExprLoc())) 12952 return; 12953 12954 // Don't warn on functions which have return type nullptr_t. 12955 if (isa<CallExpr>(E)) 12956 return; 12957 12958 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12959 const Expr::NullPointerConstantKind NullKind = 12960 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12961 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12962 return; 12963 12964 // Return if target type is a safe conversion. 12965 if (T->isAnyPointerType() || T->isBlockPointerType() || 12966 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12967 return; 12968 12969 SourceLocation Loc = E->getSourceRange().getBegin(); 12970 12971 // Venture through the macro stacks to get to the source of macro arguments. 12972 // The new location is a better location than the complete location that was 12973 // passed in. 12974 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12975 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12976 12977 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12978 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12979 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12980 Loc, S.SourceMgr, S.getLangOpts()); 12981 if (MacroName == "NULL") 12982 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12983 } 12984 12985 // Only warn if the null and context location are in the same macro expansion. 12986 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12987 return; 12988 12989 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12990 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12991 << FixItHint::CreateReplacement(Loc, 12992 S.getFixItZeroLiteralForType(T, Loc)); 12993 } 12994 12995 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12996 ObjCArrayLiteral *ArrayLiteral); 12997 12998 static void 12999 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 13000 ObjCDictionaryLiteral *DictionaryLiteral); 13001 13002 /// Check a single element within a collection literal against the 13003 /// target element type. 13004 static void checkObjCCollectionLiteralElement(Sema &S, 13005 QualType TargetElementType, 13006 Expr *Element, 13007 unsigned ElementKind) { 13008 // Skip a bitcast to 'id' or qualified 'id'. 13009 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 13010 if (ICE->getCastKind() == CK_BitCast && 13011 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 13012 Element = ICE->getSubExpr(); 13013 } 13014 13015 QualType ElementType = Element->getType(); 13016 ExprResult ElementResult(Element); 13017 if (ElementType->getAs<ObjCObjectPointerType>() && 13018 S.CheckSingleAssignmentConstraints(TargetElementType, 13019 ElementResult, 13020 false, false) 13021 != Sema::Compatible) { 13022 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 13023 << ElementType << ElementKind << TargetElementType 13024 << Element->getSourceRange(); 13025 } 13026 13027 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 13028 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 13029 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 13030 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 13031 } 13032 13033 /// Check an Objective-C array literal being converted to the given 13034 /// target type. 13035 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 13036 ObjCArrayLiteral *ArrayLiteral) { 13037 if (!S.NSArrayDecl) 13038 return; 13039 13040 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 13041 if (!TargetObjCPtr) 13042 return; 13043 13044 if (TargetObjCPtr->isUnspecialized() || 13045 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 13046 != S.NSArrayDecl->getCanonicalDecl()) 13047 return; 13048 13049 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 13050 if (TypeArgs.size() != 1) 13051 return; 13052 13053 QualType TargetElementType = TypeArgs[0]; 13054 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 13055 checkObjCCollectionLiteralElement(S, TargetElementType, 13056 ArrayLiteral->getElement(I), 13057 0); 13058 } 13059 } 13060 13061 /// Check an Objective-C dictionary literal being converted to the given 13062 /// target type. 13063 static void 13064 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 13065 ObjCDictionaryLiteral *DictionaryLiteral) { 13066 if (!S.NSDictionaryDecl) 13067 return; 13068 13069 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 13070 if (!TargetObjCPtr) 13071 return; 13072 13073 if (TargetObjCPtr->isUnspecialized() || 13074 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 13075 != S.NSDictionaryDecl->getCanonicalDecl()) 13076 return; 13077 13078 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 13079 if (TypeArgs.size() != 2) 13080 return; 13081 13082 QualType TargetKeyType = TypeArgs[0]; 13083 QualType TargetObjectType = TypeArgs[1]; 13084 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 13085 auto Element = DictionaryLiteral->getKeyValueElement(I); 13086 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 13087 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 13088 } 13089 } 13090 13091 // Helper function to filter out cases for constant width constant conversion. 13092 // Don't warn on char array initialization or for non-decimal values. 13093 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 13094 SourceLocation CC) { 13095 // If initializing from a constant, and the constant starts with '0', 13096 // then it is a binary, octal, or hexadecimal. Allow these constants 13097 // to fill all the bits, even if there is a sign change. 13098 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 13099 const char FirstLiteralCharacter = 13100 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 13101 if (FirstLiteralCharacter == '0') 13102 return false; 13103 } 13104 13105 // If the CC location points to a '{', and the type is char, then assume 13106 // assume it is an array initialization. 13107 if (CC.isValid() && T->isCharType()) { 13108 const char FirstContextCharacter = 13109 S.getSourceManager().getCharacterData(CC)[0]; 13110 if (FirstContextCharacter == '{') 13111 return false; 13112 } 13113 13114 return true; 13115 } 13116 13117 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 13118 const auto *IL = dyn_cast<IntegerLiteral>(E); 13119 if (!IL) { 13120 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 13121 if (UO->getOpcode() == UO_Minus) 13122 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 13123 } 13124 } 13125 13126 return IL; 13127 } 13128 13129 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 13130 E = E->IgnoreParenImpCasts(); 13131 SourceLocation ExprLoc = E->getExprLoc(); 13132 13133 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 13134 BinaryOperator::Opcode Opc = BO->getOpcode(); 13135 Expr::EvalResult Result; 13136 // Do not diagnose unsigned shifts. 13137 if (Opc == BO_Shl) { 13138 const auto *LHS = getIntegerLiteral(BO->getLHS()); 13139 const auto *RHS = getIntegerLiteral(BO->getRHS()); 13140 if (LHS && LHS->getValue() == 0) 13141 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 13142 else if (!E->isValueDependent() && LHS && RHS && 13143 RHS->getValue().isNonNegative() && 13144 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 13145 S.Diag(ExprLoc, diag::warn_left_shift_always) 13146 << (Result.Val.getInt() != 0); 13147 else if (E->getType()->isSignedIntegerType()) 13148 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 13149 } 13150 } 13151 13152 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 13153 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 13154 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 13155 if (!LHS || !RHS) 13156 return; 13157 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 13158 (RHS->getValue() == 0 || RHS->getValue() == 1)) 13159 // Do not diagnose common idioms. 13160 return; 13161 if (LHS->getValue() != 0 && RHS->getValue() != 0) 13162 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 13163 } 13164 } 13165 13166 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 13167 SourceLocation CC, 13168 bool *ICContext = nullptr, 13169 bool IsListInit = false) { 13170 if (E->isTypeDependent() || E->isValueDependent()) return; 13171 13172 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 13173 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 13174 if (Source == Target) return; 13175 if (Target->isDependentType()) return; 13176 13177 // If the conversion context location is invalid don't complain. We also 13178 // don't want to emit a warning if the issue occurs from the expansion of 13179 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 13180 // delay this check as long as possible. Once we detect we are in that 13181 // scenario, we just return. 13182 if (CC.isInvalid()) 13183 return; 13184 13185 if (Source->isAtomicType()) 13186 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 13187 13188 // Diagnose implicit casts to bool. 13189 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 13190 if (isa<StringLiteral>(E)) 13191 // Warn on string literal to bool. Checks for string literals in logical 13192 // and expressions, for instance, assert(0 && "error here"), are 13193 // prevented by a check in AnalyzeImplicitConversions(). 13194 return DiagnoseImpCast(S, E, T, CC, 13195 diag::warn_impcast_string_literal_to_bool); 13196 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 13197 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 13198 // This covers the literal expressions that evaluate to Objective-C 13199 // objects. 13200 return DiagnoseImpCast(S, E, T, CC, 13201 diag::warn_impcast_objective_c_literal_to_bool); 13202 } 13203 if (Source->isPointerType() || Source->canDecayToPointerType()) { 13204 // Warn on pointer to bool conversion that is always true. 13205 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 13206 SourceRange(CC)); 13207 } 13208 } 13209 13210 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 13211 // is a typedef for signed char (macOS), then that constant value has to be 1 13212 // or 0. 13213 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 13214 Expr::EvalResult Result; 13215 if (E->EvaluateAsInt(Result, S.getASTContext(), 13216 Expr::SE_AllowSideEffects)) { 13217 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 13218 adornObjCBoolConversionDiagWithTernaryFixit( 13219 S, E, 13220 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 13221 << toString(Result.Val.getInt(), 10)); 13222 } 13223 return; 13224 } 13225 } 13226 13227 // Check implicit casts from Objective-C collection literals to specialized 13228 // collection types, e.g., NSArray<NSString *> *. 13229 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 13230 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 13231 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 13232 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 13233 13234 // Strip vector types. 13235 if (isa<VectorType>(Source)) { 13236 if (Target->isVLSTBuiltinType() && 13237 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 13238 QualType(Source, 0)) || 13239 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 13240 QualType(Source, 0)))) 13241 return; 13242 13243 if (!isa<VectorType>(Target)) { 13244 if (S.SourceMgr.isInSystemMacro(CC)) 13245 return; 13246 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 13247 } 13248 13249 // If the vector cast is cast between two vectors of the same size, it is 13250 // a bitcast, not a conversion. 13251 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 13252 return; 13253 13254 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 13255 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 13256 } 13257 if (auto VecTy = dyn_cast<VectorType>(Target)) 13258 Target = VecTy->getElementType().getTypePtr(); 13259 13260 // Strip complex types. 13261 if (isa<ComplexType>(Source)) { 13262 if (!isa<ComplexType>(Target)) { 13263 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 13264 return; 13265 13266 return DiagnoseImpCast(S, E, T, CC, 13267 S.getLangOpts().CPlusPlus 13268 ? diag::err_impcast_complex_scalar 13269 : diag::warn_impcast_complex_scalar); 13270 } 13271 13272 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 13273 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 13274 } 13275 13276 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 13277 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 13278 13279 // If the source is floating point... 13280 if (SourceBT && SourceBT->isFloatingPoint()) { 13281 // ...and the target is floating point... 13282 if (TargetBT && TargetBT->isFloatingPoint()) { 13283 // ...then warn if we're dropping FP rank. 13284 13285 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 13286 QualType(SourceBT, 0), QualType(TargetBT, 0)); 13287 if (Order > 0) { 13288 // Don't warn about float constants that are precisely 13289 // representable in the target type. 13290 Expr::EvalResult result; 13291 if (E->EvaluateAsRValue(result, S.Context)) { 13292 // Value might be a float, a float vector, or a float complex. 13293 if (IsSameFloatAfterCast(result.Val, 13294 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 13295 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 13296 return; 13297 } 13298 13299 if (S.SourceMgr.isInSystemMacro(CC)) 13300 return; 13301 13302 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 13303 } 13304 // ... or possibly if we're increasing rank, too 13305 else if (Order < 0) { 13306 if (S.SourceMgr.isInSystemMacro(CC)) 13307 return; 13308 13309 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 13310 } 13311 return; 13312 } 13313 13314 // If the target is integral, always warn. 13315 if (TargetBT && TargetBT->isInteger()) { 13316 if (S.SourceMgr.isInSystemMacro(CC)) 13317 return; 13318 13319 DiagnoseFloatingImpCast(S, E, T, CC); 13320 } 13321 13322 // Detect the case where a call result is converted from floating-point to 13323 // to bool, and the final argument to the call is converted from bool, to 13324 // discover this typo: 13325 // 13326 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 13327 // 13328 // FIXME: This is an incredibly special case; is there some more general 13329 // way to detect this class of misplaced-parentheses bug? 13330 if (Target->isBooleanType() && isa<CallExpr>(E)) { 13331 // Check last argument of function call to see if it is an 13332 // implicit cast from a type matching the type the result 13333 // is being cast to. 13334 CallExpr *CEx = cast<CallExpr>(E); 13335 if (unsigned NumArgs = CEx->getNumArgs()) { 13336 Expr *LastA = CEx->getArg(NumArgs - 1); 13337 Expr *InnerE = LastA->IgnoreParenImpCasts(); 13338 if (isa<ImplicitCastExpr>(LastA) && 13339 InnerE->getType()->isBooleanType()) { 13340 // Warn on this floating-point to bool conversion 13341 DiagnoseImpCast(S, E, T, CC, 13342 diag::warn_impcast_floating_point_to_bool); 13343 } 13344 } 13345 } 13346 return; 13347 } 13348 13349 // Valid casts involving fixed point types should be accounted for here. 13350 if (Source->isFixedPointType()) { 13351 if (Target->isUnsaturatedFixedPointType()) { 13352 Expr::EvalResult Result; 13353 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 13354 S.isConstantEvaluated())) { 13355 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 13356 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 13357 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 13358 if (Value > MaxVal || Value < MinVal) { 13359 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13360 S.PDiag(diag::warn_impcast_fixed_point_range) 13361 << Value.toString() << T 13362 << E->getSourceRange() 13363 << clang::SourceRange(CC)); 13364 return; 13365 } 13366 } 13367 } else if (Target->isIntegerType()) { 13368 Expr::EvalResult Result; 13369 if (!S.isConstantEvaluated() && 13370 E->EvaluateAsFixedPoint(Result, S.Context, 13371 Expr::SE_AllowSideEffects)) { 13372 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 13373 13374 bool Overflowed; 13375 llvm::APSInt IntResult = FXResult.convertToInt( 13376 S.Context.getIntWidth(T), 13377 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 13378 13379 if (Overflowed) { 13380 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13381 S.PDiag(diag::warn_impcast_fixed_point_range) 13382 << FXResult.toString() << T 13383 << E->getSourceRange() 13384 << clang::SourceRange(CC)); 13385 return; 13386 } 13387 } 13388 } 13389 } else if (Target->isUnsaturatedFixedPointType()) { 13390 if (Source->isIntegerType()) { 13391 Expr::EvalResult Result; 13392 if (!S.isConstantEvaluated() && 13393 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 13394 llvm::APSInt Value = Result.Val.getInt(); 13395 13396 bool Overflowed; 13397 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 13398 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 13399 13400 if (Overflowed) { 13401 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13402 S.PDiag(diag::warn_impcast_fixed_point_range) 13403 << toString(Value, /*Radix=*/10) << T 13404 << E->getSourceRange() 13405 << clang::SourceRange(CC)); 13406 return; 13407 } 13408 } 13409 } 13410 } 13411 13412 // If we are casting an integer type to a floating point type without 13413 // initialization-list syntax, we might lose accuracy if the floating 13414 // point type has a narrower significand than the integer type. 13415 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 13416 TargetBT->isFloatingType() && !IsListInit) { 13417 // Determine the number of precision bits in the source integer type. 13418 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 13419 /*Approximate*/ true); 13420 unsigned int SourcePrecision = SourceRange.Width; 13421 13422 // Determine the number of precision bits in the 13423 // target floating point type. 13424 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 13425 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13426 13427 if (SourcePrecision > 0 && TargetPrecision > 0 && 13428 SourcePrecision > TargetPrecision) { 13429 13430 if (Optional<llvm::APSInt> SourceInt = 13431 E->getIntegerConstantExpr(S.Context)) { 13432 // If the source integer is a constant, convert it to the target 13433 // floating point type. Issue a warning if the value changes 13434 // during the whole conversion. 13435 llvm::APFloat TargetFloatValue( 13436 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13437 llvm::APFloat::opStatus ConversionStatus = 13438 TargetFloatValue.convertFromAPInt( 13439 *SourceInt, SourceBT->isSignedInteger(), 13440 llvm::APFloat::rmNearestTiesToEven); 13441 13442 if (ConversionStatus != llvm::APFloat::opOK) { 13443 SmallString<32> PrettySourceValue; 13444 SourceInt->toString(PrettySourceValue, 10); 13445 SmallString<32> PrettyTargetValue; 13446 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13447 13448 S.DiagRuntimeBehavior( 13449 E->getExprLoc(), E, 13450 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13451 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13452 << E->getSourceRange() << clang::SourceRange(CC)); 13453 } 13454 } else { 13455 // Otherwise, the implicit conversion may lose precision. 13456 DiagnoseImpCast(S, E, T, CC, 13457 diag::warn_impcast_integer_float_precision); 13458 } 13459 } 13460 } 13461 13462 DiagnoseNullConversion(S, E, T, CC); 13463 13464 S.DiscardMisalignedMemberAddress(Target, E); 13465 13466 if (Target->isBooleanType()) 13467 DiagnoseIntInBoolContext(S, E); 13468 13469 if (!Source->isIntegerType() || !Target->isIntegerType()) 13470 return; 13471 13472 // TODO: remove this early return once the false positives for constant->bool 13473 // in templates, macros, etc, are reduced or removed. 13474 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13475 return; 13476 13477 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13478 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13479 return adornObjCBoolConversionDiagWithTernaryFixit( 13480 S, E, 13481 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13482 << E->getType()); 13483 } 13484 13485 IntRange SourceTypeRange = 13486 IntRange::forTargetOfCanonicalType(S.Context, Source); 13487 IntRange LikelySourceRange = 13488 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13489 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13490 13491 if (LikelySourceRange.Width > TargetRange.Width) { 13492 // If the source is a constant, use a default-on diagnostic. 13493 // TODO: this should happen for bitfield stores, too. 13494 Expr::EvalResult Result; 13495 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13496 S.isConstantEvaluated())) { 13497 llvm::APSInt Value(32); 13498 Value = Result.Val.getInt(); 13499 13500 if (S.SourceMgr.isInSystemMacro(CC)) 13501 return; 13502 13503 std::string PrettySourceValue = toString(Value, 10); 13504 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13505 13506 S.DiagRuntimeBehavior( 13507 E->getExprLoc(), E, 13508 S.PDiag(diag::warn_impcast_integer_precision_constant) 13509 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13510 << E->getSourceRange() << SourceRange(CC)); 13511 return; 13512 } 13513 13514 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13515 if (S.SourceMgr.isInSystemMacro(CC)) 13516 return; 13517 13518 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13519 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13520 /* pruneControlFlow */ true); 13521 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13522 } 13523 13524 if (TargetRange.Width > SourceTypeRange.Width) { 13525 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13526 if (UO->getOpcode() == UO_Minus) 13527 if (Source->isUnsignedIntegerType()) { 13528 if (Target->isUnsignedIntegerType()) 13529 return DiagnoseImpCast(S, E, T, CC, 13530 diag::warn_impcast_high_order_zero_bits); 13531 if (Target->isSignedIntegerType()) 13532 return DiagnoseImpCast(S, E, T, CC, 13533 diag::warn_impcast_nonnegative_result); 13534 } 13535 } 13536 13537 if (TargetRange.Width == LikelySourceRange.Width && 13538 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13539 Source->isSignedIntegerType()) { 13540 // Warn when doing a signed to signed conversion, warn if the positive 13541 // source value is exactly the width of the target type, which will 13542 // cause a negative value to be stored. 13543 13544 Expr::EvalResult Result; 13545 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13546 !S.SourceMgr.isInSystemMacro(CC)) { 13547 llvm::APSInt Value = Result.Val.getInt(); 13548 if (isSameWidthConstantConversion(S, E, T, CC)) { 13549 std::string PrettySourceValue = toString(Value, 10); 13550 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13551 13552 S.DiagRuntimeBehavior( 13553 E->getExprLoc(), E, 13554 S.PDiag(diag::warn_impcast_integer_precision_constant) 13555 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13556 << E->getSourceRange() << SourceRange(CC)); 13557 return; 13558 } 13559 } 13560 13561 // Fall through for non-constants to give a sign conversion warning. 13562 } 13563 13564 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13565 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13566 LikelySourceRange.Width == TargetRange.Width)) { 13567 if (S.SourceMgr.isInSystemMacro(CC)) 13568 return; 13569 13570 unsigned DiagID = diag::warn_impcast_integer_sign; 13571 13572 // Traditionally, gcc has warned about this under -Wsign-compare. 13573 // We also want to warn about it in -Wconversion. 13574 // So if -Wconversion is off, use a completely identical diagnostic 13575 // in the sign-compare group. 13576 // The conditional-checking code will 13577 if (ICContext) { 13578 DiagID = diag::warn_impcast_integer_sign_conditional; 13579 *ICContext = true; 13580 } 13581 13582 return DiagnoseImpCast(S, E, T, CC, DiagID); 13583 } 13584 13585 // Diagnose conversions between different enumeration types. 13586 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13587 // type, to give us better diagnostics. 13588 QualType SourceType = E->getType(); 13589 if (!S.getLangOpts().CPlusPlus) { 13590 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13591 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13592 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13593 SourceType = S.Context.getTypeDeclType(Enum); 13594 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13595 } 13596 } 13597 13598 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13599 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13600 if (SourceEnum->getDecl()->hasNameForLinkage() && 13601 TargetEnum->getDecl()->hasNameForLinkage() && 13602 SourceEnum != TargetEnum) { 13603 if (S.SourceMgr.isInSystemMacro(CC)) 13604 return; 13605 13606 return DiagnoseImpCast(S, E, SourceType, T, CC, 13607 diag::warn_impcast_different_enum_types); 13608 } 13609 } 13610 13611 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13612 SourceLocation CC, QualType T); 13613 13614 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13615 SourceLocation CC, bool &ICContext) { 13616 E = E->IgnoreParenImpCasts(); 13617 13618 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13619 return CheckConditionalOperator(S, CO, CC, T); 13620 13621 AnalyzeImplicitConversions(S, E, CC); 13622 if (E->getType() != T) 13623 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13624 } 13625 13626 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13627 SourceLocation CC, QualType T) { 13628 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13629 13630 Expr *TrueExpr = E->getTrueExpr(); 13631 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13632 TrueExpr = BCO->getCommon(); 13633 13634 bool Suspicious = false; 13635 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13636 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13637 13638 if (T->isBooleanType()) 13639 DiagnoseIntInBoolContext(S, E); 13640 13641 // If -Wconversion would have warned about either of the candidates 13642 // for a signedness conversion to the context type... 13643 if (!Suspicious) return; 13644 13645 // ...but it's currently ignored... 13646 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13647 return; 13648 13649 // ...then check whether it would have warned about either of the 13650 // candidates for a signedness conversion to the condition type. 13651 if (E->getType() == T) return; 13652 13653 Suspicious = false; 13654 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13655 E->getType(), CC, &Suspicious); 13656 if (!Suspicious) 13657 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13658 E->getType(), CC, &Suspicious); 13659 } 13660 13661 /// Check conversion of given expression to boolean. 13662 /// Input argument E is a logical expression. 13663 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13664 if (S.getLangOpts().Bool) 13665 return; 13666 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13667 return; 13668 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13669 } 13670 13671 namespace { 13672 struct AnalyzeImplicitConversionsWorkItem { 13673 Expr *E; 13674 SourceLocation CC; 13675 bool IsListInit; 13676 }; 13677 } 13678 13679 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13680 /// that should be visited are added to WorkList. 13681 static void AnalyzeImplicitConversions( 13682 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13683 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13684 Expr *OrigE = Item.E; 13685 SourceLocation CC = Item.CC; 13686 13687 QualType T = OrigE->getType(); 13688 Expr *E = OrigE->IgnoreParenImpCasts(); 13689 13690 // Propagate whether we are in a C++ list initialization expression. 13691 // If so, we do not issue warnings for implicit int-float conversion 13692 // precision loss, because C++11 narrowing already handles it. 13693 bool IsListInit = Item.IsListInit || 13694 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13695 13696 if (E->isTypeDependent() || E->isValueDependent()) 13697 return; 13698 13699 Expr *SourceExpr = E; 13700 // Examine, but don't traverse into the source expression of an 13701 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13702 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13703 // evaluate it in the context of checking the specific conversion to T though. 13704 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13705 if (auto *Src = OVE->getSourceExpr()) 13706 SourceExpr = Src; 13707 13708 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13709 if (UO->getOpcode() == UO_Not && 13710 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13711 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13712 << OrigE->getSourceRange() << T->isBooleanType() 13713 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13714 13715 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13716 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13717 BO->getLHS()->isKnownToHaveBooleanValue() && 13718 BO->getRHS()->isKnownToHaveBooleanValue() && 13719 BO->getLHS()->HasSideEffects(S.Context) && 13720 BO->getRHS()->HasSideEffects(S.Context)) { 13721 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13722 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13723 << FixItHint::CreateReplacement( 13724 BO->getOperatorLoc(), 13725 (BO->getOpcode() == BO_And ? "&&" : "||")); 13726 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13727 } 13728 13729 // For conditional operators, we analyze the arguments as if they 13730 // were being fed directly into the output. 13731 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13732 CheckConditionalOperator(S, CO, CC, T); 13733 return; 13734 } 13735 13736 // Check implicit argument conversions for function calls. 13737 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13738 CheckImplicitArgumentConversions(S, Call, CC); 13739 13740 // Go ahead and check any implicit conversions we might have skipped. 13741 // The non-canonical typecheck is just an optimization; 13742 // CheckImplicitConversion will filter out dead implicit conversions. 13743 if (SourceExpr->getType() != T) 13744 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13745 13746 // Now continue drilling into this expression. 13747 13748 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13749 // The bound subexpressions in a PseudoObjectExpr are not reachable 13750 // as transitive children. 13751 // FIXME: Use a more uniform representation for this. 13752 for (auto *SE : POE->semantics()) 13753 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13754 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13755 } 13756 13757 // Skip past explicit casts. 13758 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13759 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13760 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13761 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13762 WorkList.push_back({E, CC, IsListInit}); 13763 return; 13764 } 13765 13766 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13767 // Do a somewhat different check with comparison operators. 13768 if (BO->isComparisonOp()) 13769 return AnalyzeComparison(S, BO); 13770 13771 // And with simple assignments. 13772 if (BO->getOpcode() == BO_Assign) 13773 return AnalyzeAssignment(S, BO); 13774 // And with compound assignments. 13775 if (BO->isAssignmentOp()) 13776 return AnalyzeCompoundAssignment(S, BO); 13777 } 13778 13779 // These break the otherwise-useful invariant below. Fortunately, 13780 // we don't really need to recurse into them, because any internal 13781 // expressions should have been analyzed already when they were 13782 // built into statements. 13783 if (isa<StmtExpr>(E)) return; 13784 13785 // Don't descend into unevaluated contexts. 13786 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13787 13788 // Now just recurse over the expression's children. 13789 CC = E->getExprLoc(); 13790 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13791 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13792 for (Stmt *SubStmt : E->children()) { 13793 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13794 if (!ChildExpr) 13795 continue; 13796 13797 if (IsLogicalAndOperator && 13798 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13799 // Ignore checking string literals that are in logical and operators. 13800 // This is a common pattern for asserts. 13801 continue; 13802 WorkList.push_back({ChildExpr, CC, IsListInit}); 13803 } 13804 13805 if (BO && BO->isLogicalOp()) { 13806 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13807 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13808 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13809 13810 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13811 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13812 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13813 } 13814 13815 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13816 if (U->getOpcode() == UO_LNot) { 13817 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13818 } else if (U->getOpcode() != UO_AddrOf) { 13819 if (U->getSubExpr()->getType()->isAtomicType()) 13820 S.Diag(U->getSubExpr()->getBeginLoc(), 13821 diag::warn_atomic_implicit_seq_cst); 13822 } 13823 } 13824 } 13825 13826 /// AnalyzeImplicitConversions - Find and report any interesting 13827 /// implicit conversions in the given expression. There are a couple 13828 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13829 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13830 bool IsListInit/*= false*/) { 13831 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13832 WorkList.push_back({OrigE, CC, IsListInit}); 13833 while (!WorkList.empty()) 13834 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13835 } 13836 13837 /// Diagnose integer type and any valid implicit conversion to it. 13838 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13839 // Taking into account implicit conversions, 13840 // allow any integer. 13841 if (!E->getType()->isIntegerType()) { 13842 S.Diag(E->getBeginLoc(), 13843 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13844 return true; 13845 } 13846 // Potentially emit standard warnings for implicit conversions if enabled 13847 // using -Wconversion. 13848 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13849 return false; 13850 } 13851 13852 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13853 // Returns true when emitting a warning about taking the address of a reference. 13854 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13855 const PartialDiagnostic &PD) { 13856 E = E->IgnoreParenImpCasts(); 13857 13858 const FunctionDecl *FD = nullptr; 13859 13860 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13861 if (!DRE->getDecl()->getType()->isReferenceType()) 13862 return false; 13863 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13864 if (!M->getMemberDecl()->getType()->isReferenceType()) 13865 return false; 13866 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13867 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13868 return false; 13869 FD = Call->getDirectCallee(); 13870 } else { 13871 return false; 13872 } 13873 13874 SemaRef.Diag(E->getExprLoc(), PD); 13875 13876 // If possible, point to location of function. 13877 if (FD) { 13878 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13879 } 13880 13881 return true; 13882 } 13883 13884 // Returns true if the SourceLocation is expanded from any macro body. 13885 // Returns false if the SourceLocation is invalid, is from not in a macro 13886 // expansion, or is from expanded from a top-level macro argument. 13887 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13888 if (Loc.isInvalid()) 13889 return false; 13890 13891 while (Loc.isMacroID()) { 13892 if (SM.isMacroBodyExpansion(Loc)) 13893 return true; 13894 Loc = SM.getImmediateMacroCallerLoc(Loc); 13895 } 13896 13897 return false; 13898 } 13899 13900 /// Diagnose pointers that are always non-null. 13901 /// \param E the expression containing the pointer 13902 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13903 /// compared to a null pointer 13904 /// \param IsEqual True when the comparison is equal to a null pointer 13905 /// \param Range Extra SourceRange to highlight in the diagnostic 13906 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13907 Expr::NullPointerConstantKind NullKind, 13908 bool IsEqual, SourceRange Range) { 13909 if (!E) 13910 return; 13911 13912 // Don't warn inside macros. 13913 if (E->getExprLoc().isMacroID()) { 13914 const SourceManager &SM = getSourceManager(); 13915 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13916 IsInAnyMacroBody(SM, Range.getBegin())) 13917 return; 13918 } 13919 E = E->IgnoreImpCasts(); 13920 13921 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13922 13923 if (isa<CXXThisExpr>(E)) { 13924 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13925 : diag::warn_this_bool_conversion; 13926 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13927 return; 13928 } 13929 13930 bool IsAddressOf = false; 13931 13932 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13933 if (UO->getOpcode() != UO_AddrOf) 13934 return; 13935 IsAddressOf = true; 13936 E = UO->getSubExpr(); 13937 } 13938 13939 if (IsAddressOf) { 13940 unsigned DiagID = IsCompare 13941 ? diag::warn_address_of_reference_null_compare 13942 : diag::warn_address_of_reference_bool_conversion; 13943 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13944 << IsEqual; 13945 if (CheckForReference(*this, E, PD)) { 13946 return; 13947 } 13948 } 13949 13950 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13951 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13952 std::string Str; 13953 llvm::raw_string_ostream S(Str); 13954 E->printPretty(S, nullptr, getPrintingPolicy()); 13955 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13956 : diag::warn_cast_nonnull_to_bool; 13957 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13958 << E->getSourceRange() << Range << IsEqual; 13959 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13960 }; 13961 13962 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13963 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13964 if (auto *Callee = Call->getDirectCallee()) { 13965 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13966 ComplainAboutNonnullParamOrCall(A); 13967 return; 13968 } 13969 } 13970 } 13971 13972 // Expect to find a single Decl. Skip anything more complicated. 13973 ValueDecl *D = nullptr; 13974 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13975 D = R->getDecl(); 13976 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13977 D = M->getMemberDecl(); 13978 } 13979 13980 // Weak Decls can be null. 13981 if (!D || D->isWeak()) 13982 return; 13983 13984 // Check for parameter decl with nonnull attribute 13985 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13986 if (getCurFunction() && 13987 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13988 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13989 ComplainAboutNonnullParamOrCall(A); 13990 return; 13991 } 13992 13993 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13994 // Skip function template not specialized yet. 13995 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13996 return; 13997 auto ParamIter = llvm::find(FD->parameters(), PV); 13998 assert(ParamIter != FD->param_end()); 13999 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 14000 14001 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 14002 if (!NonNull->args_size()) { 14003 ComplainAboutNonnullParamOrCall(NonNull); 14004 return; 14005 } 14006 14007 for (const ParamIdx &ArgNo : NonNull->args()) { 14008 if (ArgNo.getASTIndex() == ParamNo) { 14009 ComplainAboutNonnullParamOrCall(NonNull); 14010 return; 14011 } 14012 } 14013 } 14014 } 14015 } 14016 } 14017 14018 QualType T = D->getType(); 14019 const bool IsArray = T->isArrayType(); 14020 const bool IsFunction = T->isFunctionType(); 14021 14022 // Address of function is used to silence the function warning. 14023 if (IsAddressOf && IsFunction) { 14024 return; 14025 } 14026 14027 // Found nothing. 14028 if (!IsAddressOf && !IsFunction && !IsArray) 14029 return; 14030 14031 // Pretty print the expression for the diagnostic. 14032 std::string Str; 14033 llvm::raw_string_ostream S(Str); 14034 E->printPretty(S, nullptr, getPrintingPolicy()); 14035 14036 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 14037 : diag::warn_impcast_pointer_to_bool; 14038 enum { 14039 AddressOf, 14040 FunctionPointer, 14041 ArrayPointer 14042 } DiagType; 14043 if (IsAddressOf) 14044 DiagType = AddressOf; 14045 else if (IsFunction) 14046 DiagType = FunctionPointer; 14047 else if (IsArray) 14048 DiagType = ArrayPointer; 14049 else 14050 llvm_unreachable("Could not determine diagnostic."); 14051 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 14052 << Range << IsEqual; 14053 14054 if (!IsFunction) 14055 return; 14056 14057 // Suggest '&' to silence the function warning. 14058 Diag(E->getExprLoc(), diag::note_function_warning_silence) 14059 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 14060 14061 // Check to see if '()' fixit should be emitted. 14062 QualType ReturnType; 14063 UnresolvedSet<4> NonTemplateOverloads; 14064 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 14065 if (ReturnType.isNull()) 14066 return; 14067 14068 if (IsCompare) { 14069 // There are two cases here. If there is null constant, the only suggest 14070 // for a pointer return type. If the null is 0, then suggest if the return 14071 // type is a pointer or an integer type. 14072 if (!ReturnType->isPointerType()) { 14073 if (NullKind == Expr::NPCK_ZeroExpression || 14074 NullKind == Expr::NPCK_ZeroLiteral) { 14075 if (!ReturnType->isIntegerType()) 14076 return; 14077 } else { 14078 return; 14079 } 14080 } 14081 } else { // !IsCompare 14082 // For function to bool, only suggest if the function pointer has bool 14083 // return type. 14084 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 14085 return; 14086 } 14087 Diag(E->getExprLoc(), diag::note_function_to_function_call) 14088 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 14089 } 14090 14091 /// Diagnoses "dangerous" implicit conversions within the given 14092 /// expression (which is a full expression). Implements -Wconversion 14093 /// and -Wsign-compare. 14094 /// 14095 /// \param CC the "context" location of the implicit conversion, i.e. 14096 /// the most location of the syntactic entity requiring the implicit 14097 /// conversion 14098 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 14099 // Don't diagnose in unevaluated contexts. 14100 if (isUnevaluatedContext()) 14101 return; 14102 14103 // Don't diagnose for value- or type-dependent expressions. 14104 if (E->isTypeDependent() || E->isValueDependent()) 14105 return; 14106 14107 // Check for array bounds violations in cases where the check isn't triggered 14108 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 14109 // ArraySubscriptExpr is on the RHS of a variable initialization. 14110 CheckArrayAccess(E); 14111 14112 // This is not the right CC for (e.g.) a variable initialization. 14113 AnalyzeImplicitConversions(*this, E, CC); 14114 } 14115 14116 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 14117 /// Input argument E is a logical expression. 14118 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 14119 ::CheckBoolLikeConversion(*this, E, CC); 14120 } 14121 14122 /// Diagnose when expression is an integer constant expression and its evaluation 14123 /// results in integer overflow 14124 void Sema::CheckForIntOverflow (Expr *E) { 14125 // Use a work list to deal with nested struct initializers. 14126 SmallVector<Expr *, 2> Exprs(1, E); 14127 14128 do { 14129 Expr *OriginalE = Exprs.pop_back_val(); 14130 Expr *E = OriginalE->IgnoreParenCasts(); 14131 14132 if (isa<BinaryOperator>(E)) { 14133 E->EvaluateForOverflow(Context); 14134 continue; 14135 } 14136 14137 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 14138 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 14139 else if (isa<ObjCBoxedExpr>(OriginalE)) 14140 E->EvaluateForOverflow(Context); 14141 else if (auto Call = dyn_cast<CallExpr>(E)) 14142 Exprs.append(Call->arg_begin(), Call->arg_end()); 14143 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 14144 Exprs.append(Message->arg_begin(), Message->arg_end()); 14145 } while (!Exprs.empty()); 14146 } 14147 14148 namespace { 14149 14150 /// Visitor for expressions which looks for unsequenced operations on the 14151 /// same object. 14152 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 14153 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 14154 14155 /// A tree of sequenced regions within an expression. Two regions are 14156 /// unsequenced if one is an ancestor or a descendent of the other. When we 14157 /// finish processing an expression with sequencing, such as a comma 14158 /// expression, we fold its tree nodes into its parent, since they are 14159 /// unsequenced with respect to nodes we will visit later. 14160 class SequenceTree { 14161 struct Value { 14162 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 14163 unsigned Parent : 31; 14164 unsigned Merged : 1; 14165 }; 14166 SmallVector<Value, 8> Values; 14167 14168 public: 14169 /// A region within an expression which may be sequenced with respect 14170 /// to some other region. 14171 class Seq { 14172 friend class SequenceTree; 14173 14174 unsigned Index; 14175 14176 explicit Seq(unsigned N) : Index(N) {} 14177 14178 public: 14179 Seq() : Index(0) {} 14180 }; 14181 14182 SequenceTree() { Values.push_back(Value(0)); } 14183 Seq root() const { return Seq(0); } 14184 14185 /// Create a new sequence of operations, which is an unsequenced 14186 /// subset of \p Parent. This sequence of operations is sequenced with 14187 /// respect to other children of \p Parent. 14188 Seq allocate(Seq Parent) { 14189 Values.push_back(Value(Parent.Index)); 14190 return Seq(Values.size() - 1); 14191 } 14192 14193 /// Merge a sequence of operations into its parent. 14194 void merge(Seq S) { 14195 Values[S.Index].Merged = true; 14196 } 14197 14198 /// Determine whether two operations are unsequenced. This operation 14199 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 14200 /// should have been merged into its parent as appropriate. 14201 bool isUnsequenced(Seq Cur, Seq Old) { 14202 unsigned C = representative(Cur.Index); 14203 unsigned Target = representative(Old.Index); 14204 while (C >= Target) { 14205 if (C == Target) 14206 return true; 14207 C = Values[C].Parent; 14208 } 14209 return false; 14210 } 14211 14212 private: 14213 /// Pick a representative for a sequence. 14214 unsigned representative(unsigned K) { 14215 if (Values[K].Merged) 14216 // Perform path compression as we go. 14217 return Values[K].Parent = representative(Values[K].Parent); 14218 return K; 14219 } 14220 }; 14221 14222 /// An object for which we can track unsequenced uses. 14223 using Object = const NamedDecl *; 14224 14225 /// Different flavors of object usage which we track. We only track the 14226 /// least-sequenced usage of each kind. 14227 enum UsageKind { 14228 /// A read of an object. Multiple unsequenced reads are OK. 14229 UK_Use, 14230 14231 /// A modification of an object which is sequenced before the value 14232 /// computation of the expression, such as ++n in C++. 14233 UK_ModAsValue, 14234 14235 /// A modification of an object which is not sequenced before the value 14236 /// computation of the expression, such as n++. 14237 UK_ModAsSideEffect, 14238 14239 UK_Count = UK_ModAsSideEffect + 1 14240 }; 14241 14242 /// Bundle together a sequencing region and the expression corresponding 14243 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 14244 struct Usage { 14245 const Expr *UsageExpr; 14246 SequenceTree::Seq Seq; 14247 14248 Usage() : UsageExpr(nullptr) {} 14249 }; 14250 14251 struct UsageInfo { 14252 Usage Uses[UK_Count]; 14253 14254 /// Have we issued a diagnostic for this object already? 14255 bool Diagnosed; 14256 14257 UsageInfo() : Diagnosed(false) {} 14258 }; 14259 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 14260 14261 Sema &SemaRef; 14262 14263 /// Sequenced regions within the expression. 14264 SequenceTree Tree; 14265 14266 /// Declaration modifications and references which we have seen. 14267 UsageInfoMap UsageMap; 14268 14269 /// The region we are currently within. 14270 SequenceTree::Seq Region; 14271 14272 /// Filled in with declarations which were modified as a side-effect 14273 /// (that is, post-increment operations). 14274 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 14275 14276 /// Expressions to check later. We defer checking these to reduce 14277 /// stack usage. 14278 SmallVectorImpl<const Expr *> &WorkList; 14279 14280 /// RAII object wrapping the visitation of a sequenced subexpression of an 14281 /// expression. At the end of this process, the side-effects of the evaluation 14282 /// become sequenced with respect to the value computation of the result, so 14283 /// we downgrade any UK_ModAsSideEffect within the evaluation to 14284 /// UK_ModAsValue. 14285 struct SequencedSubexpression { 14286 SequencedSubexpression(SequenceChecker &Self) 14287 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 14288 Self.ModAsSideEffect = &ModAsSideEffect; 14289 } 14290 14291 ~SequencedSubexpression() { 14292 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 14293 // Add a new usage with usage kind UK_ModAsValue, and then restore 14294 // the previous usage with UK_ModAsSideEffect (thus clearing it if 14295 // the previous one was empty). 14296 UsageInfo &UI = Self.UsageMap[M.first]; 14297 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 14298 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 14299 SideEffectUsage = M.second; 14300 } 14301 Self.ModAsSideEffect = OldModAsSideEffect; 14302 } 14303 14304 SequenceChecker &Self; 14305 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 14306 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 14307 }; 14308 14309 /// RAII object wrapping the visitation of a subexpression which we might 14310 /// choose to evaluate as a constant. If any subexpression is evaluated and 14311 /// found to be non-constant, this allows us to suppress the evaluation of 14312 /// the outer expression. 14313 class EvaluationTracker { 14314 public: 14315 EvaluationTracker(SequenceChecker &Self) 14316 : Self(Self), Prev(Self.EvalTracker) { 14317 Self.EvalTracker = this; 14318 } 14319 14320 ~EvaluationTracker() { 14321 Self.EvalTracker = Prev; 14322 if (Prev) 14323 Prev->EvalOK &= EvalOK; 14324 } 14325 14326 bool evaluate(const Expr *E, bool &Result) { 14327 if (!EvalOK || E->isValueDependent()) 14328 return false; 14329 EvalOK = E->EvaluateAsBooleanCondition( 14330 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 14331 return EvalOK; 14332 } 14333 14334 private: 14335 SequenceChecker &Self; 14336 EvaluationTracker *Prev; 14337 bool EvalOK = true; 14338 } *EvalTracker = nullptr; 14339 14340 /// Find the object which is produced by the specified expression, 14341 /// if any. 14342 Object getObject(const Expr *E, bool Mod) const { 14343 E = E->IgnoreParenCasts(); 14344 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 14345 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 14346 return getObject(UO->getSubExpr(), Mod); 14347 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 14348 if (BO->getOpcode() == BO_Comma) 14349 return getObject(BO->getRHS(), Mod); 14350 if (Mod && BO->isAssignmentOp()) 14351 return getObject(BO->getLHS(), Mod); 14352 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14353 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 14354 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 14355 return ME->getMemberDecl(); 14356 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 14357 // FIXME: If this is a reference, map through to its value. 14358 return DRE->getDecl(); 14359 return nullptr; 14360 } 14361 14362 /// Note that an object \p O was modified or used by an expression 14363 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 14364 /// the object \p O as obtained via the \p UsageMap. 14365 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 14366 // Get the old usage for the given object and usage kind. 14367 Usage &U = UI.Uses[UK]; 14368 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 14369 // If we have a modification as side effect and are in a sequenced 14370 // subexpression, save the old Usage so that we can restore it later 14371 // in SequencedSubexpression::~SequencedSubexpression. 14372 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 14373 ModAsSideEffect->push_back(std::make_pair(O, U)); 14374 // Then record the new usage with the current sequencing region. 14375 U.UsageExpr = UsageExpr; 14376 U.Seq = Region; 14377 } 14378 } 14379 14380 /// Check whether a modification or use of an object \p O in an expression 14381 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 14382 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 14383 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 14384 /// usage and false we are checking for a mod-use unsequenced usage. 14385 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 14386 UsageKind OtherKind, bool IsModMod) { 14387 if (UI.Diagnosed) 14388 return; 14389 14390 const Usage &U = UI.Uses[OtherKind]; 14391 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 14392 return; 14393 14394 const Expr *Mod = U.UsageExpr; 14395 const Expr *ModOrUse = UsageExpr; 14396 if (OtherKind == UK_Use) 14397 std::swap(Mod, ModOrUse); 14398 14399 SemaRef.DiagRuntimeBehavior( 14400 Mod->getExprLoc(), {Mod, ModOrUse}, 14401 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 14402 : diag::warn_unsequenced_mod_use) 14403 << O << SourceRange(ModOrUse->getExprLoc())); 14404 UI.Diagnosed = true; 14405 } 14406 14407 // A note on note{Pre, Post}{Use, Mod}: 14408 // 14409 // (It helps to follow the algorithm with an expression such as 14410 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 14411 // operations before C++17 and both are well-defined in C++17). 14412 // 14413 // When visiting a node which uses/modify an object we first call notePreUse 14414 // or notePreMod before visiting its sub-expression(s). At this point the 14415 // children of the current node have not yet been visited and so the eventual 14416 // uses/modifications resulting from the children of the current node have not 14417 // been recorded yet. 14418 // 14419 // We then visit the children of the current node. After that notePostUse or 14420 // notePostMod is called. These will 1) detect an unsequenced modification 14421 // as side effect (as in "k++ + k") and 2) add a new usage with the 14422 // appropriate usage kind. 14423 // 14424 // We also have to be careful that some operation sequences modification as 14425 // side effect as well (for example: || or ,). To account for this we wrap 14426 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14427 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14428 // which record usages which are modifications as side effect, and then 14429 // downgrade them (or more accurately restore the previous usage which was a 14430 // modification as side effect) when exiting the scope of the sequenced 14431 // subexpression. 14432 14433 void notePreUse(Object O, const Expr *UseExpr) { 14434 UsageInfo &UI = UsageMap[O]; 14435 // Uses conflict with other modifications. 14436 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14437 } 14438 14439 void notePostUse(Object O, const Expr *UseExpr) { 14440 UsageInfo &UI = UsageMap[O]; 14441 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14442 /*IsModMod=*/false); 14443 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14444 } 14445 14446 void notePreMod(Object O, const Expr *ModExpr) { 14447 UsageInfo &UI = UsageMap[O]; 14448 // Modifications conflict with other modifications and with uses. 14449 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14450 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14451 } 14452 14453 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14454 UsageInfo &UI = UsageMap[O]; 14455 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14456 /*IsModMod=*/true); 14457 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14458 } 14459 14460 public: 14461 SequenceChecker(Sema &S, const Expr *E, 14462 SmallVectorImpl<const Expr *> &WorkList) 14463 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14464 Visit(E); 14465 // Silence a -Wunused-private-field since WorkList is now unused. 14466 // TODO: Evaluate if it can be used, and if not remove it. 14467 (void)this->WorkList; 14468 } 14469 14470 void VisitStmt(const Stmt *S) { 14471 // Skip all statements which aren't expressions for now. 14472 } 14473 14474 void VisitExpr(const Expr *E) { 14475 // By default, just recurse to evaluated subexpressions. 14476 Base::VisitStmt(E); 14477 } 14478 14479 void VisitCastExpr(const CastExpr *E) { 14480 Object O = Object(); 14481 if (E->getCastKind() == CK_LValueToRValue) 14482 O = getObject(E->getSubExpr(), false); 14483 14484 if (O) 14485 notePreUse(O, E); 14486 VisitExpr(E); 14487 if (O) 14488 notePostUse(O, E); 14489 } 14490 14491 void VisitSequencedExpressions(const Expr *SequencedBefore, 14492 const Expr *SequencedAfter) { 14493 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14494 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14495 SequenceTree::Seq OldRegion = Region; 14496 14497 { 14498 SequencedSubexpression SeqBefore(*this); 14499 Region = BeforeRegion; 14500 Visit(SequencedBefore); 14501 } 14502 14503 Region = AfterRegion; 14504 Visit(SequencedAfter); 14505 14506 Region = OldRegion; 14507 14508 Tree.merge(BeforeRegion); 14509 Tree.merge(AfterRegion); 14510 } 14511 14512 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14513 // C++17 [expr.sub]p1: 14514 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14515 // expression E1 is sequenced before the expression E2. 14516 if (SemaRef.getLangOpts().CPlusPlus17) 14517 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14518 else { 14519 Visit(ASE->getLHS()); 14520 Visit(ASE->getRHS()); 14521 } 14522 } 14523 14524 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14525 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14526 void VisitBinPtrMem(const BinaryOperator *BO) { 14527 // C++17 [expr.mptr.oper]p4: 14528 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14529 // the expression E1 is sequenced before the expression E2. 14530 if (SemaRef.getLangOpts().CPlusPlus17) 14531 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14532 else { 14533 Visit(BO->getLHS()); 14534 Visit(BO->getRHS()); 14535 } 14536 } 14537 14538 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14539 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14540 void VisitBinShlShr(const BinaryOperator *BO) { 14541 // C++17 [expr.shift]p4: 14542 // The expression E1 is sequenced before the expression E2. 14543 if (SemaRef.getLangOpts().CPlusPlus17) 14544 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14545 else { 14546 Visit(BO->getLHS()); 14547 Visit(BO->getRHS()); 14548 } 14549 } 14550 14551 void VisitBinComma(const BinaryOperator *BO) { 14552 // C++11 [expr.comma]p1: 14553 // Every value computation and side effect associated with the left 14554 // expression is sequenced before every value computation and side 14555 // effect associated with the right expression. 14556 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14557 } 14558 14559 void VisitBinAssign(const BinaryOperator *BO) { 14560 SequenceTree::Seq RHSRegion; 14561 SequenceTree::Seq LHSRegion; 14562 if (SemaRef.getLangOpts().CPlusPlus17) { 14563 RHSRegion = Tree.allocate(Region); 14564 LHSRegion = Tree.allocate(Region); 14565 } else { 14566 RHSRegion = Region; 14567 LHSRegion = Region; 14568 } 14569 SequenceTree::Seq OldRegion = Region; 14570 14571 // C++11 [expr.ass]p1: 14572 // [...] the assignment is sequenced after the value computation 14573 // of the right and left operands, [...] 14574 // 14575 // so check it before inspecting the operands and update the 14576 // map afterwards. 14577 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14578 if (O) 14579 notePreMod(O, BO); 14580 14581 if (SemaRef.getLangOpts().CPlusPlus17) { 14582 // C++17 [expr.ass]p1: 14583 // [...] The right operand is sequenced before the left operand. [...] 14584 { 14585 SequencedSubexpression SeqBefore(*this); 14586 Region = RHSRegion; 14587 Visit(BO->getRHS()); 14588 } 14589 14590 Region = LHSRegion; 14591 Visit(BO->getLHS()); 14592 14593 if (O && isa<CompoundAssignOperator>(BO)) 14594 notePostUse(O, BO); 14595 14596 } else { 14597 // C++11 does not specify any sequencing between the LHS and RHS. 14598 Region = LHSRegion; 14599 Visit(BO->getLHS()); 14600 14601 if (O && isa<CompoundAssignOperator>(BO)) 14602 notePostUse(O, BO); 14603 14604 Region = RHSRegion; 14605 Visit(BO->getRHS()); 14606 } 14607 14608 // C++11 [expr.ass]p1: 14609 // the assignment is sequenced [...] before the value computation of the 14610 // assignment expression. 14611 // C11 6.5.16/3 has no such rule. 14612 Region = OldRegion; 14613 if (O) 14614 notePostMod(O, BO, 14615 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14616 : UK_ModAsSideEffect); 14617 if (SemaRef.getLangOpts().CPlusPlus17) { 14618 Tree.merge(RHSRegion); 14619 Tree.merge(LHSRegion); 14620 } 14621 } 14622 14623 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14624 VisitBinAssign(CAO); 14625 } 14626 14627 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14628 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14629 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14630 Object O = getObject(UO->getSubExpr(), true); 14631 if (!O) 14632 return VisitExpr(UO); 14633 14634 notePreMod(O, UO); 14635 Visit(UO->getSubExpr()); 14636 // C++11 [expr.pre.incr]p1: 14637 // the expression ++x is equivalent to x+=1 14638 notePostMod(O, UO, 14639 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14640 : UK_ModAsSideEffect); 14641 } 14642 14643 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14644 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14645 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14646 Object O = getObject(UO->getSubExpr(), true); 14647 if (!O) 14648 return VisitExpr(UO); 14649 14650 notePreMod(O, UO); 14651 Visit(UO->getSubExpr()); 14652 notePostMod(O, UO, UK_ModAsSideEffect); 14653 } 14654 14655 void VisitBinLOr(const BinaryOperator *BO) { 14656 // C++11 [expr.log.or]p2: 14657 // If the second expression is evaluated, every value computation and 14658 // side effect associated with the first expression is sequenced before 14659 // every value computation and side effect associated with the 14660 // second expression. 14661 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14662 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14663 SequenceTree::Seq OldRegion = Region; 14664 14665 EvaluationTracker Eval(*this); 14666 { 14667 SequencedSubexpression Sequenced(*this); 14668 Region = LHSRegion; 14669 Visit(BO->getLHS()); 14670 } 14671 14672 // C++11 [expr.log.or]p1: 14673 // [...] the second operand is not evaluated if the first operand 14674 // evaluates to true. 14675 bool EvalResult = false; 14676 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14677 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14678 if (ShouldVisitRHS) { 14679 Region = RHSRegion; 14680 Visit(BO->getRHS()); 14681 } 14682 14683 Region = OldRegion; 14684 Tree.merge(LHSRegion); 14685 Tree.merge(RHSRegion); 14686 } 14687 14688 void VisitBinLAnd(const BinaryOperator *BO) { 14689 // C++11 [expr.log.and]p2: 14690 // If the second expression is evaluated, every value computation and 14691 // side effect associated with the first expression is sequenced before 14692 // every value computation and side effect associated with the 14693 // second expression. 14694 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14695 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14696 SequenceTree::Seq OldRegion = Region; 14697 14698 EvaluationTracker Eval(*this); 14699 { 14700 SequencedSubexpression Sequenced(*this); 14701 Region = LHSRegion; 14702 Visit(BO->getLHS()); 14703 } 14704 14705 // C++11 [expr.log.and]p1: 14706 // [...] the second operand is not evaluated if the first operand is false. 14707 bool EvalResult = false; 14708 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14709 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14710 if (ShouldVisitRHS) { 14711 Region = RHSRegion; 14712 Visit(BO->getRHS()); 14713 } 14714 14715 Region = OldRegion; 14716 Tree.merge(LHSRegion); 14717 Tree.merge(RHSRegion); 14718 } 14719 14720 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14721 // C++11 [expr.cond]p1: 14722 // [...] Every value computation and side effect associated with the first 14723 // expression is sequenced before every value computation and side effect 14724 // associated with the second or third expression. 14725 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14726 14727 // No sequencing is specified between the true and false expression. 14728 // However since exactly one of both is going to be evaluated we can 14729 // consider them to be sequenced. This is needed to avoid warning on 14730 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14731 // both the true and false expressions because we can't evaluate x. 14732 // This will still allow us to detect an expression like (pre C++17) 14733 // "(x ? y += 1 : y += 2) = y". 14734 // 14735 // We don't wrap the visitation of the true and false expression with 14736 // SequencedSubexpression because we don't want to downgrade modifications 14737 // as side effect in the true and false expressions after the visition 14738 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14739 // not warn between the two "y++", but we should warn between the "y++" 14740 // and the "y". 14741 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14742 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14743 SequenceTree::Seq OldRegion = Region; 14744 14745 EvaluationTracker Eval(*this); 14746 { 14747 SequencedSubexpression Sequenced(*this); 14748 Region = ConditionRegion; 14749 Visit(CO->getCond()); 14750 } 14751 14752 // C++11 [expr.cond]p1: 14753 // [...] The first expression is contextually converted to bool (Clause 4). 14754 // It is evaluated and if it is true, the result of the conditional 14755 // expression is the value of the second expression, otherwise that of the 14756 // third expression. Only one of the second and third expressions is 14757 // evaluated. [...] 14758 bool EvalResult = false; 14759 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14760 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14761 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14762 if (ShouldVisitTrueExpr) { 14763 Region = TrueRegion; 14764 Visit(CO->getTrueExpr()); 14765 } 14766 if (ShouldVisitFalseExpr) { 14767 Region = FalseRegion; 14768 Visit(CO->getFalseExpr()); 14769 } 14770 14771 Region = OldRegion; 14772 Tree.merge(ConditionRegion); 14773 Tree.merge(TrueRegion); 14774 Tree.merge(FalseRegion); 14775 } 14776 14777 void VisitCallExpr(const CallExpr *CE) { 14778 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14779 14780 if (CE->isUnevaluatedBuiltinCall(Context)) 14781 return; 14782 14783 // C++11 [intro.execution]p15: 14784 // When calling a function [...], every value computation and side effect 14785 // associated with any argument expression, or with the postfix expression 14786 // designating the called function, is sequenced before execution of every 14787 // expression or statement in the body of the function [and thus before 14788 // the value computation of its result]. 14789 SequencedSubexpression Sequenced(*this); 14790 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14791 // C++17 [expr.call]p5 14792 // The postfix-expression is sequenced before each expression in the 14793 // expression-list and any default argument. [...] 14794 SequenceTree::Seq CalleeRegion; 14795 SequenceTree::Seq OtherRegion; 14796 if (SemaRef.getLangOpts().CPlusPlus17) { 14797 CalleeRegion = Tree.allocate(Region); 14798 OtherRegion = Tree.allocate(Region); 14799 } else { 14800 CalleeRegion = Region; 14801 OtherRegion = Region; 14802 } 14803 SequenceTree::Seq OldRegion = Region; 14804 14805 // Visit the callee expression first. 14806 Region = CalleeRegion; 14807 if (SemaRef.getLangOpts().CPlusPlus17) { 14808 SequencedSubexpression Sequenced(*this); 14809 Visit(CE->getCallee()); 14810 } else { 14811 Visit(CE->getCallee()); 14812 } 14813 14814 // Then visit the argument expressions. 14815 Region = OtherRegion; 14816 for (const Expr *Argument : CE->arguments()) 14817 Visit(Argument); 14818 14819 Region = OldRegion; 14820 if (SemaRef.getLangOpts().CPlusPlus17) { 14821 Tree.merge(CalleeRegion); 14822 Tree.merge(OtherRegion); 14823 } 14824 }); 14825 } 14826 14827 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14828 // C++17 [over.match.oper]p2: 14829 // [...] the operator notation is first transformed to the equivalent 14830 // function-call notation as summarized in Table 12 (where @ denotes one 14831 // of the operators covered in the specified subclause). However, the 14832 // operands are sequenced in the order prescribed for the built-in 14833 // operator (Clause 8). 14834 // 14835 // From the above only overloaded binary operators and overloaded call 14836 // operators have sequencing rules in C++17 that we need to handle 14837 // separately. 14838 if (!SemaRef.getLangOpts().CPlusPlus17 || 14839 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14840 return VisitCallExpr(CXXOCE); 14841 14842 enum { 14843 NoSequencing, 14844 LHSBeforeRHS, 14845 RHSBeforeLHS, 14846 LHSBeforeRest 14847 } SequencingKind; 14848 switch (CXXOCE->getOperator()) { 14849 case OO_Equal: 14850 case OO_PlusEqual: 14851 case OO_MinusEqual: 14852 case OO_StarEqual: 14853 case OO_SlashEqual: 14854 case OO_PercentEqual: 14855 case OO_CaretEqual: 14856 case OO_AmpEqual: 14857 case OO_PipeEqual: 14858 case OO_LessLessEqual: 14859 case OO_GreaterGreaterEqual: 14860 SequencingKind = RHSBeforeLHS; 14861 break; 14862 14863 case OO_LessLess: 14864 case OO_GreaterGreater: 14865 case OO_AmpAmp: 14866 case OO_PipePipe: 14867 case OO_Comma: 14868 case OO_ArrowStar: 14869 case OO_Subscript: 14870 SequencingKind = LHSBeforeRHS; 14871 break; 14872 14873 case OO_Call: 14874 SequencingKind = LHSBeforeRest; 14875 break; 14876 14877 default: 14878 SequencingKind = NoSequencing; 14879 break; 14880 } 14881 14882 if (SequencingKind == NoSequencing) 14883 return VisitCallExpr(CXXOCE); 14884 14885 // This is a call, so all subexpressions are sequenced before the result. 14886 SequencedSubexpression Sequenced(*this); 14887 14888 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14889 assert(SemaRef.getLangOpts().CPlusPlus17 && 14890 "Should only get there with C++17 and above!"); 14891 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14892 "Should only get there with an overloaded binary operator" 14893 " or an overloaded call operator!"); 14894 14895 if (SequencingKind == LHSBeforeRest) { 14896 assert(CXXOCE->getOperator() == OO_Call && 14897 "We should only have an overloaded call operator here!"); 14898 14899 // This is very similar to VisitCallExpr, except that we only have the 14900 // C++17 case. The postfix-expression is the first argument of the 14901 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14902 // are in the following arguments. 14903 // 14904 // Note that we intentionally do not visit the callee expression since 14905 // it is just a decayed reference to a function. 14906 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14907 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14908 SequenceTree::Seq OldRegion = Region; 14909 14910 assert(CXXOCE->getNumArgs() >= 1 && 14911 "An overloaded call operator must have at least one argument" 14912 " for the postfix-expression!"); 14913 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14914 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14915 CXXOCE->getNumArgs() - 1); 14916 14917 // Visit the postfix-expression first. 14918 { 14919 Region = PostfixExprRegion; 14920 SequencedSubexpression Sequenced(*this); 14921 Visit(PostfixExpr); 14922 } 14923 14924 // Then visit the argument expressions. 14925 Region = ArgsRegion; 14926 for (const Expr *Arg : Args) 14927 Visit(Arg); 14928 14929 Region = OldRegion; 14930 Tree.merge(PostfixExprRegion); 14931 Tree.merge(ArgsRegion); 14932 } else { 14933 assert(CXXOCE->getNumArgs() == 2 && 14934 "Should only have two arguments here!"); 14935 assert((SequencingKind == LHSBeforeRHS || 14936 SequencingKind == RHSBeforeLHS) && 14937 "Unexpected sequencing kind!"); 14938 14939 // We do not visit the callee expression since it is just a decayed 14940 // reference to a function. 14941 const Expr *E1 = CXXOCE->getArg(0); 14942 const Expr *E2 = CXXOCE->getArg(1); 14943 if (SequencingKind == RHSBeforeLHS) 14944 std::swap(E1, E2); 14945 14946 return VisitSequencedExpressions(E1, E2); 14947 } 14948 }); 14949 } 14950 14951 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14952 // This is a call, so all subexpressions are sequenced before the result. 14953 SequencedSubexpression Sequenced(*this); 14954 14955 if (!CCE->isListInitialization()) 14956 return VisitExpr(CCE); 14957 14958 // In C++11, list initializations are sequenced. 14959 SmallVector<SequenceTree::Seq, 32> Elts; 14960 SequenceTree::Seq Parent = Region; 14961 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14962 E = CCE->arg_end(); 14963 I != E; ++I) { 14964 Region = Tree.allocate(Parent); 14965 Elts.push_back(Region); 14966 Visit(*I); 14967 } 14968 14969 // Forget that the initializers are sequenced. 14970 Region = Parent; 14971 for (unsigned I = 0; I < Elts.size(); ++I) 14972 Tree.merge(Elts[I]); 14973 } 14974 14975 void VisitInitListExpr(const InitListExpr *ILE) { 14976 if (!SemaRef.getLangOpts().CPlusPlus11) 14977 return VisitExpr(ILE); 14978 14979 // In C++11, list initializations are sequenced. 14980 SmallVector<SequenceTree::Seq, 32> Elts; 14981 SequenceTree::Seq Parent = Region; 14982 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14983 const Expr *E = ILE->getInit(I); 14984 if (!E) 14985 continue; 14986 Region = Tree.allocate(Parent); 14987 Elts.push_back(Region); 14988 Visit(E); 14989 } 14990 14991 // Forget that the initializers are sequenced. 14992 Region = Parent; 14993 for (unsigned I = 0; I < Elts.size(); ++I) 14994 Tree.merge(Elts[I]); 14995 } 14996 }; 14997 14998 } // namespace 14999 15000 void Sema::CheckUnsequencedOperations(const Expr *E) { 15001 SmallVector<const Expr *, 8> WorkList; 15002 WorkList.push_back(E); 15003 while (!WorkList.empty()) { 15004 const Expr *Item = WorkList.pop_back_val(); 15005 SequenceChecker(*this, Item, WorkList); 15006 } 15007 } 15008 15009 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 15010 bool IsConstexpr) { 15011 llvm::SaveAndRestore<bool> ConstantContext( 15012 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 15013 CheckImplicitConversions(E, CheckLoc); 15014 if (!E->isInstantiationDependent()) 15015 CheckUnsequencedOperations(E); 15016 if (!IsConstexpr && !E->isValueDependent()) 15017 CheckForIntOverflow(E); 15018 DiagnoseMisalignedMembers(); 15019 } 15020 15021 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 15022 FieldDecl *BitField, 15023 Expr *Init) { 15024 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 15025 } 15026 15027 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 15028 SourceLocation Loc) { 15029 if (!PType->isVariablyModifiedType()) 15030 return; 15031 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 15032 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 15033 return; 15034 } 15035 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 15036 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 15037 return; 15038 } 15039 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 15040 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 15041 return; 15042 } 15043 15044 const ArrayType *AT = S.Context.getAsArrayType(PType); 15045 if (!AT) 15046 return; 15047 15048 if (AT->getSizeModifier() != ArrayType::Star) { 15049 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 15050 return; 15051 } 15052 15053 S.Diag(Loc, diag::err_array_star_in_function_definition); 15054 } 15055 15056 /// CheckParmsForFunctionDef - Check that the parameters of the given 15057 /// function are appropriate for the definition of a function. This 15058 /// takes care of any checks that cannot be performed on the 15059 /// declaration itself, e.g., that the types of each of the function 15060 /// parameters are complete. 15061 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 15062 bool CheckParameterNames) { 15063 bool HasInvalidParm = false; 15064 for (ParmVarDecl *Param : Parameters) { 15065 // C99 6.7.5.3p4: the parameters in a parameter type list in a 15066 // function declarator that is part of a function definition of 15067 // that function shall not have incomplete type. 15068 // 15069 // This is also C++ [dcl.fct]p6. 15070 if (!Param->isInvalidDecl() && 15071 RequireCompleteType(Param->getLocation(), Param->getType(), 15072 diag::err_typecheck_decl_incomplete_type)) { 15073 Param->setInvalidDecl(); 15074 HasInvalidParm = true; 15075 } 15076 15077 // C99 6.9.1p5: If the declarator includes a parameter type list, the 15078 // declaration of each parameter shall include an identifier. 15079 if (CheckParameterNames && Param->getIdentifier() == nullptr && 15080 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 15081 // Diagnose this as an extension in C17 and earlier. 15082 if (!getLangOpts().C2x) 15083 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15084 } 15085 15086 // C99 6.7.5.3p12: 15087 // If the function declarator is not part of a definition of that 15088 // function, parameters may have incomplete type and may use the [*] 15089 // notation in their sequences of declarator specifiers to specify 15090 // variable length array types. 15091 QualType PType = Param->getOriginalType(); 15092 // FIXME: This diagnostic should point the '[*]' if source-location 15093 // information is added for it. 15094 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 15095 15096 // If the parameter is a c++ class type and it has to be destructed in the 15097 // callee function, declare the destructor so that it can be called by the 15098 // callee function. Do not perform any direct access check on the dtor here. 15099 if (!Param->isInvalidDecl()) { 15100 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 15101 if (!ClassDecl->isInvalidDecl() && 15102 !ClassDecl->hasIrrelevantDestructor() && 15103 !ClassDecl->isDependentContext() && 15104 ClassDecl->isParamDestroyedInCallee()) { 15105 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15106 MarkFunctionReferenced(Param->getLocation(), Destructor); 15107 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 15108 } 15109 } 15110 } 15111 15112 // Parameters with the pass_object_size attribute only need to be marked 15113 // constant at function definitions. Because we lack information about 15114 // whether we're on a declaration or definition when we're instantiating the 15115 // attribute, we need to check for constness here. 15116 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 15117 if (!Param->getType().isConstQualified()) 15118 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 15119 << Attr->getSpelling() << 1; 15120 15121 // Check for parameter names shadowing fields from the class. 15122 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 15123 // The owning context for the parameter should be the function, but we 15124 // want to see if this function's declaration context is a record. 15125 DeclContext *DC = Param->getDeclContext(); 15126 if (DC && DC->isFunctionOrMethod()) { 15127 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 15128 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 15129 RD, /*DeclIsField*/ false); 15130 } 15131 } 15132 } 15133 15134 return HasInvalidParm; 15135 } 15136 15137 Optional<std::pair<CharUnits, CharUnits>> 15138 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 15139 15140 /// Compute the alignment and offset of the base class object given the 15141 /// derived-to-base cast expression and the alignment and offset of the derived 15142 /// class object. 15143 static std::pair<CharUnits, CharUnits> 15144 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 15145 CharUnits BaseAlignment, CharUnits Offset, 15146 ASTContext &Ctx) { 15147 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 15148 ++PathI) { 15149 const CXXBaseSpecifier *Base = *PathI; 15150 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 15151 if (Base->isVirtual()) { 15152 // The complete object may have a lower alignment than the non-virtual 15153 // alignment of the base, in which case the base may be misaligned. Choose 15154 // the smaller of the non-virtual alignment and BaseAlignment, which is a 15155 // conservative lower bound of the complete object alignment. 15156 CharUnits NonVirtualAlignment = 15157 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 15158 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 15159 Offset = CharUnits::Zero(); 15160 } else { 15161 const ASTRecordLayout &RL = 15162 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 15163 Offset += RL.getBaseClassOffset(BaseDecl); 15164 } 15165 DerivedType = Base->getType(); 15166 } 15167 15168 return std::make_pair(BaseAlignment, Offset); 15169 } 15170 15171 /// Compute the alignment and offset of a binary additive operator. 15172 static Optional<std::pair<CharUnits, CharUnits>> 15173 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 15174 bool IsSub, ASTContext &Ctx) { 15175 QualType PointeeType = PtrE->getType()->getPointeeType(); 15176 15177 if (!PointeeType->isConstantSizeType()) 15178 return llvm::None; 15179 15180 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 15181 15182 if (!P) 15183 return llvm::None; 15184 15185 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 15186 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 15187 CharUnits Offset = EltSize * IdxRes->getExtValue(); 15188 if (IsSub) 15189 Offset = -Offset; 15190 return std::make_pair(P->first, P->second + Offset); 15191 } 15192 15193 // If the integer expression isn't a constant expression, compute the lower 15194 // bound of the alignment using the alignment and offset of the pointer 15195 // expression and the element size. 15196 return std::make_pair( 15197 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 15198 CharUnits::Zero()); 15199 } 15200 15201 /// This helper function takes an lvalue expression and returns the alignment of 15202 /// a VarDecl and a constant offset from the VarDecl. 15203 Optional<std::pair<CharUnits, CharUnits>> 15204 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 15205 E = E->IgnoreParens(); 15206 switch (E->getStmtClass()) { 15207 default: 15208 break; 15209 case Stmt::CStyleCastExprClass: 15210 case Stmt::CXXStaticCastExprClass: 15211 case Stmt::ImplicitCastExprClass: { 15212 auto *CE = cast<CastExpr>(E); 15213 const Expr *From = CE->getSubExpr(); 15214 switch (CE->getCastKind()) { 15215 default: 15216 break; 15217 case CK_NoOp: 15218 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15219 case CK_UncheckedDerivedToBase: 15220 case CK_DerivedToBase: { 15221 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15222 if (!P) 15223 break; 15224 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 15225 P->second, Ctx); 15226 } 15227 } 15228 break; 15229 } 15230 case Stmt::ArraySubscriptExprClass: { 15231 auto *ASE = cast<ArraySubscriptExpr>(E); 15232 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 15233 false, Ctx); 15234 } 15235 case Stmt::DeclRefExprClass: { 15236 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 15237 // FIXME: If VD is captured by copy or is an escaping __block variable, 15238 // use the alignment of VD's type. 15239 if (!VD->getType()->isReferenceType()) 15240 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 15241 if (VD->hasInit()) 15242 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 15243 } 15244 break; 15245 } 15246 case Stmt::MemberExprClass: { 15247 auto *ME = cast<MemberExpr>(E); 15248 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 15249 if (!FD || FD->getType()->isReferenceType() || 15250 FD->getParent()->isInvalidDecl()) 15251 break; 15252 Optional<std::pair<CharUnits, CharUnits>> P; 15253 if (ME->isArrow()) 15254 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 15255 else 15256 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 15257 if (!P) 15258 break; 15259 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 15260 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 15261 return std::make_pair(P->first, 15262 P->second + CharUnits::fromQuantity(Offset)); 15263 } 15264 case Stmt::UnaryOperatorClass: { 15265 auto *UO = cast<UnaryOperator>(E); 15266 switch (UO->getOpcode()) { 15267 default: 15268 break; 15269 case UO_Deref: 15270 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 15271 } 15272 break; 15273 } 15274 case Stmt::BinaryOperatorClass: { 15275 auto *BO = cast<BinaryOperator>(E); 15276 auto Opcode = BO->getOpcode(); 15277 switch (Opcode) { 15278 default: 15279 break; 15280 case BO_Comma: 15281 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 15282 } 15283 break; 15284 } 15285 } 15286 return llvm::None; 15287 } 15288 15289 /// This helper function takes a pointer expression and returns the alignment of 15290 /// a VarDecl and a constant offset from the VarDecl. 15291 Optional<std::pair<CharUnits, CharUnits>> 15292 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 15293 E = E->IgnoreParens(); 15294 switch (E->getStmtClass()) { 15295 default: 15296 break; 15297 case Stmt::CStyleCastExprClass: 15298 case Stmt::CXXStaticCastExprClass: 15299 case Stmt::ImplicitCastExprClass: { 15300 auto *CE = cast<CastExpr>(E); 15301 const Expr *From = CE->getSubExpr(); 15302 switch (CE->getCastKind()) { 15303 default: 15304 break; 15305 case CK_NoOp: 15306 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15307 case CK_ArrayToPointerDecay: 15308 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15309 case CK_UncheckedDerivedToBase: 15310 case CK_DerivedToBase: { 15311 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15312 if (!P) 15313 break; 15314 return getDerivedToBaseAlignmentAndOffset( 15315 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 15316 } 15317 } 15318 break; 15319 } 15320 case Stmt::CXXThisExprClass: { 15321 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 15322 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 15323 return std::make_pair(Alignment, CharUnits::Zero()); 15324 } 15325 case Stmt::UnaryOperatorClass: { 15326 auto *UO = cast<UnaryOperator>(E); 15327 if (UO->getOpcode() == UO_AddrOf) 15328 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 15329 break; 15330 } 15331 case Stmt::BinaryOperatorClass: { 15332 auto *BO = cast<BinaryOperator>(E); 15333 auto Opcode = BO->getOpcode(); 15334 switch (Opcode) { 15335 default: 15336 break; 15337 case BO_Add: 15338 case BO_Sub: { 15339 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 15340 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 15341 std::swap(LHS, RHS); 15342 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 15343 Ctx); 15344 } 15345 case BO_Comma: 15346 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 15347 } 15348 break; 15349 } 15350 } 15351 return llvm::None; 15352 } 15353 15354 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 15355 // See if we can compute the alignment of a VarDecl and an offset from it. 15356 Optional<std::pair<CharUnits, CharUnits>> P = 15357 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 15358 15359 if (P) 15360 return P->first.alignmentAtOffset(P->second); 15361 15362 // If that failed, return the type's alignment. 15363 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 15364 } 15365 15366 /// CheckCastAlign - Implements -Wcast-align, which warns when a 15367 /// pointer cast increases the alignment requirements. 15368 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 15369 // This is actually a lot of work to potentially be doing on every 15370 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 15371 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 15372 return; 15373 15374 // Ignore dependent types. 15375 if (T->isDependentType() || Op->getType()->isDependentType()) 15376 return; 15377 15378 // Require that the destination be a pointer type. 15379 const PointerType *DestPtr = T->getAs<PointerType>(); 15380 if (!DestPtr) return; 15381 15382 // If the destination has alignment 1, we're done. 15383 QualType DestPointee = DestPtr->getPointeeType(); 15384 if (DestPointee->isIncompleteType()) return; 15385 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 15386 if (DestAlign.isOne()) return; 15387 15388 // Require that the source be a pointer type. 15389 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 15390 if (!SrcPtr) return; 15391 QualType SrcPointee = SrcPtr->getPointeeType(); 15392 15393 // Explicitly allow casts from cv void*. We already implicitly 15394 // allowed casts to cv void*, since they have alignment 1. 15395 // Also allow casts involving incomplete types, which implicitly 15396 // includes 'void'. 15397 if (SrcPointee->isIncompleteType()) return; 15398 15399 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 15400 15401 if (SrcAlign >= DestAlign) return; 15402 15403 Diag(TRange.getBegin(), diag::warn_cast_align) 15404 << Op->getType() << T 15405 << static_cast<unsigned>(SrcAlign.getQuantity()) 15406 << static_cast<unsigned>(DestAlign.getQuantity()) 15407 << TRange << Op->getSourceRange(); 15408 } 15409 15410 /// Check whether this array fits the idiom of a size-one tail padded 15411 /// array member of a struct. 15412 /// 15413 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 15414 /// commonly used to emulate flexible arrays in C89 code. 15415 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 15416 const NamedDecl *ND) { 15417 if (Size != 1 || !ND) return false; 15418 15419 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 15420 if (!FD) return false; 15421 15422 // Don't consider sizes resulting from macro expansions or template argument 15423 // substitution to form C89 tail-padded arrays. 15424 15425 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15426 while (TInfo) { 15427 TypeLoc TL = TInfo->getTypeLoc(); 15428 // Look through typedefs. 15429 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15430 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15431 TInfo = TDL->getTypeSourceInfo(); 15432 continue; 15433 } 15434 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15435 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15436 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15437 return false; 15438 } 15439 break; 15440 } 15441 15442 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15443 if (!RD) return false; 15444 if (RD->isUnion()) return false; 15445 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15446 if (!CRD->isStandardLayout()) return false; 15447 } 15448 15449 // See if this is the last field decl in the record. 15450 const Decl *D = FD; 15451 while ((D = D->getNextDeclInContext())) 15452 if (isa<FieldDecl>(D)) 15453 return false; 15454 return true; 15455 } 15456 15457 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15458 const ArraySubscriptExpr *ASE, 15459 bool AllowOnePastEnd, bool IndexNegated) { 15460 // Already diagnosed by the constant evaluator. 15461 if (isConstantEvaluated()) 15462 return; 15463 15464 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15465 if (IndexExpr->isValueDependent()) 15466 return; 15467 15468 const Type *EffectiveType = 15469 BaseExpr->getType()->getPointeeOrArrayElementType(); 15470 BaseExpr = BaseExpr->IgnoreParenCasts(); 15471 const ConstantArrayType *ArrayTy = 15472 Context.getAsConstantArrayType(BaseExpr->getType()); 15473 15474 const Type *BaseType = 15475 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15476 bool IsUnboundedArray = (BaseType == nullptr); 15477 if (EffectiveType->isDependentType() || 15478 (!IsUnboundedArray && BaseType->isDependentType())) 15479 return; 15480 15481 Expr::EvalResult Result; 15482 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15483 return; 15484 15485 llvm::APSInt index = Result.Val.getInt(); 15486 if (IndexNegated) { 15487 index.setIsUnsigned(false); 15488 index = -index; 15489 } 15490 15491 const NamedDecl *ND = nullptr; 15492 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15493 ND = DRE->getDecl(); 15494 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15495 ND = ME->getMemberDecl(); 15496 15497 if (IsUnboundedArray) { 15498 if (index.isUnsigned() || !index.isNegative()) { 15499 const auto &ASTC = getASTContext(); 15500 unsigned AddrBits = 15501 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15502 EffectiveType->getCanonicalTypeInternal())); 15503 if (index.getBitWidth() < AddrBits) 15504 index = index.zext(AddrBits); 15505 Optional<CharUnits> ElemCharUnits = 15506 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15507 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15508 // pointer) bounds-checking isn't meaningful. 15509 if (!ElemCharUnits) 15510 return; 15511 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15512 // If index has more active bits than address space, we already know 15513 // we have a bounds violation to warn about. Otherwise, compute 15514 // address of (index + 1)th element, and warn about bounds violation 15515 // only if that address exceeds address space. 15516 if (index.getActiveBits() <= AddrBits) { 15517 bool Overflow; 15518 llvm::APInt Product(index); 15519 Product += 1; 15520 Product = Product.umul_ov(ElemBytes, Overflow); 15521 if (!Overflow && Product.getActiveBits() <= AddrBits) 15522 return; 15523 } 15524 15525 // Need to compute max possible elements in address space, since that 15526 // is included in diag message. 15527 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15528 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15529 MaxElems += 1; 15530 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15531 MaxElems = MaxElems.udiv(ElemBytes); 15532 15533 unsigned DiagID = 15534 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15535 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15536 15537 // Diag message shows element size in bits and in "bytes" (platform- 15538 // dependent CharUnits) 15539 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15540 PDiag(DiagID) 15541 << toString(index, 10, true) << AddrBits 15542 << (unsigned)ASTC.toBits(*ElemCharUnits) 15543 << toString(ElemBytes, 10, false) 15544 << toString(MaxElems, 10, false) 15545 << (unsigned)MaxElems.getLimitedValue(~0U) 15546 << IndexExpr->getSourceRange()); 15547 15548 if (!ND) { 15549 // Try harder to find a NamedDecl to point at in the note. 15550 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15551 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15552 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15553 ND = DRE->getDecl(); 15554 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15555 ND = ME->getMemberDecl(); 15556 } 15557 15558 if (ND) 15559 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15560 PDiag(diag::note_array_declared_here) << ND); 15561 } 15562 return; 15563 } 15564 15565 if (index.isUnsigned() || !index.isNegative()) { 15566 // It is possible that the type of the base expression after 15567 // IgnoreParenCasts is incomplete, even though the type of the base 15568 // expression before IgnoreParenCasts is complete (see PR39746 for an 15569 // example). In this case we have no information about whether the array 15570 // access exceeds the array bounds. However we can still diagnose an array 15571 // access which precedes the array bounds. 15572 if (BaseType->isIncompleteType()) 15573 return; 15574 15575 llvm::APInt size = ArrayTy->getSize(); 15576 if (!size.isStrictlyPositive()) 15577 return; 15578 15579 if (BaseType != EffectiveType) { 15580 // Make sure we're comparing apples to apples when comparing index to size 15581 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15582 uint64_t array_typesize = Context.getTypeSize(BaseType); 15583 // Handle ptrarith_typesize being zero, such as when casting to void* 15584 if (!ptrarith_typesize) ptrarith_typesize = 1; 15585 if (ptrarith_typesize != array_typesize) { 15586 // There's a cast to a different size type involved 15587 uint64_t ratio = array_typesize / ptrarith_typesize; 15588 // TODO: Be smarter about handling cases where array_typesize is not a 15589 // multiple of ptrarith_typesize 15590 if (ptrarith_typesize * ratio == array_typesize) 15591 size *= llvm::APInt(size.getBitWidth(), ratio); 15592 } 15593 } 15594 15595 if (size.getBitWidth() > index.getBitWidth()) 15596 index = index.zext(size.getBitWidth()); 15597 else if (size.getBitWidth() < index.getBitWidth()) 15598 size = size.zext(index.getBitWidth()); 15599 15600 // For array subscripting the index must be less than size, but for pointer 15601 // arithmetic also allow the index (offset) to be equal to size since 15602 // computing the next address after the end of the array is legal and 15603 // commonly done e.g. in C++ iterators and range-based for loops. 15604 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15605 return; 15606 15607 // Also don't warn for arrays of size 1 which are members of some 15608 // structure. These are often used to approximate flexible arrays in C89 15609 // code. 15610 if (IsTailPaddedMemberArray(*this, size, ND)) 15611 return; 15612 15613 // Suppress the warning if the subscript expression (as identified by the 15614 // ']' location) and the index expression are both from macro expansions 15615 // within a system header. 15616 if (ASE) { 15617 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15618 ASE->getRBracketLoc()); 15619 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15620 SourceLocation IndexLoc = 15621 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15622 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15623 return; 15624 } 15625 } 15626 15627 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15628 : diag::warn_ptr_arith_exceeds_bounds; 15629 15630 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15631 PDiag(DiagID) << toString(index, 10, true) 15632 << toString(size, 10, true) 15633 << (unsigned)size.getLimitedValue(~0U) 15634 << IndexExpr->getSourceRange()); 15635 } else { 15636 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15637 if (!ASE) { 15638 DiagID = diag::warn_ptr_arith_precedes_bounds; 15639 if (index.isNegative()) index = -index; 15640 } 15641 15642 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15643 PDiag(DiagID) << toString(index, 10, true) 15644 << IndexExpr->getSourceRange()); 15645 } 15646 15647 if (!ND) { 15648 // Try harder to find a NamedDecl to point at in the note. 15649 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15650 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15651 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15652 ND = DRE->getDecl(); 15653 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15654 ND = ME->getMemberDecl(); 15655 } 15656 15657 if (ND) 15658 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15659 PDiag(diag::note_array_declared_here) << ND); 15660 } 15661 15662 void Sema::CheckArrayAccess(const Expr *expr) { 15663 int AllowOnePastEnd = 0; 15664 while (expr) { 15665 expr = expr->IgnoreParenImpCasts(); 15666 switch (expr->getStmtClass()) { 15667 case Stmt::ArraySubscriptExprClass: { 15668 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15669 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15670 AllowOnePastEnd > 0); 15671 expr = ASE->getBase(); 15672 break; 15673 } 15674 case Stmt::MemberExprClass: { 15675 expr = cast<MemberExpr>(expr)->getBase(); 15676 break; 15677 } 15678 case Stmt::OMPArraySectionExprClass: { 15679 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15680 if (ASE->getLowerBound()) 15681 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15682 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15683 return; 15684 } 15685 case Stmt::UnaryOperatorClass: { 15686 // Only unwrap the * and & unary operators 15687 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15688 expr = UO->getSubExpr(); 15689 switch (UO->getOpcode()) { 15690 case UO_AddrOf: 15691 AllowOnePastEnd++; 15692 break; 15693 case UO_Deref: 15694 AllowOnePastEnd--; 15695 break; 15696 default: 15697 return; 15698 } 15699 break; 15700 } 15701 case Stmt::ConditionalOperatorClass: { 15702 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15703 if (const Expr *lhs = cond->getLHS()) 15704 CheckArrayAccess(lhs); 15705 if (const Expr *rhs = cond->getRHS()) 15706 CheckArrayAccess(rhs); 15707 return; 15708 } 15709 case Stmt::CXXOperatorCallExprClass: { 15710 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15711 for (const auto *Arg : OCE->arguments()) 15712 CheckArrayAccess(Arg); 15713 return; 15714 } 15715 default: 15716 return; 15717 } 15718 } 15719 } 15720 15721 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15722 15723 namespace { 15724 15725 struct RetainCycleOwner { 15726 VarDecl *Variable = nullptr; 15727 SourceRange Range; 15728 SourceLocation Loc; 15729 bool Indirect = false; 15730 15731 RetainCycleOwner() = default; 15732 15733 void setLocsFrom(Expr *e) { 15734 Loc = e->getExprLoc(); 15735 Range = e->getSourceRange(); 15736 } 15737 }; 15738 15739 } // namespace 15740 15741 /// Consider whether capturing the given variable can possibly lead to 15742 /// a retain cycle. 15743 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15744 // In ARC, it's captured strongly iff the variable has __strong 15745 // lifetime. In MRR, it's captured strongly if the variable is 15746 // __block and has an appropriate type. 15747 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15748 return false; 15749 15750 owner.Variable = var; 15751 if (ref) 15752 owner.setLocsFrom(ref); 15753 return true; 15754 } 15755 15756 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15757 while (true) { 15758 e = e->IgnoreParens(); 15759 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15760 switch (cast->getCastKind()) { 15761 case CK_BitCast: 15762 case CK_LValueBitCast: 15763 case CK_LValueToRValue: 15764 case CK_ARCReclaimReturnedObject: 15765 e = cast->getSubExpr(); 15766 continue; 15767 15768 default: 15769 return false; 15770 } 15771 } 15772 15773 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15774 ObjCIvarDecl *ivar = ref->getDecl(); 15775 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15776 return false; 15777 15778 // Try to find a retain cycle in the base. 15779 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15780 return false; 15781 15782 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15783 owner.Indirect = true; 15784 return true; 15785 } 15786 15787 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15788 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15789 if (!var) return false; 15790 return considerVariable(var, ref, owner); 15791 } 15792 15793 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15794 if (member->isArrow()) return false; 15795 15796 // Don't count this as an indirect ownership. 15797 e = member->getBase(); 15798 continue; 15799 } 15800 15801 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15802 // Only pay attention to pseudo-objects on property references. 15803 ObjCPropertyRefExpr *pre 15804 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15805 ->IgnoreParens()); 15806 if (!pre) return false; 15807 if (pre->isImplicitProperty()) return false; 15808 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15809 if (!property->isRetaining() && 15810 !(property->getPropertyIvarDecl() && 15811 property->getPropertyIvarDecl()->getType() 15812 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15813 return false; 15814 15815 owner.Indirect = true; 15816 if (pre->isSuperReceiver()) { 15817 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15818 if (!owner.Variable) 15819 return false; 15820 owner.Loc = pre->getLocation(); 15821 owner.Range = pre->getSourceRange(); 15822 return true; 15823 } 15824 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15825 ->getSourceExpr()); 15826 continue; 15827 } 15828 15829 // Array ivars? 15830 15831 return false; 15832 } 15833 } 15834 15835 namespace { 15836 15837 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15838 ASTContext &Context; 15839 VarDecl *Variable; 15840 Expr *Capturer = nullptr; 15841 bool VarWillBeReased = false; 15842 15843 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15844 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15845 Context(Context), Variable(variable) {} 15846 15847 void VisitDeclRefExpr(DeclRefExpr *ref) { 15848 if (ref->getDecl() == Variable && !Capturer) 15849 Capturer = ref; 15850 } 15851 15852 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15853 if (Capturer) return; 15854 Visit(ref->getBase()); 15855 if (Capturer && ref->isFreeIvar()) 15856 Capturer = ref; 15857 } 15858 15859 void VisitBlockExpr(BlockExpr *block) { 15860 // Look inside nested blocks 15861 if (block->getBlockDecl()->capturesVariable(Variable)) 15862 Visit(block->getBlockDecl()->getBody()); 15863 } 15864 15865 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15866 if (Capturer) return; 15867 if (OVE->getSourceExpr()) 15868 Visit(OVE->getSourceExpr()); 15869 } 15870 15871 void VisitBinaryOperator(BinaryOperator *BinOp) { 15872 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15873 return; 15874 Expr *LHS = BinOp->getLHS(); 15875 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15876 if (DRE->getDecl() != Variable) 15877 return; 15878 if (Expr *RHS = BinOp->getRHS()) { 15879 RHS = RHS->IgnoreParenCasts(); 15880 Optional<llvm::APSInt> Value; 15881 VarWillBeReased = 15882 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15883 *Value == 0); 15884 } 15885 } 15886 } 15887 }; 15888 15889 } // namespace 15890 15891 /// Check whether the given argument is a block which captures a 15892 /// variable. 15893 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15894 assert(owner.Variable && owner.Loc.isValid()); 15895 15896 e = e->IgnoreParenCasts(); 15897 15898 // Look through [^{...} copy] and Block_copy(^{...}). 15899 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15900 Selector Cmd = ME->getSelector(); 15901 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15902 e = ME->getInstanceReceiver(); 15903 if (!e) 15904 return nullptr; 15905 e = e->IgnoreParenCasts(); 15906 } 15907 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15908 if (CE->getNumArgs() == 1) { 15909 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15910 if (Fn) { 15911 const IdentifierInfo *FnI = Fn->getIdentifier(); 15912 if (FnI && FnI->isStr("_Block_copy")) { 15913 e = CE->getArg(0)->IgnoreParenCasts(); 15914 } 15915 } 15916 } 15917 } 15918 15919 BlockExpr *block = dyn_cast<BlockExpr>(e); 15920 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15921 return nullptr; 15922 15923 FindCaptureVisitor visitor(S.Context, owner.Variable); 15924 visitor.Visit(block->getBlockDecl()->getBody()); 15925 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15926 } 15927 15928 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15929 RetainCycleOwner &owner) { 15930 assert(capturer); 15931 assert(owner.Variable && owner.Loc.isValid()); 15932 15933 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15934 << owner.Variable << capturer->getSourceRange(); 15935 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15936 << owner.Indirect << owner.Range; 15937 } 15938 15939 /// Check for a keyword selector that starts with the word 'add' or 15940 /// 'set'. 15941 static bool isSetterLikeSelector(Selector sel) { 15942 if (sel.isUnarySelector()) return false; 15943 15944 StringRef str = sel.getNameForSlot(0); 15945 while (!str.empty() && str.front() == '_') str = str.substr(1); 15946 if (str.startswith("set")) 15947 str = str.substr(3); 15948 else if (str.startswith("add")) { 15949 // Specially allow 'addOperationWithBlock:'. 15950 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15951 return false; 15952 str = str.substr(3); 15953 } 15954 else 15955 return false; 15956 15957 if (str.empty()) return true; 15958 return !isLowercase(str.front()); 15959 } 15960 15961 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15962 ObjCMessageExpr *Message) { 15963 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15964 Message->getReceiverInterface(), 15965 NSAPI::ClassId_NSMutableArray); 15966 if (!IsMutableArray) { 15967 return None; 15968 } 15969 15970 Selector Sel = Message->getSelector(); 15971 15972 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15973 S.NSAPIObj->getNSArrayMethodKind(Sel); 15974 if (!MKOpt) { 15975 return None; 15976 } 15977 15978 NSAPI::NSArrayMethodKind MK = *MKOpt; 15979 15980 switch (MK) { 15981 case NSAPI::NSMutableArr_addObject: 15982 case NSAPI::NSMutableArr_insertObjectAtIndex: 15983 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15984 return 0; 15985 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15986 return 1; 15987 15988 default: 15989 return None; 15990 } 15991 15992 return None; 15993 } 15994 15995 static 15996 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15997 ObjCMessageExpr *Message) { 15998 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15999 Message->getReceiverInterface(), 16000 NSAPI::ClassId_NSMutableDictionary); 16001 if (!IsMutableDictionary) { 16002 return None; 16003 } 16004 16005 Selector Sel = Message->getSelector(); 16006 16007 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 16008 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 16009 if (!MKOpt) { 16010 return None; 16011 } 16012 16013 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 16014 16015 switch (MK) { 16016 case NSAPI::NSMutableDict_setObjectForKey: 16017 case NSAPI::NSMutableDict_setValueForKey: 16018 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 16019 return 0; 16020 16021 default: 16022 return None; 16023 } 16024 16025 return None; 16026 } 16027 16028 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 16029 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 16030 Message->getReceiverInterface(), 16031 NSAPI::ClassId_NSMutableSet); 16032 16033 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 16034 Message->getReceiverInterface(), 16035 NSAPI::ClassId_NSMutableOrderedSet); 16036 if (!IsMutableSet && !IsMutableOrderedSet) { 16037 return None; 16038 } 16039 16040 Selector Sel = Message->getSelector(); 16041 16042 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 16043 if (!MKOpt) { 16044 return None; 16045 } 16046 16047 NSAPI::NSSetMethodKind MK = *MKOpt; 16048 16049 switch (MK) { 16050 case NSAPI::NSMutableSet_addObject: 16051 case NSAPI::NSOrderedSet_setObjectAtIndex: 16052 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 16053 case NSAPI::NSOrderedSet_insertObjectAtIndex: 16054 return 0; 16055 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 16056 return 1; 16057 } 16058 16059 return None; 16060 } 16061 16062 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 16063 if (!Message->isInstanceMessage()) { 16064 return; 16065 } 16066 16067 Optional<int> ArgOpt; 16068 16069 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 16070 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 16071 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 16072 return; 16073 } 16074 16075 int ArgIndex = *ArgOpt; 16076 16077 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 16078 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 16079 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 16080 } 16081 16082 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 16083 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 16084 if (ArgRE->isObjCSelfExpr()) { 16085 Diag(Message->getSourceRange().getBegin(), 16086 diag::warn_objc_circular_container) 16087 << ArgRE->getDecl() << StringRef("'super'"); 16088 } 16089 } 16090 } else { 16091 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 16092 16093 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 16094 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 16095 } 16096 16097 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 16098 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 16099 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 16100 ValueDecl *Decl = ReceiverRE->getDecl(); 16101 Diag(Message->getSourceRange().getBegin(), 16102 diag::warn_objc_circular_container) 16103 << Decl << Decl; 16104 if (!ArgRE->isObjCSelfExpr()) { 16105 Diag(Decl->getLocation(), 16106 diag::note_objc_circular_container_declared_here) 16107 << Decl; 16108 } 16109 } 16110 } 16111 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 16112 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 16113 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 16114 ObjCIvarDecl *Decl = IvarRE->getDecl(); 16115 Diag(Message->getSourceRange().getBegin(), 16116 diag::warn_objc_circular_container) 16117 << Decl << Decl; 16118 Diag(Decl->getLocation(), 16119 diag::note_objc_circular_container_declared_here) 16120 << Decl; 16121 } 16122 } 16123 } 16124 } 16125 } 16126 16127 /// Check a message send to see if it's likely to cause a retain cycle. 16128 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 16129 // Only check instance methods whose selector looks like a setter. 16130 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 16131 return; 16132 16133 // Try to find a variable that the receiver is strongly owned by. 16134 RetainCycleOwner owner; 16135 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 16136 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 16137 return; 16138 } else { 16139 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 16140 owner.Variable = getCurMethodDecl()->getSelfDecl(); 16141 owner.Loc = msg->getSuperLoc(); 16142 owner.Range = msg->getSuperLoc(); 16143 } 16144 16145 // Check whether the receiver is captured by any of the arguments. 16146 const ObjCMethodDecl *MD = msg->getMethodDecl(); 16147 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 16148 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 16149 // noescape blocks should not be retained by the method. 16150 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 16151 continue; 16152 return diagnoseRetainCycle(*this, capturer, owner); 16153 } 16154 } 16155 } 16156 16157 /// Check a property assign to see if it's likely to cause a retain cycle. 16158 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 16159 RetainCycleOwner owner; 16160 if (!findRetainCycleOwner(*this, receiver, owner)) 16161 return; 16162 16163 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 16164 diagnoseRetainCycle(*this, capturer, owner); 16165 } 16166 16167 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 16168 RetainCycleOwner Owner; 16169 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 16170 return; 16171 16172 // Because we don't have an expression for the variable, we have to set the 16173 // location explicitly here. 16174 Owner.Loc = Var->getLocation(); 16175 Owner.Range = Var->getSourceRange(); 16176 16177 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 16178 diagnoseRetainCycle(*this, Capturer, Owner); 16179 } 16180 16181 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 16182 Expr *RHS, bool isProperty) { 16183 // Check if RHS is an Objective-C object literal, which also can get 16184 // immediately zapped in a weak reference. Note that we explicitly 16185 // allow ObjCStringLiterals, since those are designed to never really die. 16186 RHS = RHS->IgnoreParenImpCasts(); 16187 16188 // This enum needs to match with the 'select' in 16189 // warn_objc_arc_literal_assign (off-by-1). 16190 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 16191 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 16192 return false; 16193 16194 S.Diag(Loc, diag::warn_arc_literal_assign) 16195 << (unsigned) Kind 16196 << (isProperty ? 0 : 1) 16197 << RHS->getSourceRange(); 16198 16199 return true; 16200 } 16201 16202 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 16203 Qualifiers::ObjCLifetime LT, 16204 Expr *RHS, bool isProperty) { 16205 // Strip off any implicit cast added to get to the one ARC-specific. 16206 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16207 if (cast->getCastKind() == CK_ARCConsumeObject) { 16208 S.Diag(Loc, diag::warn_arc_retained_assign) 16209 << (LT == Qualifiers::OCL_ExplicitNone) 16210 << (isProperty ? 0 : 1) 16211 << RHS->getSourceRange(); 16212 return true; 16213 } 16214 RHS = cast->getSubExpr(); 16215 } 16216 16217 if (LT == Qualifiers::OCL_Weak && 16218 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 16219 return true; 16220 16221 return false; 16222 } 16223 16224 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 16225 QualType LHS, Expr *RHS) { 16226 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 16227 16228 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 16229 return false; 16230 16231 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 16232 return true; 16233 16234 return false; 16235 } 16236 16237 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 16238 Expr *LHS, Expr *RHS) { 16239 QualType LHSType; 16240 // PropertyRef on LHS type need be directly obtained from 16241 // its declaration as it has a PseudoType. 16242 ObjCPropertyRefExpr *PRE 16243 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 16244 if (PRE && !PRE->isImplicitProperty()) { 16245 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16246 if (PD) 16247 LHSType = PD->getType(); 16248 } 16249 16250 if (LHSType.isNull()) 16251 LHSType = LHS->getType(); 16252 16253 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 16254 16255 if (LT == Qualifiers::OCL_Weak) { 16256 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 16257 getCurFunction()->markSafeWeakUse(LHS); 16258 } 16259 16260 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 16261 return; 16262 16263 // FIXME. Check for other life times. 16264 if (LT != Qualifiers::OCL_None) 16265 return; 16266 16267 if (PRE) { 16268 if (PRE->isImplicitProperty()) 16269 return; 16270 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16271 if (!PD) 16272 return; 16273 16274 unsigned Attributes = PD->getPropertyAttributes(); 16275 if (Attributes & ObjCPropertyAttribute::kind_assign) { 16276 // when 'assign' attribute was not explicitly specified 16277 // by user, ignore it and rely on property type itself 16278 // for lifetime info. 16279 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 16280 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 16281 LHSType->isObjCRetainableType()) 16282 return; 16283 16284 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16285 if (cast->getCastKind() == CK_ARCConsumeObject) { 16286 Diag(Loc, diag::warn_arc_retained_property_assign) 16287 << RHS->getSourceRange(); 16288 return; 16289 } 16290 RHS = cast->getSubExpr(); 16291 } 16292 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 16293 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 16294 return; 16295 } 16296 } 16297 } 16298 16299 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 16300 16301 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 16302 SourceLocation StmtLoc, 16303 const NullStmt *Body) { 16304 // Do not warn if the body is a macro that expands to nothing, e.g: 16305 // 16306 // #define CALL(x) 16307 // if (condition) 16308 // CALL(0); 16309 if (Body->hasLeadingEmptyMacro()) 16310 return false; 16311 16312 // Get line numbers of statement and body. 16313 bool StmtLineInvalid; 16314 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 16315 &StmtLineInvalid); 16316 if (StmtLineInvalid) 16317 return false; 16318 16319 bool BodyLineInvalid; 16320 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 16321 &BodyLineInvalid); 16322 if (BodyLineInvalid) 16323 return false; 16324 16325 // Warn if null statement and body are on the same line. 16326 if (StmtLine != BodyLine) 16327 return false; 16328 16329 return true; 16330 } 16331 16332 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 16333 const Stmt *Body, 16334 unsigned DiagID) { 16335 // Since this is a syntactic check, don't emit diagnostic for template 16336 // instantiations, this just adds noise. 16337 if (CurrentInstantiationScope) 16338 return; 16339 16340 // The body should be a null statement. 16341 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16342 if (!NBody) 16343 return; 16344 16345 // Do the usual checks. 16346 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16347 return; 16348 16349 Diag(NBody->getSemiLoc(), DiagID); 16350 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16351 } 16352 16353 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 16354 const Stmt *PossibleBody) { 16355 assert(!CurrentInstantiationScope); // Ensured by caller 16356 16357 SourceLocation StmtLoc; 16358 const Stmt *Body; 16359 unsigned DiagID; 16360 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 16361 StmtLoc = FS->getRParenLoc(); 16362 Body = FS->getBody(); 16363 DiagID = diag::warn_empty_for_body; 16364 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 16365 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 16366 Body = WS->getBody(); 16367 DiagID = diag::warn_empty_while_body; 16368 } else 16369 return; // Neither `for' nor `while'. 16370 16371 // The body should be a null statement. 16372 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16373 if (!NBody) 16374 return; 16375 16376 // Skip expensive checks if diagnostic is disabled. 16377 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 16378 return; 16379 16380 // Do the usual checks. 16381 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16382 return; 16383 16384 // `for(...);' and `while(...);' are popular idioms, so in order to keep 16385 // noise level low, emit diagnostics only if for/while is followed by a 16386 // CompoundStmt, e.g.: 16387 // for (int i = 0; i < n; i++); 16388 // { 16389 // a(i); 16390 // } 16391 // or if for/while is followed by a statement with more indentation 16392 // than for/while itself: 16393 // for (int i = 0; i < n; i++); 16394 // a(i); 16395 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 16396 if (!ProbableTypo) { 16397 bool BodyColInvalid; 16398 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 16399 PossibleBody->getBeginLoc(), &BodyColInvalid); 16400 if (BodyColInvalid) 16401 return; 16402 16403 bool StmtColInvalid; 16404 unsigned StmtCol = 16405 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 16406 if (StmtColInvalid) 16407 return; 16408 16409 if (BodyCol > StmtCol) 16410 ProbableTypo = true; 16411 } 16412 16413 if (ProbableTypo) { 16414 Diag(NBody->getSemiLoc(), DiagID); 16415 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16416 } 16417 } 16418 16419 //===--- CHECK: Warn on self move with std::move. -------------------------===// 16420 16421 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 16422 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 16423 SourceLocation OpLoc) { 16424 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 16425 return; 16426 16427 if (inTemplateInstantiation()) 16428 return; 16429 16430 // Strip parens and casts away. 16431 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16432 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16433 16434 // Check for a call expression 16435 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16436 if (!CE || CE->getNumArgs() != 1) 16437 return; 16438 16439 // Check for a call to std::move 16440 if (!CE->isCallToStdMove()) 16441 return; 16442 16443 // Get argument from std::move 16444 RHSExpr = CE->getArg(0); 16445 16446 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16447 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16448 16449 // Two DeclRefExpr's, check that the decls are the same. 16450 if (LHSDeclRef && RHSDeclRef) { 16451 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16452 return; 16453 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16454 RHSDeclRef->getDecl()->getCanonicalDecl()) 16455 return; 16456 16457 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16458 << LHSExpr->getSourceRange() 16459 << RHSExpr->getSourceRange(); 16460 return; 16461 } 16462 16463 // Member variables require a different approach to check for self moves. 16464 // MemberExpr's are the same if every nested MemberExpr refers to the same 16465 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16466 // the base Expr's are CXXThisExpr's. 16467 const Expr *LHSBase = LHSExpr; 16468 const Expr *RHSBase = RHSExpr; 16469 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16470 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16471 if (!LHSME || !RHSME) 16472 return; 16473 16474 while (LHSME && RHSME) { 16475 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16476 RHSME->getMemberDecl()->getCanonicalDecl()) 16477 return; 16478 16479 LHSBase = LHSME->getBase(); 16480 RHSBase = RHSME->getBase(); 16481 LHSME = dyn_cast<MemberExpr>(LHSBase); 16482 RHSME = dyn_cast<MemberExpr>(RHSBase); 16483 } 16484 16485 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16486 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16487 if (LHSDeclRef && RHSDeclRef) { 16488 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16489 return; 16490 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16491 RHSDeclRef->getDecl()->getCanonicalDecl()) 16492 return; 16493 16494 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16495 << LHSExpr->getSourceRange() 16496 << RHSExpr->getSourceRange(); 16497 return; 16498 } 16499 16500 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16501 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16502 << LHSExpr->getSourceRange() 16503 << RHSExpr->getSourceRange(); 16504 } 16505 16506 //===--- Layout compatibility ----------------------------------------------// 16507 16508 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16509 16510 /// Check if two enumeration types are layout-compatible. 16511 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16512 // C++11 [dcl.enum] p8: 16513 // Two enumeration types are layout-compatible if they have the same 16514 // underlying type. 16515 return ED1->isComplete() && ED2->isComplete() && 16516 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16517 } 16518 16519 /// Check if two fields are layout-compatible. 16520 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16521 FieldDecl *Field2) { 16522 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16523 return false; 16524 16525 if (Field1->isBitField() != Field2->isBitField()) 16526 return false; 16527 16528 if (Field1->isBitField()) { 16529 // Make sure that the bit-fields are the same length. 16530 unsigned Bits1 = Field1->getBitWidthValue(C); 16531 unsigned Bits2 = Field2->getBitWidthValue(C); 16532 16533 if (Bits1 != Bits2) 16534 return false; 16535 } 16536 16537 return true; 16538 } 16539 16540 /// Check if two standard-layout structs are layout-compatible. 16541 /// (C++11 [class.mem] p17) 16542 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16543 RecordDecl *RD2) { 16544 // If both records are C++ classes, check that base classes match. 16545 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16546 // If one of records is a CXXRecordDecl we are in C++ mode, 16547 // thus the other one is a CXXRecordDecl, too. 16548 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16549 // Check number of base classes. 16550 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16551 return false; 16552 16553 // Check the base classes. 16554 for (CXXRecordDecl::base_class_const_iterator 16555 Base1 = D1CXX->bases_begin(), 16556 BaseEnd1 = D1CXX->bases_end(), 16557 Base2 = D2CXX->bases_begin(); 16558 Base1 != BaseEnd1; 16559 ++Base1, ++Base2) { 16560 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16561 return false; 16562 } 16563 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16564 // If only RD2 is a C++ class, it should have zero base classes. 16565 if (D2CXX->getNumBases() > 0) 16566 return false; 16567 } 16568 16569 // Check the fields. 16570 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16571 Field2End = RD2->field_end(), 16572 Field1 = RD1->field_begin(), 16573 Field1End = RD1->field_end(); 16574 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16575 if (!isLayoutCompatible(C, *Field1, *Field2)) 16576 return false; 16577 } 16578 if (Field1 != Field1End || Field2 != Field2End) 16579 return false; 16580 16581 return true; 16582 } 16583 16584 /// Check if two standard-layout unions are layout-compatible. 16585 /// (C++11 [class.mem] p18) 16586 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16587 RecordDecl *RD2) { 16588 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16589 for (auto *Field2 : RD2->fields()) 16590 UnmatchedFields.insert(Field2); 16591 16592 for (auto *Field1 : RD1->fields()) { 16593 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16594 I = UnmatchedFields.begin(), 16595 E = UnmatchedFields.end(); 16596 16597 for ( ; I != E; ++I) { 16598 if (isLayoutCompatible(C, Field1, *I)) { 16599 bool Result = UnmatchedFields.erase(*I); 16600 (void) Result; 16601 assert(Result); 16602 break; 16603 } 16604 } 16605 if (I == E) 16606 return false; 16607 } 16608 16609 return UnmatchedFields.empty(); 16610 } 16611 16612 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16613 RecordDecl *RD2) { 16614 if (RD1->isUnion() != RD2->isUnion()) 16615 return false; 16616 16617 if (RD1->isUnion()) 16618 return isLayoutCompatibleUnion(C, RD1, RD2); 16619 else 16620 return isLayoutCompatibleStruct(C, RD1, RD2); 16621 } 16622 16623 /// Check if two types are layout-compatible in C++11 sense. 16624 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16625 if (T1.isNull() || T2.isNull()) 16626 return false; 16627 16628 // C++11 [basic.types] p11: 16629 // If two types T1 and T2 are the same type, then T1 and T2 are 16630 // layout-compatible types. 16631 if (C.hasSameType(T1, T2)) 16632 return true; 16633 16634 T1 = T1.getCanonicalType().getUnqualifiedType(); 16635 T2 = T2.getCanonicalType().getUnqualifiedType(); 16636 16637 const Type::TypeClass TC1 = T1->getTypeClass(); 16638 const Type::TypeClass TC2 = T2->getTypeClass(); 16639 16640 if (TC1 != TC2) 16641 return false; 16642 16643 if (TC1 == Type::Enum) { 16644 return isLayoutCompatible(C, 16645 cast<EnumType>(T1)->getDecl(), 16646 cast<EnumType>(T2)->getDecl()); 16647 } else if (TC1 == Type::Record) { 16648 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16649 return false; 16650 16651 return isLayoutCompatible(C, 16652 cast<RecordType>(T1)->getDecl(), 16653 cast<RecordType>(T2)->getDecl()); 16654 } 16655 16656 return false; 16657 } 16658 16659 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16660 16661 /// Given a type tag expression find the type tag itself. 16662 /// 16663 /// \param TypeExpr Type tag expression, as it appears in user's code. 16664 /// 16665 /// \param VD Declaration of an identifier that appears in a type tag. 16666 /// 16667 /// \param MagicValue Type tag magic value. 16668 /// 16669 /// \param isConstantEvaluated whether the evalaution should be performed in 16670 16671 /// constant context. 16672 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16673 const ValueDecl **VD, uint64_t *MagicValue, 16674 bool isConstantEvaluated) { 16675 while(true) { 16676 if (!TypeExpr) 16677 return false; 16678 16679 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16680 16681 switch (TypeExpr->getStmtClass()) { 16682 case Stmt::UnaryOperatorClass: { 16683 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16684 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16685 TypeExpr = UO->getSubExpr(); 16686 continue; 16687 } 16688 return false; 16689 } 16690 16691 case Stmt::DeclRefExprClass: { 16692 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16693 *VD = DRE->getDecl(); 16694 return true; 16695 } 16696 16697 case Stmt::IntegerLiteralClass: { 16698 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16699 llvm::APInt MagicValueAPInt = IL->getValue(); 16700 if (MagicValueAPInt.getActiveBits() <= 64) { 16701 *MagicValue = MagicValueAPInt.getZExtValue(); 16702 return true; 16703 } else 16704 return false; 16705 } 16706 16707 case Stmt::BinaryConditionalOperatorClass: 16708 case Stmt::ConditionalOperatorClass: { 16709 const AbstractConditionalOperator *ACO = 16710 cast<AbstractConditionalOperator>(TypeExpr); 16711 bool Result; 16712 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16713 isConstantEvaluated)) { 16714 if (Result) 16715 TypeExpr = ACO->getTrueExpr(); 16716 else 16717 TypeExpr = ACO->getFalseExpr(); 16718 continue; 16719 } 16720 return false; 16721 } 16722 16723 case Stmt::BinaryOperatorClass: { 16724 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16725 if (BO->getOpcode() == BO_Comma) { 16726 TypeExpr = BO->getRHS(); 16727 continue; 16728 } 16729 return false; 16730 } 16731 16732 default: 16733 return false; 16734 } 16735 } 16736 } 16737 16738 /// Retrieve the C type corresponding to type tag TypeExpr. 16739 /// 16740 /// \param TypeExpr Expression that specifies a type tag. 16741 /// 16742 /// \param MagicValues Registered magic values. 16743 /// 16744 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16745 /// kind. 16746 /// 16747 /// \param TypeInfo Information about the corresponding C type. 16748 /// 16749 /// \param isConstantEvaluated whether the evalaution should be performed in 16750 /// constant context. 16751 /// 16752 /// \returns true if the corresponding C type was found. 16753 static bool GetMatchingCType( 16754 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16755 const ASTContext &Ctx, 16756 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16757 *MagicValues, 16758 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16759 bool isConstantEvaluated) { 16760 FoundWrongKind = false; 16761 16762 // Variable declaration that has type_tag_for_datatype attribute. 16763 const ValueDecl *VD = nullptr; 16764 16765 uint64_t MagicValue; 16766 16767 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16768 return false; 16769 16770 if (VD) { 16771 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16772 if (I->getArgumentKind() != ArgumentKind) { 16773 FoundWrongKind = true; 16774 return false; 16775 } 16776 TypeInfo.Type = I->getMatchingCType(); 16777 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16778 TypeInfo.MustBeNull = I->getMustBeNull(); 16779 return true; 16780 } 16781 return false; 16782 } 16783 16784 if (!MagicValues) 16785 return false; 16786 16787 llvm::DenseMap<Sema::TypeTagMagicValue, 16788 Sema::TypeTagData>::const_iterator I = 16789 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16790 if (I == MagicValues->end()) 16791 return false; 16792 16793 TypeInfo = I->second; 16794 return true; 16795 } 16796 16797 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16798 uint64_t MagicValue, QualType Type, 16799 bool LayoutCompatible, 16800 bool MustBeNull) { 16801 if (!TypeTagForDatatypeMagicValues) 16802 TypeTagForDatatypeMagicValues.reset( 16803 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16804 16805 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16806 (*TypeTagForDatatypeMagicValues)[Magic] = 16807 TypeTagData(Type, LayoutCompatible, MustBeNull); 16808 } 16809 16810 static bool IsSameCharType(QualType T1, QualType T2) { 16811 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16812 if (!BT1) 16813 return false; 16814 16815 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16816 if (!BT2) 16817 return false; 16818 16819 BuiltinType::Kind T1Kind = BT1->getKind(); 16820 BuiltinType::Kind T2Kind = BT2->getKind(); 16821 16822 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16823 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16824 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16825 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16826 } 16827 16828 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16829 const ArrayRef<const Expr *> ExprArgs, 16830 SourceLocation CallSiteLoc) { 16831 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16832 bool IsPointerAttr = Attr->getIsPointer(); 16833 16834 // Retrieve the argument representing the 'type_tag'. 16835 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16836 if (TypeTagIdxAST >= ExprArgs.size()) { 16837 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16838 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16839 return; 16840 } 16841 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16842 bool FoundWrongKind; 16843 TypeTagData TypeInfo; 16844 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16845 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16846 TypeInfo, isConstantEvaluated())) { 16847 if (FoundWrongKind) 16848 Diag(TypeTagExpr->getExprLoc(), 16849 diag::warn_type_tag_for_datatype_wrong_kind) 16850 << TypeTagExpr->getSourceRange(); 16851 return; 16852 } 16853 16854 // Retrieve the argument representing the 'arg_idx'. 16855 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16856 if (ArgumentIdxAST >= ExprArgs.size()) { 16857 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16858 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16859 return; 16860 } 16861 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16862 if (IsPointerAttr) { 16863 // Skip implicit cast of pointer to `void *' (as a function argument). 16864 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16865 if (ICE->getType()->isVoidPointerType() && 16866 ICE->getCastKind() == CK_BitCast) 16867 ArgumentExpr = ICE->getSubExpr(); 16868 } 16869 QualType ArgumentType = ArgumentExpr->getType(); 16870 16871 // Passing a `void*' pointer shouldn't trigger a warning. 16872 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16873 return; 16874 16875 if (TypeInfo.MustBeNull) { 16876 // Type tag with matching void type requires a null pointer. 16877 if (!ArgumentExpr->isNullPointerConstant(Context, 16878 Expr::NPC_ValueDependentIsNotNull)) { 16879 Diag(ArgumentExpr->getExprLoc(), 16880 diag::warn_type_safety_null_pointer_required) 16881 << ArgumentKind->getName() 16882 << ArgumentExpr->getSourceRange() 16883 << TypeTagExpr->getSourceRange(); 16884 } 16885 return; 16886 } 16887 16888 QualType RequiredType = TypeInfo.Type; 16889 if (IsPointerAttr) 16890 RequiredType = Context.getPointerType(RequiredType); 16891 16892 bool mismatch = false; 16893 if (!TypeInfo.LayoutCompatible) { 16894 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16895 16896 // C++11 [basic.fundamental] p1: 16897 // Plain char, signed char, and unsigned char are three distinct types. 16898 // 16899 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16900 // char' depending on the current char signedness mode. 16901 if (mismatch) 16902 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16903 RequiredType->getPointeeType())) || 16904 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16905 mismatch = false; 16906 } else 16907 if (IsPointerAttr) 16908 mismatch = !isLayoutCompatible(Context, 16909 ArgumentType->getPointeeType(), 16910 RequiredType->getPointeeType()); 16911 else 16912 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16913 16914 if (mismatch) 16915 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16916 << ArgumentType << ArgumentKind 16917 << TypeInfo.LayoutCompatible << RequiredType 16918 << ArgumentExpr->getSourceRange() 16919 << TypeTagExpr->getSourceRange(); 16920 } 16921 16922 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16923 CharUnits Alignment) { 16924 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16925 } 16926 16927 void Sema::DiagnoseMisalignedMembers() { 16928 for (MisalignedMember &m : MisalignedMembers) { 16929 const NamedDecl *ND = m.RD; 16930 if (ND->getName().empty()) { 16931 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16932 ND = TD; 16933 } 16934 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16935 << m.MD << ND << m.E->getSourceRange(); 16936 } 16937 MisalignedMembers.clear(); 16938 } 16939 16940 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16941 E = E->IgnoreParens(); 16942 if (!T->isPointerType() && !T->isIntegerType()) 16943 return; 16944 if (isa<UnaryOperator>(E) && 16945 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16946 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16947 if (isa<MemberExpr>(Op)) { 16948 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16949 if (MA != MisalignedMembers.end() && 16950 (T->isIntegerType() || 16951 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16952 Context.getTypeAlignInChars( 16953 T->getPointeeType()) <= MA->Alignment)))) 16954 MisalignedMembers.erase(MA); 16955 } 16956 } 16957 } 16958 16959 void Sema::RefersToMemberWithReducedAlignment( 16960 Expr *E, 16961 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16962 Action) { 16963 const auto *ME = dyn_cast<MemberExpr>(E); 16964 if (!ME) 16965 return; 16966 16967 // No need to check expressions with an __unaligned-qualified type. 16968 if (E->getType().getQualifiers().hasUnaligned()) 16969 return; 16970 16971 // For a chain of MemberExpr like "a.b.c.d" this list 16972 // will keep FieldDecl's like [d, c, b]. 16973 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16974 const MemberExpr *TopME = nullptr; 16975 bool AnyIsPacked = false; 16976 do { 16977 QualType BaseType = ME->getBase()->getType(); 16978 if (BaseType->isDependentType()) 16979 return; 16980 if (ME->isArrow()) 16981 BaseType = BaseType->getPointeeType(); 16982 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16983 if (RD->isInvalidDecl()) 16984 return; 16985 16986 ValueDecl *MD = ME->getMemberDecl(); 16987 auto *FD = dyn_cast<FieldDecl>(MD); 16988 // We do not care about non-data members. 16989 if (!FD || FD->isInvalidDecl()) 16990 return; 16991 16992 AnyIsPacked = 16993 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16994 ReverseMemberChain.push_back(FD); 16995 16996 TopME = ME; 16997 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16998 } while (ME); 16999 assert(TopME && "We did not compute a topmost MemberExpr!"); 17000 17001 // Not the scope of this diagnostic. 17002 if (!AnyIsPacked) 17003 return; 17004 17005 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 17006 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 17007 // TODO: The innermost base of the member expression may be too complicated. 17008 // For now, just disregard these cases. This is left for future 17009 // improvement. 17010 if (!DRE && !isa<CXXThisExpr>(TopBase)) 17011 return; 17012 17013 // Alignment expected by the whole expression. 17014 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 17015 17016 // No need to do anything else with this case. 17017 if (ExpectedAlignment.isOne()) 17018 return; 17019 17020 // Synthesize offset of the whole access. 17021 CharUnits Offset; 17022 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain)) 17023 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD)); 17024 17025 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 17026 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 17027 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 17028 17029 // The base expression of the innermost MemberExpr may give 17030 // stronger guarantees than the class containing the member. 17031 if (DRE && !TopME->isArrow()) { 17032 const ValueDecl *VD = DRE->getDecl(); 17033 if (!VD->getType()->isReferenceType()) 17034 CompleteObjectAlignment = 17035 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 17036 } 17037 17038 // Check if the synthesized offset fulfills the alignment. 17039 if (Offset % ExpectedAlignment != 0 || 17040 // It may fulfill the offset it but the effective alignment may still be 17041 // lower than the expected expression alignment. 17042 CompleteObjectAlignment < ExpectedAlignment) { 17043 // If this happens, we want to determine a sensible culprit of this. 17044 // Intuitively, watching the chain of member expressions from right to 17045 // left, we start with the required alignment (as required by the field 17046 // type) but some packed attribute in that chain has reduced the alignment. 17047 // It may happen that another packed structure increases it again. But if 17048 // we are here such increase has not been enough. So pointing the first 17049 // FieldDecl that either is packed or else its RecordDecl is, 17050 // seems reasonable. 17051 FieldDecl *FD = nullptr; 17052 CharUnits Alignment; 17053 for (FieldDecl *FDI : ReverseMemberChain) { 17054 if (FDI->hasAttr<PackedAttr>() || 17055 FDI->getParent()->hasAttr<PackedAttr>()) { 17056 FD = FDI; 17057 Alignment = std::min( 17058 Context.getTypeAlignInChars(FD->getType()), 17059 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 17060 break; 17061 } 17062 } 17063 assert(FD && "We did not find a packed FieldDecl!"); 17064 Action(E, FD->getParent(), FD, Alignment); 17065 } 17066 } 17067 17068 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 17069 using namespace std::placeholders; 17070 17071 RefersToMemberWithReducedAlignment( 17072 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 17073 _2, _3, _4)); 17074 } 17075 17076 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 17077 // not a valid type, emit an error message and return true. Otherwise return 17078 // false. 17079 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 17080 QualType Ty) { 17081 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 17082 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 17083 << 1 << /* vector, integer or float ty*/ 0 << Ty; 17084 return true; 17085 } 17086 return false; 17087 } 17088 17089 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) { 17090 if (checkArgCount(*this, TheCall, 1)) 17091 return true; 17092 17093 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 17094 if (A.isInvalid()) 17095 return true; 17096 17097 TheCall->setArg(0, A.get()); 17098 QualType TyA = A.get()->getType(); 17099 17100 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 17101 return true; 17102 17103 TheCall->setType(TyA); 17104 return false; 17105 } 17106 17107 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 17108 if (checkArgCount(*this, TheCall, 2)) 17109 return true; 17110 17111 ExprResult A = TheCall->getArg(0); 17112 ExprResult B = TheCall->getArg(1); 17113 // Do standard promotions between the two arguments, returning their common 17114 // type. 17115 QualType Res = 17116 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 17117 if (A.isInvalid() || B.isInvalid()) 17118 return true; 17119 17120 QualType TyA = A.get()->getType(); 17121 QualType TyB = B.get()->getType(); 17122 17123 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 17124 return Diag(A.get()->getBeginLoc(), 17125 diag::err_typecheck_call_different_arg_types) 17126 << TyA << TyB; 17127 17128 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 17129 return true; 17130 17131 TheCall->setArg(0, A.get()); 17132 TheCall->setArg(1, B.get()); 17133 TheCall->setType(Res); 17134 return false; 17135 } 17136 17137 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) { 17138 if (checkArgCount(*this, TheCall, 1)) 17139 return true; 17140 17141 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 17142 if (A.isInvalid()) 17143 return true; 17144 17145 TheCall->setArg(0, A.get()); 17146 return false; 17147 } 17148 17149 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 17150 ExprResult CallResult) { 17151 if (checkArgCount(*this, TheCall, 1)) 17152 return ExprError(); 17153 17154 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 17155 if (MatrixArg.isInvalid()) 17156 return MatrixArg; 17157 Expr *Matrix = MatrixArg.get(); 17158 17159 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 17160 if (!MType) { 17161 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17162 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 17163 return ExprError(); 17164 } 17165 17166 // Create returned matrix type by swapping rows and columns of the argument 17167 // matrix type. 17168 QualType ResultType = Context.getConstantMatrixType( 17169 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 17170 17171 // Change the return type to the type of the returned matrix. 17172 TheCall->setType(ResultType); 17173 17174 // Update call argument to use the possibly converted matrix argument. 17175 TheCall->setArg(0, Matrix); 17176 return CallResult; 17177 } 17178 17179 // Get and verify the matrix dimensions. 17180 static llvm::Optional<unsigned> 17181 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 17182 SourceLocation ErrorPos; 17183 Optional<llvm::APSInt> Value = 17184 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 17185 if (!Value) { 17186 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 17187 << Name; 17188 return {}; 17189 } 17190 uint64_t Dim = Value->getZExtValue(); 17191 if (!ConstantMatrixType::isDimensionValid(Dim)) { 17192 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 17193 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 17194 return {}; 17195 } 17196 return Dim; 17197 } 17198 17199 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 17200 ExprResult CallResult) { 17201 if (!getLangOpts().MatrixTypes) { 17202 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 17203 return ExprError(); 17204 } 17205 17206 if (checkArgCount(*this, TheCall, 4)) 17207 return ExprError(); 17208 17209 unsigned PtrArgIdx = 0; 17210 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17211 Expr *RowsExpr = TheCall->getArg(1); 17212 Expr *ColumnsExpr = TheCall->getArg(2); 17213 Expr *StrideExpr = TheCall->getArg(3); 17214 17215 bool ArgError = false; 17216 17217 // Check pointer argument. 17218 { 17219 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17220 if (PtrConv.isInvalid()) 17221 return PtrConv; 17222 PtrExpr = PtrConv.get(); 17223 TheCall->setArg(0, PtrExpr); 17224 if (PtrExpr->isTypeDependent()) { 17225 TheCall->setType(Context.DependentTy); 17226 return TheCall; 17227 } 17228 } 17229 17230 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17231 QualType ElementTy; 17232 if (!PtrTy) { 17233 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17234 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17235 ArgError = true; 17236 } else { 17237 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 17238 17239 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 17240 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17241 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 17242 << PtrExpr->getType(); 17243 ArgError = true; 17244 } 17245 } 17246 17247 // Apply default Lvalue conversions and convert the expression to size_t. 17248 auto ApplyArgumentConversions = [this](Expr *E) { 17249 ExprResult Conv = DefaultLvalueConversion(E); 17250 if (Conv.isInvalid()) 17251 return Conv; 17252 17253 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 17254 }; 17255 17256 // Apply conversion to row and column expressions. 17257 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 17258 if (!RowsConv.isInvalid()) { 17259 RowsExpr = RowsConv.get(); 17260 TheCall->setArg(1, RowsExpr); 17261 } else 17262 RowsExpr = nullptr; 17263 17264 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 17265 if (!ColumnsConv.isInvalid()) { 17266 ColumnsExpr = ColumnsConv.get(); 17267 TheCall->setArg(2, ColumnsExpr); 17268 } else 17269 ColumnsExpr = nullptr; 17270 17271 // If any any part of the result matrix type is still pending, just use 17272 // Context.DependentTy, until all parts are resolved. 17273 if ((RowsExpr && RowsExpr->isTypeDependent()) || 17274 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 17275 TheCall->setType(Context.DependentTy); 17276 return CallResult; 17277 } 17278 17279 // Check row and column dimensions. 17280 llvm::Optional<unsigned> MaybeRows; 17281 if (RowsExpr) 17282 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 17283 17284 llvm::Optional<unsigned> MaybeColumns; 17285 if (ColumnsExpr) 17286 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 17287 17288 // Check stride argument. 17289 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 17290 if (StrideConv.isInvalid()) 17291 return ExprError(); 17292 StrideExpr = StrideConv.get(); 17293 TheCall->setArg(3, StrideExpr); 17294 17295 if (MaybeRows) { 17296 if (Optional<llvm::APSInt> Value = 17297 StrideExpr->getIntegerConstantExpr(Context)) { 17298 uint64_t Stride = Value->getZExtValue(); 17299 if (Stride < *MaybeRows) { 17300 Diag(StrideExpr->getBeginLoc(), 17301 diag::err_builtin_matrix_stride_too_small); 17302 ArgError = true; 17303 } 17304 } 17305 } 17306 17307 if (ArgError || !MaybeRows || !MaybeColumns) 17308 return ExprError(); 17309 17310 TheCall->setType( 17311 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 17312 return CallResult; 17313 } 17314 17315 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 17316 ExprResult CallResult) { 17317 if (checkArgCount(*this, TheCall, 3)) 17318 return ExprError(); 17319 17320 unsigned PtrArgIdx = 1; 17321 Expr *MatrixExpr = TheCall->getArg(0); 17322 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17323 Expr *StrideExpr = TheCall->getArg(2); 17324 17325 bool ArgError = false; 17326 17327 { 17328 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 17329 if (MatrixConv.isInvalid()) 17330 return MatrixConv; 17331 MatrixExpr = MatrixConv.get(); 17332 TheCall->setArg(0, MatrixExpr); 17333 } 17334 if (MatrixExpr->isTypeDependent()) { 17335 TheCall->setType(Context.DependentTy); 17336 return TheCall; 17337 } 17338 17339 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 17340 if (!MatrixTy) { 17341 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17342 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 17343 ArgError = true; 17344 } 17345 17346 { 17347 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17348 if (PtrConv.isInvalid()) 17349 return PtrConv; 17350 PtrExpr = PtrConv.get(); 17351 TheCall->setArg(1, PtrExpr); 17352 if (PtrExpr->isTypeDependent()) { 17353 TheCall->setType(Context.DependentTy); 17354 return TheCall; 17355 } 17356 } 17357 17358 // Check pointer argument. 17359 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17360 if (!PtrTy) { 17361 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17362 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17363 ArgError = true; 17364 } else { 17365 QualType ElementTy = PtrTy->getPointeeType(); 17366 if (ElementTy.isConstQualified()) { 17367 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 17368 ArgError = true; 17369 } 17370 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 17371 if (MatrixTy && 17372 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 17373 Diag(PtrExpr->getBeginLoc(), 17374 diag::err_builtin_matrix_pointer_arg_mismatch) 17375 << ElementTy << MatrixTy->getElementType(); 17376 ArgError = true; 17377 } 17378 } 17379 17380 // Apply default Lvalue conversions and convert the stride expression to 17381 // size_t. 17382 { 17383 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 17384 if (StrideConv.isInvalid()) 17385 return StrideConv; 17386 17387 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 17388 if (StrideConv.isInvalid()) 17389 return StrideConv; 17390 StrideExpr = StrideConv.get(); 17391 TheCall->setArg(2, StrideExpr); 17392 } 17393 17394 // Check stride argument. 17395 if (MatrixTy) { 17396 if (Optional<llvm::APSInt> Value = 17397 StrideExpr->getIntegerConstantExpr(Context)) { 17398 uint64_t Stride = Value->getZExtValue(); 17399 if (Stride < MatrixTy->getNumRows()) { 17400 Diag(StrideExpr->getBeginLoc(), 17401 diag::err_builtin_matrix_stride_too_small); 17402 ArgError = true; 17403 } 17404 } 17405 } 17406 17407 if (ArgError) 17408 return ExprError(); 17409 17410 return CallResult; 17411 } 17412 17413 /// \brief Enforce the bounds of a TCB 17414 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 17415 /// directly calls other functions in the same TCB as marked by the enforce_tcb 17416 /// and enforce_tcb_leaf attributes. 17417 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc, 17418 const NamedDecl *Callee) { 17419 const NamedDecl *Caller = getCurFunctionOrMethodDecl(); 17420 17421 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>()) 17422 return; 17423 17424 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 17425 // all TCBs the callee is a part of. 17426 llvm::StringSet<> CalleeTCBs; 17427 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 17428 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17429 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 17430 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17431 17432 // Go through the TCBs the caller is a part of and emit warnings if Caller 17433 // is in a TCB that the Callee is not. 17434 for_each( 17435 Caller->specific_attrs<EnforceTCBAttr>(), 17436 [&](const auto *A) { 17437 StringRef CallerTCB = A->getTCBName(); 17438 if (CalleeTCBs.count(CallerTCB) == 0) { 17439 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation) 17440 << Callee << CallerTCB; 17441 } 17442 }); 17443 } 17444