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 the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 594 isConstantEvaluated()) 595 return; 596 597 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 598 if (!BuiltinID) 599 return; 600 601 const TargetInfo &TI = getASTContext().getTargetInfo(); 602 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 603 604 auto ComputeExplicitObjectSizeArgument = 605 [&](unsigned Index) -> Optional<llvm::APSInt> { 606 Expr::EvalResult Result; 607 Expr *SizeArg = TheCall->getArg(Index); 608 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 609 return llvm::None; 610 return Result.Val.getInt(); 611 }; 612 613 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 614 // If the parameter has a pass_object_size attribute, then we should use its 615 // (potentially) more strict checking mode. Otherwise, conservatively assume 616 // type 0. 617 int BOSType = 0; 618 if (const auto *POS = 619 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 620 BOSType = POS->getType(); 621 622 const Expr *ObjArg = TheCall->getArg(Index); 623 uint64_t Result; 624 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 625 return llvm::None; 626 627 // Get the object size in the target's size_t width. 628 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 629 }; 630 631 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 632 Expr *ObjArg = TheCall->getArg(Index); 633 uint64_t Result; 634 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 635 return llvm::None; 636 // Add 1 for null byte. 637 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 638 }; 639 640 Optional<llvm::APSInt> SourceSize; 641 Optional<llvm::APSInt> DestinationSize; 642 unsigned DiagID = 0; 643 bool IsChkVariant = false; 644 645 switch (BuiltinID) { 646 default: 647 return; 648 case Builtin::BI__builtin_strcpy: 649 case Builtin::BIstrcpy: { 650 DiagID = diag::warn_fortify_strlen_overflow; 651 SourceSize = ComputeStrLenArgument(1); 652 DestinationSize = ComputeSizeArgument(0); 653 break; 654 } 655 656 case Builtin::BI__builtin___strcpy_chk: { 657 DiagID = diag::warn_fortify_strlen_overflow; 658 SourceSize = ComputeStrLenArgument(1); 659 DestinationSize = ComputeExplicitObjectSizeArgument(2); 660 IsChkVariant = true; 661 break; 662 } 663 664 case Builtin::BIsprintf: 665 case Builtin::BI__builtin___sprintf_chk: { 666 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 667 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 668 669 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 670 671 if (!Format->isAscii() && !Format->isUTF8()) 672 return; 673 674 StringRef FormatStrRef = Format->getString(); 675 EstimateSizeFormatHandler H(FormatStrRef); 676 const char *FormatBytes = FormatStrRef.data(); 677 const ConstantArrayType *T = 678 Context.getAsConstantArrayType(Format->getType()); 679 assert(T && "String literal not of constant array type!"); 680 size_t TypeSize = T->getSize().getZExtValue(); 681 682 // In case there's a null byte somewhere. 683 size_t StrLen = 684 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 685 if (!analyze_format_string::ParsePrintfString( 686 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 687 Context.getTargetInfo(), false)) { 688 DiagID = diag::warn_fortify_source_format_overflow; 689 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 690 .extOrTrunc(SizeTypeWidth); 691 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 692 DestinationSize = ComputeExplicitObjectSizeArgument(2); 693 IsChkVariant = true; 694 } else { 695 DestinationSize = ComputeSizeArgument(0); 696 } 697 break; 698 } 699 } 700 return; 701 } 702 case Builtin::BI__builtin___memcpy_chk: 703 case Builtin::BI__builtin___memmove_chk: 704 case Builtin::BI__builtin___memset_chk: 705 case Builtin::BI__builtin___strlcat_chk: 706 case Builtin::BI__builtin___strlcpy_chk: 707 case Builtin::BI__builtin___strncat_chk: 708 case Builtin::BI__builtin___strncpy_chk: 709 case Builtin::BI__builtin___stpncpy_chk: 710 case Builtin::BI__builtin___memccpy_chk: 711 case Builtin::BI__builtin___mempcpy_chk: { 712 DiagID = diag::warn_builtin_chk_overflow; 713 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 714 DestinationSize = 715 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 716 IsChkVariant = true; 717 break; 718 } 719 720 case Builtin::BI__builtin___snprintf_chk: 721 case Builtin::BI__builtin___vsnprintf_chk: { 722 DiagID = diag::warn_builtin_chk_overflow; 723 SourceSize = ComputeExplicitObjectSizeArgument(1); 724 DestinationSize = ComputeExplicitObjectSizeArgument(3); 725 IsChkVariant = true; 726 break; 727 } 728 729 case Builtin::BIstrncat: 730 case Builtin::BI__builtin_strncat: 731 case Builtin::BIstrncpy: 732 case Builtin::BI__builtin_strncpy: 733 case Builtin::BIstpncpy: 734 case Builtin::BI__builtin_stpncpy: { 735 // Whether these functions overflow depends on the runtime strlen of the 736 // string, not just the buffer size, so emitting the "always overflow" 737 // diagnostic isn't quite right. We should still diagnose passing a buffer 738 // size larger than the destination buffer though; this is a runtime abort 739 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 740 DiagID = diag::warn_fortify_source_size_mismatch; 741 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 742 DestinationSize = ComputeSizeArgument(0); 743 break; 744 } 745 746 case Builtin::BImemcpy: 747 case Builtin::BI__builtin_memcpy: 748 case Builtin::BImemmove: 749 case Builtin::BI__builtin_memmove: 750 case Builtin::BImemset: 751 case Builtin::BI__builtin_memset: 752 case Builtin::BImempcpy: 753 case Builtin::BI__builtin_mempcpy: { 754 DiagID = diag::warn_fortify_source_overflow; 755 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 756 DestinationSize = ComputeSizeArgument(0); 757 break; 758 } 759 case Builtin::BIsnprintf: 760 case Builtin::BI__builtin_snprintf: 761 case Builtin::BIvsnprintf: 762 case Builtin::BI__builtin_vsnprintf: { 763 DiagID = diag::warn_fortify_source_size_mismatch; 764 SourceSize = ComputeExplicitObjectSizeArgument(1); 765 DestinationSize = ComputeSizeArgument(0); 766 break; 767 } 768 } 769 770 if (!SourceSize || !DestinationSize || 771 SourceSize.getValue().ule(DestinationSize.getValue())) 772 return; 773 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 explicitly. 777 if (IsChkVariant) { 778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 779 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 780 } else if (FunctionName.startswith("__builtin_")) { 781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 782 } 783 784 SmallString<16> DestinationStr; 785 SmallString<16> SourceStr; 786 DestinationSize->toString(DestinationStr, /*Radix=*/10); 787 SourceSize->toString(SourceStr, /*Radix=*/10); 788 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 789 PDiag(DiagID) 790 << FunctionName << DestinationStr << SourceStr); 791 } 792 793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 794 Scope::ScopeFlags NeededScopeFlags, 795 unsigned DiagID) { 796 // Scopes aren't available during instantiation. Fortunately, builtin 797 // functions cannot be template args so they cannot be formed through template 798 // instantiation. Therefore checking once during the parse is sufficient. 799 if (SemaRef.inTemplateInstantiation()) 800 return false; 801 802 Scope *S = SemaRef.getCurScope(); 803 while (S && !S->isSEHExceptScope()) 804 S = S->getParent(); 805 if (!S || !(S->getFlags() & NeededScopeFlags)) { 806 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 807 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 808 << DRE->getDecl()->getIdentifier(); 809 return true; 810 } 811 812 return false; 813 } 814 815 static inline bool isBlockPointer(Expr *Arg) { 816 return Arg->getType()->isBlockPointerType(); 817 } 818 819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 820 /// void*, which is a requirement of device side enqueue. 821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 822 const BlockPointerType *BPT = 823 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 824 ArrayRef<QualType> Params = 825 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 826 unsigned ArgCounter = 0; 827 bool IllegalParams = false; 828 // Iterate through the block parameters until either one is found that is not 829 // a local void*, or the block is valid. 830 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 831 I != E; ++I, ++ArgCounter) { 832 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 833 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 834 LangAS::opencl_local) { 835 // Get the location of the error. If a block literal has been passed 836 // (BlockExpr) then we can point straight to the offending argument, 837 // else we just point to the variable reference. 838 SourceLocation ErrorLoc; 839 if (isa<BlockExpr>(BlockArg)) { 840 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 841 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 842 } else if (isa<DeclRefExpr>(BlockArg)) { 843 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 844 } 845 S.Diag(ErrorLoc, 846 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 847 IllegalParams = true; 848 } 849 } 850 851 return IllegalParams; 852 } 853 854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 855 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 857 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 858 return true; 859 } 860 return false; 861 } 862 863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 864 if (checkArgCount(S, TheCall, 2)) 865 return true; 866 867 if (checkOpenCLSubgroupExt(S, TheCall)) 868 return true; 869 870 // First argument is an ndrange_t type. 871 Expr *NDRangeArg = TheCall->getArg(0); 872 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 873 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 874 << TheCall->getDirectCallee() << "'ndrange_t'"; 875 return true; 876 } 877 878 Expr *BlockArg = TheCall->getArg(1); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 888 /// get_kernel_work_group_size 889 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 891 if (checkArgCount(S, TheCall, 1)) 892 return true; 893 894 Expr *BlockArg = TheCall->getArg(0); 895 if (!isBlockPointer(BlockArg)) { 896 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 897 << TheCall->getDirectCallee() << "block"; 898 return true; 899 } 900 return checkOpenCLBlockArgs(S, BlockArg); 901 } 902 903 /// Diagnose integer type and any valid implicit conversion to it. 904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 905 const QualType &IntType); 906 907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 908 unsigned Start, unsigned End) { 909 bool IllegalParams = false; 910 for (unsigned I = Start; I <= End; ++I) 911 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 912 S.Context.getSizeType()); 913 return IllegalParams; 914 } 915 916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 917 /// 'local void*' parameter of passed block. 918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 919 Expr *BlockArg, 920 unsigned NumNonVarArgs) { 921 const BlockPointerType *BPT = 922 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 923 unsigned NumBlockParams = 924 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 925 unsigned TotalNumArgs = TheCall->getNumArgs(); 926 927 // For each argument passed to the block, a corresponding uint needs to 928 // be passed to describe the size of the local memory. 929 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 930 S.Diag(TheCall->getBeginLoc(), 931 diag::err_opencl_enqueue_kernel_local_size_args); 932 return true; 933 } 934 935 // Check that the sizes of the local memory are specified by integers. 936 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 937 TotalNumArgs - 1); 938 } 939 940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 941 /// overload formats specified in Table 6.13.17.1. 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// void (^block)(void)) 946 /// int enqueue_kernel(queue_t queue, 947 /// kernel_enqueue_flags_t flags, 948 /// const ndrange_t ndrange, 949 /// uint num_events_in_wait_list, 950 /// clk_event_t *event_wait_list, 951 /// clk_event_t *event_ret, 952 /// void (^block)(void)) 953 /// int enqueue_kernel(queue_t queue, 954 /// kernel_enqueue_flags_t flags, 955 /// const ndrange_t ndrange, 956 /// void (^block)(local void*, ...), 957 /// uint size0, ...) 958 /// int enqueue_kernel(queue_t queue, 959 /// kernel_enqueue_flags_t flags, 960 /// const ndrange_t ndrange, 961 /// uint num_events_in_wait_list, 962 /// clk_event_t *event_wait_list, 963 /// clk_event_t *event_ret, 964 /// void (^block)(local void*, ...), 965 /// uint size0, ...) 966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 967 unsigned NumArgs = TheCall->getNumArgs(); 968 969 if (NumArgs < 4) { 970 S.Diag(TheCall->getBeginLoc(), 971 diag::err_typecheck_call_too_few_args_at_least) 972 << 0 << 4 << NumArgs; 973 return true; 974 } 975 976 Expr *Arg0 = TheCall->getArg(0); 977 Expr *Arg1 = TheCall->getArg(1); 978 Expr *Arg2 = TheCall->getArg(2); 979 Expr *Arg3 = TheCall->getArg(3); 980 981 // First argument always needs to be a queue_t type. 982 if (!Arg0->getType()->isQueueT()) { 983 S.Diag(TheCall->getArg(0)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 986 return true; 987 } 988 989 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 990 if (!Arg1->getType()->isIntegerType()) { 991 S.Diag(TheCall->getArg(1)->getBeginLoc(), 992 diag::err_opencl_builtin_expected_type) 993 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 994 return true; 995 } 996 997 // Third argument is always an ndrange_t type. 998 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 999 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1000 diag::err_opencl_builtin_expected_type) 1001 << TheCall->getDirectCallee() << "'ndrange_t'"; 1002 return true; 1003 } 1004 1005 // With four arguments, there is only one form that the function could be 1006 // called in: no events and no variable arguments. 1007 if (NumArgs == 4) { 1008 // check that the last argument is the right block type. 1009 if (!isBlockPointer(Arg3)) { 1010 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1011 << TheCall->getDirectCallee() << "block"; 1012 return true; 1013 } 1014 // we have a block type, check the prototype 1015 const BlockPointerType *BPT = 1016 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1017 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1018 S.Diag(Arg3->getBeginLoc(), 1019 diag::err_opencl_enqueue_kernel_blocks_no_args); 1020 return true; 1021 } 1022 return false; 1023 } 1024 // we can have block + varargs. 1025 if (isBlockPointer(Arg3)) 1026 return (checkOpenCLBlockArgs(S, Arg3) || 1027 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1028 // last two cases with either exactly 7 args or 7 args and varargs. 1029 if (NumArgs >= 7) { 1030 // check common block argument. 1031 Expr *Arg6 = TheCall->getArg(6); 1032 if (!isBlockPointer(Arg6)) { 1033 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1034 << TheCall->getDirectCallee() << "block"; 1035 return true; 1036 } 1037 if (checkOpenCLBlockArgs(S, Arg6)) 1038 return true; 1039 1040 // Forth argument has to be any integer type. 1041 if (!Arg3->getType()->isIntegerType()) { 1042 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1043 diag::err_opencl_builtin_expected_type) 1044 << TheCall->getDirectCallee() << "integer"; 1045 return true; 1046 } 1047 // check remaining common arguments. 1048 Expr *Arg4 = TheCall->getArg(4); 1049 Expr *Arg5 = TheCall->getArg(5); 1050 1051 // Fifth argument is always passed as a pointer to clk_event_t. 1052 if (!Arg4->isNullPointerConstant(S.Context, 1053 Expr::NPC_ValueDependentIsNotNull) && 1054 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1055 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1056 diag::err_opencl_builtin_expected_type) 1057 << TheCall->getDirectCallee() 1058 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1059 return true; 1060 } 1061 1062 // Sixth argument is always passed as a pointer to clk_event_t. 1063 if (!Arg5->isNullPointerConstant(S.Context, 1064 Expr::NPC_ValueDependentIsNotNull) && 1065 !(Arg5->getType()->isPointerType() && 1066 Arg5->getType()->getPointeeType()->isClkEventT())) { 1067 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1068 diag::err_opencl_builtin_expected_type) 1069 << TheCall->getDirectCallee() 1070 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1071 return true; 1072 } 1073 1074 if (NumArgs == 7) 1075 return false; 1076 1077 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1078 } 1079 1080 // None of the specific case has been detected, give generic error 1081 S.Diag(TheCall->getBeginLoc(), 1082 diag::err_opencl_enqueue_kernel_incorrect_args); 1083 return true; 1084 } 1085 1086 /// Returns OpenCL access qual. 1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1088 return D->getAttr<OpenCLAccessAttr>(); 1089 } 1090 1091 /// Returns true if pipe element type is different from the pointer. 1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1093 const Expr *Arg0 = Call->getArg(0); 1094 // First argument type should always be pipe. 1095 if (!Arg0->getType()->isPipeType()) { 1096 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1097 << Call->getDirectCallee() << Arg0->getSourceRange(); 1098 return true; 1099 } 1100 OpenCLAccessAttr *AccessQual = 1101 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1102 // Validates the access qualifier is compatible with the call. 1103 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1104 // read_only and write_only, and assumed to be read_only if no qualifier is 1105 // specified. 1106 switch (Call->getDirectCallee()->getBuiltinID()) { 1107 case Builtin::BIread_pipe: 1108 case Builtin::BIreserve_read_pipe: 1109 case Builtin::BIcommit_read_pipe: 1110 case Builtin::BIwork_group_reserve_read_pipe: 1111 case Builtin::BIsub_group_reserve_read_pipe: 1112 case Builtin::BIwork_group_commit_read_pipe: 1113 case Builtin::BIsub_group_commit_read_pipe: 1114 if (!(!AccessQual || AccessQual->isReadOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "read_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 case Builtin::BIwrite_pipe: 1122 case Builtin::BIreserve_write_pipe: 1123 case Builtin::BIcommit_write_pipe: 1124 case Builtin::BIwork_group_reserve_write_pipe: 1125 case Builtin::BIsub_group_reserve_write_pipe: 1126 case Builtin::BIwork_group_commit_write_pipe: 1127 case Builtin::BIsub_group_commit_write_pipe: 1128 if (!(AccessQual && AccessQual->isWriteOnly())) { 1129 S.Diag(Arg0->getBeginLoc(), 1130 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1131 << "write_only" << Arg0->getSourceRange(); 1132 return true; 1133 } 1134 break; 1135 default: 1136 break; 1137 } 1138 return false; 1139 } 1140 1141 /// Returns true if pipe element type is different from the pointer. 1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1143 const Expr *Arg0 = Call->getArg(0); 1144 const Expr *ArgIdx = Call->getArg(Idx); 1145 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1146 const QualType EltTy = PipeTy->getElementType(); 1147 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1148 // The Idx argument should be a pointer and the type of the pointer and 1149 // the type of pipe element should also be the same. 1150 if (!ArgTy || 1151 !S.Context.hasSameType( 1152 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1153 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1154 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1155 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 // Performs semantic analysis for the read/write_pipe call. 1162 // \param S Reference to the semantic analyzer. 1163 // \param Call A pointer to the builtin call. 1164 // \return True if a semantic error has been found, false otherwise. 1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1166 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1167 // functions have two forms. 1168 switch (Call->getNumArgs()) { 1169 case 2: 1170 if (checkOpenCLPipeArg(S, Call)) 1171 return true; 1172 // The call with 2 arguments should be 1173 // read/write_pipe(pipe T, T*). 1174 // Check packet type T. 1175 if (checkOpenCLPipePacketType(S, Call, 1)) 1176 return true; 1177 break; 1178 1179 case 4: { 1180 if (checkOpenCLPipeArg(S, Call)) 1181 return true; 1182 // The call with 4 arguments should be 1183 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1184 // Check reserve_id_t. 1185 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1186 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1187 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1188 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1189 return true; 1190 } 1191 1192 // Check the index. 1193 const Expr *Arg2 = Call->getArg(2); 1194 if (!Arg2->getType()->isIntegerType() && 1195 !Arg2->getType()->isUnsignedIntegerType()) { 1196 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1197 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1198 << Arg2->getType() << Arg2->getSourceRange(); 1199 return true; 1200 } 1201 1202 // Check packet type T. 1203 if (checkOpenCLPipePacketType(S, Call, 3)) 1204 return true; 1205 } break; 1206 default: 1207 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1208 << Call->getDirectCallee() << Call->getSourceRange(); 1209 return true; 1210 } 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on the {work_group_/sub_group_ 1216 // /_}reserve_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check the reserve size. 1228 if (!Call->getArg(1)->getType()->isIntegerType() && 1229 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1230 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1231 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1232 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1233 return true; 1234 } 1235 1236 // Since return type of reserve_read/write_pipe built-in function is 1237 // reserve_id_t, which is not defined in the builtin def file , we used int 1238 // as return type and need to override the return type of these functions. 1239 Call->setType(S.Context.OCLReserveIDTy); 1240 1241 return false; 1242 } 1243 1244 // Performs a semantic analysis on {work_group_/sub_group_ 1245 // /_}commit_{read/write}_pipe 1246 // \param S Reference to the semantic analyzer. 1247 // \param Call The call to the builtin function to be analyzed. 1248 // \return True if a semantic error was found, false otherwise. 1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1250 if (checkArgCount(S, Call, 2)) 1251 return true; 1252 1253 if (checkOpenCLPipeArg(S, Call)) 1254 return true; 1255 1256 // Check reserve_id_t. 1257 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1258 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1259 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1260 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1261 return true; 1262 } 1263 1264 return false; 1265 } 1266 1267 // Performs a semantic analysis on the call to built-in Pipe 1268 // Query Functions. 1269 // \param S Reference to the semantic analyzer. 1270 // \param Call The call to the builtin function to be analyzed. 1271 // \return True if a semantic error was found, false otherwise. 1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1273 if (checkArgCount(S, Call, 1)) 1274 return true; 1275 1276 if (!Call->getArg(0)->getType()->isPipeType()) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1278 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1279 return true; 1280 } 1281 1282 return false; 1283 } 1284 1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1286 // Performs semantic analysis for the to_global/local/private call. 1287 // \param S Reference to the semantic analyzer. 1288 // \param BuiltinID ID of the builtin function. 1289 // \param Call A pointer to the builtin call. 1290 // \return True if a semantic error has been found, false otherwise. 1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1292 CallExpr *Call) { 1293 if (checkArgCount(S, Call, 1)) 1294 return true; 1295 1296 auto RT = Call->getArg(0)->getType(); 1297 if (!RT->isPointerType() || RT->getPointeeType() 1298 .getAddressSpace() == LangAS::opencl_constant) { 1299 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1300 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1301 return true; 1302 } 1303 1304 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1305 S.Diag(Call->getArg(0)->getBeginLoc(), 1306 diag::warn_opencl_generic_address_space_arg) 1307 << Call->getDirectCallee()->getNameInfo().getAsString() 1308 << Call->getArg(0)->getSourceRange(); 1309 } 1310 1311 RT = RT->getPointeeType(); 1312 auto Qual = RT.getQualifiers(); 1313 switch (BuiltinID) { 1314 case Builtin::BIto_global: 1315 Qual.setAddressSpace(LangAS::opencl_global); 1316 break; 1317 case Builtin::BIto_local: 1318 Qual.setAddressSpace(LangAS::opencl_local); 1319 break; 1320 case Builtin::BIto_private: 1321 Qual.setAddressSpace(LangAS::opencl_private); 1322 break; 1323 default: 1324 llvm_unreachable("Invalid builtin function"); 1325 } 1326 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1327 RT.getUnqualifiedType(), Qual))); 1328 1329 return false; 1330 } 1331 1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1333 if (checkArgCount(S, TheCall, 1)) 1334 return ExprError(); 1335 1336 // Compute __builtin_launder's parameter type from the argument. 1337 // The parameter type is: 1338 // * The type of the argument if it's not an array or function type, 1339 // Otherwise, 1340 // * The decayed argument type. 1341 QualType ParamTy = [&]() { 1342 QualType ArgTy = TheCall->getArg(0)->getType(); 1343 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1344 return S.Context.getPointerType(Ty->getElementType()); 1345 if (ArgTy->isFunctionType()) { 1346 return S.Context.getPointerType(ArgTy); 1347 } 1348 return ArgTy; 1349 }(); 1350 1351 TheCall->setType(ParamTy); 1352 1353 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1354 if (!ParamTy->isPointerType()) 1355 return 0; 1356 if (ParamTy->isFunctionPointerType()) 1357 return 1; 1358 if (ParamTy->isVoidPointerType()) 1359 return 2; 1360 return llvm::Optional<unsigned>{}; 1361 }(); 1362 if (DiagSelect.hasValue()) { 1363 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1364 << DiagSelect.getValue() << TheCall->getSourceRange(); 1365 return ExprError(); 1366 } 1367 1368 // We either have an incomplete class type, or we have a class template 1369 // whose instantiation has not been forced. Example: 1370 // 1371 // template <class T> struct Foo { T value; }; 1372 // Foo<int> *p = nullptr; 1373 // auto *d = __builtin_launder(p); 1374 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1375 diag::err_incomplete_type)) 1376 return ExprError(); 1377 1378 assert(ParamTy->getPointeeType()->isObjectType() && 1379 "Unhandled non-object pointer case"); 1380 1381 InitializedEntity Entity = 1382 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1383 ExprResult Arg = 1384 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1385 if (Arg.isInvalid()) 1386 return ExprError(); 1387 TheCall->setArg(0, Arg.get()); 1388 1389 return TheCall; 1390 } 1391 1392 // Emit an error and return true if the current architecture is not in the list 1393 // of supported architectures. 1394 static bool 1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1396 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1397 llvm::Triple::ArchType CurArch = 1398 S.getASTContext().getTargetInfo().getTriple().getArch(); 1399 if (llvm::is_contained(SupportedArchs, CurArch)) 1400 return false; 1401 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1402 << TheCall->getSourceRange(); 1403 return true; 1404 } 1405 1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1407 SourceLocation CallSiteLoc); 1408 1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1410 CallExpr *TheCall) { 1411 switch (TI.getTriple().getArch()) { 1412 default: 1413 // Some builtins don't require additional checking, so just consider these 1414 // acceptable. 1415 return false; 1416 case llvm::Triple::arm: 1417 case llvm::Triple::armeb: 1418 case llvm::Triple::thumb: 1419 case llvm::Triple::thumbeb: 1420 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::aarch64: 1422 case llvm::Triple::aarch64_32: 1423 case llvm::Triple::aarch64_be: 1424 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::bpfeb: 1426 case llvm::Triple::bpfel: 1427 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1428 case llvm::Triple::hexagon: 1429 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1430 case llvm::Triple::mips: 1431 case llvm::Triple::mipsel: 1432 case llvm::Triple::mips64: 1433 case llvm::Triple::mips64el: 1434 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 case llvm::Triple::systemz: 1436 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1437 case llvm::Triple::x86: 1438 case llvm::Triple::x86_64: 1439 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1440 case llvm::Triple::ppc: 1441 case llvm::Triple::ppcle: 1442 case llvm::Triple::ppc64: 1443 case llvm::Triple::ppc64le: 1444 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1445 case llvm::Triple::amdgcn: 1446 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1447 case llvm::Triple::riscv32: 1448 case llvm::Triple::riscv64: 1449 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1450 } 1451 } 1452 1453 ExprResult 1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1455 CallExpr *TheCall) { 1456 ExprResult TheCallResult(TheCall); 1457 1458 // Find out if any arguments are required to be integer constant expressions. 1459 unsigned ICEArguments = 0; 1460 ASTContext::GetBuiltinTypeError Error; 1461 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1462 if (Error != ASTContext::GE_None) 1463 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1464 1465 // If any arguments are required to be ICE's, check and diagnose. 1466 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1467 // Skip arguments not required to be ICE's. 1468 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1469 1470 llvm::APSInt Result; 1471 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1472 return true; 1473 ICEArguments &= ~(1 << ArgNo); 1474 } 1475 1476 switch (BuiltinID) { 1477 case Builtin::BI__builtin___CFStringMakeConstantString: 1478 assert(TheCall->getNumArgs() == 1 && 1479 "Wrong # arguments to builtin CFStringMakeConstantString"); 1480 if (CheckObjCString(TheCall->getArg(0))) 1481 return ExprError(); 1482 break; 1483 case Builtin::BI__builtin_ms_va_start: 1484 case Builtin::BI__builtin_stdarg_start: 1485 case Builtin::BI__builtin_va_start: 1486 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1487 return ExprError(); 1488 break; 1489 case Builtin::BI__va_start: { 1490 switch (Context.getTargetInfo().getTriple().getArch()) { 1491 case llvm::Triple::aarch64: 1492 case llvm::Triple::arm: 1493 case llvm::Triple::thumb: 1494 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1495 return ExprError(); 1496 break; 1497 default: 1498 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1499 return ExprError(); 1500 break; 1501 } 1502 break; 1503 } 1504 1505 // The acquire, release, and no fence variants are ARM and AArch64 only. 1506 case Builtin::BI_interlockedbittestandset_acq: 1507 case Builtin::BI_interlockedbittestandset_rel: 1508 case Builtin::BI_interlockedbittestandset_nf: 1509 case Builtin::BI_interlockedbittestandreset_acq: 1510 case Builtin::BI_interlockedbittestandreset_rel: 1511 case Builtin::BI_interlockedbittestandreset_nf: 1512 if (CheckBuiltinTargetSupport( 1513 *this, BuiltinID, TheCall, 1514 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1515 return ExprError(); 1516 break; 1517 1518 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1519 case Builtin::BI_bittest64: 1520 case Builtin::BI_bittestandcomplement64: 1521 case Builtin::BI_bittestandreset64: 1522 case Builtin::BI_bittestandset64: 1523 case Builtin::BI_interlockedbittestandreset64: 1524 case Builtin::BI_interlockedbittestandset64: 1525 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1526 {llvm::Triple::x86_64, llvm::Triple::arm, 1527 llvm::Triple::thumb, llvm::Triple::aarch64})) 1528 return ExprError(); 1529 break; 1530 1531 case Builtin::BI__builtin_isgreater: 1532 case Builtin::BI__builtin_isgreaterequal: 1533 case Builtin::BI__builtin_isless: 1534 case Builtin::BI__builtin_islessequal: 1535 case Builtin::BI__builtin_islessgreater: 1536 case Builtin::BI__builtin_isunordered: 1537 if (SemaBuiltinUnorderedCompare(TheCall)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_fpclassify: 1541 if (SemaBuiltinFPClassification(TheCall, 6)) 1542 return ExprError(); 1543 break; 1544 case Builtin::BI__builtin_isfinite: 1545 case Builtin::BI__builtin_isinf: 1546 case Builtin::BI__builtin_isinf_sign: 1547 case Builtin::BI__builtin_isnan: 1548 case Builtin::BI__builtin_isnormal: 1549 case Builtin::BI__builtin_signbit: 1550 case Builtin::BI__builtin_signbitf: 1551 case Builtin::BI__builtin_signbitl: 1552 if (SemaBuiltinFPClassification(TheCall, 1)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_shufflevector: 1556 return SemaBuiltinShuffleVector(TheCall); 1557 // TheCall will be freed by the smart pointer here, but that's fine, since 1558 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1559 case Builtin::BI__builtin_prefetch: 1560 if (SemaBuiltinPrefetch(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_alloca_with_align: 1564 if (SemaBuiltinAllocaWithAlign(TheCall)) 1565 return ExprError(); 1566 LLVM_FALLTHROUGH; 1567 case Builtin::BI__builtin_alloca: 1568 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1569 << TheCall->getDirectCallee(); 1570 break; 1571 case Builtin::BI__arithmetic_fence: 1572 if (SemaBuiltinArithmeticFence(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__assume: 1576 case Builtin::BI__builtin_assume: 1577 if (SemaBuiltinAssume(TheCall)) 1578 return ExprError(); 1579 break; 1580 case Builtin::BI__builtin_assume_aligned: 1581 if (SemaBuiltinAssumeAligned(TheCall)) 1582 return ExprError(); 1583 break; 1584 case Builtin::BI__builtin_dynamic_object_size: 1585 case Builtin::BI__builtin_object_size: 1586 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BI__builtin_longjmp: 1590 if (SemaBuiltinLongjmp(TheCall)) 1591 return ExprError(); 1592 break; 1593 case Builtin::BI__builtin_setjmp: 1594 if (SemaBuiltinSetjmp(TheCall)) 1595 return ExprError(); 1596 break; 1597 case Builtin::BI__builtin_classify_type: 1598 if (checkArgCount(*this, TheCall, 1)) return true; 1599 TheCall->setType(Context.IntTy); 1600 break; 1601 case Builtin::BI__builtin_complex: 1602 if (SemaBuiltinComplex(TheCall)) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_constant_p: { 1606 if (checkArgCount(*this, TheCall, 1)) return true; 1607 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1608 if (Arg.isInvalid()) return true; 1609 TheCall->setArg(0, Arg.get()); 1610 TheCall->setType(Context.IntTy); 1611 break; 1612 } 1613 case Builtin::BI__builtin_launder: 1614 return SemaBuiltinLaunder(*this, TheCall); 1615 case Builtin::BI__sync_fetch_and_add: 1616 case Builtin::BI__sync_fetch_and_add_1: 1617 case Builtin::BI__sync_fetch_and_add_2: 1618 case Builtin::BI__sync_fetch_and_add_4: 1619 case Builtin::BI__sync_fetch_and_add_8: 1620 case Builtin::BI__sync_fetch_and_add_16: 1621 case Builtin::BI__sync_fetch_and_sub: 1622 case Builtin::BI__sync_fetch_and_sub_1: 1623 case Builtin::BI__sync_fetch_and_sub_2: 1624 case Builtin::BI__sync_fetch_and_sub_4: 1625 case Builtin::BI__sync_fetch_and_sub_8: 1626 case Builtin::BI__sync_fetch_and_sub_16: 1627 case Builtin::BI__sync_fetch_and_or: 1628 case Builtin::BI__sync_fetch_and_or_1: 1629 case Builtin::BI__sync_fetch_and_or_2: 1630 case Builtin::BI__sync_fetch_and_or_4: 1631 case Builtin::BI__sync_fetch_and_or_8: 1632 case Builtin::BI__sync_fetch_and_or_16: 1633 case Builtin::BI__sync_fetch_and_and: 1634 case Builtin::BI__sync_fetch_and_and_1: 1635 case Builtin::BI__sync_fetch_and_and_2: 1636 case Builtin::BI__sync_fetch_and_and_4: 1637 case Builtin::BI__sync_fetch_and_and_8: 1638 case Builtin::BI__sync_fetch_and_and_16: 1639 case Builtin::BI__sync_fetch_and_xor: 1640 case Builtin::BI__sync_fetch_and_xor_1: 1641 case Builtin::BI__sync_fetch_and_xor_2: 1642 case Builtin::BI__sync_fetch_and_xor_4: 1643 case Builtin::BI__sync_fetch_and_xor_8: 1644 case Builtin::BI__sync_fetch_and_xor_16: 1645 case Builtin::BI__sync_fetch_and_nand: 1646 case Builtin::BI__sync_fetch_and_nand_1: 1647 case Builtin::BI__sync_fetch_and_nand_2: 1648 case Builtin::BI__sync_fetch_and_nand_4: 1649 case Builtin::BI__sync_fetch_and_nand_8: 1650 case Builtin::BI__sync_fetch_and_nand_16: 1651 case Builtin::BI__sync_add_and_fetch: 1652 case Builtin::BI__sync_add_and_fetch_1: 1653 case Builtin::BI__sync_add_and_fetch_2: 1654 case Builtin::BI__sync_add_and_fetch_4: 1655 case Builtin::BI__sync_add_and_fetch_8: 1656 case Builtin::BI__sync_add_and_fetch_16: 1657 case Builtin::BI__sync_sub_and_fetch: 1658 case Builtin::BI__sync_sub_and_fetch_1: 1659 case Builtin::BI__sync_sub_and_fetch_2: 1660 case Builtin::BI__sync_sub_and_fetch_4: 1661 case Builtin::BI__sync_sub_and_fetch_8: 1662 case Builtin::BI__sync_sub_and_fetch_16: 1663 case Builtin::BI__sync_and_and_fetch: 1664 case Builtin::BI__sync_and_and_fetch_1: 1665 case Builtin::BI__sync_and_and_fetch_2: 1666 case Builtin::BI__sync_and_and_fetch_4: 1667 case Builtin::BI__sync_and_and_fetch_8: 1668 case Builtin::BI__sync_and_and_fetch_16: 1669 case Builtin::BI__sync_or_and_fetch: 1670 case Builtin::BI__sync_or_and_fetch_1: 1671 case Builtin::BI__sync_or_and_fetch_2: 1672 case Builtin::BI__sync_or_and_fetch_4: 1673 case Builtin::BI__sync_or_and_fetch_8: 1674 case Builtin::BI__sync_or_and_fetch_16: 1675 case Builtin::BI__sync_xor_and_fetch: 1676 case Builtin::BI__sync_xor_and_fetch_1: 1677 case Builtin::BI__sync_xor_and_fetch_2: 1678 case Builtin::BI__sync_xor_and_fetch_4: 1679 case Builtin::BI__sync_xor_and_fetch_8: 1680 case Builtin::BI__sync_xor_and_fetch_16: 1681 case Builtin::BI__sync_nand_and_fetch: 1682 case Builtin::BI__sync_nand_and_fetch_1: 1683 case Builtin::BI__sync_nand_and_fetch_2: 1684 case Builtin::BI__sync_nand_and_fetch_4: 1685 case Builtin::BI__sync_nand_and_fetch_8: 1686 case Builtin::BI__sync_nand_and_fetch_16: 1687 case Builtin::BI__sync_val_compare_and_swap: 1688 case Builtin::BI__sync_val_compare_and_swap_1: 1689 case Builtin::BI__sync_val_compare_and_swap_2: 1690 case Builtin::BI__sync_val_compare_and_swap_4: 1691 case Builtin::BI__sync_val_compare_and_swap_8: 1692 case Builtin::BI__sync_val_compare_and_swap_16: 1693 case Builtin::BI__sync_bool_compare_and_swap: 1694 case Builtin::BI__sync_bool_compare_and_swap_1: 1695 case Builtin::BI__sync_bool_compare_and_swap_2: 1696 case Builtin::BI__sync_bool_compare_and_swap_4: 1697 case Builtin::BI__sync_bool_compare_and_swap_8: 1698 case Builtin::BI__sync_bool_compare_and_swap_16: 1699 case Builtin::BI__sync_lock_test_and_set: 1700 case Builtin::BI__sync_lock_test_and_set_1: 1701 case Builtin::BI__sync_lock_test_and_set_2: 1702 case Builtin::BI__sync_lock_test_and_set_4: 1703 case Builtin::BI__sync_lock_test_and_set_8: 1704 case Builtin::BI__sync_lock_test_and_set_16: 1705 case Builtin::BI__sync_lock_release: 1706 case Builtin::BI__sync_lock_release_1: 1707 case Builtin::BI__sync_lock_release_2: 1708 case Builtin::BI__sync_lock_release_4: 1709 case Builtin::BI__sync_lock_release_8: 1710 case Builtin::BI__sync_lock_release_16: 1711 case Builtin::BI__sync_swap: 1712 case Builtin::BI__sync_swap_1: 1713 case Builtin::BI__sync_swap_2: 1714 case Builtin::BI__sync_swap_4: 1715 case Builtin::BI__sync_swap_8: 1716 case Builtin::BI__sync_swap_16: 1717 return SemaBuiltinAtomicOverloaded(TheCallResult); 1718 case Builtin::BI__sync_synchronize: 1719 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1720 << TheCall->getCallee()->getSourceRange(); 1721 break; 1722 case Builtin::BI__builtin_nontemporal_load: 1723 case Builtin::BI__builtin_nontemporal_store: 1724 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1725 case Builtin::BI__builtin_memcpy_inline: { 1726 clang::Expr *SizeOp = TheCall->getArg(2); 1727 // We warn about copying to or from `nullptr` pointers when `size` is 1728 // greater than 0. When `size` is value dependent we cannot evaluate its 1729 // value so we bail out. 1730 if (SizeOp->isValueDependent()) 1731 break; 1732 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1733 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1734 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1735 } 1736 break; 1737 } 1738 #define BUILTIN(ID, TYPE, ATTRS) 1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1740 case Builtin::BI##ID: \ 1741 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1742 #include "clang/Basic/Builtins.def" 1743 case Builtin::BI__annotation: 1744 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_annotation: 1748 if (SemaBuiltinAnnotation(*this, TheCall)) 1749 return ExprError(); 1750 break; 1751 case Builtin::BI__builtin_addressof: 1752 if (SemaBuiltinAddressof(*this, TheCall)) 1753 return ExprError(); 1754 break; 1755 case Builtin::BI__builtin_is_aligned: 1756 case Builtin::BI__builtin_align_up: 1757 case Builtin::BI__builtin_align_down: 1758 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_add_overflow: 1762 case Builtin::BI__builtin_sub_overflow: 1763 case Builtin::BI__builtin_mul_overflow: 1764 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__builtin_operator_new: 1768 case Builtin::BI__builtin_operator_delete: { 1769 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1770 ExprResult Res = 1771 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1772 if (Res.isInvalid()) 1773 CorrectDelayedTyposInExpr(TheCallResult.get()); 1774 return Res; 1775 } 1776 case Builtin::BI__builtin_dump_struct: { 1777 // We first want to ensure we are called with 2 arguments 1778 if (checkArgCount(*this, TheCall, 2)) 1779 return ExprError(); 1780 // Ensure that the first argument is of type 'struct XX *' 1781 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1782 const QualType PtrArgType = PtrArg->getType(); 1783 if (!PtrArgType->isPointerType() || 1784 !PtrArgType->getPointeeType()->isRecordType()) { 1785 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1786 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1787 << "structure pointer"; 1788 return ExprError(); 1789 } 1790 1791 // Ensure that the second argument is of type 'FunctionType' 1792 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1793 const QualType FnPtrArgType = FnPtrArg->getType(); 1794 if (!FnPtrArgType->isPointerType()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1797 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 1801 const auto *FuncType = 1802 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1803 1804 if (!FuncType) { 1805 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1806 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1807 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1808 return ExprError(); 1809 } 1810 1811 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1812 if (!FT->getNumParams()) { 1813 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1814 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1815 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1816 return ExprError(); 1817 } 1818 QualType PT = FT->getParamType(0); 1819 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1820 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1821 !PT->getPointeeType().isConstQualified()) { 1822 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1823 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1824 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1825 return ExprError(); 1826 } 1827 } 1828 1829 TheCall->setType(Context.IntTy); 1830 break; 1831 } 1832 case Builtin::BI__builtin_expect_with_probability: { 1833 // We first want to ensure we are called with 3 arguments 1834 if (checkArgCount(*this, TheCall, 3)) 1835 return ExprError(); 1836 // then check probability is constant float in range [0.0, 1.0] 1837 const Expr *ProbArg = TheCall->getArg(2); 1838 SmallVector<PartialDiagnosticAt, 8> Notes; 1839 Expr::EvalResult Eval; 1840 Eval.Diag = &Notes; 1841 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1842 !Eval.Val.isFloat()) { 1843 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1844 << ProbArg->getSourceRange(); 1845 for (const PartialDiagnosticAt &PDiag : Notes) 1846 Diag(PDiag.first, PDiag.second); 1847 return ExprError(); 1848 } 1849 llvm::APFloat Probability = Eval.Val.getFloat(); 1850 bool LoseInfo = false; 1851 Probability.convert(llvm::APFloat::IEEEdouble(), 1852 llvm::RoundingMode::Dynamic, &LoseInfo); 1853 if (!(Probability >= llvm::APFloat(0.0) && 1854 Probability <= llvm::APFloat(1.0))) { 1855 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1856 << ProbArg->getSourceRange(); 1857 return ExprError(); 1858 } 1859 break; 1860 } 1861 case Builtin::BI__builtin_preserve_access_index: 1862 if (SemaBuiltinPreserveAI(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BI__builtin_call_with_static_chain: 1866 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__exception_code: 1870 case Builtin::BI_exception_code: 1871 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1872 diag::err_seh___except_block)) 1873 return ExprError(); 1874 break; 1875 case Builtin::BI__exception_info: 1876 case Builtin::BI_exception_info: 1877 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1878 diag::err_seh___except_filter)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BI__GetExceptionInfo: 1882 if (checkArgCount(*this, TheCall, 1)) 1883 return ExprError(); 1884 1885 if (CheckCXXThrowOperand( 1886 TheCall->getBeginLoc(), 1887 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1888 TheCall)) 1889 return ExprError(); 1890 1891 TheCall->setType(Context.VoidPtrTy); 1892 break; 1893 // OpenCL v2.0, s6.13.16 - Pipe functions 1894 case Builtin::BIread_pipe: 1895 case Builtin::BIwrite_pipe: 1896 // Since those two functions are declared with var args, we need a semantic 1897 // check for the argument. 1898 if (SemaBuiltinRWPipe(*this, TheCall)) 1899 return ExprError(); 1900 break; 1901 case Builtin::BIreserve_read_pipe: 1902 case Builtin::BIreserve_write_pipe: 1903 case Builtin::BIwork_group_reserve_read_pipe: 1904 case Builtin::BIwork_group_reserve_write_pipe: 1905 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIsub_group_reserve_read_pipe: 1909 case Builtin::BIsub_group_reserve_write_pipe: 1910 if (checkOpenCLSubgroupExt(*this, TheCall) || 1911 SemaBuiltinReserveRWPipe(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIcommit_read_pipe: 1915 case Builtin::BIcommit_write_pipe: 1916 case Builtin::BIwork_group_commit_read_pipe: 1917 case Builtin::BIwork_group_commit_write_pipe: 1918 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1919 return ExprError(); 1920 break; 1921 case Builtin::BIsub_group_commit_read_pipe: 1922 case Builtin::BIsub_group_commit_write_pipe: 1923 if (checkOpenCLSubgroupExt(*this, TheCall) || 1924 SemaBuiltinCommitRWPipe(*this, TheCall)) 1925 return ExprError(); 1926 break; 1927 case Builtin::BIget_pipe_num_packets: 1928 case Builtin::BIget_pipe_max_packets: 1929 if (SemaBuiltinPipePackets(*this, TheCall)) 1930 return ExprError(); 1931 break; 1932 case Builtin::BIto_global: 1933 case Builtin::BIto_local: 1934 case Builtin::BIto_private: 1935 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1936 return ExprError(); 1937 break; 1938 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1939 case Builtin::BIenqueue_kernel: 1940 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1941 return ExprError(); 1942 break; 1943 case Builtin::BIget_kernel_work_group_size: 1944 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1945 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1946 return ExprError(); 1947 break; 1948 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1949 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1950 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1951 return ExprError(); 1952 break; 1953 case Builtin::BI__builtin_os_log_format: 1954 Cleanup.setExprNeedsCleanups(true); 1955 LLVM_FALLTHROUGH; 1956 case Builtin::BI__builtin_os_log_format_buffer_size: 1957 if (SemaBuiltinOSLogFormat(TheCall)) 1958 return ExprError(); 1959 break; 1960 case Builtin::BI__builtin_frame_address: 1961 case Builtin::BI__builtin_return_address: { 1962 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1963 return ExprError(); 1964 1965 // -Wframe-address warning if non-zero passed to builtin 1966 // return/frame address. 1967 Expr::EvalResult Result; 1968 if (!TheCall->getArg(0)->isValueDependent() && 1969 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1970 Result.Val.getInt() != 0) 1971 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1972 << ((BuiltinID == Builtin::BI__builtin_return_address) 1973 ? "__builtin_return_address" 1974 : "__builtin_frame_address") 1975 << TheCall->getSourceRange(); 1976 break; 1977 } 1978 1979 case Builtin::BI__builtin_matrix_transpose: 1980 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1981 1982 case Builtin::BI__builtin_matrix_column_major_load: 1983 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1984 1985 case Builtin::BI__builtin_matrix_column_major_store: 1986 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1987 1988 case Builtin::BI__builtin_get_device_side_mangled_name: { 1989 auto Check = [](CallExpr *TheCall) { 1990 if (TheCall->getNumArgs() != 1) 1991 return false; 1992 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1993 if (!DRE) 1994 return false; 1995 auto *D = DRE->getDecl(); 1996 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1997 return false; 1998 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1999 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2000 }; 2001 if (!Check(TheCall)) { 2002 Diag(TheCall->getBeginLoc(), 2003 diag::err_hip_invalid_args_builtin_mangled_name); 2004 return ExprError(); 2005 } 2006 } 2007 } 2008 2009 // Since the target specific builtins for each arch overlap, only check those 2010 // of the arch we are compiling for. 2011 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2012 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2013 assert(Context.getAuxTargetInfo() && 2014 "Aux Target Builtin, but not an aux target?"); 2015 2016 if (CheckTSBuiltinFunctionCall( 2017 *Context.getAuxTargetInfo(), 2018 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2019 return ExprError(); 2020 } else { 2021 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2022 TheCall)) 2023 return ExprError(); 2024 } 2025 } 2026 2027 return TheCallResult; 2028 } 2029 2030 // Get the valid immediate range for the specified NEON type code. 2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2032 NeonTypeFlags Type(t); 2033 int IsQuad = ForceQuad ? true : Type.isQuad(); 2034 switch (Type.getEltType()) { 2035 case NeonTypeFlags::Int8: 2036 case NeonTypeFlags::Poly8: 2037 return shift ? 7 : (8 << IsQuad) - 1; 2038 case NeonTypeFlags::Int16: 2039 case NeonTypeFlags::Poly16: 2040 return shift ? 15 : (4 << IsQuad) - 1; 2041 case NeonTypeFlags::Int32: 2042 return shift ? 31 : (2 << IsQuad) - 1; 2043 case NeonTypeFlags::Int64: 2044 case NeonTypeFlags::Poly64: 2045 return shift ? 63 : (1 << IsQuad) - 1; 2046 case NeonTypeFlags::Poly128: 2047 return shift ? 127 : (1 << IsQuad) - 1; 2048 case NeonTypeFlags::Float16: 2049 assert(!shift && "cannot shift float types!"); 2050 return (4 << IsQuad) - 1; 2051 case NeonTypeFlags::Float32: 2052 assert(!shift && "cannot shift float types!"); 2053 return (2 << IsQuad) - 1; 2054 case NeonTypeFlags::Float64: 2055 assert(!shift && "cannot shift float types!"); 2056 return (1 << IsQuad) - 1; 2057 case NeonTypeFlags::BFloat16: 2058 assert(!shift && "cannot shift float types!"); 2059 return (4 << IsQuad) - 1; 2060 } 2061 llvm_unreachable("Invalid NeonTypeFlag!"); 2062 } 2063 2064 /// getNeonEltType - Return the QualType corresponding to the elements of 2065 /// the vector type specified by the NeonTypeFlags. This is used to check 2066 /// the pointer arguments for Neon load/store intrinsics. 2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2068 bool IsPolyUnsigned, bool IsInt64Long) { 2069 switch (Flags.getEltType()) { 2070 case NeonTypeFlags::Int8: 2071 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2072 case NeonTypeFlags::Int16: 2073 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2074 case NeonTypeFlags::Int32: 2075 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2076 case NeonTypeFlags::Int64: 2077 if (IsInt64Long) 2078 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2079 else 2080 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2081 : Context.LongLongTy; 2082 case NeonTypeFlags::Poly8: 2083 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2084 case NeonTypeFlags::Poly16: 2085 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2086 case NeonTypeFlags::Poly64: 2087 if (IsInt64Long) 2088 return Context.UnsignedLongTy; 2089 else 2090 return Context.UnsignedLongLongTy; 2091 case NeonTypeFlags::Poly128: 2092 break; 2093 case NeonTypeFlags::Float16: 2094 return Context.HalfTy; 2095 case NeonTypeFlags::Float32: 2096 return Context.FloatTy; 2097 case NeonTypeFlags::Float64: 2098 return Context.DoubleTy; 2099 case NeonTypeFlags::BFloat16: 2100 return Context.BFloat16Ty; 2101 } 2102 llvm_unreachable("Invalid NeonTypeFlag!"); 2103 } 2104 2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2106 // Range check SVE intrinsics that take immediate values. 2107 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2108 2109 switch (BuiltinID) { 2110 default: 2111 return false; 2112 #define GET_SVE_IMMEDIATE_CHECK 2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2114 #undef GET_SVE_IMMEDIATE_CHECK 2115 } 2116 2117 // Perform all the immediate checks for this builtin call. 2118 bool HasError = false; 2119 for (auto &I : ImmChecks) { 2120 int ArgNum, CheckTy, ElementSizeInBits; 2121 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2122 2123 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2124 2125 // Function that checks whether the operand (ArgNum) is an immediate 2126 // that is one of the predefined values. 2127 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2128 int ErrDiag) -> bool { 2129 // We can't check the value of a dependent argument. 2130 Expr *Arg = TheCall->getArg(ArgNum); 2131 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2132 return false; 2133 2134 // Check constant-ness first. 2135 llvm::APSInt Imm; 2136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2137 return true; 2138 2139 if (!CheckImm(Imm.getSExtValue())) 2140 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2141 return false; 2142 }; 2143 2144 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2145 case SVETypeFlags::ImmCheck0_31: 2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheck0_13: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2151 HasError = true; 2152 break; 2153 case SVETypeFlags::ImmCheck1_16: 2154 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheck0_7: 2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckExtract: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 (2048 / ElementSizeInBits) - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckShiftRight: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2168 HasError = true; 2169 break; 2170 case SVETypeFlags::ImmCheckShiftRightNarrow: 2171 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2172 ElementSizeInBits / 2)) 2173 HasError = true; 2174 break; 2175 case SVETypeFlags::ImmCheckShiftLeft: 2176 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2177 ElementSizeInBits - 1)) 2178 HasError = true; 2179 break; 2180 case SVETypeFlags::ImmCheckLaneIndex: 2181 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2182 (128 / (1 * ElementSizeInBits)) - 1)) 2183 HasError = true; 2184 break; 2185 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2186 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2187 (128 / (2 * ElementSizeInBits)) - 1)) 2188 HasError = true; 2189 break; 2190 case SVETypeFlags::ImmCheckLaneIndexDot: 2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2192 (128 / (4 * ElementSizeInBits)) - 1)) 2193 HasError = true; 2194 break; 2195 case SVETypeFlags::ImmCheckComplexRot90_270: 2196 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2197 diag::err_rotation_argument_to_cadd)) 2198 HasError = true; 2199 break; 2200 case SVETypeFlags::ImmCheckComplexRotAll90: 2201 if (CheckImmediateInSet( 2202 [](int64_t V) { 2203 return V == 0 || V == 90 || V == 180 || V == 270; 2204 }, 2205 diag::err_rotation_argument_to_cmla)) 2206 HasError = true; 2207 break; 2208 case SVETypeFlags::ImmCheck0_1: 2209 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2210 HasError = true; 2211 break; 2212 case SVETypeFlags::ImmCheck0_2: 2213 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2214 HasError = true; 2215 break; 2216 case SVETypeFlags::ImmCheck0_3: 2217 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2218 HasError = true; 2219 break; 2220 } 2221 } 2222 2223 return HasError; 2224 } 2225 2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2227 unsigned BuiltinID, CallExpr *TheCall) { 2228 llvm::APSInt Result; 2229 uint64_t mask = 0; 2230 unsigned TV = 0; 2231 int PtrArgNum = -1; 2232 bool HasConstPtr = false; 2233 switch (BuiltinID) { 2234 #define GET_NEON_OVERLOAD_CHECK 2235 #include "clang/Basic/arm_neon.inc" 2236 #include "clang/Basic/arm_fp16.inc" 2237 #undef GET_NEON_OVERLOAD_CHECK 2238 } 2239 2240 // For NEON intrinsics which are overloaded on vector element type, validate 2241 // the immediate which specifies which variant to emit. 2242 unsigned ImmArg = TheCall->getNumArgs()-1; 2243 if (mask) { 2244 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2245 return true; 2246 2247 TV = Result.getLimitedValue(64); 2248 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2249 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2250 << TheCall->getArg(ImmArg)->getSourceRange(); 2251 } 2252 2253 if (PtrArgNum >= 0) { 2254 // Check that pointer arguments have the specified type. 2255 Expr *Arg = TheCall->getArg(PtrArgNum); 2256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2257 Arg = ICE->getSubExpr(); 2258 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2259 QualType RHSTy = RHS.get()->getType(); 2260 2261 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2262 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2263 Arch == llvm::Triple::aarch64_32 || 2264 Arch == llvm::Triple::aarch64_be; 2265 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2266 QualType EltTy = 2267 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2268 if (HasConstPtr) 2269 EltTy = EltTy.withConst(); 2270 QualType LHSTy = Context.getPointerType(EltTy); 2271 AssignConvertType ConvTy; 2272 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2273 if (RHS.isInvalid()) 2274 return true; 2275 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2276 RHS.get(), AA_Assigning)) 2277 return true; 2278 } 2279 2280 // For NEON intrinsics which take an immediate value as part of the 2281 // instruction, range check them here. 2282 unsigned i = 0, l = 0, u = 0; 2283 switch (BuiltinID) { 2284 default: 2285 return false; 2286 #define GET_NEON_IMMEDIATE_CHECK 2287 #include "clang/Basic/arm_neon.inc" 2288 #include "clang/Basic/arm_fp16.inc" 2289 #undef GET_NEON_IMMEDIATE_CHECK 2290 } 2291 2292 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2293 } 2294 2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2296 switch (BuiltinID) { 2297 default: 2298 return false; 2299 #include "clang/Basic/arm_mve_builtin_sema.inc" 2300 } 2301 } 2302 2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2304 CallExpr *TheCall) { 2305 bool Err = false; 2306 switch (BuiltinID) { 2307 default: 2308 return false; 2309 #include "clang/Basic/arm_cde_builtin_sema.inc" 2310 } 2311 2312 if (Err) 2313 return true; 2314 2315 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2316 } 2317 2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2319 const Expr *CoprocArg, bool WantCDE) { 2320 if (isConstantEvaluated()) 2321 return false; 2322 2323 // We can't check the value of a dependent argument. 2324 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2325 return false; 2326 2327 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2328 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2329 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2330 2331 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2332 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2333 2334 if (IsCDECoproc != WantCDE) 2335 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2336 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2337 2338 return false; 2339 } 2340 2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2342 unsigned MaxWidth) { 2343 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2344 BuiltinID == ARM::BI__builtin_arm_ldaex || 2345 BuiltinID == ARM::BI__builtin_arm_strex || 2346 BuiltinID == ARM::BI__builtin_arm_stlex || 2347 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2348 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2349 BuiltinID == AArch64::BI__builtin_arm_strex || 2350 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2351 "unexpected ARM builtin"); 2352 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2353 BuiltinID == ARM::BI__builtin_arm_ldaex || 2354 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2355 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2356 2357 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2358 2359 // Ensure that we have the proper number of arguments. 2360 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2361 return true; 2362 2363 // Inspect the pointer argument of the atomic builtin. This should always be 2364 // a pointer type, whose element is an integral scalar or pointer type. 2365 // Because it is a pointer type, we don't have to worry about any implicit 2366 // casts here. 2367 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2368 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2369 if (PointerArgRes.isInvalid()) 2370 return true; 2371 PointerArg = PointerArgRes.get(); 2372 2373 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2374 if (!pointerType) { 2375 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2376 << PointerArg->getType() << PointerArg->getSourceRange(); 2377 return true; 2378 } 2379 2380 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2381 // task is to insert the appropriate casts into the AST. First work out just 2382 // what the appropriate type is. 2383 QualType ValType = pointerType->getPointeeType(); 2384 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2385 if (IsLdrex) 2386 AddrType.addConst(); 2387 2388 // Issue a warning if the cast is dodgy. 2389 CastKind CastNeeded = CK_NoOp; 2390 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2391 CastNeeded = CK_BitCast; 2392 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2393 << PointerArg->getType() << Context.getPointerType(AddrType) 2394 << AA_Passing << PointerArg->getSourceRange(); 2395 } 2396 2397 // Finally, do the cast and replace the argument with the corrected version. 2398 AddrType = Context.getPointerType(AddrType); 2399 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2400 if (PointerArgRes.isInvalid()) 2401 return true; 2402 PointerArg = PointerArgRes.get(); 2403 2404 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2405 2406 // In general, we allow ints, floats and pointers to be loaded and stored. 2407 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2408 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2409 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2410 << PointerArg->getType() << PointerArg->getSourceRange(); 2411 return true; 2412 } 2413 2414 // But ARM doesn't have instructions to deal with 128-bit versions. 2415 if (Context.getTypeSize(ValType) > MaxWidth) { 2416 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2417 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2418 << PointerArg->getType() << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 switch (ValType.getObjCLifetime()) { 2423 case Qualifiers::OCL_None: 2424 case Qualifiers::OCL_ExplicitNone: 2425 // okay 2426 break; 2427 2428 case Qualifiers::OCL_Weak: 2429 case Qualifiers::OCL_Strong: 2430 case Qualifiers::OCL_Autoreleasing: 2431 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2432 << ValType << PointerArg->getSourceRange(); 2433 return true; 2434 } 2435 2436 if (IsLdrex) { 2437 TheCall->setType(ValType); 2438 return false; 2439 } 2440 2441 // Initialize the argument to be stored. 2442 ExprResult ValArg = TheCall->getArg(0); 2443 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2444 Context, ValType, /*consume*/ false); 2445 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2446 if (ValArg.isInvalid()) 2447 return true; 2448 TheCall->setArg(0, ValArg.get()); 2449 2450 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2451 // but the custom checker bypasses all default analysis. 2452 TheCall->setType(Context.IntTy); 2453 return false; 2454 } 2455 2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2457 CallExpr *TheCall) { 2458 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2459 BuiltinID == ARM::BI__builtin_arm_ldaex || 2460 BuiltinID == ARM::BI__builtin_arm_strex || 2461 BuiltinID == ARM::BI__builtin_arm_stlex) { 2462 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2463 } 2464 2465 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2466 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2467 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2468 } 2469 2470 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2471 BuiltinID == ARM::BI__builtin_arm_wsr64) 2472 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2473 2474 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2475 BuiltinID == ARM::BI__builtin_arm_rsrp || 2476 BuiltinID == ARM::BI__builtin_arm_wsr || 2477 BuiltinID == ARM::BI__builtin_arm_wsrp) 2478 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2479 2480 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2481 return true; 2482 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2483 return true; 2484 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2485 return true; 2486 2487 // For intrinsics which take an immediate value as part of the instruction, 2488 // range check them here. 2489 // FIXME: VFP Intrinsics should error if VFP not present. 2490 switch (BuiltinID) { 2491 default: return false; 2492 case ARM::BI__builtin_arm_ssat: 2493 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2494 case ARM::BI__builtin_arm_usat: 2495 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2496 case ARM::BI__builtin_arm_ssat16: 2497 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2498 case ARM::BI__builtin_arm_usat16: 2499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2500 case ARM::BI__builtin_arm_vcvtr_f: 2501 case ARM::BI__builtin_arm_vcvtr_d: 2502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2503 case ARM::BI__builtin_arm_dmb: 2504 case ARM::BI__builtin_arm_dsb: 2505 case ARM::BI__builtin_arm_isb: 2506 case ARM::BI__builtin_arm_dbg: 2507 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2508 case ARM::BI__builtin_arm_cdp: 2509 case ARM::BI__builtin_arm_cdp2: 2510 case ARM::BI__builtin_arm_mcr: 2511 case ARM::BI__builtin_arm_mcr2: 2512 case ARM::BI__builtin_arm_mrc: 2513 case ARM::BI__builtin_arm_mrc2: 2514 case ARM::BI__builtin_arm_mcrr: 2515 case ARM::BI__builtin_arm_mcrr2: 2516 case ARM::BI__builtin_arm_mrrc: 2517 case ARM::BI__builtin_arm_mrrc2: 2518 case ARM::BI__builtin_arm_ldc: 2519 case ARM::BI__builtin_arm_ldcl: 2520 case ARM::BI__builtin_arm_ldc2: 2521 case ARM::BI__builtin_arm_ldc2l: 2522 case ARM::BI__builtin_arm_stc: 2523 case ARM::BI__builtin_arm_stcl: 2524 case ARM::BI__builtin_arm_stc2: 2525 case ARM::BI__builtin_arm_stc2l: 2526 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2527 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2528 /*WantCDE*/ false); 2529 } 2530 } 2531 2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2533 unsigned BuiltinID, 2534 CallExpr *TheCall) { 2535 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2536 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2537 BuiltinID == AArch64::BI__builtin_arm_strex || 2538 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2539 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2540 } 2541 2542 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2543 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2544 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2545 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2546 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2550 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2551 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2552 2553 // Memory Tagging Extensions (MTE) Intrinsics 2554 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2555 BuiltinID == AArch64::BI__builtin_arm_addg || 2556 BuiltinID == AArch64::BI__builtin_arm_gmi || 2557 BuiltinID == AArch64::BI__builtin_arm_ldg || 2558 BuiltinID == AArch64::BI__builtin_arm_stg || 2559 BuiltinID == AArch64::BI__builtin_arm_subp) { 2560 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2561 } 2562 2563 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2564 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2565 BuiltinID == AArch64::BI__builtin_arm_wsr || 2566 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2567 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2568 2569 // Only check the valid encoding range. Any constant in this range would be 2570 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2571 // an exception for incorrect registers. This matches MSVC behavior. 2572 if (BuiltinID == AArch64::BI_ReadStatusReg || 2573 BuiltinID == AArch64::BI_WriteStatusReg) 2574 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2575 2576 if (BuiltinID == AArch64::BI__getReg) 2577 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2578 2579 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2580 return true; 2581 2582 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2583 return true; 2584 2585 // For intrinsics which take an immediate value as part of the instruction, 2586 // range check them here. 2587 unsigned i = 0, l = 0, u = 0; 2588 switch (BuiltinID) { 2589 default: return false; 2590 case AArch64::BI__builtin_arm_dmb: 2591 case AArch64::BI__builtin_arm_dsb: 2592 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2593 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2594 } 2595 2596 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2597 } 2598 2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2600 if (Arg->getType()->getAsPlaceholderType()) 2601 return false; 2602 2603 // The first argument needs to be a record field access. 2604 // If it is an array element access, we delay decision 2605 // to BPF backend to check whether the access is a 2606 // field access or not. 2607 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2608 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2609 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2610 } 2611 2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2613 QualType VectorTy, QualType EltTy) { 2614 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2615 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2616 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2617 << Call->getSourceRange() << VectorEltTy << EltTy; 2618 return false; 2619 } 2620 return true; 2621 } 2622 2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2624 QualType ArgType = Arg->getType(); 2625 if (ArgType->getAsPlaceholderType()) 2626 return false; 2627 2628 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2629 // format: 2630 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2631 // 2. <type> var; 2632 // __builtin_preserve_type_info(var, flag); 2633 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2634 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2635 return false; 2636 2637 // Typedef type. 2638 if (ArgType->getAs<TypedefType>()) 2639 return true; 2640 2641 // Record type or Enum type. 2642 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2643 if (const auto *RT = Ty->getAs<RecordType>()) { 2644 if (!RT->getDecl()->getDeclName().isEmpty()) 2645 return true; 2646 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2647 if (!ET->getDecl()->getDeclName().isEmpty()) 2648 return true; 2649 } 2650 2651 return false; 2652 } 2653 2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2655 QualType ArgType = Arg->getType(); 2656 if (ArgType->getAsPlaceholderType()) 2657 return false; 2658 2659 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2660 // format: 2661 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2662 // flag); 2663 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2664 if (!UO) 2665 return false; 2666 2667 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2668 if (!CE) 2669 return false; 2670 if (CE->getCastKind() != CK_IntegralToPointer && 2671 CE->getCastKind() != CK_NullToPointer) 2672 return false; 2673 2674 // The integer must be from an EnumConstantDecl. 2675 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2676 if (!DR) 2677 return false; 2678 2679 const EnumConstantDecl *Enumerator = 2680 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2681 if (!Enumerator) 2682 return false; 2683 2684 // The type must be EnumType. 2685 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2686 const auto *ET = Ty->getAs<EnumType>(); 2687 if (!ET) 2688 return false; 2689 2690 // The enum value must be supported. 2691 for (auto *EDI : ET->getDecl()->enumerators()) { 2692 if (EDI == Enumerator) 2693 return true; 2694 } 2695 2696 return false; 2697 } 2698 2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2700 CallExpr *TheCall) { 2701 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2702 BuiltinID == BPF::BI__builtin_btf_type_id || 2703 BuiltinID == BPF::BI__builtin_preserve_type_info || 2704 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2705 "unexpected BPF builtin"); 2706 2707 if (checkArgCount(*this, TheCall, 2)) 2708 return true; 2709 2710 // The second argument needs to be a constant int 2711 Expr *Arg = TheCall->getArg(1); 2712 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2713 diag::kind kind; 2714 if (!Value) { 2715 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2716 kind = diag::err_preserve_field_info_not_const; 2717 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2718 kind = diag::err_btf_type_id_not_const; 2719 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2720 kind = diag::err_preserve_type_info_not_const; 2721 else 2722 kind = diag::err_preserve_enum_value_not_const; 2723 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2724 return true; 2725 } 2726 2727 // The first argument 2728 Arg = TheCall->getArg(0); 2729 bool InvalidArg = false; 2730 bool ReturnUnsignedInt = true; 2731 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2732 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2733 InvalidArg = true; 2734 kind = diag::err_preserve_field_info_not_field; 2735 } 2736 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2737 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2738 InvalidArg = true; 2739 kind = diag::err_preserve_type_info_invalid; 2740 } 2741 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2742 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2743 InvalidArg = true; 2744 kind = diag::err_preserve_enum_value_invalid; 2745 } 2746 ReturnUnsignedInt = false; 2747 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2748 ReturnUnsignedInt = false; 2749 } 2750 2751 if (InvalidArg) { 2752 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2753 return true; 2754 } 2755 2756 if (ReturnUnsignedInt) 2757 TheCall->setType(Context.UnsignedIntTy); 2758 else 2759 TheCall->setType(Context.UnsignedLongTy); 2760 return false; 2761 } 2762 2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2764 struct ArgInfo { 2765 uint8_t OpNum; 2766 bool IsSigned; 2767 uint8_t BitWidth; 2768 uint8_t Align; 2769 }; 2770 struct BuiltinInfo { 2771 unsigned BuiltinID; 2772 ArgInfo Infos[2]; 2773 }; 2774 2775 static BuiltinInfo Infos[] = { 2776 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2777 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2778 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2779 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2780 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2782 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2783 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2784 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2785 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2786 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2787 2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2799 2800 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2852 {{ 1, false, 6, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2860 {{ 1, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2867 { 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2869 { 2, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2871 { 3, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2873 { 3, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2890 {{ 2, false, 4, 0 }, 2891 { 3, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2893 {{ 2, false, 4, 0 }, 2894 { 3, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2896 {{ 2, false, 4, 0 }, 2897 { 3, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2899 {{ 2, false, 4, 0 }, 2900 { 3, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2912 { 2, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2914 { 2, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2924 {{ 1, false, 4, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2927 {{ 1, false, 4, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2948 {{ 3, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2953 {{ 3, false, 1, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2958 {{ 3, false, 1, 0 }} }, 2959 }; 2960 2961 // Use a dynamically initialized static to sort the table exactly once on 2962 // first run. 2963 static const bool SortOnce = 2964 (llvm::sort(Infos, 2965 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2966 return LHS.BuiltinID < RHS.BuiltinID; 2967 }), 2968 true); 2969 (void)SortOnce; 2970 2971 const BuiltinInfo *F = llvm::partition_point( 2972 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2973 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2974 return false; 2975 2976 bool Error = false; 2977 2978 for (const ArgInfo &A : F->Infos) { 2979 // Ignore empty ArgInfo elements. 2980 if (A.BitWidth == 0) 2981 continue; 2982 2983 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2984 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2985 if (!A.Align) { 2986 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2987 } else { 2988 unsigned M = 1 << A.Align; 2989 Min *= M; 2990 Max *= M; 2991 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2992 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2993 } 2994 } 2995 return Error; 2996 } 2997 2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2999 CallExpr *TheCall) { 3000 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3001 } 3002 3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3004 unsigned BuiltinID, CallExpr *TheCall) { 3005 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3006 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3007 } 3008 3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3010 CallExpr *TheCall) { 3011 3012 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3013 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3014 if (!TI.hasFeature("dsp")) 3015 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3016 } 3017 3018 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3019 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3020 if (!TI.hasFeature("dspr2")) 3021 return Diag(TheCall->getBeginLoc(), 3022 diag::err_mips_builtin_requires_dspr2); 3023 } 3024 3025 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3026 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3027 if (!TI.hasFeature("msa")) 3028 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3029 } 3030 3031 return false; 3032 } 3033 3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3036 // ordering for DSP is unspecified. MSA is ordered by the data format used 3037 // by the underlying instruction i.e., df/m, df/n and then by size. 3038 // 3039 // FIXME: The size tests here should instead be tablegen'd along with the 3040 // definitions from include/clang/Basic/BuiltinsMips.def. 3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3042 // be too. 3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3044 unsigned i = 0, l = 0, u = 0, m = 0; 3045 switch (BuiltinID) { 3046 default: return false; 3047 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3048 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3049 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3050 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3051 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3052 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3053 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3054 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3055 // df/m field. 3056 // These intrinsics take an unsigned 3 bit immediate. 3057 case Mips::BI__builtin_msa_bclri_b: 3058 case Mips::BI__builtin_msa_bnegi_b: 3059 case Mips::BI__builtin_msa_bseti_b: 3060 case Mips::BI__builtin_msa_sat_s_b: 3061 case Mips::BI__builtin_msa_sat_u_b: 3062 case Mips::BI__builtin_msa_slli_b: 3063 case Mips::BI__builtin_msa_srai_b: 3064 case Mips::BI__builtin_msa_srari_b: 3065 case Mips::BI__builtin_msa_srli_b: 3066 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3067 case Mips::BI__builtin_msa_binsli_b: 3068 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3069 // These intrinsics take an unsigned 4 bit immediate. 3070 case Mips::BI__builtin_msa_bclri_h: 3071 case Mips::BI__builtin_msa_bnegi_h: 3072 case Mips::BI__builtin_msa_bseti_h: 3073 case Mips::BI__builtin_msa_sat_s_h: 3074 case Mips::BI__builtin_msa_sat_u_h: 3075 case Mips::BI__builtin_msa_slli_h: 3076 case Mips::BI__builtin_msa_srai_h: 3077 case Mips::BI__builtin_msa_srari_h: 3078 case Mips::BI__builtin_msa_srli_h: 3079 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3080 case Mips::BI__builtin_msa_binsli_h: 3081 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3082 // These intrinsics take an unsigned 5 bit immediate. 3083 // The first block of intrinsics actually have an unsigned 5 bit field, 3084 // not a df/n field. 3085 case Mips::BI__builtin_msa_cfcmsa: 3086 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3087 case Mips::BI__builtin_msa_clei_u_b: 3088 case Mips::BI__builtin_msa_clei_u_h: 3089 case Mips::BI__builtin_msa_clei_u_w: 3090 case Mips::BI__builtin_msa_clei_u_d: 3091 case Mips::BI__builtin_msa_clti_u_b: 3092 case Mips::BI__builtin_msa_clti_u_h: 3093 case Mips::BI__builtin_msa_clti_u_w: 3094 case Mips::BI__builtin_msa_clti_u_d: 3095 case Mips::BI__builtin_msa_maxi_u_b: 3096 case Mips::BI__builtin_msa_maxi_u_h: 3097 case Mips::BI__builtin_msa_maxi_u_w: 3098 case Mips::BI__builtin_msa_maxi_u_d: 3099 case Mips::BI__builtin_msa_mini_u_b: 3100 case Mips::BI__builtin_msa_mini_u_h: 3101 case Mips::BI__builtin_msa_mini_u_w: 3102 case Mips::BI__builtin_msa_mini_u_d: 3103 case Mips::BI__builtin_msa_addvi_b: 3104 case Mips::BI__builtin_msa_addvi_h: 3105 case Mips::BI__builtin_msa_addvi_w: 3106 case Mips::BI__builtin_msa_addvi_d: 3107 case Mips::BI__builtin_msa_bclri_w: 3108 case Mips::BI__builtin_msa_bnegi_w: 3109 case Mips::BI__builtin_msa_bseti_w: 3110 case Mips::BI__builtin_msa_sat_s_w: 3111 case Mips::BI__builtin_msa_sat_u_w: 3112 case Mips::BI__builtin_msa_slli_w: 3113 case Mips::BI__builtin_msa_srai_w: 3114 case Mips::BI__builtin_msa_srari_w: 3115 case Mips::BI__builtin_msa_srli_w: 3116 case Mips::BI__builtin_msa_srlri_w: 3117 case Mips::BI__builtin_msa_subvi_b: 3118 case Mips::BI__builtin_msa_subvi_h: 3119 case Mips::BI__builtin_msa_subvi_w: 3120 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3121 case Mips::BI__builtin_msa_binsli_w: 3122 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3123 // These intrinsics take an unsigned 6 bit immediate. 3124 case Mips::BI__builtin_msa_bclri_d: 3125 case Mips::BI__builtin_msa_bnegi_d: 3126 case Mips::BI__builtin_msa_bseti_d: 3127 case Mips::BI__builtin_msa_sat_s_d: 3128 case Mips::BI__builtin_msa_sat_u_d: 3129 case Mips::BI__builtin_msa_slli_d: 3130 case Mips::BI__builtin_msa_srai_d: 3131 case Mips::BI__builtin_msa_srari_d: 3132 case Mips::BI__builtin_msa_srli_d: 3133 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3134 case Mips::BI__builtin_msa_binsli_d: 3135 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3136 // These intrinsics take a signed 5 bit immediate. 3137 case Mips::BI__builtin_msa_ceqi_b: 3138 case Mips::BI__builtin_msa_ceqi_h: 3139 case Mips::BI__builtin_msa_ceqi_w: 3140 case Mips::BI__builtin_msa_ceqi_d: 3141 case Mips::BI__builtin_msa_clti_s_b: 3142 case Mips::BI__builtin_msa_clti_s_h: 3143 case Mips::BI__builtin_msa_clti_s_w: 3144 case Mips::BI__builtin_msa_clti_s_d: 3145 case Mips::BI__builtin_msa_clei_s_b: 3146 case Mips::BI__builtin_msa_clei_s_h: 3147 case Mips::BI__builtin_msa_clei_s_w: 3148 case Mips::BI__builtin_msa_clei_s_d: 3149 case Mips::BI__builtin_msa_maxi_s_b: 3150 case Mips::BI__builtin_msa_maxi_s_h: 3151 case Mips::BI__builtin_msa_maxi_s_w: 3152 case Mips::BI__builtin_msa_maxi_s_d: 3153 case Mips::BI__builtin_msa_mini_s_b: 3154 case Mips::BI__builtin_msa_mini_s_h: 3155 case Mips::BI__builtin_msa_mini_s_w: 3156 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3157 // These intrinsics take an unsigned 8 bit immediate. 3158 case Mips::BI__builtin_msa_andi_b: 3159 case Mips::BI__builtin_msa_nori_b: 3160 case Mips::BI__builtin_msa_ori_b: 3161 case Mips::BI__builtin_msa_shf_b: 3162 case Mips::BI__builtin_msa_shf_h: 3163 case Mips::BI__builtin_msa_shf_w: 3164 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3165 case Mips::BI__builtin_msa_bseli_b: 3166 case Mips::BI__builtin_msa_bmnzi_b: 3167 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3168 // df/n format 3169 // These intrinsics take an unsigned 4 bit immediate. 3170 case Mips::BI__builtin_msa_copy_s_b: 3171 case Mips::BI__builtin_msa_copy_u_b: 3172 case Mips::BI__builtin_msa_insve_b: 3173 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3174 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3175 // These intrinsics take an unsigned 3 bit immediate. 3176 case Mips::BI__builtin_msa_copy_s_h: 3177 case Mips::BI__builtin_msa_copy_u_h: 3178 case Mips::BI__builtin_msa_insve_h: 3179 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3180 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3181 // These intrinsics take an unsigned 2 bit immediate. 3182 case Mips::BI__builtin_msa_copy_s_w: 3183 case Mips::BI__builtin_msa_copy_u_w: 3184 case Mips::BI__builtin_msa_insve_w: 3185 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3186 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3187 // These intrinsics take an unsigned 1 bit immediate. 3188 case Mips::BI__builtin_msa_copy_s_d: 3189 case Mips::BI__builtin_msa_copy_u_d: 3190 case Mips::BI__builtin_msa_insve_d: 3191 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3192 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3193 // Memory offsets and immediate loads. 3194 // These intrinsics take a signed 10 bit immediate. 3195 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3196 case Mips::BI__builtin_msa_ldi_h: 3197 case Mips::BI__builtin_msa_ldi_w: 3198 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3199 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3200 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3201 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3202 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3203 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3204 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3205 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3206 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3207 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3208 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3209 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3210 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3211 } 3212 3213 if (!m) 3214 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3215 3216 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3217 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3218 } 3219 3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3221 /// advancing the pointer over the consumed characters. The decoded type is 3222 /// returned. If the decoded type represents a constant integer with a 3223 /// constraint on its value then Mask is set to that value. The type descriptors 3224 /// used in Str are specific to PPC MMA builtins and are documented in the file 3225 /// defining the PPC builtins. 3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3227 unsigned &Mask) { 3228 bool RequireICE = false; 3229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3230 switch (*Str++) { 3231 case 'V': 3232 return Context.getVectorType(Context.UnsignedCharTy, 16, 3233 VectorType::VectorKind::AltiVecVector); 3234 case 'i': { 3235 char *End; 3236 unsigned size = strtoul(Str, &End, 10); 3237 assert(End != Str && "Missing constant parameter constraint"); 3238 Str = End; 3239 Mask = size; 3240 return Context.IntTy; 3241 } 3242 case 'W': { 3243 char *End; 3244 unsigned size = strtoul(Str, &End, 10); 3245 assert(End != Str && "Missing PowerPC MMA type size"); 3246 Str = End; 3247 QualType Type; 3248 switch (size) { 3249 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3250 case size: Type = Context.Id##Ty; break; 3251 #include "clang/Basic/PPCTypes.def" 3252 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3253 } 3254 bool CheckVectorArgs = false; 3255 while (!CheckVectorArgs) { 3256 switch (*Str++) { 3257 case '*': 3258 Type = Context.getPointerType(Type); 3259 break; 3260 case 'C': 3261 Type = Type.withConst(); 3262 break; 3263 default: 3264 CheckVectorArgs = true; 3265 --Str; 3266 break; 3267 } 3268 } 3269 return Type; 3270 } 3271 default: 3272 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3273 } 3274 } 3275 3276 static bool isPPC_64Builtin(unsigned BuiltinID) { 3277 // These builtins only work on PPC 64bit targets. 3278 switch (BuiltinID) { 3279 case PPC::BI__builtin_divde: 3280 case PPC::BI__builtin_divdeu: 3281 case PPC::BI__builtin_bpermd: 3282 case PPC::BI__builtin_ppc_ldarx: 3283 case PPC::BI__builtin_ppc_stdcx: 3284 case PPC::BI__builtin_ppc_tdw: 3285 case PPC::BI__builtin_ppc_trapd: 3286 case PPC::BI__builtin_ppc_cmpeqb: 3287 case PPC::BI__builtin_ppc_setb: 3288 case PPC::BI__builtin_ppc_mulhd: 3289 case PPC::BI__builtin_ppc_mulhdu: 3290 case PPC::BI__builtin_ppc_maddhd: 3291 case PPC::BI__builtin_ppc_maddhdu: 3292 case PPC::BI__builtin_ppc_maddld: 3293 case PPC::BI__builtin_ppc_load8r: 3294 case PPC::BI__builtin_ppc_store8r: 3295 case PPC::BI__builtin_ppc_insert_exp: 3296 case PPC::BI__builtin_ppc_extract_sig: 3297 case PPC::BI__builtin_ppc_addex: 3298 case PPC::BI__builtin_darn: 3299 case PPC::BI__builtin_darn_raw: 3300 case PPC::BI__builtin_ppc_compare_and_swaplp: 3301 case PPC::BI__builtin_ppc_fetch_and_addlp: 3302 case PPC::BI__builtin_ppc_fetch_and_andlp: 3303 case PPC::BI__builtin_ppc_fetch_and_orlp: 3304 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3305 return true; 3306 } 3307 return false; 3308 } 3309 3310 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3311 StringRef FeatureToCheck, unsigned DiagID, 3312 StringRef DiagArg = "") { 3313 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3314 return false; 3315 3316 if (DiagArg.empty()) 3317 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3318 else 3319 S.Diag(TheCall->getBeginLoc(), DiagID) 3320 << DiagArg << TheCall->getSourceRange(); 3321 3322 return true; 3323 } 3324 3325 /// Returns true if the argument consists of one contiguous run of 1s with any 3326 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3327 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3328 /// since all 1s are not contiguous. 3329 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3330 llvm::APSInt Result; 3331 // We can't check the value of a dependent argument. 3332 Expr *Arg = TheCall->getArg(ArgNum); 3333 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3334 return false; 3335 3336 // Check constant-ness first. 3337 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3338 return true; 3339 3340 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3341 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3342 return false; 3343 3344 return Diag(TheCall->getBeginLoc(), 3345 diag::err_argument_not_contiguous_bit_field) 3346 << ArgNum << Arg->getSourceRange(); 3347 } 3348 3349 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3350 CallExpr *TheCall) { 3351 unsigned i = 0, l = 0, u = 0; 3352 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3353 llvm::APSInt Result; 3354 3355 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3356 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3357 << TheCall->getSourceRange(); 3358 3359 switch (BuiltinID) { 3360 default: return false; 3361 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3362 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3363 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3364 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3365 case PPC::BI__builtin_altivec_dss: 3366 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3367 case PPC::BI__builtin_tbegin: 3368 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3369 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3370 case PPC::BI__builtin_tabortwc: 3371 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3372 case PPC::BI__builtin_tabortwci: 3373 case PPC::BI__builtin_tabortdci: 3374 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3375 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3376 case PPC::BI__builtin_altivec_dst: 3377 case PPC::BI__builtin_altivec_dstt: 3378 case PPC::BI__builtin_altivec_dstst: 3379 case PPC::BI__builtin_altivec_dststt: 3380 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3381 case PPC::BI__builtin_vsx_xxpermdi: 3382 case PPC::BI__builtin_vsx_xxsldwi: 3383 return SemaBuiltinVSX(TheCall); 3384 case PPC::BI__builtin_divwe: 3385 case PPC::BI__builtin_divweu: 3386 case PPC::BI__builtin_divde: 3387 case PPC::BI__builtin_divdeu: 3388 return SemaFeatureCheck(*this, TheCall, "extdiv", 3389 diag::err_ppc_builtin_only_on_arch, "7"); 3390 case PPC::BI__builtin_bpermd: 3391 return SemaFeatureCheck(*this, TheCall, "bpermd", 3392 diag::err_ppc_builtin_only_on_arch, "7"); 3393 case PPC::BI__builtin_unpack_vector_int128: 3394 return SemaFeatureCheck(*this, TheCall, "vsx", 3395 diag::err_ppc_builtin_only_on_arch, "7") || 3396 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3397 case PPC::BI__builtin_pack_vector_int128: 3398 return SemaFeatureCheck(*this, TheCall, "vsx", 3399 diag::err_ppc_builtin_only_on_arch, "7"); 3400 case PPC::BI__builtin_altivec_vgnb: 3401 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3402 case PPC::BI__builtin_altivec_vec_replace_elt: 3403 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3404 QualType VecTy = TheCall->getArg(0)->getType(); 3405 QualType EltTy = TheCall->getArg(1)->getType(); 3406 unsigned Width = Context.getIntWidth(EltTy); 3407 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3408 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3409 } 3410 case PPC::BI__builtin_vsx_xxeval: 3411 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3412 case PPC::BI__builtin_altivec_vsldbi: 3413 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3414 case PPC::BI__builtin_altivec_vsrdbi: 3415 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3416 case PPC::BI__builtin_vsx_xxpermx: 3417 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3418 case PPC::BI__builtin_ppc_tw: 3419 case PPC::BI__builtin_ppc_tdw: 3420 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3421 case PPC::BI__builtin_ppc_cmpeqb: 3422 case PPC::BI__builtin_ppc_setb: 3423 case PPC::BI__builtin_ppc_maddhd: 3424 case PPC::BI__builtin_ppc_maddhdu: 3425 case PPC::BI__builtin_ppc_maddld: 3426 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3427 diag::err_ppc_builtin_only_on_arch, "9"); 3428 case PPC::BI__builtin_ppc_cmprb: 3429 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3430 diag::err_ppc_builtin_only_on_arch, "9") || 3431 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3432 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3433 // be a constant that represents a contiguous bit field. 3434 case PPC::BI__builtin_ppc_rlwnm: 3435 return SemaBuiltinConstantArg(TheCall, 1, Result) || 3436 SemaValueIsRunOfOnes(TheCall, 2); 3437 case PPC::BI__builtin_ppc_rlwimi: 3438 case PPC::BI__builtin_ppc_rldimi: 3439 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3440 SemaValueIsRunOfOnes(TheCall, 3); 3441 case PPC::BI__builtin_ppc_extract_exp: 3442 case PPC::BI__builtin_ppc_extract_sig: 3443 case PPC::BI__builtin_ppc_insert_exp: 3444 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3445 diag::err_ppc_builtin_only_on_arch, "9"); 3446 case PPC::BI__builtin_ppc_addex: { 3447 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3448 diag::err_ppc_builtin_only_on_arch, "9") || 3449 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3450 return true; 3451 // Output warning for reserved values 1 to 3. 3452 int ArgValue = 3453 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3454 if (ArgValue != 0) 3455 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3456 << ArgValue; 3457 return false; 3458 } 3459 case PPC::BI__builtin_ppc_mtfsb0: 3460 case PPC::BI__builtin_ppc_mtfsb1: 3461 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3462 case PPC::BI__builtin_ppc_mtfsf: 3463 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3464 case PPC::BI__builtin_ppc_mtfsfi: 3465 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3466 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3467 case PPC::BI__builtin_ppc_alignx: 3468 return SemaBuiltinConstantArgPower2(TheCall, 0); 3469 case PPC::BI__builtin_ppc_rdlam: 3470 return SemaValueIsRunOfOnes(TheCall, 2); 3471 case PPC::BI__builtin_ppc_icbt: 3472 case PPC::BI__builtin_ppc_sthcx: 3473 case PPC::BI__builtin_ppc_stbcx: 3474 case PPC::BI__builtin_ppc_lharx: 3475 case PPC::BI__builtin_ppc_lbarx: 3476 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3477 diag::err_ppc_builtin_only_on_arch, "8"); 3478 case PPC::BI__builtin_vsx_ldrmb: 3479 case PPC::BI__builtin_vsx_strmb: 3480 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3481 diag::err_ppc_builtin_only_on_arch, "8") || 3482 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3483 case PPC::BI__builtin_altivec_vcntmbb: 3484 case PPC::BI__builtin_altivec_vcntmbh: 3485 case PPC::BI__builtin_altivec_vcntmbw: 3486 case PPC::BI__builtin_altivec_vcntmbd: 3487 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3488 case PPC::BI__builtin_darn: 3489 case PPC::BI__builtin_darn_raw: 3490 case PPC::BI__builtin_darn_32: 3491 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3492 diag::err_ppc_builtin_only_on_arch, "9"); 3493 case PPC::BI__builtin_vsx_xxgenpcvbm: 3494 case PPC::BI__builtin_vsx_xxgenpcvhm: 3495 case PPC::BI__builtin_vsx_xxgenpcvwm: 3496 case PPC::BI__builtin_vsx_xxgenpcvdm: 3497 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3498 case PPC::BI__builtin_ppc_compare_exp_uo: 3499 case PPC::BI__builtin_ppc_compare_exp_lt: 3500 case PPC::BI__builtin_ppc_compare_exp_gt: 3501 case PPC::BI__builtin_ppc_compare_exp_eq: 3502 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3503 diag::err_ppc_builtin_only_on_arch, "9") || 3504 SemaFeatureCheck(*this, TheCall, "vsx", 3505 diag::err_ppc_builtin_requires_vsx); 3506 case PPC::BI__builtin_ppc_test_data_class: { 3507 // Check if the first argument of the __builtin_ppc_test_data_class call is 3508 // valid. The argument must be either a 'float' or a 'double'. 3509 QualType ArgType = TheCall->getArg(0)->getType(); 3510 if (ArgType != QualType(Context.FloatTy) && 3511 ArgType != QualType(Context.DoubleTy)) 3512 return Diag(TheCall->getBeginLoc(), 3513 diag::err_ppc_invalid_test_data_class_type); 3514 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3515 diag::err_ppc_builtin_only_on_arch, "9") || 3516 SemaFeatureCheck(*this, TheCall, "vsx", 3517 diag::err_ppc_builtin_requires_vsx) || 3518 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3519 } 3520 case PPC::BI__builtin_ppc_load8r: 3521 case PPC::BI__builtin_ppc_store8r: 3522 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3523 diag::err_ppc_builtin_only_on_arch, "7"); 3524 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3525 case PPC::BI__builtin_##Name: \ 3526 return SemaBuiltinPPCMMACall(TheCall, Types); 3527 #include "clang/Basic/BuiltinsPPC.def" 3528 } 3529 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3530 } 3531 3532 // Check if the given type is a non-pointer PPC MMA type. This function is used 3533 // in Sema to prevent invalid uses of restricted PPC MMA types. 3534 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3535 if (Type->isPointerType() || Type->isArrayType()) 3536 return false; 3537 3538 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3539 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3540 if (false 3541 #include "clang/Basic/PPCTypes.def" 3542 ) { 3543 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3544 return true; 3545 } 3546 return false; 3547 } 3548 3549 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3550 CallExpr *TheCall) { 3551 // position of memory order and scope arguments in the builtin 3552 unsigned OrderIndex, ScopeIndex; 3553 switch (BuiltinID) { 3554 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3555 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3556 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3557 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3558 OrderIndex = 2; 3559 ScopeIndex = 3; 3560 break; 3561 case AMDGPU::BI__builtin_amdgcn_fence: 3562 OrderIndex = 0; 3563 ScopeIndex = 1; 3564 break; 3565 default: 3566 return false; 3567 } 3568 3569 ExprResult Arg = TheCall->getArg(OrderIndex); 3570 auto ArgExpr = Arg.get(); 3571 Expr::EvalResult ArgResult; 3572 3573 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3574 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3575 << ArgExpr->getType(); 3576 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3577 3578 // Check validity of memory ordering as per C11 / C++11's memody model. 3579 // Only fence needs check. Atomic dec/inc allow all memory orders. 3580 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3581 return Diag(ArgExpr->getBeginLoc(), 3582 diag::warn_atomic_op_has_invalid_memory_order) 3583 << ArgExpr->getSourceRange(); 3584 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3585 case llvm::AtomicOrderingCABI::relaxed: 3586 case llvm::AtomicOrderingCABI::consume: 3587 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3588 return Diag(ArgExpr->getBeginLoc(), 3589 diag::warn_atomic_op_has_invalid_memory_order) 3590 << ArgExpr->getSourceRange(); 3591 break; 3592 case llvm::AtomicOrderingCABI::acquire: 3593 case llvm::AtomicOrderingCABI::release: 3594 case llvm::AtomicOrderingCABI::acq_rel: 3595 case llvm::AtomicOrderingCABI::seq_cst: 3596 break; 3597 } 3598 3599 Arg = TheCall->getArg(ScopeIndex); 3600 ArgExpr = Arg.get(); 3601 Expr::EvalResult ArgResult1; 3602 // Check that sync scope is a constant literal 3603 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3604 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3605 << ArgExpr->getType(); 3606 3607 return false; 3608 } 3609 3610 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3611 llvm::APSInt Result; 3612 3613 // We can't check the value of a dependent argument. 3614 Expr *Arg = TheCall->getArg(ArgNum); 3615 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3616 return false; 3617 3618 // Check constant-ness first. 3619 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3620 return true; 3621 3622 int64_t Val = Result.getSExtValue(); 3623 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3624 return false; 3625 3626 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3627 << Arg->getSourceRange(); 3628 } 3629 3630 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3631 unsigned BuiltinID, 3632 CallExpr *TheCall) { 3633 // CodeGenFunction can also detect this, but this gives a better error 3634 // message. 3635 bool FeatureMissing = false; 3636 SmallVector<StringRef> ReqFeatures; 3637 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3638 Features.split(ReqFeatures, ','); 3639 3640 // Check if each required feature is included 3641 for (StringRef F : ReqFeatures) { 3642 if (TI.hasFeature(F)) 3643 continue; 3644 3645 // If the feature is 64bit, alter the string so it will print better in 3646 // the diagnostic. 3647 if (F == "64bit") 3648 F = "RV64"; 3649 3650 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3651 F.consume_front("experimental-"); 3652 std::string FeatureStr = F.str(); 3653 FeatureStr[0] = std::toupper(FeatureStr[0]); 3654 3655 // Error message 3656 FeatureMissing = true; 3657 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3658 << TheCall->getSourceRange() << StringRef(FeatureStr); 3659 } 3660 3661 if (FeatureMissing) 3662 return true; 3663 3664 switch (BuiltinID) { 3665 case RISCV::BI__builtin_rvv_vsetvli: 3666 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3667 CheckRISCVLMUL(TheCall, 2); 3668 case RISCV::BI__builtin_rvv_vsetvlimax: 3669 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3670 CheckRISCVLMUL(TheCall, 1); 3671 case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1: 3672 case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1: 3673 case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1: 3674 case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1: 3675 case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1: 3676 case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1: 3677 case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1: 3678 case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1: 3679 case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1: 3680 case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1: 3681 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2: 3682 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2: 3683 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2: 3684 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2: 3685 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2: 3686 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2: 3687 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2: 3688 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2: 3689 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2: 3690 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2: 3691 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4: 3692 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4: 3693 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4: 3694 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4: 3695 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4: 3696 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4: 3697 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4: 3698 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4: 3699 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4: 3700 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4: 3701 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3702 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1: 3703 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1: 3704 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1: 3705 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1: 3706 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1: 3707 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1: 3708 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1: 3709 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1: 3710 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1: 3711 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1: 3712 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2: 3713 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2: 3714 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2: 3715 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2: 3716 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2: 3717 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2: 3718 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2: 3719 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2: 3720 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2: 3721 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2: 3722 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3723 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1: 3724 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1: 3725 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1: 3726 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1: 3727 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1: 3728 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1: 3729 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1: 3730 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1: 3731 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1: 3732 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1: 3733 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3734 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2: 3735 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2: 3736 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2: 3737 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2: 3738 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2: 3739 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2: 3740 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2: 3741 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2: 3742 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2: 3743 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2: 3744 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4: 3745 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4: 3746 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4: 3747 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4: 3748 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4: 3749 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4: 3750 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4: 3751 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4: 3752 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4: 3753 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4: 3754 case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8: 3755 case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8: 3756 case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8: 3757 case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8: 3758 case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8: 3759 case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8: 3760 case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8: 3761 case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8: 3762 case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8: 3763 case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8: 3764 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3765 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4: 3766 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4: 3767 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4: 3768 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4: 3769 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4: 3770 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4: 3771 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4: 3772 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4: 3773 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4: 3774 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4: 3775 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8: 3776 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8: 3777 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8: 3778 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8: 3779 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8: 3780 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8: 3781 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8: 3782 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8: 3783 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8: 3784 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8: 3785 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3786 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8: 3787 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8: 3788 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8: 3789 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8: 3790 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8: 3791 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8: 3792 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8: 3793 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8: 3794 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8: 3795 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8: 3796 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3797 } 3798 3799 return false; 3800 } 3801 3802 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3803 CallExpr *TheCall) { 3804 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3805 Expr *Arg = TheCall->getArg(0); 3806 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3807 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3808 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3809 << Arg->getSourceRange(); 3810 } 3811 3812 // For intrinsics which take an immediate value as part of the instruction, 3813 // range check them here. 3814 unsigned i = 0, l = 0, u = 0; 3815 switch (BuiltinID) { 3816 default: return false; 3817 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3818 case SystemZ::BI__builtin_s390_verimb: 3819 case SystemZ::BI__builtin_s390_verimh: 3820 case SystemZ::BI__builtin_s390_verimf: 3821 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3822 case SystemZ::BI__builtin_s390_vfaeb: 3823 case SystemZ::BI__builtin_s390_vfaeh: 3824 case SystemZ::BI__builtin_s390_vfaef: 3825 case SystemZ::BI__builtin_s390_vfaebs: 3826 case SystemZ::BI__builtin_s390_vfaehs: 3827 case SystemZ::BI__builtin_s390_vfaefs: 3828 case SystemZ::BI__builtin_s390_vfaezb: 3829 case SystemZ::BI__builtin_s390_vfaezh: 3830 case SystemZ::BI__builtin_s390_vfaezf: 3831 case SystemZ::BI__builtin_s390_vfaezbs: 3832 case SystemZ::BI__builtin_s390_vfaezhs: 3833 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3834 case SystemZ::BI__builtin_s390_vfisb: 3835 case SystemZ::BI__builtin_s390_vfidb: 3836 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3837 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3838 case SystemZ::BI__builtin_s390_vftcisb: 3839 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3840 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3841 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3842 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3843 case SystemZ::BI__builtin_s390_vstrcb: 3844 case SystemZ::BI__builtin_s390_vstrch: 3845 case SystemZ::BI__builtin_s390_vstrcf: 3846 case SystemZ::BI__builtin_s390_vstrczb: 3847 case SystemZ::BI__builtin_s390_vstrczh: 3848 case SystemZ::BI__builtin_s390_vstrczf: 3849 case SystemZ::BI__builtin_s390_vstrcbs: 3850 case SystemZ::BI__builtin_s390_vstrchs: 3851 case SystemZ::BI__builtin_s390_vstrcfs: 3852 case SystemZ::BI__builtin_s390_vstrczbs: 3853 case SystemZ::BI__builtin_s390_vstrczhs: 3854 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3855 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3856 case SystemZ::BI__builtin_s390_vfminsb: 3857 case SystemZ::BI__builtin_s390_vfmaxsb: 3858 case SystemZ::BI__builtin_s390_vfmindb: 3859 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3860 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3861 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3862 case SystemZ::BI__builtin_s390_vclfnhs: 3863 case SystemZ::BI__builtin_s390_vclfnls: 3864 case SystemZ::BI__builtin_s390_vcfn: 3865 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3866 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3867 } 3868 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3869 } 3870 3871 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3872 /// This checks that the target supports __builtin_cpu_supports and 3873 /// that the string argument is constant and valid. 3874 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3875 CallExpr *TheCall) { 3876 Expr *Arg = TheCall->getArg(0); 3877 3878 // Check if the argument is a string literal. 3879 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3880 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3881 << Arg->getSourceRange(); 3882 3883 // Check the contents of the string. 3884 StringRef Feature = 3885 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3886 if (!TI.validateCpuSupports(Feature)) 3887 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3888 << Arg->getSourceRange(); 3889 return false; 3890 } 3891 3892 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3893 /// This checks that the target supports __builtin_cpu_is and 3894 /// that the string argument is constant and valid. 3895 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3896 Expr *Arg = TheCall->getArg(0); 3897 3898 // Check if the argument is a string literal. 3899 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3900 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3901 << Arg->getSourceRange(); 3902 3903 // Check the contents of the string. 3904 StringRef Feature = 3905 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3906 if (!TI.validateCpuIs(Feature)) 3907 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3908 << Arg->getSourceRange(); 3909 return false; 3910 } 3911 3912 // Check if the rounding mode is legal. 3913 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3914 // Indicates if this instruction has rounding control or just SAE. 3915 bool HasRC = false; 3916 3917 unsigned ArgNum = 0; 3918 switch (BuiltinID) { 3919 default: 3920 return false; 3921 case X86::BI__builtin_ia32_vcvttsd2si32: 3922 case X86::BI__builtin_ia32_vcvttsd2si64: 3923 case X86::BI__builtin_ia32_vcvttsd2usi32: 3924 case X86::BI__builtin_ia32_vcvttsd2usi64: 3925 case X86::BI__builtin_ia32_vcvttss2si32: 3926 case X86::BI__builtin_ia32_vcvttss2si64: 3927 case X86::BI__builtin_ia32_vcvttss2usi32: 3928 case X86::BI__builtin_ia32_vcvttss2usi64: 3929 case X86::BI__builtin_ia32_vcvttsh2si32: 3930 case X86::BI__builtin_ia32_vcvttsh2si64: 3931 case X86::BI__builtin_ia32_vcvttsh2usi32: 3932 case X86::BI__builtin_ia32_vcvttsh2usi64: 3933 ArgNum = 1; 3934 break; 3935 case X86::BI__builtin_ia32_maxpd512: 3936 case X86::BI__builtin_ia32_maxps512: 3937 case X86::BI__builtin_ia32_minpd512: 3938 case X86::BI__builtin_ia32_minps512: 3939 case X86::BI__builtin_ia32_maxph512: 3940 case X86::BI__builtin_ia32_minph512: 3941 ArgNum = 2; 3942 break; 3943 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3944 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3945 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3946 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3947 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3948 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3949 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3950 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3951 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3952 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3953 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3954 case X86::BI__builtin_ia32_vcvttph2w512_mask: 3955 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 3956 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 3957 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 3958 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 3959 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 3960 case X86::BI__builtin_ia32_exp2pd_mask: 3961 case X86::BI__builtin_ia32_exp2ps_mask: 3962 case X86::BI__builtin_ia32_getexppd512_mask: 3963 case X86::BI__builtin_ia32_getexpps512_mask: 3964 case X86::BI__builtin_ia32_getexpph512_mask: 3965 case X86::BI__builtin_ia32_rcp28pd_mask: 3966 case X86::BI__builtin_ia32_rcp28ps_mask: 3967 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3968 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3969 case X86::BI__builtin_ia32_vcomisd: 3970 case X86::BI__builtin_ia32_vcomiss: 3971 case X86::BI__builtin_ia32_vcomish: 3972 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3973 ArgNum = 3; 3974 break; 3975 case X86::BI__builtin_ia32_cmppd512_mask: 3976 case X86::BI__builtin_ia32_cmpps512_mask: 3977 case X86::BI__builtin_ia32_cmpsd_mask: 3978 case X86::BI__builtin_ia32_cmpss_mask: 3979 case X86::BI__builtin_ia32_cmpsh_mask: 3980 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 3981 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 3982 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3983 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3984 case X86::BI__builtin_ia32_getexpss128_round_mask: 3985 case X86::BI__builtin_ia32_getexpsh128_round_mask: 3986 case X86::BI__builtin_ia32_getmantpd512_mask: 3987 case X86::BI__builtin_ia32_getmantps512_mask: 3988 case X86::BI__builtin_ia32_getmantph512_mask: 3989 case X86::BI__builtin_ia32_maxsd_round_mask: 3990 case X86::BI__builtin_ia32_maxss_round_mask: 3991 case X86::BI__builtin_ia32_maxsh_round_mask: 3992 case X86::BI__builtin_ia32_minsd_round_mask: 3993 case X86::BI__builtin_ia32_minss_round_mask: 3994 case X86::BI__builtin_ia32_minsh_round_mask: 3995 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3996 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3997 case X86::BI__builtin_ia32_reducepd512_mask: 3998 case X86::BI__builtin_ia32_reduceps512_mask: 3999 case X86::BI__builtin_ia32_reduceph512_mask: 4000 case X86::BI__builtin_ia32_rndscalepd_mask: 4001 case X86::BI__builtin_ia32_rndscaleps_mask: 4002 case X86::BI__builtin_ia32_rndscaleph_mask: 4003 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4004 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4005 ArgNum = 4; 4006 break; 4007 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4008 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4009 case X86::BI__builtin_ia32_fixupimmps512_mask: 4010 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4011 case X86::BI__builtin_ia32_fixupimmsd_mask: 4012 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4013 case X86::BI__builtin_ia32_fixupimmss_mask: 4014 case X86::BI__builtin_ia32_fixupimmss_maskz: 4015 case X86::BI__builtin_ia32_getmantsd_round_mask: 4016 case X86::BI__builtin_ia32_getmantss_round_mask: 4017 case X86::BI__builtin_ia32_getmantsh_round_mask: 4018 case X86::BI__builtin_ia32_rangepd512_mask: 4019 case X86::BI__builtin_ia32_rangeps512_mask: 4020 case X86::BI__builtin_ia32_rangesd128_round_mask: 4021 case X86::BI__builtin_ia32_rangess128_round_mask: 4022 case X86::BI__builtin_ia32_reducesd_mask: 4023 case X86::BI__builtin_ia32_reducess_mask: 4024 case X86::BI__builtin_ia32_reducesh_mask: 4025 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4026 case X86::BI__builtin_ia32_rndscaless_round_mask: 4027 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4028 ArgNum = 5; 4029 break; 4030 case X86::BI__builtin_ia32_vcvtsd2si64: 4031 case X86::BI__builtin_ia32_vcvtsd2si32: 4032 case X86::BI__builtin_ia32_vcvtsd2usi32: 4033 case X86::BI__builtin_ia32_vcvtsd2usi64: 4034 case X86::BI__builtin_ia32_vcvtss2si32: 4035 case X86::BI__builtin_ia32_vcvtss2si64: 4036 case X86::BI__builtin_ia32_vcvtss2usi32: 4037 case X86::BI__builtin_ia32_vcvtss2usi64: 4038 case X86::BI__builtin_ia32_vcvtsh2si32: 4039 case X86::BI__builtin_ia32_vcvtsh2si64: 4040 case X86::BI__builtin_ia32_vcvtsh2usi32: 4041 case X86::BI__builtin_ia32_vcvtsh2usi64: 4042 case X86::BI__builtin_ia32_sqrtpd512: 4043 case X86::BI__builtin_ia32_sqrtps512: 4044 case X86::BI__builtin_ia32_sqrtph512: 4045 ArgNum = 1; 4046 HasRC = true; 4047 break; 4048 case X86::BI__builtin_ia32_addph512: 4049 case X86::BI__builtin_ia32_divph512: 4050 case X86::BI__builtin_ia32_mulph512: 4051 case X86::BI__builtin_ia32_subph512: 4052 case X86::BI__builtin_ia32_addpd512: 4053 case X86::BI__builtin_ia32_addps512: 4054 case X86::BI__builtin_ia32_divpd512: 4055 case X86::BI__builtin_ia32_divps512: 4056 case X86::BI__builtin_ia32_mulpd512: 4057 case X86::BI__builtin_ia32_mulps512: 4058 case X86::BI__builtin_ia32_subpd512: 4059 case X86::BI__builtin_ia32_subps512: 4060 case X86::BI__builtin_ia32_cvtsi2sd64: 4061 case X86::BI__builtin_ia32_cvtsi2ss32: 4062 case X86::BI__builtin_ia32_cvtsi2ss64: 4063 case X86::BI__builtin_ia32_cvtusi2sd64: 4064 case X86::BI__builtin_ia32_cvtusi2ss32: 4065 case X86::BI__builtin_ia32_cvtusi2ss64: 4066 case X86::BI__builtin_ia32_vcvtusi2sh: 4067 case X86::BI__builtin_ia32_vcvtusi642sh: 4068 case X86::BI__builtin_ia32_vcvtsi2sh: 4069 case X86::BI__builtin_ia32_vcvtsi642sh: 4070 ArgNum = 2; 4071 HasRC = true; 4072 break; 4073 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4074 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4075 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4076 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4077 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4078 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4079 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4080 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4081 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4082 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4083 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4084 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4085 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4086 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4087 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4088 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4089 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4090 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4091 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4092 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4093 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4094 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4095 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4096 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4097 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4098 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4099 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4100 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4101 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4102 ArgNum = 3; 4103 HasRC = true; 4104 break; 4105 case X86::BI__builtin_ia32_addsh_round_mask: 4106 case X86::BI__builtin_ia32_addss_round_mask: 4107 case X86::BI__builtin_ia32_addsd_round_mask: 4108 case X86::BI__builtin_ia32_divsh_round_mask: 4109 case X86::BI__builtin_ia32_divss_round_mask: 4110 case X86::BI__builtin_ia32_divsd_round_mask: 4111 case X86::BI__builtin_ia32_mulsh_round_mask: 4112 case X86::BI__builtin_ia32_mulss_round_mask: 4113 case X86::BI__builtin_ia32_mulsd_round_mask: 4114 case X86::BI__builtin_ia32_subsh_round_mask: 4115 case X86::BI__builtin_ia32_subss_round_mask: 4116 case X86::BI__builtin_ia32_subsd_round_mask: 4117 case X86::BI__builtin_ia32_scalefph512_mask: 4118 case X86::BI__builtin_ia32_scalefpd512_mask: 4119 case X86::BI__builtin_ia32_scalefps512_mask: 4120 case X86::BI__builtin_ia32_scalefsd_round_mask: 4121 case X86::BI__builtin_ia32_scalefss_round_mask: 4122 case X86::BI__builtin_ia32_scalefsh_round_mask: 4123 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4124 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4125 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4126 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4127 case X86::BI__builtin_ia32_sqrtss_round_mask: 4128 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4129 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4130 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4131 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4132 case X86::BI__builtin_ia32_vfmaddss3_mask: 4133 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4134 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4135 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4136 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4137 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4138 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4139 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4140 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4141 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4142 case X86::BI__builtin_ia32_vfmaddps512_mask: 4143 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4144 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4145 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4146 case X86::BI__builtin_ia32_vfmaddph512_mask: 4147 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4148 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4149 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4150 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4151 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4152 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4153 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4154 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4155 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4156 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4157 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4158 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4159 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4160 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4161 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4162 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4163 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4164 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4165 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4166 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4167 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4168 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4169 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4170 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4171 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4172 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4173 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4174 case X86::BI__builtin_ia32_vfmulcsh_mask: 4175 case X86::BI__builtin_ia32_vfmulcph512_mask: 4176 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4177 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4178 ArgNum = 4; 4179 HasRC = true; 4180 break; 4181 } 4182 4183 llvm::APSInt Result; 4184 4185 // We can't check the value of a dependent argument. 4186 Expr *Arg = TheCall->getArg(ArgNum); 4187 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4188 return false; 4189 4190 // Check constant-ness first. 4191 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4192 return true; 4193 4194 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4195 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4196 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4197 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4198 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4199 Result == 8/*ROUND_NO_EXC*/ || 4200 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4201 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4202 return false; 4203 4204 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4205 << Arg->getSourceRange(); 4206 } 4207 4208 // Check if the gather/scatter scale is legal. 4209 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4210 CallExpr *TheCall) { 4211 unsigned ArgNum = 0; 4212 switch (BuiltinID) { 4213 default: 4214 return false; 4215 case X86::BI__builtin_ia32_gatherpfdpd: 4216 case X86::BI__builtin_ia32_gatherpfdps: 4217 case X86::BI__builtin_ia32_gatherpfqpd: 4218 case X86::BI__builtin_ia32_gatherpfqps: 4219 case X86::BI__builtin_ia32_scatterpfdpd: 4220 case X86::BI__builtin_ia32_scatterpfdps: 4221 case X86::BI__builtin_ia32_scatterpfqpd: 4222 case X86::BI__builtin_ia32_scatterpfqps: 4223 ArgNum = 3; 4224 break; 4225 case X86::BI__builtin_ia32_gatherd_pd: 4226 case X86::BI__builtin_ia32_gatherd_pd256: 4227 case X86::BI__builtin_ia32_gatherq_pd: 4228 case X86::BI__builtin_ia32_gatherq_pd256: 4229 case X86::BI__builtin_ia32_gatherd_ps: 4230 case X86::BI__builtin_ia32_gatherd_ps256: 4231 case X86::BI__builtin_ia32_gatherq_ps: 4232 case X86::BI__builtin_ia32_gatherq_ps256: 4233 case X86::BI__builtin_ia32_gatherd_q: 4234 case X86::BI__builtin_ia32_gatherd_q256: 4235 case X86::BI__builtin_ia32_gatherq_q: 4236 case X86::BI__builtin_ia32_gatherq_q256: 4237 case X86::BI__builtin_ia32_gatherd_d: 4238 case X86::BI__builtin_ia32_gatherd_d256: 4239 case X86::BI__builtin_ia32_gatherq_d: 4240 case X86::BI__builtin_ia32_gatherq_d256: 4241 case X86::BI__builtin_ia32_gather3div2df: 4242 case X86::BI__builtin_ia32_gather3div2di: 4243 case X86::BI__builtin_ia32_gather3div4df: 4244 case X86::BI__builtin_ia32_gather3div4di: 4245 case X86::BI__builtin_ia32_gather3div4sf: 4246 case X86::BI__builtin_ia32_gather3div4si: 4247 case X86::BI__builtin_ia32_gather3div8sf: 4248 case X86::BI__builtin_ia32_gather3div8si: 4249 case X86::BI__builtin_ia32_gather3siv2df: 4250 case X86::BI__builtin_ia32_gather3siv2di: 4251 case X86::BI__builtin_ia32_gather3siv4df: 4252 case X86::BI__builtin_ia32_gather3siv4di: 4253 case X86::BI__builtin_ia32_gather3siv4sf: 4254 case X86::BI__builtin_ia32_gather3siv4si: 4255 case X86::BI__builtin_ia32_gather3siv8sf: 4256 case X86::BI__builtin_ia32_gather3siv8si: 4257 case X86::BI__builtin_ia32_gathersiv8df: 4258 case X86::BI__builtin_ia32_gathersiv16sf: 4259 case X86::BI__builtin_ia32_gatherdiv8df: 4260 case X86::BI__builtin_ia32_gatherdiv16sf: 4261 case X86::BI__builtin_ia32_gathersiv8di: 4262 case X86::BI__builtin_ia32_gathersiv16si: 4263 case X86::BI__builtin_ia32_gatherdiv8di: 4264 case X86::BI__builtin_ia32_gatherdiv16si: 4265 case X86::BI__builtin_ia32_scatterdiv2df: 4266 case X86::BI__builtin_ia32_scatterdiv2di: 4267 case X86::BI__builtin_ia32_scatterdiv4df: 4268 case X86::BI__builtin_ia32_scatterdiv4di: 4269 case X86::BI__builtin_ia32_scatterdiv4sf: 4270 case X86::BI__builtin_ia32_scatterdiv4si: 4271 case X86::BI__builtin_ia32_scatterdiv8sf: 4272 case X86::BI__builtin_ia32_scatterdiv8si: 4273 case X86::BI__builtin_ia32_scattersiv2df: 4274 case X86::BI__builtin_ia32_scattersiv2di: 4275 case X86::BI__builtin_ia32_scattersiv4df: 4276 case X86::BI__builtin_ia32_scattersiv4di: 4277 case X86::BI__builtin_ia32_scattersiv4sf: 4278 case X86::BI__builtin_ia32_scattersiv4si: 4279 case X86::BI__builtin_ia32_scattersiv8sf: 4280 case X86::BI__builtin_ia32_scattersiv8si: 4281 case X86::BI__builtin_ia32_scattersiv8df: 4282 case X86::BI__builtin_ia32_scattersiv16sf: 4283 case X86::BI__builtin_ia32_scatterdiv8df: 4284 case X86::BI__builtin_ia32_scatterdiv16sf: 4285 case X86::BI__builtin_ia32_scattersiv8di: 4286 case X86::BI__builtin_ia32_scattersiv16si: 4287 case X86::BI__builtin_ia32_scatterdiv8di: 4288 case X86::BI__builtin_ia32_scatterdiv16si: 4289 ArgNum = 4; 4290 break; 4291 } 4292 4293 llvm::APSInt Result; 4294 4295 // We can't check the value of a dependent argument. 4296 Expr *Arg = TheCall->getArg(ArgNum); 4297 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4298 return false; 4299 4300 // Check constant-ness first. 4301 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4302 return true; 4303 4304 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4305 return false; 4306 4307 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4308 << Arg->getSourceRange(); 4309 } 4310 4311 enum { TileRegLow = 0, TileRegHigh = 7 }; 4312 4313 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4314 ArrayRef<int> ArgNums) { 4315 for (int ArgNum : ArgNums) { 4316 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4317 return true; 4318 } 4319 return false; 4320 } 4321 4322 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4323 ArrayRef<int> ArgNums) { 4324 // Because the max number of tile register is TileRegHigh + 1, so here we use 4325 // each bit to represent the usage of them in bitset. 4326 std::bitset<TileRegHigh + 1> ArgValues; 4327 for (int ArgNum : ArgNums) { 4328 Expr *Arg = TheCall->getArg(ArgNum); 4329 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4330 continue; 4331 4332 llvm::APSInt Result; 4333 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4334 return true; 4335 int ArgExtValue = Result.getExtValue(); 4336 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4337 "Incorrect tile register num."); 4338 if (ArgValues.test(ArgExtValue)) 4339 return Diag(TheCall->getBeginLoc(), 4340 diag::err_x86_builtin_tile_arg_duplicate) 4341 << TheCall->getArg(ArgNum)->getSourceRange(); 4342 ArgValues.set(ArgExtValue); 4343 } 4344 return false; 4345 } 4346 4347 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4348 ArrayRef<int> ArgNums) { 4349 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4350 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4351 } 4352 4353 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4354 switch (BuiltinID) { 4355 default: 4356 return false; 4357 case X86::BI__builtin_ia32_tileloadd64: 4358 case X86::BI__builtin_ia32_tileloaddt164: 4359 case X86::BI__builtin_ia32_tilestored64: 4360 case X86::BI__builtin_ia32_tilezero: 4361 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4362 case X86::BI__builtin_ia32_tdpbssd: 4363 case X86::BI__builtin_ia32_tdpbsud: 4364 case X86::BI__builtin_ia32_tdpbusd: 4365 case X86::BI__builtin_ia32_tdpbuud: 4366 case X86::BI__builtin_ia32_tdpbf16ps: 4367 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4368 } 4369 } 4370 static bool isX86_32Builtin(unsigned BuiltinID) { 4371 // These builtins only work on x86-32 targets. 4372 switch (BuiltinID) { 4373 case X86::BI__builtin_ia32_readeflags_u32: 4374 case X86::BI__builtin_ia32_writeeflags_u32: 4375 return true; 4376 } 4377 4378 return false; 4379 } 4380 4381 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4382 CallExpr *TheCall) { 4383 if (BuiltinID == X86::BI__builtin_cpu_supports) 4384 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4385 4386 if (BuiltinID == X86::BI__builtin_cpu_is) 4387 return SemaBuiltinCpuIs(*this, TI, TheCall); 4388 4389 // Check for 32-bit only builtins on a 64-bit target. 4390 const llvm::Triple &TT = TI.getTriple(); 4391 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4392 return Diag(TheCall->getCallee()->getBeginLoc(), 4393 diag::err_32_bit_builtin_64_bit_tgt); 4394 4395 // If the intrinsic has rounding or SAE make sure its valid. 4396 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4397 return true; 4398 4399 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4400 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4401 return true; 4402 4403 // If the intrinsic has a tile arguments, make sure they are valid. 4404 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4405 return true; 4406 4407 // For intrinsics which take an immediate value as part of the instruction, 4408 // range check them here. 4409 int i = 0, l = 0, u = 0; 4410 switch (BuiltinID) { 4411 default: 4412 return false; 4413 case X86::BI__builtin_ia32_vec_ext_v2si: 4414 case X86::BI__builtin_ia32_vec_ext_v2di: 4415 case X86::BI__builtin_ia32_vextractf128_pd256: 4416 case X86::BI__builtin_ia32_vextractf128_ps256: 4417 case X86::BI__builtin_ia32_vextractf128_si256: 4418 case X86::BI__builtin_ia32_extract128i256: 4419 case X86::BI__builtin_ia32_extractf64x4_mask: 4420 case X86::BI__builtin_ia32_extracti64x4_mask: 4421 case X86::BI__builtin_ia32_extractf32x8_mask: 4422 case X86::BI__builtin_ia32_extracti32x8_mask: 4423 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4424 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4425 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4426 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4427 i = 1; l = 0; u = 1; 4428 break; 4429 case X86::BI__builtin_ia32_vec_set_v2di: 4430 case X86::BI__builtin_ia32_vinsertf128_pd256: 4431 case X86::BI__builtin_ia32_vinsertf128_ps256: 4432 case X86::BI__builtin_ia32_vinsertf128_si256: 4433 case X86::BI__builtin_ia32_insert128i256: 4434 case X86::BI__builtin_ia32_insertf32x8: 4435 case X86::BI__builtin_ia32_inserti32x8: 4436 case X86::BI__builtin_ia32_insertf64x4: 4437 case X86::BI__builtin_ia32_inserti64x4: 4438 case X86::BI__builtin_ia32_insertf64x2_256: 4439 case X86::BI__builtin_ia32_inserti64x2_256: 4440 case X86::BI__builtin_ia32_insertf32x4_256: 4441 case X86::BI__builtin_ia32_inserti32x4_256: 4442 i = 2; l = 0; u = 1; 4443 break; 4444 case X86::BI__builtin_ia32_vpermilpd: 4445 case X86::BI__builtin_ia32_vec_ext_v4hi: 4446 case X86::BI__builtin_ia32_vec_ext_v4si: 4447 case X86::BI__builtin_ia32_vec_ext_v4sf: 4448 case X86::BI__builtin_ia32_vec_ext_v4di: 4449 case X86::BI__builtin_ia32_extractf32x4_mask: 4450 case X86::BI__builtin_ia32_extracti32x4_mask: 4451 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4452 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4453 i = 1; l = 0; u = 3; 4454 break; 4455 case X86::BI_mm_prefetch: 4456 case X86::BI__builtin_ia32_vec_ext_v8hi: 4457 case X86::BI__builtin_ia32_vec_ext_v8si: 4458 i = 1; l = 0; u = 7; 4459 break; 4460 case X86::BI__builtin_ia32_sha1rnds4: 4461 case X86::BI__builtin_ia32_blendpd: 4462 case X86::BI__builtin_ia32_shufpd: 4463 case X86::BI__builtin_ia32_vec_set_v4hi: 4464 case X86::BI__builtin_ia32_vec_set_v4si: 4465 case X86::BI__builtin_ia32_vec_set_v4di: 4466 case X86::BI__builtin_ia32_shuf_f32x4_256: 4467 case X86::BI__builtin_ia32_shuf_f64x2_256: 4468 case X86::BI__builtin_ia32_shuf_i32x4_256: 4469 case X86::BI__builtin_ia32_shuf_i64x2_256: 4470 case X86::BI__builtin_ia32_insertf64x2_512: 4471 case X86::BI__builtin_ia32_inserti64x2_512: 4472 case X86::BI__builtin_ia32_insertf32x4: 4473 case X86::BI__builtin_ia32_inserti32x4: 4474 i = 2; l = 0; u = 3; 4475 break; 4476 case X86::BI__builtin_ia32_vpermil2pd: 4477 case X86::BI__builtin_ia32_vpermil2pd256: 4478 case X86::BI__builtin_ia32_vpermil2ps: 4479 case X86::BI__builtin_ia32_vpermil2ps256: 4480 i = 3; l = 0; u = 3; 4481 break; 4482 case X86::BI__builtin_ia32_cmpb128_mask: 4483 case X86::BI__builtin_ia32_cmpw128_mask: 4484 case X86::BI__builtin_ia32_cmpd128_mask: 4485 case X86::BI__builtin_ia32_cmpq128_mask: 4486 case X86::BI__builtin_ia32_cmpb256_mask: 4487 case X86::BI__builtin_ia32_cmpw256_mask: 4488 case X86::BI__builtin_ia32_cmpd256_mask: 4489 case X86::BI__builtin_ia32_cmpq256_mask: 4490 case X86::BI__builtin_ia32_cmpb512_mask: 4491 case X86::BI__builtin_ia32_cmpw512_mask: 4492 case X86::BI__builtin_ia32_cmpd512_mask: 4493 case X86::BI__builtin_ia32_cmpq512_mask: 4494 case X86::BI__builtin_ia32_ucmpb128_mask: 4495 case X86::BI__builtin_ia32_ucmpw128_mask: 4496 case X86::BI__builtin_ia32_ucmpd128_mask: 4497 case X86::BI__builtin_ia32_ucmpq128_mask: 4498 case X86::BI__builtin_ia32_ucmpb256_mask: 4499 case X86::BI__builtin_ia32_ucmpw256_mask: 4500 case X86::BI__builtin_ia32_ucmpd256_mask: 4501 case X86::BI__builtin_ia32_ucmpq256_mask: 4502 case X86::BI__builtin_ia32_ucmpb512_mask: 4503 case X86::BI__builtin_ia32_ucmpw512_mask: 4504 case X86::BI__builtin_ia32_ucmpd512_mask: 4505 case X86::BI__builtin_ia32_ucmpq512_mask: 4506 case X86::BI__builtin_ia32_vpcomub: 4507 case X86::BI__builtin_ia32_vpcomuw: 4508 case X86::BI__builtin_ia32_vpcomud: 4509 case X86::BI__builtin_ia32_vpcomuq: 4510 case X86::BI__builtin_ia32_vpcomb: 4511 case X86::BI__builtin_ia32_vpcomw: 4512 case X86::BI__builtin_ia32_vpcomd: 4513 case X86::BI__builtin_ia32_vpcomq: 4514 case X86::BI__builtin_ia32_vec_set_v8hi: 4515 case X86::BI__builtin_ia32_vec_set_v8si: 4516 i = 2; l = 0; u = 7; 4517 break; 4518 case X86::BI__builtin_ia32_vpermilpd256: 4519 case X86::BI__builtin_ia32_roundps: 4520 case X86::BI__builtin_ia32_roundpd: 4521 case X86::BI__builtin_ia32_roundps256: 4522 case X86::BI__builtin_ia32_roundpd256: 4523 case X86::BI__builtin_ia32_getmantpd128_mask: 4524 case X86::BI__builtin_ia32_getmantpd256_mask: 4525 case X86::BI__builtin_ia32_getmantps128_mask: 4526 case X86::BI__builtin_ia32_getmantps256_mask: 4527 case X86::BI__builtin_ia32_getmantpd512_mask: 4528 case X86::BI__builtin_ia32_getmantps512_mask: 4529 case X86::BI__builtin_ia32_getmantph128_mask: 4530 case X86::BI__builtin_ia32_getmantph256_mask: 4531 case X86::BI__builtin_ia32_getmantph512_mask: 4532 case X86::BI__builtin_ia32_vec_ext_v16qi: 4533 case X86::BI__builtin_ia32_vec_ext_v16hi: 4534 i = 1; l = 0; u = 15; 4535 break; 4536 case X86::BI__builtin_ia32_pblendd128: 4537 case X86::BI__builtin_ia32_blendps: 4538 case X86::BI__builtin_ia32_blendpd256: 4539 case X86::BI__builtin_ia32_shufpd256: 4540 case X86::BI__builtin_ia32_roundss: 4541 case X86::BI__builtin_ia32_roundsd: 4542 case X86::BI__builtin_ia32_rangepd128_mask: 4543 case X86::BI__builtin_ia32_rangepd256_mask: 4544 case X86::BI__builtin_ia32_rangepd512_mask: 4545 case X86::BI__builtin_ia32_rangeps128_mask: 4546 case X86::BI__builtin_ia32_rangeps256_mask: 4547 case X86::BI__builtin_ia32_rangeps512_mask: 4548 case X86::BI__builtin_ia32_getmantsd_round_mask: 4549 case X86::BI__builtin_ia32_getmantss_round_mask: 4550 case X86::BI__builtin_ia32_getmantsh_round_mask: 4551 case X86::BI__builtin_ia32_vec_set_v16qi: 4552 case X86::BI__builtin_ia32_vec_set_v16hi: 4553 i = 2; l = 0; u = 15; 4554 break; 4555 case X86::BI__builtin_ia32_vec_ext_v32qi: 4556 i = 1; l = 0; u = 31; 4557 break; 4558 case X86::BI__builtin_ia32_cmpps: 4559 case X86::BI__builtin_ia32_cmpss: 4560 case X86::BI__builtin_ia32_cmppd: 4561 case X86::BI__builtin_ia32_cmpsd: 4562 case X86::BI__builtin_ia32_cmpps256: 4563 case X86::BI__builtin_ia32_cmppd256: 4564 case X86::BI__builtin_ia32_cmpps128_mask: 4565 case X86::BI__builtin_ia32_cmppd128_mask: 4566 case X86::BI__builtin_ia32_cmpps256_mask: 4567 case X86::BI__builtin_ia32_cmppd256_mask: 4568 case X86::BI__builtin_ia32_cmpps512_mask: 4569 case X86::BI__builtin_ia32_cmppd512_mask: 4570 case X86::BI__builtin_ia32_cmpsd_mask: 4571 case X86::BI__builtin_ia32_cmpss_mask: 4572 case X86::BI__builtin_ia32_vec_set_v32qi: 4573 i = 2; l = 0; u = 31; 4574 break; 4575 case X86::BI__builtin_ia32_permdf256: 4576 case X86::BI__builtin_ia32_permdi256: 4577 case X86::BI__builtin_ia32_permdf512: 4578 case X86::BI__builtin_ia32_permdi512: 4579 case X86::BI__builtin_ia32_vpermilps: 4580 case X86::BI__builtin_ia32_vpermilps256: 4581 case X86::BI__builtin_ia32_vpermilpd512: 4582 case X86::BI__builtin_ia32_vpermilps512: 4583 case X86::BI__builtin_ia32_pshufd: 4584 case X86::BI__builtin_ia32_pshufd256: 4585 case X86::BI__builtin_ia32_pshufd512: 4586 case X86::BI__builtin_ia32_pshufhw: 4587 case X86::BI__builtin_ia32_pshufhw256: 4588 case X86::BI__builtin_ia32_pshufhw512: 4589 case X86::BI__builtin_ia32_pshuflw: 4590 case X86::BI__builtin_ia32_pshuflw256: 4591 case X86::BI__builtin_ia32_pshuflw512: 4592 case X86::BI__builtin_ia32_vcvtps2ph: 4593 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4594 case X86::BI__builtin_ia32_vcvtps2ph256: 4595 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4596 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4597 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4598 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4599 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4600 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4601 case X86::BI__builtin_ia32_rndscaleps_mask: 4602 case X86::BI__builtin_ia32_rndscalepd_mask: 4603 case X86::BI__builtin_ia32_rndscaleph_mask: 4604 case X86::BI__builtin_ia32_reducepd128_mask: 4605 case X86::BI__builtin_ia32_reducepd256_mask: 4606 case X86::BI__builtin_ia32_reducepd512_mask: 4607 case X86::BI__builtin_ia32_reduceps128_mask: 4608 case X86::BI__builtin_ia32_reduceps256_mask: 4609 case X86::BI__builtin_ia32_reduceps512_mask: 4610 case X86::BI__builtin_ia32_reduceph128_mask: 4611 case X86::BI__builtin_ia32_reduceph256_mask: 4612 case X86::BI__builtin_ia32_reduceph512_mask: 4613 case X86::BI__builtin_ia32_prold512: 4614 case X86::BI__builtin_ia32_prolq512: 4615 case X86::BI__builtin_ia32_prold128: 4616 case X86::BI__builtin_ia32_prold256: 4617 case X86::BI__builtin_ia32_prolq128: 4618 case X86::BI__builtin_ia32_prolq256: 4619 case X86::BI__builtin_ia32_prord512: 4620 case X86::BI__builtin_ia32_prorq512: 4621 case X86::BI__builtin_ia32_prord128: 4622 case X86::BI__builtin_ia32_prord256: 4623 case X86::BI__builtin_ia32_prorq128: 4624 case X86::BI__builtin_ia32_prorq256: 4625 case X86::BI__builtin_ia32_fpclasspd128_mask: 4626 case X86::BI__builtin_ia32_fpclasspd256_mask: 4627 case X86::BI__builtin_ia32_fpclassps128_mask: 4628 case X86::BI__builtin_ia32_fpclassps256_mask: 4629 case X86::BI__builtin_ia32_fpclassps512_mask: 4630 case X86::BI__builtin_ia32_fpclasspd512_mask: 4631 case X86::BI__builtin_ia32_fpclassph128_mask: 4632 case X86::BI__builtin_ia32_fpclassph256_mask: 4633 case X86::BI__builtin_ia32_fpclassph512_mask: 4634 case X86::BI__builtin_ia32_fpclasssd_mask: 4635 case X86::BI__builtin_ia32_fpclassss_mask: 4636 case X86::BI__builtin_ia32_fpclasssh_mask: 4637 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4638 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4639 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4640 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4641 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4642 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4643 case X86::BI__builtin_ia32_kshiftliqi: 4644 case X86::BI__builtin_ia32_kshiftlihi: 4645 case X86::BI__builtin_ia32_kshiftlisi: 4646 case X86::BI__builtin_ia32_kshiftlidi: 4647 case X86::BI__builtin_ia32_kshiftriqi: 4648 case X86::BI__builtin_ia32_kshiftrihi: 4649 case X86::BI__builtin_ia32_kshiftrisi: 4650 case X86::BI__builtin_ia32_kshiftridi: 4651 i = 1; l = 0; u = 255; 4652 break; 4653 case X86::BI__builtin_ia32_vperm2f128_pd256: 4654 case X86::BI__builtin_ia32_vperm2f128_ps256: 4655 case X86::BI__builtin_ia32_vperm2f128_si256: 4656 case X86::BI__builtin_ia32_permti256: 4657 case X86::BI__builtin_ia32_pblendw128: 4658 case X86::BI__builtin_ia32_pblendw256: 4659 case X86::BI__builtin_ia32_blendps256: 4660 case X86::BI__builtin_ia32_pblendd256: 4661 case X86::BI__builtin_ia32_palignr128: 4662 case X86::BI__builtin_ia32_palignr256: 4663 case X86::BI__builtin_ia32_palignr512: 4664 case X86::BI__builtin_ia32_alignq512: 4665 case X86::BI__builtin_ia32_alignd512: 4666 case X86::BI__builtin_ia32_alignd128: 4667 case X86::BI__builtin_ia32_alignd256: 4668 case X86::BI__builtin_ia32_alignq128: 4669 case X86::BI__builtin_ia32_alignq256: 4670 case X86::BI__builtin_ia32_vcomisd: 4671 case X86::BI__builtin_ia32_vcomiss: 4672 case X86::BI__builtin_ia32_shuf_f32x4: 4673 case X86::BI__builtin_ia32_shuf_f64x2: 4674 case X86::BI__builtin_ia32_shuf_i32x4: 4675 case X86::BI__builtin_ia32_shuf_i64x2: 4676 case X86::BI__builtin_ia32_shufpd512: 4677 case X86::BI__builtin_ia32_shufps: 4678 case X86::BI__builtin_ia32_shufps256: 4679 case X86::BI__builtin_ia32_shufps512: 4680 case X86::BI__builtin_ia32_dbpsadbw128: 4681 case X86::BI__builtin_ia32_dbpsadbw256: 4682 case X86::BI__builtin_ia32_dbpsadbw512: 4683 case X86::BI__builtin_ia32_vpshldd128: 4684 case X86::BI__builtin_ia32_vpshldd256: 4685 case X86::BI__builtin_ia32_vpshldd512: 4686 case X86::BI__builtin_ia32_vpshldq128: 4687 case X86::BI__builtin_ia32_vpshldq256: 4688 case X86::BI__builtin_ia32_vpshldq512: 4689 case X86::BI__builtin_ia32_vpshldw128: 4690 case X86::BI__builtin_ia32_vpshldw256: 4691 case X86::BI__builtin_ia32_vpshldw512: 4692 case X86::BI__builtin_ia32_vpshrdd128: 4693 case X86::BI__builtin_ia32_vpshrdd256: 4694 case X86::BI__builtin_ia32_vpshrdd512: 4695 case X86::BI__builtin_ia32_vpshrdq128: 4696 case X86::BI__builtin_ia32_vpshrdq256: 4697 case X86::BI__builtin_ia32_vpshrdq512: 4698 case X86::BI__builtin_ia32_vpshrdw128: 4699 case X86::BI__builtin_ia32_vpshrdw256: 4700 case X86::BI__builtin_ia32_vpshrdw512: 4701 i = 2; l = 0; u = 255; 4702 break; 4703 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4704 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4705 case X86::BI__builtin_ia32_fixupimmps512_mask: 4706 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4707 case X86::BI__builtin_ia32_fixupimmsd_mask: 4708 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4709 case X86::BI__builtin_ia32_fixupimmss_mask: 4710 case X86::BI__builtin_ia32_fixupimmss_maskz: 4711 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4712 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4713 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4714 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4715 case X86::BI__builtin_ia32_fixupimmps128_mask: 4716 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4717 case X86::BI__builtin_ia32_fixupimmps256_mask: 4718 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4719 case X86::BI__builtin_ia32_pternlogd512_mask: 4720 case X86::BI__builtin_ia32_pternlogd512_maskz: 4721 case X86::BI__builtin_ia32_pternlogq512_mask: 4722 case X86::BI__builtin_ia32_pternlogq512_maskz: 4723 case X86::BI__builtin_ia32_pternlogd128_mask: 4724 case X86::BI__builtin_ia32_pternlogd128_maskz: 4725 case X86::BI__builtin_ia32_pternlogd256_mask: 4726 case X86::BI__builtin_ia32_pternlogd256_maskz: 4727 case X86::BI__builtin_ia32_pternlogq128_mask: 4728 case X86::BI__builtin_ia32_pternlogq128_maskz: 4729 case X86::BI__builtin_ia32_pternlogq256_mask: 4730 case X86::BI__builtin_ia32_pternlogq256_maskz: 4731 i = 3; l = 0; u = 255; 4732 break; 4733 case X86::BI__builtin_ia32_gatherpfdpd: 4734 case X86::BI__builtin_ia32_gatherpfdps: 4735 case X86::BI__builtin_ia32_gatherpfqpd: 4736 case X86::BI__builtin_ia32_gatherpfqps: 4737 case X86::BI__builtin_ia32_scatterpfdpd: 4738 case X86::BI__builtin_ia32_scatterpfdps: 4739 case X86::BI__builtin_ia32_scatterpfqpd: 4740 case X86::BI__builtin_ia32_scatterpfqps: 4741 i = 4; l = 2; u = 3; 4742 break; 4743 case X86::BI__builtin_ia32_reducesd_mask: 4744 case X86::BI__builtin_ia32_reducess_mask: 4745 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4746 case X86::BI__builtin_ia32_rndscaless_round_mask: 4747 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4748 case X86::BI__builtin_ia32_reducesh_mask: 4749 i = 4; l = 0; u = 255; 4750 break; 4751 } 4752 4753 // Note that we don't force a hard error on the range check here, allowing 4754 // template-generated or macro-generated dead code to potentially have out-of- 4755 // range values. These need to code generate, but don't need to necessarily 4756 // make any sense. We use a warning that defaults to an error. 4757 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4758 } 4759 4760 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4761 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4762 /// Returns true when the format fits the function and the FormatStringInfo has 4763 /// been populated. 4764 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4765 FormatStringInfo *FSI) { 4766 FSI->HasVAListArg = Format->getFirstArg() == 0; 4767 FSI->FormatIdx = Format->getFormatIdx() - 1; 4768 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4769 4770 // The way the format attribute works in GCC, the implicit this argument 4771 // of member functions is counted. However, it doesn't appear in our own 4772 // lists, so decrement format_idx in that case. 4773 if (IsCXXMember) { 4774 if(FSI->FormatIdx == 0) 4775 return false; 4776 --FSI->FormatIdx; 4777 if (FSI->FirstDataArg != 0) 4778 --FSI->FirstDataArg; 4779 } 4780 return true; 4781 } 4782 4783 /// Checks if a the given expression evaluates to null. 4784 /// 4785 /// Returns true if the value evaluates to null. 4786 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4787 // If the expression has non-null type, it doesn't evaluate to null. 4788 if (auto nullability 4789 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4790 if (*nullability == NullabilityKind::NonNull) 4791 return false; 4792 } 4793 4794 // As a special case, transparent unions initialized with zero are 4795 // considered null for the purposes of the nonnull attribute. 4796 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4797 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4798 if (const CompoundLiteralExpr *CLE = 4799 dyn_cast<CompoundLiteralExpr>(Expr)) 4800 if (const InitListExpr *ILE = 4801 dyn_cast<InitListExpr>(CLE->getInitializer())) 4802 Expr = ILE->getInit(0); 4803 } 4804 4805 bool Result; 4806 return (!Expr->isValueDependent() && 4807 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4808 !Result); 4809 } 4810 4811 static void CheckNonNullArgument(Sema &S, 4812 const Expr *ArgExpr, 4813 SourceLocation CallSiteLoc) { 4814 if (CheckNonNullExpr(S, ArgExpr)) 4815 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4816 S.PDiag(diag::warn_null_arg) 4817 << ArgExpr->getSourceRange()); 4818 } 4819 4820 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4821 FormatStringInfo FSI; 4822 if ((GetFormatStringType(Format) == FST_NSString) && 4823 getFormatStringInfo(Format, false, &FSI)) { 4824 Idx = FSI.FormatIdx; 4825 return true; 4826 } 4827 return false; 4828 } 4829 4830 /// Diagnose use of %s directive in an NSString which is being passed 4831 /// as formatting string to formatting method. 4832 static void 4833 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4834 const NamedDecl *FDecl, 4835 Expr **Args, 4836 unsigned NumArgs) { 4837 unsigned Idx = 0; 4838 bool Format = false; 4839 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4840 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4841 Idx = 2; 4842 Format = true; 4843 } 4844 else 4845 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4846 if (S.GetFormatNSStringIdx(I, Idx)) { 4847 Format = true; 4848 break; 4849 } 4850 } 4851 if (!Format || NumArgs <= Idx) 4852 return; 4853 const Expr *FormatExpr = Args[Idx]; 4854 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4855 FormatExpr = CSCE->getSubExpr(); 4856 const StringLiteral *FormatString; 4857 if (const ObjCStringLiteral *OSL = 4858 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4859 FormatString = OSL->getString(); 4860 else 4861 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4862 if (!FormatString) 4863 return; 4864 if (S.FormatStringHasSArg(FormatString)) { 4865 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4866 << "%s" << 1 << 1; 4867 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4868 << FDecl->getDeclName(); 4869 } 4870 } 4871 4872 /// Determine whether the given type has a non-null nullability annotation. 4873 static bool isNonNullType(ASTContext &ctx, QualType type) { 4874 if (auto nullability = type->getNullability(ctx)) 4875 return *nullability == NullabilityKind::NonNull; 4876 4877 return false; 4878 } 4879 4880 static void CheckNonNullArguments(Sema &S, 4881 const NamedDecl *FDecl, 4882 const FunctionProtoType *Proto, 4883 ArrayRef<const Expr *> Args, 4884 SourceLocation CallSiteLoc) { 4885 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4886 4887 // Already checked by by constant evaluator. 4888 if (S.isConstantEvaluated()) 4889 return; 4890 // Check the attributes attached to the method/function itself. 4891 llvm::SmallBitVector NonNullArgs; 4892 if (FDecl) { 4893 // Handle the nonnull attribute on the function/method declaration itself. 4894 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4895 if (!NonNull->args_size()) { 4896 // Easy case: all pointer arguments are nonnull. 4897 for (const auto *Arg : Args) 4898 if (S.isValidPointerAttrType(Arg->getType())) 4899 CheckNonNullArgument(S, Arg, CallSiteLoc); 4900 return; 4901 } 4902 4903 for (const ParamIdx &Idx : NonNull->args()) { 4904 unsigned IdxAST = Idx.getASTIndex(); 4905 if (IdxAST >= Args.size()) 4906 continue; 4907 if (NonNullArgs.empty()) 4908 NonNullArgs.resize(Args.size()); 4909 NonNullArgs.set(IdxAST); 4910 } 4911 } 4912 } 4913 4914 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4915 // Handle the nonnull attribute on the parameters of the 4916 // function/method. 4917 ArrayRef<ParmVarDecl*> parms; 4918 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4919 parms = FD->parameters(); 4920 else 4921 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4922 4923 unsigned ParamIndex = 0; 4924 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4925 I != E; ++I, ++ParamIndex) { 4926 const ParmVarDecl *PVD = *I; 4927 if (PVD->hasAttr<NonNullAttr>() || 4928 isNonNullType(S.Context, PVD->getType())) { 4929 if (NonNullArgs.empty()) 4930 NonNullArgs.resize(Args.size()); 4931 4932 NonNullArgs.set(ParamIndex); 4933 } 4934 } 4935 } else { 4936 // If we have a non-function, non-method declaration but no 4937 // function prototype, try to dig out the function prototype. 4938 if (!Proto) { 4939 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4940 QualType type = VD->getType().getNonReferenceType(); 4941 if (auto pointerType = type->getAs<PointerType>()) 4942 type = pointerType->getPointeeType(); 4943 else if (auto blockType = type->getAs<BlockPointerType>()) 4944 type = blockType->getPointeeType(); 4945 // FIXME: data member pointers? 4946 4947 // Dig out the function prototype, if there is one. 4948 Proto = type->getAs<FunctionProtoType>(); 4949 } 4950 } 4951 4952 // Fill in non-null argument information from the nullability 4953 // information on the parameter types (if we have them). 4954 if (Proto) { 4955 unsigned Index = 0; 4956 for (auto paramType : Proto->getParamTypes()) { 4957 if (isNonNullType(S.Context, paramType)) { 4958 if (NonNullArgs.empty()) 4959 NonNullArgs.resize(Args.size()); 4960 4961 NonNullArgs.set(Index); 4962 } 4963 4964 ++Index; 4965 } 4966 } 4967 } 4968 4969 // Check for non-null arguments. 4970 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4971 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4972 if (NonNullArgs[ArgIndex]) 4973 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4974 } 4975 } 4976 4977 /// Warn if a pointer or reference argument passed to a function points to an 4978 /// object that is less aligned than the parameter. This can happen when 4979 /// creating a typedef with a lower alignment than the original type and then 4980 /// calling functions defined in terms of the original type. 4981 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4982 StringRef ParamName, QualType ArgTy, 4983 QualType ParamTy) { 4984 4985 // If a function accepts a pointer or reference type 4986 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4987 return; 4988 4989 // If the parameter is a pointer type, get the pointee type for the 4990 // argument too. If the parameter is a reference type, don't try to get 4991 // the pointee type for the argument. 4992 if (ParamTy->isPointerType()) 4993 ArgTy = ArgTy->getPointeeType(); 4994 4995 // Remove reference or pointer 4996 ParamTy = ParamTy->getPointeeType(); 4997 4998 // Find expected alignment, and the actual alignment of the passed object. 4999 // getTypeAlignInChars requires complete types 5000 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5001 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5002 ArgTy->isUndeducedType()) 5003 return; 5004 5005 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5006 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5007 5008 // If the argument is less aligned than the parameter, there is a 5009 // potential alignment issue. 5010 if (ArgAlign < ParamAlign) 5011 Diag(Loc, diag::warn_param_mismatched_alignment) 5012 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5013 << ParamName << FDecl; 5014 } 5015 5016 /// Handles the checks for format strings, non-POD arguments to vararg 5017 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5018 /// attributes. 5019 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5020 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5021 bool IsMemberFunction, SourceLocation Loc, 5022 SourceRange Range, VariadicCallType CallType) { 5023 // FIXME: We should check as much as we can in the template definition. 5024 if (CurContext->isDependentContext()) 5025 return; 5026 5027 // Printf and scanf checking. 5028 llvm::SmallBitVector CheckedVarArgs; 5029 if (FDecl) { 5030 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5031 // Only create vector if there are format attributes. 5032 CheckedVarArgs.resize(Args.size()); 5033 5034 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5035 CheckedVarArgs); 5036 } 5037 } 5038 5039 // Refuse POD arguments that weren't caught by the format string 5040 // checks above. 5041 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5042 if (CallType != VariadicDoesNotApply && 5043 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5044 unsigned NumParams = Proto ? Proto->getNumParams() 5045 : FDecl && isa<FunctionDecl>(FDecl) 5046 ? cast<FunctionDecl>(FDecl)->getNumParams() 5047 : FDecl && isa<ObjCMethodDecl>(FDecl) 5048 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5049 : 0; 5050 5051 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5052 // Args[ArgIdx] can be null in malformed code. 5053 if (const Expr *Arg = Args[ArgIdx]) { 5054 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5055 checkVariadicArgument(Arg, CallType); 5056 } 5057 } 5058 } 5059 5060 if (FDecl || Proto) { 5061 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5062 5063 // Type safety checking. 5064 if (FDecl) { 5065 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5066 CheckArgumentWithTypeTag(I, Args, Loc); 5067 } 5068 } 5069 5070 // Check that passed arguments match the alignment of original arguments. 5071 // Try to get the missing prototype from the declaration. 5072 if (!Proto && FDecl) { 5073 const auto *FT = FDecl->getFunctionType(); 5074 if (isa_and_nonnull<FunctionProtoType>(FT)) 5075 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5076 } 5077 if (Proto) { 5078 // For variadic functions, we may have more args than parameters. 5079 // For some K&R functions, we may have less args than parameters. 5080 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5081 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5082 // Args[ArgIdx] can be null in malformed code. 5083 if (const Expr *Arg = Args[ArgIdx]) { 5084 if (Arg->containsErrors()) 5085 continue; 5086 5087 QualType ParamTy = Proto->getParamType(ArgIdx); 5088 QualType ArgTy = Arg->getType(); 5089 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5090 ArgTy, ParamTy); 5091 } 5092 } 5093 } 5094 5095 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5096 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5097 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5098 if (!Arg->isValueDependent()) { 5099 Expr::EvalResult Align; 5100 if (Arg->EvaluateAsInt(Align, Context)) { 5101 const llvm::APSInt &I = Align.Val.getInt(); 5102 if (!I.isPowerOf2()) 5103 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5104 << Arg->getSourceRange(); 5105 5106 if (I > Sema::MaximumAlignment) 5107 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5108 << Arg->getSourceRange() << Sema::MaximumAlignment; 5109 } 5110 } 5111 } 5112 5113 if (FD) 5114 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5115 } 5116 5117 /// CheckConstructorCall - Check a constructor call for correctness and safety 5118 /// properties not enforced by the C type system. 5119 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5120 ArrayRef<const Expr *> Args, 5121 const FunctionProtoType *Proto, 5122 SourceLocation Loc) { 5123 VariadicCallType CallType = 5124 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5125 5126 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5127 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5128 Context.getPointerType(Ctor->getThisObjectType())); 5129 5130 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5131 Loc, SourceRange(), CallType); 5132 } 5133 5134 /// CheckFunctionCall - Check a direct function call for various correctness 5135 /// and safety properties not strictly enforced by the C type system. 5136 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5137 const FunctionProtoType *Proto) { 5138 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5139 isa<CXXMethodDecl>(FDecl); 5140 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5141 IsMemberOperatorCall; 5142 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5143 TheCall->getCallee()); 5144 Expr** Args = TheCall->getArgs(); 5145 unsigned NumArgs = TheCall->getNumArgs(); 5146 5147 Expr *ImplicitThis = nullptr; 5148 if (IsMemberOperatorCall) { 5149 // If this is a call to a member operator, hide the first argument 5150 // from checkCall. 5151 // FIXME: Our choice of AST representation here is less than ideal. 5152 ImplicitThis = Args[0]; 5153 ++Args; 5154 --NumArgs; 5155 } else if (IsMemberFunction) 5156 ImplicitThis = 5157 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5158 5159 if (ImplicitThis) { 5160 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5161 // used. 5162 QualType ThisType = ImplicitThis->getType(); 5163 if (!ThisType->isPointerType()) { 5164 assert(!ThisType->isReferenceType()); 5165 ThisType = Context.getPointerType(ThisType); 5166 } 5167 5168 QualType ThisTypeFromDecl = 5169 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5170 5171 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5172 ThisTypeFromDecl); 5173 } 5174 5175 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5176 IsMemberFunction, TheCall->getRParenLoc(), 5177 TheCall->getCallee()->getSourceRange(), CallType); 5178 5179 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5180 // None of the checks below are needed for functions that don't have 5181 // simple names (e.g., C++ conversion functions). 5182 if (!FnInfo) 5183 return false; 5184 5185 CheckTCBEnforcement(TheCall, FDecl); 5186 5187 CheckAbsoluteValueFunction(TheCall, FDecl); 5188 CheckMaxUnsignedZero(TheCall, FDecl); 5189 5190 if (getLangOpts().ObjC) 5191 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5192 5193 unsigned CMId = FDecl->getMemoryFunctionKind(); 5194 5195 // Handle memory setting and copying functions. 5196 switch (CMId) { 5197 case 0: 5198 return false; 5199 case Builtin::BIstrlcpy: // fallthrough 5200 case Builtin::BIstrlcat: 5201 CheckStrlcpycatArguments(TheCall, FnInfo); 5202 break; 5203 case Builtin::BIstrncat: 5204 CheckStrncatArguments(TheCall, FnInfo); 5205 break; 5206 case Builtin::BIfree: 5207 CheckFreeArguments(TheCall); 5208 break; 5209 default: 5210 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5211 } 5212 5213 return false; 5214 } 5215 5216 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5217 ArrayRef<const Expr *> Args) { 5218 VariadicCallType CallType = 5219 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5220 5221 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5222 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5223 CallType); 5224 5225 return false; 5226 } 5227 5228 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5229 const FunctionProtoType *Proto) { 5230 QualType Ty; 5231 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5232 Ty = V->getType().getNonReferenceType(); 5233 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5234 Ty = F->getType().getNonReferenceType(); 5235 else 5236 return false; 5237 5238 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5239 !Ty->isFunctionProtoType()) 5240 return false; 5241 5242 VariadicCallType CallType; 5243 if (!Proto || !Proto->isVariadic()) { 5244 CallType = VariadicDoesNotApply; 5245 } else if (Ty->isBlockPointerType()) { 5246 CallType = VariadicBlock; 5247 } else { // Ty->isFunctionPointerType() 5248 CallType = VariadicFunction; 5249 } 5250 5251 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5252 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5253 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5254 TheCall->getCallee()->getSourceRange(), CallType); 5255 5256 return false; 5257 } 5258 5259 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5260 /// such as function pointers returned from functions. 5261 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5262 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5263 TheCall->getCallee()); 5264 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5265 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5266 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5267 TheCall->getCallee()->getSourceRange(), CallType); 5268 5269 return false; 5270 } 5271 5272 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5273 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5274 return false; 5275 5276 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5277 switch (Op) { 5278 case AtomicExpr::AO__c11_atomic_init: 5279 case AtomicExpr::AO__opencl_atomic_init: 5280 llvm_unreachable("There is no ordering argument for an init"); 5281 5282 case AtomicExpr::AO__c11_atomic_load: 5283 case AtomicExpr::AO__opencl_atomic_load: 5284 case AtomicExpr::AO__atomic_load_n: 5285 case AtomicExpr::AO__atomic_load: 5286 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5287 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5288 5289 case AtomicExpr::AO__c11_atomic_store: 5290 case AtomicExpr::AO__opencl_atomic_store: 5291 case AtomicExpr::AO__atomic_store: 5292 case AtomicExpr::AO__atomic_store_n: 5293 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5294 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5295 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5296 5297 default: 5298 return true; 5299 } 5300 } 5301 5302 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5303 AtomicExpr::AtomicOp Op) { 5304 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5305 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5306 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5307 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5308 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5309 Op); 5310 } 5311 5312 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5313 SourceLocation RParenLoc, MultiExprArg Args, 5314 AtomicExpr::AtomicOp Op, 5315 AtomicArgumentOrder ArgOrder) { 5316 // All the non-OpenCL operations take one of the following forms. 5317 // The OpenCL operations take the __c11 forms with one extra argument for 5318 // synchronization scope. 5319 enum { 5320 // C __c11_atomic_init(A *, C) 5321 Init, 5322 5323 // C __c11_atomic_load(A *, int) 5324 Load, 5325 5326 // void __atomic_load(A *, CP, int) 5327 LoadCopy, 5328 5329 // void __atomic_store(A *, CP, int) 5330 Copy, 5331 5332 // C __c11_atomic_add(A *, M, int) 5333 Arithmetic, 5334 5335 // C __atomic_exchange_n(A *, CP, int) 5336 Xchg, 5337 5338 // void __atomic_exchange(A *, C *, CP, int) 5339 GNUXchg, 5340 5341 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5342 C11CmpXchg, 5343 5344 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5345 GNUCmpXchg 5346 } Form = Init; 5347 5348 const unsigned NumForm = GNUCmpXchg + 1; 5349 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5350 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5351 // where: 5352 // C is an appropriate type, 5353 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5354 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5355 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5356 // the int parameters are for orderings. 5357 5358 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5359 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5360 "need to update code for modified forms"); 5361 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5362 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5363 AtomicExpr::AO__atomic_load, 5364 "need to update code for modified C11 atomics"); 5365 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5366 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5367 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5368 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5369 IsOpenCL; 5370 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5371 Op == AtomicExpr::AO__atomic_store_n || 5372 Op == AtomicExpr::AO__atomic_exchange_n || 5373 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5374 bool IsAddSub = false; 5375 5376 switch (Op) { 5377 case AtomicExpr::AO__c11_atomic_init: 5378 case AtomicExpr::AO__opencl_atomic_init: 5379 Form = Init; 5380 break; 5381 5382 case AtomicExpr::AO__c11_atomic_load: 5383 case AtomicExpr::AO__opencl_atomic_load: 5384 case AtomicExpr::AO__atomic_load_n: 5385 Form = Load; 5386 break; 5387 5388 case AtomicExpr::AO__atomic_load: 5389 Form = LoadCopy; 5390 break; 5391 5392 case AtomicExpr::AO__c11_atomic_store: 5393 case AtomicExpr::AO__opencl_atomic_store: 5394 case AtomicExpr::AO__atomic_store: 5395 case AtomicExpr::AO__atomic_store_n: 5396 Form = Copy; 5397 break; 5398 5399 case AtomicExpr::AO__c11_atomic_fetch_add: 5400 case AtomicExpr::AO__c11_atomic_fetch_sub: 5401 case AtomicExpr::AO__opencl_atomic_fetch_add: 5402 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5403 case AtomicExpr::AO__atomic_fetch_add: 5404 case AtomicExpr::AO__atomic_fetch_sub: 5405 case AtomicExpr::AO__atomic_add_fetch: 5406 case AtomicExpr::AO__atomic_sub_fetch: 5407 IsAddSub = true; 5408 Form = Arithmetic; 5409 break; 5410 case AtomicExpr::AO__c11_atomic_fetch_and: 5411 case AtomicExpr::AO__c11_atomic_fetch_or: 5412 case AtomicExpr::AO__c11_atomic_fetch_xor: 5413 case AtomicExpr::AO__opencl_atomic_fetch_and: 5414 case AtomicExpr::AO__opencl_atomic_fetch_or: 5415 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5416 case AtomicExpr::AO__atomic_fetch_and: 5417 case AtomicExpr::AO__atomic_fetch_or: 5418 case AtomicExpr::AO__atomic_fetch_xor: 5419 case AtomicExpr::AO__atomic_fetch_nand: 5420 case AtomicExpr::AO__atomic_and_fetch: 5421 case AtomicExpr::AO__atomic_or_fetch: 5422 case AtomicExpr::AO__atomic_xor_fetch: 5423 case AtomicExpr::AO__atomic_nand_fetch: 5424 Form = Arithmetic; 5425 break; 5426 case AtomicExpr::AO__c11_atomic_fetch_min: 5427 case AtomicExpr::AO__c11_atomic_fetch_max: 5428 case AtomicExpr::AO__opencl_atomic_fetch_min: 5429 case AtomicExpr::AO__opencl_atomic_fetch_max: 5430 case AtomicExpr::AO__atomic_min_fetch: 5431 case AtomicExpr::AO__atomic_max_fetch: 5432 case AtomicExpr::AO__atomic_fetch_min: 5433 case AtomicExpr::AO__atomic_fetch_max: 5434 Form = Arithmetic; 5435 break; 5436 5437 case AtomicExpr::AO__c11_atomic_exchange: 5438 case AtomicExpr::AO__opencl_atomic_exchange: 5439 case AtomicExpr::AO__atomic_exchange_n: 5440 Form = Xchg; 5441 break; 5442 5443 case AtomicExpr::AO__atomic_exchange: 5444 Form = GNUXchg; 5445 break; 5446 5447 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5448 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5449 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5450 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5451 Form = C11CmpXchg; 5452 break; 5453 5454 case AtomicExpr::AO__atomic_compare_exchange: 5455 case AtomicExpr::AO__atomic_compare_exchange_n: 5456 Form = GNUCmpXchg; 5457 break; 5458 } 5459 5460 unsigned AdjustedNumArgs = NumArgs[Form]; 5461 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5462 ++AdjustedNumArgs; 5463 // Check we have the right number of arguments. 5464 if (Args.size() < AdjustedNumArgs) { 5465 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5466 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5467 << ExprRange; 5468 return ExprError(); 5469 } else if (Args.size() > AdjustedNumArgs) { 5470 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5471 diag::err_typecheck_call_too_many_args) 5472 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5473 << ExprRange; 5474 return ExprError(); 5475 } 5476 5477 // Inspect the first argument of the atomic operation. 5478 Expr *Ptr = Args[0]; 5479 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5480 if (ConvertedPtr.isInvalid()) 5481 return ExprError(); 5482 5483 Ptr = ConvertedPtr.get(); 5484 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5485 if (!pointerType) { 5486 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5487 << Ptr->getType() << Ptr->getSourceRange(); 5488 return ExprError(); 5489 } 5490 5491 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5492 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5493 QualType ValType = AtomTy; // 'C' 5494 if (IsC11) { 5495 if (!AtomTy->isAtomicType()) { 5496 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5497 << Ptr->getType() << Ptr->getSourceRange(); 5498 return ExprError(); 5499 } 5500 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5501 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5502 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5503 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5504 << Ptr->getSourceRange(); 5505 return ExprError(); 5506 } 5507 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5508 } else if (Form != Load && Form != LoadCopy) { 5509 if (ValType.isConstQualified()) { 5510 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5511 << Ptr->getType() << Ptr->getSourceRange(); 5512 return ExprError(); 5513 } 5514 } 5515 5516 // For an arithmetic operation, the implied arithmetic must be well-formed. 5517 if (Form == Arithmetic) { 5518 // gcc does not enforce these rules for GNU atomics, but we do so for 5519 // sanity. 5520 auto IsAllowedValueType = [&](QualType ValType) { 5521 if (ValType->isIntegerType()) 5522 return true; 5523 if (ValType->isPointerType()) 5524 return true; 5525 if (!ValType->isFloatingType()) 5526 return false; 5527 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5528 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5529 &Context.getTargetInfo().getLongDoubleFormat() == 5530 &llvm::APFloat::x87DoubleExtended()) 5531 return false; 5532 return true; 5533 }; 5534 if (IsAddSub && !IsAllowedValueType(ValType)) { 5535 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5536 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5537 return ExprError(); 5538 } 5539 if (!IsAddSub && !ValType->isIntegerType()) { 5540 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5541 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5542 return ExprError(); 5543 } 5544 if (IsC11 && ValType->isPointerType() && 5545 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5546 diag::err_incomplete_type)) { 5547 return ExprError(); 5548 } 5549 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5550 // For __atomic_*_n operations, the value type must be a scalar integral or 5551 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5552 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5553 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5554 return ExprError(); 5555 } 5556 5557 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5558 !AtomTy->isScalarType()) { 5559 // For GNU atomics, require a trivially-copyable type. This is not part of 5560 // the GNU atomics specification, but we enforce it for sanity. 5561 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5562 << Ptr->getType() << Ptr->getSourceRange(); 5563 return ExprError(); 5564 } 5565 5566 switch (ValType.getObjCLifetime()) { 5567 case Qualifiers::OCL_None: 5568 case Qualifiers::OCL_ExplicitNone: 5569 // okay 5570 break; 5571 5572 case Qualifiers::OCL_Weak: 5573 case Qualifiers::OCL_Strong: 5574 case Qualifiers::OCL_Autoreleasing: 5575 // FIXME: Can this happen? By this point, ValType should be known 5576 // to be trivially copyable. 5577 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5578 << ValType << Ptr->getSourceRange(); 5579 return ExprError(); 5580 } 5581 5582 // All atomic operations have an overload which takes a pointer to a volatile 5583 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5584 // into the result or the other operands. Similarly atomic_load takes a 5585 // pointer to a const 'A'. 5586 ValType.removeLocalVolatile(); 5587 ValType.removeLocalConst(); 5588 QualType ResultType = ValType; 5589 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5590 Form == Init) 5591 ResultType = Context.VoidTy; 5592 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5593 ResultType = Context.BoolTy; 5594 5595 // The type of a parameter passed 'by value'. In the GNU atomics, such 5596 // arguments are actually passed as pointers. 5597 QualType ByValType = ValType; // 'CP' 5598 bool IsPassedByAddress = false; 5599 if (!IsC11 && !IsN) { 5600 ByValType = Ptr->getType(); 5601 IsPassedByAddress = true; 5602 } 5603 5604 SmallVector<Expr *, 5> APIOrderedArgs; 5605 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5606 APIOrderedArgs.push_back(Args[0]); 5607 switch (Form) { 5608 case Init: 5609 case Load: 5610 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5611 break; 5612 case LoadCopy: 5613 case Copy: 5614 case Arithmetic: 5615 case Xchg: 5616 APIOrderedArgs.push_back(Args[2]); // Val1 5617 APIOrderedArgs.push_back(Args[1]); // Order 5618 break; 5619 case GNUXchg: 5620 APIOrderedArgs.push_back(Args[2]); // Val1 5621 APIOrderedArgs.push_back(Args[3]); // Val2 5622 APIOrderedArgs.push_back(Args[1]); // Order 5623 break; 5624 case C11CmpXchg: 5625 APIOrderedArgs.push_back(Args[2]); // Val1 5626 APIOrderedArgs.push_back(Args[4]); // Val2 5627 APIOrderedArgs.push_back(Args[1]); // Order 5628 APIOrderedArgs.push_back(Args[3]); // OrderFail 5629 break; 5630 case GNUCmpXchg: 5631 APIOrderedArgs.push_back(Args[2]); // Val1 5632 APIOrderedArgs.push_back(Args[4]); // Val2 5633 APIOrderedArgs.push_back(Args[5]); // Weak 5634 APIOrderedArgs.push_back(Args[1]); // Order 5635 APIOrderedArgs.push_back(Args[3]); // OrderFail 5636 break; 5637 } 5638 } else 5639 APIOrderedArgs.append(Args.begin(), Args.end()); 5640 5641 // The first argument's non-CV pointer type is used to deduce the type of 5642 // subsequent arguments, except for: 5643 // - weak flag (always converted to bool) 5644 // - memory order (always converted to int) 5645 // - scope (always converted to int) 5646 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5647 QualType Ty; 5648 if (i < NumVals[Form] + 1) { 5649 switch (i) { 5650 case 0: 5651 // The first argument is always a pointer. It has a fixed type. 5652 // It is always dereferenced, a nullptr is undefined. 5653 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5654 // Nothing else to do: we already know all we want about this pointer. 5655 continue; 5656 case 1: 5657 // The second argument is the non-atomic operand. For arithmetic, this 5658 // is always passed by value, and for a compare_exchange it is always 5659 // passed by address. For the rest, GNU uses by-address and C11 uses 5660 // by-value. 5661 assert(Form != Load); 5662 if (Form == Arithmetic && ValType->isPointerType()) 5663 Ty = Context.getPointerDiffType(); 5664 else if (Form == Init || Form == Arithmetic) 5665 Ty = ValType; 5666 else if (Form == Copy || Form == Xchg) { 5667 if (IsPassedByAddress) { 5668 // The value pointer is always dereferenced, a nullptr is undefined. 5669 CheckNonNullArgument(*this, APIOrderedArgs[i], 5670 ExprRange.getBegin()); 5671 } 5672 Ty = ByValType; 5673 } else { 5674 Expr *ValArg = APIOrderedArgs[i]; 5675 // The value pointer is always dereferenced, a nullptr is undefined. 5676 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5677 LangAS AS = LangAS::Default; 5678 // Keep address space of non-atomic pointer type. 5679 if (const PointerType *PtrTy = 5680 ValArg->getType()->getAs<PointerType>()) { 5681 AS = PtrTy->getPointeeType().getAddressSpace(); 5682 } 5683 Ty = Context.getPointerType( 5684 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5685 } 5686 break; 5687 case 2: 5688 // The third argument to compare_exchange / GNU exchange is the desired 5689 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5690 if (IsPassedByAddress) 5691 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5692 Ty = ByValType; 5693 break; 5694 case 3: 5695 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5696 Ty = Context.BoolTy; 5697 break; 5698 } 5699 } else { 5700 // The order(s) and scope are always converted to int. 5701 Ty = Context.IntTy; 5702 } 5703 5704 InitializedEntity Entity = 5705 InitializedEntity::InitializeParameter(Context, Ty, false); 5706 ExprResult Arg = APIOrderedArgs[i]; 5707 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5708 if (Arg.isInvalid()) 5709 return true; 5710 APIOrderedArgs[i] = Arg.get(); 5711 } 5712 5713 // Permute the arguments into a 'consistent' order. 5714 SmallVector<Expr*, 5> SubExprs; 5715 SubExprs.push_back(Ptr); 5716 switch (Form) { 5717 case Init: 5718 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5719 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5720 break; 5721 case Load: 5722 SubExprs.push_back(APIOrderedArgs[1]); // Order 5723 break; 5724 case LoadCopy: 5725 case Copy: 5726 case Arithmetic: 5727 case Xchg: 5728 SubExprs.push_back(APIOrderedArgs[2]); // Order 5729 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5730 break; 5731 case GNUXchg: 5732 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5733 SubExprs.push_back(APIOrderedArgs[3]); // Order 5734 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5735 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5736 break; 5737 case C11CmpXchg: 5738 SubExprs.push_back(APIOrderedArgs[3]); // Order 5739 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5740 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5741 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5742 break; 5743 case GNUCmpXchg: 5744 SubExprs.push_back(APIOrderedArgs[4]); // Order 5745 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5746 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5747 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5748 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5749 break; 5750 } 5751 5752 if (SubExprs.size() >= 2 && Form != Init) { 5753 if (Optional<llvm::APSInt> Result = 5754 SubExprs[1]->getIntegerConstantExpr(Context)) 5755 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5756 Diag(SubExprs[1]->getBeginLoc(), 5757 diag::warn_atomic_op_has_invalid_memory_order) 5758 << SubExprs[1]->getSourceRange(); 5759 } 5760 5761 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5762 auto *Scope = Args[Args.size() - 1]; 5763 if (Optional<llvm::APSInt> Result = 5764 Scope->getIntegerConstantExpr(Context)) { 5765 if (!ScopeModel->isValid(Result->getZExtValue())) 5766 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5767 << Scope->getSourceRange(); 5768 } 5769 SubExprs.push_back(Scope); 5770 } 5771 5772 AtomicExpr *AE = new (Context) 5773 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5774 5775 if ((Op == AtomicExpr::AO__c11_atomic_load || 5776 Op == AtomicExpr::AO__c11_atomic_store || 5777 Op == AtomicExpr::AO__opencl_atomic_load || 5778 Op == AtomicExpr::AO__opencl_atomic_store ) && 5779 Context.AtomicUsesUnsupportedLibcall(AE)) 5780 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5781 << ((Op == AtomicExpr::AO__c11_atomic_load || 5782 Op == AtomicExpr::AO__opencl_atomic_load) 5783 ? 0 5784 : 1); 5785 5786 if (ValType->isExtIntType()) { 5787 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5788 return ExprError(); 5789 } 5790 5791 return AE; 5792 } 5793 5794 /// checkBuiltinArgument - Given a call to a builtin function, perform 5795 /// normal type-checking on the given argument, updating the call in 5796 /// place. This is useful when a builtin function requires custom 5797 /// type-checking for some of its arguments but not necessarily all of 5798 /// them. 5799 /// 5800 /// Returns true on error. 5801 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5802 FunctionDecl *Fn = E->getDirectCallee(); 5803 assert(Fn && "builtin call without direct callee!"); 5804 5805 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5806 InitializedEntity Entity = 5807 InitializedEntity::InitializeParameter(S.Context, Param); 5808 5809 ExprResult Arg = E->getArg(0); 5810 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5811 if (Arg.isInvalid()) 5812 return true; 5813 5814 E->setArg(ArgIndex, Arg.get()); 5815 return false; 5816 } 5817 5818 /// We have a call to a function like __sync_fetch_and_add, which is an 5819 /// overloaded function based on the pointer type of its first argument. 5820 /// The main BuildCallExpr routines have already promoted the types of 5821 /// arguments because all of these calls are prototyped as void(...). 5822 /// 5823 /// This function goes through and does final semantic checking for these 5824 /// builtins, as well as generating any warnings. 5825 ExprResult 5826 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5827 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5828 Expr *Callee = TheCall->getCallee(); 5829 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5830 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5831 5832 // Ensure that we have at least one argument to do type inference from. 5833 if (TheCall->getNumArgs() < 1) { 5834 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5835 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5836 return ExprError(); 5837 } 5838 5839 // Inspect the first argument of the atomic builtin. This should always be 5840 // a pointer type, whose element is an integral scalar or pointer type. 5841 // Because it is a pointer type, we don't have to worry about any implicit 5842 // casts here. 5843 // FIXME: We don't allow floating point scalars as input. 5844 Expr *FirstArg = TheCall->getArg(0); 5845 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5846 if (FirstArgResult.isInvalid()) 5847 return ExprError(); 5848 FirstArg = FirstArgResult.get(); 5849 TheCall->setArg(0, FirstArg); 5850 5851 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5852 if (!pointerType) { 5853 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5854 << FirstArg->getType() << FirstArg->getSourceRange(); 5855 return ExprError(); 5856 } 5857 5858 QualType ValType = pointerType->getPointeeType(); 5859 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5860 !ValType->isBlockPointerType()) { 5861 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5862 << FirstArg->getType() << FirstArg->getSourceRange(); 5863 return ExprError(); 5864 } 5865 5866 if (ValType.isConstQualified()) { 5867 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5868 << FirstArg->getType() << FirstArg->getSourceRange(); 5869 return ExprError(); 5870 } 5871 5872 switch (ValType.getObjCLifetime()) { 5873 case Qualifiers::OCL_None: 5874 case Qualifiers::OCL_ExplicitNone: 5875 // okay 5876 break; 5877 5878 case Qualifiers::OCL_Weak: 5879 case Qualifiers::OCL_Strong: 5880 case Qualifiers::OCL_Autoreleasing: 5881 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5882 << ValType << FirstArg->getSourceRange(); 5883 return ExprError(); 5884 } 5885 5886 // Strip any qualifiers off ValType. 5887 ValType = ValType.getUnqualifiedType(); 5888 5889 // The majority of builtins return a value, but a few have special return 5890 // types, so allow them to override appropriately below. 5891 QualType ResultType = ValType; 5892 5893 // We need to figure out which concrete builtin this maps onto. For example, 5894 // __sync_fetch_and_add with a 2 byte object turns into 5895 // __sync_fetch_and_add_2. 5896 #define BUILTIN_ROW(x) \ 5897 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5898 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5899 5900 static const unsigned BuiltinIndices[][5] = { 5901 BUILTIN_ROW(__sync_fetch_and_add), 5902 BUILTIN_ROW(__sync_fetch_and_sub), 5903 BUILTIN_ROW(__sync_fetch_and_or), 5904 BUILTIN_ROW(__sync_fetch_and_and), 5905 BUILTIN_ROW(__sync_fetch_and_xor), 5906 BUILTIN_ROW(__sync_fetch_and_nand), 5907 5908 BUILTIN_ROW(__sync_add_and_fetch), 5909 BUILTIN_ROW(__sync_sub_and_fetch), 5910 BUILTIN_ROW(__sync_and_and_fetch), 5911 BUILTIN_ROW(__sync_or_and_fetch), 5912 BUILTIN_ROW(__sync_xor_and_fetch), 5913 BUILTIN_ROW(__sync_nand_and_fetch), 5914 5915 BUILTIN_ROW(__sync_val_compare_and_swap), 5916 BUILTIN_ROW(__sync_bool_compare_and_swap), 5917 BUILTIN_ROW(__sync_lock_test_and_set), 5918 BUILTIN_ROW(__sync_lock_release), 5919 BUILTIN_ROW(__sync_swap) 5920 }; 5921 #undef BUILTIN_ROW 5922 5923 // Determine the index of the size. 5924 unsigned SizeIndex; 5925 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5926 case 1: SizeIndex = 0; break; 5927 case 2: SizeIndex = 1; break; 5928 case 4: SizeIndex = 2; break; 5929 case 8: SizeIndex = 3; break; 5930 case 16: SizeIndex = 4; break; 5931 default: 5932 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5933 << FirstArg->getType() << FirstArg->getSourceRange(); 5934 return ExprError(); 5935 } 5936 5937 // Each of these builtins has one pointer argument, followed by some number of 5938 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5939 // that we ignore. Find out which row of BuiltinIndices to read from as well 5940 // as the number of fixed args. 5941 unsigned BuiltinID = FDecl->getBuiltinID(); 5942 unsigned BuiltinIndex, NumFixed = 1; 5943 bool WarnAboutSemanticsChange = false; 5944 switch (BuiltinID) { 5945 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5946 case Builtin::BI__sync_fetch_and_add: 5947 case Builtin::BI__sync_fetch_and_add_1: 5948 case Builtin::BI__sync_fetch_and_add_2: 5949 case Builtin::BI__sync_fetch_and_add_4: 5950 case Builtin::BI__sync_fetch_and_add_8: 5951 case Builtin::BI__sync_fetch_and_add_16: 5952 BuiltinIndex = 0; 5953 break; 5954 5955 case Builtin::BI__sync_fetch_and_sub: 5956 case Builtin::BI__sync_fetch_and_sub_1: 5957 case Builtin::BI__sync_fetch_and_sub_2: 5958 case Builtin::BI__sync_fetch_and_sub_4: 5959 case Builtin::BI__sync_fetch_and_sub_8: 5960 case Builtin::BI__sync_fetch_and_sub_16: 5961 BuiltinIndex = 1; 5962 break; 5963 5964 case Builtin::BI__sync_fetch_and_or: 5965 case Builtin::BI__sync_fetch_and_or_1: 5966 case Builtin::BI__sync_fetch_and_or_2: 5967 case Builtin::BI__sync_fetch_and_or_4: 5968 case Builtin::BI__sync_fetch_and_or_8: 5969 case Builtin::BI__sync_fetch_and_or_16: 5970 BuiltinIndex = 2; 5971 break; 5972 5973 case Builtin::BI__sync_fetch_and_and: 5974 case Builtin::BI__sync_fetch_and_and_1: 5975 case Builtin::BI__sync_fetch_and_and_2: 5976 case Builtin::BI__sync_fetch_and_and_4: 5977 case Builtin::BI__sync_fetch_and_and_8: 5978 case Builtin::BI__sync_fetch_and_and_16: 5979 BuiltinIndex = 3; 5980 break; 5981 5982 case Builtin::BI__sync_fetch_and_xor: 5983 case Builtin::BI__sync_fetch_and_xor_1: 5984 case Builtin::BI__sync_fetch_and_xor_2: 5985 case Builtin::BI__sync_fetch_and_xor_4: 5986 case Builtin::BI__sync_fetch_and_xor_8: 5987 case Builtin::BI__sync_fetch_and_xor_16: 5988 BuiltinIndex = 4; 5989 break; 5990 5991 case Builtin::BI__sync_fetch_and_nand: 5992 case Builtin::BI__sync_fetch_and_nand_1: 5993 case Builtin::BI__sync_fetch_and_nand_2: 5994 case Builtin::BI__sync_fetch_and_nand_4: 5995 case Builtin::BI__sync_fetch_and_nand_8: 5996 case Builtin::BI__sync_fetch_and_nand_16: 5997 BuiltinIndex = 5; 5998 WarnAboutSemanticsChange = true; 5999 break; 6000 6001 case Builtin::BI__sync_add_and_fetch: 6002 case Builtin::BI__sync_add_and_fetch_1: 6003 case Builtin::BI__sync_add_and_fetch_2: 6004 case Builtin::BI__sync_add_and_fetch_4: 6005 case Builtin::BI__sync_add_and_fetch_8: 6006 case Builtin::BI__sync_add_and_fetch_16: 6007 BuiltinIndex = 6; 6008 break; 6009 6010 case Builtin::BI__sync_sub_and_fetch: 6011 case Builtin::BI__sync_sub_and_fetch_1: 6012 case Builtin::BI__sync_sub_and_fetch_2: 6013 case Builtin::BI__sync_sub_and_fetch_4: 6014 case Builtin::BI__sync_sub_and_fetch_8: 6015 case Builtin::BI__sync_sub_and_fetch_16: 6016 BuiltinIndex = 7; 6017 break; 6018 6019 case Builtin::BI__sync_and_and_fetch: 6020 case Builtin::BI__sync_and_and_fetch_1: 6021 case Builtin::BI__sync_and_and_fetch_2: 6022 case Builtin::BI__sync_and_and_fetch_4: 6023 case Builtin::BI__sync_and_and_fetch_8: 6024 case Builtin::BI__sync_and_and_fetch_16: 6025 BuiltinIndex = 8; 6026 break; 6027 6028 case Builtin::BI__sync_or_and_fetch: 6029 case Builtin::BI__sync_or_and_fetch_1: 6030 case Builtin::BI__sync_or_and_fetch_2: 6031 case Builtin::BI__sync_or_and_fetch_4: 6032 case Builtin::BI__sync_or_and_fetch_8: 6033 case Builtin::BI__sync_or_and_fetch_16: 6034 BuiltinIndex = 9; 6035 break; 6036 6037 case Builtin::BI__sync_xor_and_fetch: 6038 case Builtin::BI__sync_xor_and_fetch_1: 6039 case Builtin::BI__sync_xor_and_fetch_2: 6040 case Builtin::BI__sync_xor_and_fetch_4: 6041 case Builtin::BI__sync_xor_and_fetch_8: 6042 case Builtin::BI__sync_xor_and_fetch_16: 6043 BuiltinIndex = 10; 6044 break; 6045 6046 case Builtin::BI__sync_nand_and_fetch: 6047 case Builtin::BI__sync_nand_and_fetch_1: 6048 case Builtin::BI__sync_nand_and_fetch_2: 6049 case Builtin::BI__sync_nand_and_fetch_4: 6050 case Builtin::BI__sync_nand_and_fetch_8: 6051 case Builtin::BI__sync_nand_and_fetch_16: 6052 BuiltinIndex = 11; 6053 WarnAboutSemanticsChange = true; 6054 break; 6055 6056 case Builtin::BI__sync_val_compare_and_swap: 6057 case Builtin::BI__sync_val_compare_and_swap_1: 6058 case Builtin::BI__sync_val_compare_and_swap_2: 6059 case Builtin::BI__sync_val_compare_and_swap_4: 6060 case Builtin::BI__sync_val_compare_and_swap_8: 6061 case Builtin::BI__sync_val_compare_and_swap_16: 6062 BuiltinIndex = 12; 6063 NumFixed = 2; 6064 break; 6065 6066 case Builtin::BI__sync_bool_compare_and_swap: 6067 case Builtin::BI__sync_bool_compare_and_swap_1: 6068 case Builtin::BI__sync_bool_compare_and_swap_2: 6069 case Builtin::BI__sync_bool_compare_and_swap_4: 6070 case Builtin::BI__sync_bool_compare_and_swap_8: 6071 case Builtin::BI__sync_bool_compare_and_swap_16: 6072 BuiltinIndex = 13; 6073 NumFixed = 2; 6074 ResultType = Context.BoolTy; 6075 break; 6076 6077 case Builtin::BI__sync_lock_test_and_set: 6078 case Builtin::BI__sync_lock_test_and_set_1: 6079 case Builtin::BI__sync_lock_test_and_set_2: 6080 case Builtin::BI__sync_lock_test_and_set_4: 6081 case Builtin::BI__sync_lock_test_and_set_8: 6082 case Builtin::BI__sync_lock_test_and_set_16: 6083 BuiltinIndex = 14; 6084 break; 6085 6086 case Builtin::BI__sync_lock_release: 6087 case Builtin::BI__sync_lock_release_1: 6088 case Builtin::BI__sync_lock_release_2: 6089 case Builtin::BI__sync_lock_release_4: 6090 case Builtin::BI__sync_lock_release_8: 6091 case Builtin::BI__sync_lock_release_16: 6092 BuiltinIndex = 15; 6093 NumFixed = 0; 6094 ResultType = Context.VoidTy; 6095 break; 6096 6097 case Builtin::BI__sync_swap: 6098 case Builtin::BI__sync_swap_1: 6099 case Builtin::BI__sync_swap_2: 6100 case Builtin::BI__sync_swap_4: 6101 case Builtin::BI__sync_swap_8: 6102 case Builtin::BI__sync_swap_16: 6103 BuiltinIndex = 16; 6104 break; 6105 } 6106 6107 // Now that we know how many fixed arguments we expect, first check that we 6108 // have at least that many. 6109 if (TheCall->getNumArgs() < 1+NumFixed) { 6110 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6111 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6112 << Callee->getSourceRange(); 6113 return ExprError(); 6114 } 6115 6116 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6117 << Callee->getSourceRange(); 6118 6119 if (WarnAboutSemanticsChange) { 6120 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6121 << Callee->getSourceRange(); 6122 } 6123 6124 // Get the decl for the concrete builtin from this, we can tell what the 6125 // concrete integer type we should convert to is. 6126 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6127 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6128 FunctionDecl *NewBuiltinDecl; 6129 if (NewBuiltinID == BuiltinID) 6130 NewBuiltinDecl = FDecl; 6131 else { 6132 // Perform builtin lookup to avoid redeclaring it. 6133 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6134 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6135 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6136 assert(Res.getFoundDecl()); 6137 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6138 if (!NewBuiltinDecl) 6139 return ExprError(); 6140 } 6141 6142 // The first argument --- the pointer --- has a fixed type; we 6143 // deduce the types of the rest of the arguments accordingly. Walk 6144 // the remaining arguments, converting them to the deduced value type. 6145 for (unsigned i = 0; i != NumFixed; ++i) { 6146 ExprResult Arg = TheCall->getArg(i+1); 6147 6148 // GCC does an implicit conversion to the pointer or integer ValType. This 6149 // can fail in some cases (1i -> int**), check for this error case now. 6150 // Initialize the argument. 6151 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6152 ValType, /*consume*/ false); 6153 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6154 if (Arg.isInvalid()) 6155 return ExprError(); 6156 6157 // Okay, we have something that *can* be converted to the right type. Check 6158 // to see if there is a potentially weird extension going on here. This can 6159 // happen when you do an atomic operation on something like an char* and 6160 // pass in 42. The 42 gets converted to char. This is even more strange 6161 // for things like 45.123 -> char, etc. 6162 // FIXME: Do this check. 6163 TheCall->setArg(i+1, Arg.get()); 6164 } 6165 6166 // Create a new DeclRefExpr to refer to the new decl. 6167 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6168 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6169 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6170 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6171 6172 // Set the callee in the CallExpr. 6173 // FIXME: This loses syntactic information. 6174 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6175 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6176 CK_BuiltinFnToFnPtr); 6177 TheCall->setCallee(PromotedCall.get()); 6178 6179 // Change the result type of the call to match the original value type. This 6180 // is arbitrary, but the codegen for these builtins ins design to handle it 6181 // gracefully. 6182 TheCall->setType(ResultType); 6183 6184 // Prohibit use of _ExtInt with atomic builtins. 6185 // The arguments would have already been converted to the first argument's 6186 // type, so only need to check the first argument. 6187 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6188 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6189 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6190 return ExprError(); 6191 } 6192 6193 return TheCallResult; 6194 } 6195 6196 /// SemaBuiltinNontemporalOverloaded - We have a call to 6197 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6198 /// overloaded function based on the pointer type of its last argument. 6199 /// 6200 /// This function goes through and does final semantic checking for these 6201 /// builtins. 6202 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6203 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6204 DeclRefExpr *DRE = 6205 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6206 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6207 unsigned BuiltinID = FDecl->getBuiltinID(); 6208 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6209 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6210 "Unexpected nontemporal load/store builtin!"); 6211 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6212 unsigned numArgs = isStore ? 2 : 1; 6213 6214 // Ensure that we have the proper number of arguments. 6215 if (checkArgCount(*this, TheCall, numArgs)) 6216 return ExprError(); 6217 6218 // Inspect the last argument of the nontemporal builtin. This should always 6219 // be a pointer type, from which we imply the type of the memory access. 6220 // Because it is a pointer type, we don't have to worry about any implicit 6221 // casts here. 6222 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6223 ExprResult PointerArgResult = 6224 DefaultFunctionArrayLvalueConversion(PointerArg); 6225 6226 if (PointerArgResult.isInvalid()) 6227 return ExprError(); 6228 PointerArg = PointerArgResult.get(); 6229 TheCall->setArg(numArgs - 1, PointerArg); 6230 6231 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6232 if (!pointerType) { 6233 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6234 << PointerArg->getType() << PointerArg->getSourceRange(); 6235 return ExprError(); 6236 } 6237 6238 QualType ValType = pointerType->getPointeeType(); 6239 6240 // Strip any qualifiers off ValType. 6241 ValType = ValType.getUnqualifiedType(); 6242 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6243 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6244 !ValType->isVectorType()) { 6245 Diag(DRE->getBeginLoc(), 6246 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6247 << PointerArg->getType() << PointerArg->getSourceRange(); 6248 return ExprError(); 6249 } 6250 6251 if (!isStore) { 6252 TheCall->setType(ValType); 6253 return TheCallResult; 6254 } 6255 6256 ExprResult ValArg = TheCall->getArg(0); 6257 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6258 Context, ValType, /*consume*/ false); 6259 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6260 if (ValArg.isInvalid()) 6261 return ExprError(); 6262 6263 TheCall->setArg(0, ValArg.get()); 6264 TheCall->setType(Context.VoidTy); 6265 return TheCallResult; 6266 } 6267 6268 /// CheckObjCString - Checks that the argument to the builtin 6269 /// CFString constructor is correct 6270 /// Note: It might also make sense to do the UTF-16 conversion here (would 6271 /// simplify the backend). 6272 bool Sema::CheckObjCString(Expr *Arg) { 6273 Arg = Arg->IgnoreParenCasts(); 6274 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6275 6276 if (!Literal || !Literal->isAscii()) { 6277 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6278 << Arg->getSourceRange(); 6279 return true; 6280 } 6281 6282 if (Literal->containsNonAsciiOrNull()) { 6283 StringRef String = Literal->getString(); 6284 unsigned NumBytes = String.size(); 6285 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6286 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6287 llvm::UTF16 *ToPtr = &ToBuf[0]; 6288 6289 llvm::ConversionResult Result = 6290 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6291 ToPtr + NumBytes, llvm::strictConversion); 6292 // Check for conversion failure. 6293 if (Result != llvm::conversionOK) 6294 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6295 << Arg->getSourceRange(); 6296 } 6297 return false; 6298 } 6299 6300 /// CheckObjCString - Checks that the format string argument to the os_log() 6301 /// and os_trace() functions is correct, and converts it to const char *. 6302 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6303 Arg = Arg->IgnoreParenCasts(); 6304 auto *Literal = dyn_cast<StringLiteral>(Arg); 6305 if (!Literal) { 6306 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6307 Literal = ObjcLiteral->getString(); 6308 } 6309 } 6310 6311 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6312 return ExprError( 6313 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6314 << Arg->getSourceRange()); 6315 } 6316 6317 ExprResult Result(Literal); 6318 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6319 InitializedEntity Entity = 6320 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6321 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6322 return Result; 6323 } 6324 6325 /// Check that the user is calling the appropriate va_start builtin for the 6326 /// target and calling convention. 6327 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6328 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6329 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6330 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6331 TT.getArch() == llvm::Triple::aarch64_32); 6332 bool IsWindows = TT.isOSWindows(); 6333 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6334 if (IsX64 || IsAArch64) { 6335 CallingConv CC = CC_C; 6336 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6337 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6338 if (IsMSVAStart) { 6339 // Don't allow this in System V ABI functions. 6340 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6341 return S.Diag(Fn->getBeginLoc(), 6342 diag::err_ms_va_start_used_in_sysv_function); 6343 } else { 6344 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6345 // On x64 Windows, don't allow this in System V ABI functions. 6346 // (Yes, that means there's no corresponding way to support variadic 6347 // System V ABI functions on Windows.) 6348 if ((IsWindows && CC == CC_X86_64SysV) || 6349 (!IsWindows && CC == CC_Win64)) 6350 return S.Diag(Fn->getBeginLoc(), 6351 diag::err_va_start_used_in_wrong_abi_function) 6352 << !IsWindows; 6353 } 6354 return false; 6355 } 6356 6357 if (IsMSVAStart) 6358 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6359 return false; 6360 } 6361 6362 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6363 ParmVarDecl **LastParam = nullptr) { 6364 // Determine whether the current function, block, or obj-c method is variadic 6365 // and get its parameter list. 6366 bool IsVariadic = false; 6367 ArrayRef<ParmVarDecl *> Params; 6368 DeclContext *Caller = S.CurContext; 6369 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6370 IsVariadic = Block->isVariadic(); 6371 Params = Block->parameters(); 6372 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6373 IsVariadic = FD->isVariadic(); 6374 Params = FD->parameters(); 6375 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6376 IsVariadic = MD->isVariadic(); 6377 // FIXME: This isn't correct for methods (results in bogus warning). 6378 Params = MD->parameters(); 6379 } else if (isa<CapturedDecl>(Caller)) { 6380 // We don't support va_start in a CapturedDecl. 6381 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6382 return true; 6383 } else { 6384 // This must be some other declcontext that parses exprs. 6385 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6386 return true; 6387 } 6388 6389 if (!IsVariadic) { 6390 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6391 return true; 6392 } 6393 6394 if (LastParam) 6395 *LastParam = Params.empty() ? nullptr : Params.back(); 6396 6397 return false; 6398 } 6399 6400 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6401 /// for validity. Emit an error and return true on failure; return false 6402 /// on success. 6403 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6404 Expr *Fn = TheCall->getCallee(); 6405 6406 if (checkVAStartABI(*this, BuiltinID, Fn)) 6407 return true; 6408 6409 if (checkArgCount(*this, TheCall, 2)) 6410 return true; 6411 6412 // Type-check the first argument normally. 6413 if (checkBuiltinArgument(*this, TheCall, 0)) 6414 return true; 6415 6416 // Check that the current function is variadic, and get its last parameter. 6417 ParmVarDecl *LastParam; 6418 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6419 return true; 6420 6421 // Verify that the second argument to the builtin is the last argument of the 6422 // current function or method. 6423 bool SecondArgIsLastNamedArgument = false; 6424 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6425 6426 // These are valid if SecondArgIsLastNamedArgument is false after the next 6427 // block. 6428 QualType Type; 6429 SourceLocation ParamLoc; 6430 bool IsCRegister = false; 6431 6432 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6433 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6434 SecondArgIsLastNamedArgument = PV == LastParam; 6435 6436 Type = PV->getType(); 6437 ParamLoc = PV->getLocation(); 6438 IsCRegister = 6439 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6440 } 6441 } 6442 6443 if (!SecondArgIsLastNamedArgument) 6444 Diag(TheCall->getArg(1)->getBeginLoc(), 6445 diag::warn_second_arg_of_va_start_not_last_named_param); 6446 else if (IsCRegister || Type->isReferenceType() || 6447 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6448 // Promotable integers are UB, but enumerations need a bit of 6449 // extra checking to see what their promotable type actually is. 6450 if (!Type->isPromotableIntegerType()) 6451 return false; 6452 if (!Type->isEnumeralType()) 6453 return true; 6454 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6455 return !(ED && 6456 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6457 }()) { 6458 unsigned Reason = 0; 6459 if (Type->isReferenceType()) Reason = 1; 6460 else if (IsCRegister) Reason = 2; 6461 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6462 Diag(ParamLoc, diag::note_parameter_type) << Type; 6463 } 6464 6465 TheCall->setType(Context.VoidTy); 6466 return false; 6467 } 6468 6469 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6470 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6471 const LangOptions &LO = getLangOpts(); 6472 6473 if (LO.CPlusPlus) 6474 return Arg->getType() 6475 .getCanonicalType() 6476 .getTypePtr() 6477 ->getPointeeType() 6478 .withoutLocalFastQualifiers() == Context.CharTy; 6479 6480 // In C, allow aliasing through `char *`, this is required for AArch64 at 6481 // least. 6482 return true; 6483 }; 6484 6485 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6486 // const char *named_addr); 6487 6488 Expr *Func = Call->getCallee(); 6489 6490 if (Call->getNumArgs() < 3) 6491 return Diag(Call->getEndLoc(), 6492 diag::err_typecheck_call_too_few_args_at_least) 6493 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6494 6495 // Type-check the first argument normally. 6496 if (checkBuiltinArgument(*this, Call, 0)) 6497 return true; 6498 6499 // Check that the current function is variadic. 6500 if (checkVAStartIsInVariadicFunction(*this, Func)) 6501 return true; 6502 6503 // __va_start on Windows does not validate the parameter qualifiers 6504 6505 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6506 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6507 6508 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6509 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6510 6511 const QualType &ConstCharPtrTy = 6512 Context.getPointerType(Context.CharTy.withConst()); 6513 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6514 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6515 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6516 << 0 /* qualifier difference */ 6517 << 3 /* parameter mismatch */ 6518 << 2 << Arg1->getType() << ConstCharPtrTy; 6519 6520 const QualType SizeTy = Context.getSizeType(); 6521 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6522 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6523 << Arg2->getType() << SizeTy << 1 /* different class */ 6524 << 0 /* qualifier difference */ 6525 << 3 /* parameter mismatch */ 6526 << 3 << Arg2->getType() << SizeTy; 6527 6528 return false; 6529 } 6530 6531 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6532 /// friends. This is declared to take (...), so we have to check everything. 6533 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6534 if (checkArgCount(*this, TheCall, 2)) 6535 return true; 6536 6537 ExprResult OrigArg0 = TheCall->getArg(0); 6538 ExprResult OrigArg1 = TheCall->getArg(1); 6539 6540 // Do standard promotions between the two arguments, returning their common 6541 // type. 6542 QualType Res = UsualArithmeticConversions( 6543 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6544 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6545 return true; 6546 6547 // Make sure any conversions are pushed back into the call; this is 6548 // type safe since unordered compare builtins are declared as "_Bool 6549 // foo(...)". 6550 TheCall->setArg(0, OrigArg0.get()); 6551 TheCall->setArg(1, OrigArg1.get()); 6552 6553 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6554 return false; 6555 6556 // If the common type isn't a real floating type, then the arguments were 6557 // invalid for this operation. 6558 if (Res.isNull() || !Res->isRealFloatingType()) 6559 return Diag(OrigArg0.get()->getBeginLoc(), 6560 diag::err_typecheck_call_invalid_ordered_compare) 6561 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6562 << SourceRange(OrigArg0.get()->getBeginLoc(), 6563 OrigArg1.get()->getEndLoc()); 6564 6565 return false; 6566 } 6567 6568 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6569 /// __builtin_isnan and friends. This is declared to take (...), so we have 6570 /// to check everything. We expect the last argument to be a floating point 6571 /// value. 6572 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6573 if (checkArgCount(*this, TheCall, NumArgs)) 6574 return true; 6575 6576 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6577 // on all preceding parameters just being int. Try all of those. 6578 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6579 Expr *Arg = TheCall->getArg(i); 6580 6581 if (Arg->isTypeDependent()) 6582 return false; 6583 6584 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6585 6586 if (Res.isInvalid()) 6587 return true; 6588 TheCall->setArg(i, Res.get()); 6589 } 6590 6591 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6592 6593 if (OrigArg->isTypeDependent()) 6594 return false; 6595 6596 // Usual Unary Conversions will convert half to float, which we want for 6597 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6598 // type how it is, but do normal L->Rvalue conversions. 6599 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6600 OrigArg = UsualUnaryConversions(OrigArg).get(); 6601 else 6602 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6603 TheCall->setArg(NumArgs - 1, OrigArg); 6604 6605 // This operation requires a non-_Complex floating-point number. 6606 if (!OrigArg->getType()->isRealFloatingType()) 6607 return Diag(OrigArg->getBeginLoc(), 6608 diag::err_typecheck_call_invalid_unary_fp) 6609 << OrigArg->getType() << OrigArg->getSourceRange(); 6610 6611 return false; 6612 } 6613 6614 /// Perform semantic analysis for a call to __builtin_complex. 6615 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6616 if (checkArgCount(*this, TheCall, 2)) 6617 return true; 6618 6619 bool Dependent = false; 6620 for (unsigned I = 0; I != 2; ++I) { 6621 Expr *Arg = TheCall->getArg(I); 6622 QualType T = Arg->getType(); 6623 if (T->isDependentType()) { 6624 Dependent = true; 6625 continue; 6626 } 6627 6628 // Despite supporting _Complex int, GCC requires a real floating point type 6629 // for the operands of __builtin_complex. 6630 if (!T->isRealFloatingType()) { 6631 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6632 << Arg->getType() << Arg->getSourceRange(); 6633 } 6634 6635 ExprResult Converted = DefaultLvalueConversion(Arg); 6636 if (Converted.isInvalid()) 6637 return true; 6638 TheCall->setArg(I, Converted.get()); 6639 } 6640 6641 if (Dependent) { 6642 TheCall->setType(Context.DependentTy); 6643 return false; 6644 } 6645 6646 Expr *Real = TheCall->getArg(0); 6647 Expr *Imag = TheCall->getArg(1); 6648 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6649 return Diag(Real->getBeginLoc(), 6650 diag::err_typecheck_call_different_arg_types) 6651 << Real->getType() << Imag->getType() 6652 << Real->getSourceRange() << Imag->getSourceRange(); 6653 } 6654 6655 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6656 // don't allow this builtin to form those types either. 6657 // FIXME: Should we allow these types? 6658 if (Real->getType()->isFloat16Type()) 6659 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6660 << "_Float16"; 6661 if (Real->getType()->isHalfType()) 6662 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6663 << "half"; 6664 6665 TheCall->setType(Context.getComplexType(Real->getType())); 6666 return false; 6667 } 6668 6669 // Customized Sema Checking for VSX builtins that have the following signature: 6670 // vector [...] builtinName(vector [...], vector [...], const int); 6671 // Which takes the same type of vectors (any legal vector type) for the first 6672 // two arguments and takes compile time constant for the third argument. 6673 // Example builtins are : 6674 // vector double vec_xxpermdi(vector double, vector double, int); 6675 // vector short vec_xxsldwi(vector short, vector short, int); 6676 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6677 unsigned ExpectedNumArgs = 3; 6678 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6679 return true; 6680 6681 // Check the third argument is a compile time constant 6682 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6683 return Diag(TheCall->getBeginLoc(), 6684 diag::err_vsx_builtin_nonconstant_argument) 6685 << 3 /* argument index */ << TheCall->getDirectCallee() 6686 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6687 TheCall->getArg(2)->getEndLoc()); 6688 6689 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6690 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6691 6692 // Check the type of argument 1 and argument 2 are vectors. 6693 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6694 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6695 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6696 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6697 << TheCall->getDirectCallee() 6698 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6699 TheCall->getArg(1)->getEndLoc()); 6700 } 6701 6702 // Check the first two arguments are the same type. 6703 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6704 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6705 << TheCall->getDirectCallee() 6706 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6707 TheCall->getArg(1)->getEndLoc()); 6708 } 6709 6710 // When default clang type checking is turned off and the customized type 6711 // checking is used, the returning type of the function must be explicitly 6712 // set. Otherwise it is _Bool by default. 6713 TheCall->setType(Arg1Ty); 6714 6715 return false; 6716 } 6717 6718 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6719 // This is declared to take (...), so we have to check everything. 6720 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6721 if (TheCall->getNumArgs() < 2) 6722 return ExprError(Diag(TheCall->getEndLoc(), 6723 diag::err_typecheck_call_too_few_args_at_least) 6724 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6725 << TheCall->getSourceRange()); 6726 6727 // Determine which of the following types of shufflevector we're checking: 6728 // 1) unary, vector mask: (lhs, mask) 6729 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6730 QualType resType = TheCall->getArg(0)->getType(); 6731 unsigned numElements = 0; 6732 6733 if (!TheCall->getArg(0)->isTypeDependent() && 6734 !TheCall->getArg(1)->isTypeDependent()) { 6735 QualType LHSType = TheCall->getArg(0)->getType(); 6736 QualType RHSType = TheCall->getArg(1)->getType(); 6737 6738 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6739 return ExprError( 6740 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6741 << TheCall->getDirectCallee() 6742 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6743 TheCall->getArg(1)->getEndLoc())); 6744 6745 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6746 unsigned numResElements = TheCall->getNumArgs() - 2; 6747 6748 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6749 // with mask. If so, verify that RHS is an integer vector type with the 6750 // same number of elts as lhs. 6751 if (TheCall->getNumArgs() == 2) { 6752 if (!RHSType->hasIntegerRepresentation() || 6753 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6754 return ExprError(Diag(TheCall->getBeginLoc(), 6755 diag::err_vec_builtin_incompatible_vector) 6756 << TheCall->getDirectCallee() 6757 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6758 TheCall->getArg(1)->getEndLoc())); 6759 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6760 return ExprError(Diag(TheCall->getBeginLoc(), 6761 diag::err_vec_builtin_incompatible_vector) 6762 << TheCall->getDirectCallee() 6763 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6764 TheCall->getArg(1)->getEndLoc())); 6765 } else if (numElements != numResElements) { 6766 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6767 resType = Context.getVectorType(eltType, numResElements, 6768 VectorType::GenericVector); 6769 } 6770 } 6771 6772 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6773 if (TheCall->getArg(i)->isTypeDependent() || 6774 TheCall->getArg(i)->isValueDependent()) 6775 continue; 6776 6777 Optional<llvm::APSInt> Result; 6778 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6779 return ExprError(Diag(TheCall->getBeginLoc(), 6780 diag::err_shufflevector_nonconstant_argument) 6781 << TheCall->getArg(i)->getSourceRange()); 6782 6783 // Allow -1 which will be translated to undef in the IR. 6784 if (Result->isSigned() && Result->isAllOnes()) 6785 continue; 6786 6787 if (Result->getActiveBits() > 64 || 6788 Result->getZExtValue() >= numElements * 2) 6789 return ExprError(Diag(TheCall->getBeginLoc(), 6790 diag::err_shufflevector_argument_too_large) 6791 << TheCall->getArg(i)->getSourceRange()); 6792 } 6793 6794 SmallVector<Expr*, 32> exprs; 6795 6796 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6797 exprs.push_back(TheCall->getArg(i)); 6798 TheCall->setArg(i, nullptr); 6799 } 6800 6801 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6802 TheCall->getCallee()->getBeginLoc(), 6803 TheCall->getRParenLoc()); 6804 } 6805 6806 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6807 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6808 SourceLocation BuiltinLoc, 6809 SourceLocation RParenLoc) { 6810 ExprValueKind VK = VK_PRValue; 6811 ExprObjectKind OK = OK_Ordinary; 6812 QualType DstTy = TInfo->getType(); 6813 QualType SrcTy = E->getType(); 6814 6815 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6816 return ExprError(Diag(BuiltinLoc, 6817 diag::err_convertvector_non_vector) 6818 << E->getSourceRange()); 6819 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6820 return ExprError(Diag(BuiltinLoc, 6821 diag::err_convertvector_non_vector_type)); 6822 6823 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6824 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6825 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6826 if (SrcElts != DstElts) 6827 return ExprError(Diag(BuiltinLoc, 6828 diag::err_convertvector_incompatible_vector) 6829 << E->getSourceRange()); 6830 } 6831 6832 return new (Context) 6833 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6834 } 6835 6836 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6837 // This is declared to take (const void*, ...) and can take two 6838 // optional constant int args. 6839 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6840 unsigned NumArgs = TheCall->getNumArgs(); 6841 6842 if (NumArgs > 3) 6843 return Diag(TheCall->getEndLoc(), 6844 diag::err_typecheck_call_too_many_args_at_most) 6845 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6846 6847 // Argument 0 is checked for us and the remaining arguments must be 6848 // constant integers. 6849 for (unsigned i = 1; i != NumArgs; ++i) 6850 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6851 return true; 6852 6853 return false; 6854 } 6855 6856 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6857 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6858 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6859 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6860 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6861 if (checkArgCount(*this, TheCall, 1)) 6862 return true; 6863 Expr *Arg = TheCall->getArg(0); 6864 if (Arg->isInstantiationDependent()) 6865 return false; 6866 6867 QualType ArgTy = Arg->getType(); 6868 if (!ArgTy->hasFloatingRepresentation()) 6869 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6870 << ArgTy; 6871 if (Arg->isLValue()) { 6872 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6873 TheCall->setArg(0, FirstArg.get()); 6874 } 6875 TheCall->setType(TheCall->getArg(0)->getType()); 6876 return false; 6877 } 6878 6879 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6880 // __assume does not evaluate its arguments, and should warn if its argument 6881 // has side effects. 6882 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6883 Expr *Arg = TheCall->getArg(0); 6884 if (Arg->isInstantiationDependent()) return false; 6885 6886 if (Arg->HasSideEffects(Context)) 6887 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6888 << Arg->getSourceRange() 6889 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6890 6891 return false; 6892 } 6893 6894 /// Handle __builtin_alloca_with_align. This is declared 6895 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6896 /// than 8. 6897 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6898 // The alignment must be a constant integer. 6899 Expr *Arg = TheCall->getArg(1); 6900 6901 // We can't check the value of a dependent argument. 6902 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6903 if (const auto *UE = 6904 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6905 if (UE->getKind() == UETT_AlignOf || 6906 UE->getKind() == UETT_PreferredAlignOf) 6907 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6908 << Arg->getSourceRange(); 6909 6910 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6911 6912 if (!Result.isPowerOf2()) 6913 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6914 << Arg->getSourceRange(); 6915 6916 if (Result < Context.getCharWidth()) 6917 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6918 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6919 6920 if (Result > std::numeric_limits<int32_t>::max()) 6921 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6922 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6923 } 6924 6925 return false; 6926 } 6927 6928 /// Handle __builtin_assume_aligned. This is declared 6929 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6930 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6931 unsigned NumArgs = TheCall->getNumArgs(); 6932 6933 if (NumArgs > 3) 6934 return Diag(TheCall->getEndLoc(), 6935 diag::err_typecheck_call_too_many_args_at_most) 6936 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6937 6938 // The alignment must be a constant integer. 6939 Expr *Arg = TheCall->getArg(1); 6940 6941 // We can't check the value of a dependent argument. 6942 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6943 llvm::APSInt Result; 6944 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6945 return true; 6946 6947 if (!Result.isPowerOf2()) 6948 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6949 << Arg->getSourceRange(); 6950 6951 if (Result > Sema::MaximumAlignment) 6952 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6953 << Arg->getSourceRange() << Sema::MaximumAlignment; 6954 } 6955 6956 if (NumArgs > 2) { 6957 ExprResult Arg(TheCall->getArg(2)); 6958 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6959 Context.getSizeType(), false); 6960 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6961 if (Arg.isInvalid()) return true; 6962 TheCall->setArg(2, Arg.get()); 6963 } 6964 6965 return false; 6966 } 6967 6968 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6969 unsigned BuiltinID = 6970 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6971 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6972 6973 unsigned NumArgs = TheCall->getNumArgs(); 6974 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6975 if (NumArgs < NumRequiredArgs) { 6976 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6977 << 0 /* function call */ << NumRequiredArgs << NumArgs 6978 << TheCall->getSourceRange(); 6979 } 6980 if (NumArgs >= NumRequiredArgs + 0x100) { 6981 return Diag(TheCall->getEndLoc(), 6982 diag::err_typecheck_call_too_many_args_at_most) 6983 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6984 << TheCall->getSourceRange(); 6985 } 6986 unsigned i = 0; 6987 6988 // For formatting call, check buffer arg. 6989 if (!IsSizeCall) { 6990 ExprResult Arg(TheCall->getArg(i)); 6991 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6992 Context, Context.VoidPtrTy, false); 6993 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6994 if (Arg.isInvalid()) 6995 return true; 6996 TheCall->setArg(i, Arg.get()); 6997 i++; 6998 } 6999 7000 // Check string literal arg. 7001 unsigned FormatIdx = i; 7002 { 7003 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7004 if (Arg.isInvalid()) 7005 return true; 7006 TheCall->setArg(i, Arg.get()); 7007 i++; 7008 } 7009 7010 // Make sure variadic args are scalar. 7011 unsigned FirstDataArg = i; 7012 while (i < NumArgs) { 7013 ExprResult Arg = DefaultVariadicArgumentPromotion( 7014 TheCall->getArg(i), VariadicFunction, nullptr); 7015 if (Arg.isInvalid()) 7016 return true; 7017 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7018 if (ArgSize.getQuantity() >= 0x100) { 7019 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7020 << i << (int)ArgSize.getQuantity() << 0xff 7021 << TheCall->getSourceRange(); 7022 } 7023 TheCall->setArg(i, Arg.get()); 7024 i++; 7025 } 7026 7027 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7028 // call to avoid duplicate diagnostics. 7029 if (!IsSizeCall) { 7030 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7031 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7032 bool Success = CheckFormatArguments( 7033 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7034 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7035 CheckedVarArgs); 7036 if (!Success) 7037 return true; 7038 } 7039 7040 if (IsSizeCall) { 7041 TheCall->setType(Context.getSizeType()); 7042 } else { 7043 TheCall->setType(Context.VoidPtrTy); 7044 } 7045 return false; 7046 } 7047 7048 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7049 /// TheCall is a constant expression. 7050 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7051 llvm::APSInt &Result) { 7052 Expr *Arg = TheCall->getArg(ArgNum); 7053 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7054 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7055 7056 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7057 7058 Optional<llvm::APSInt> R; 7059 if (!(R = Arg->getIntegerConstantExpr(Context))) 7060 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7061 << FDecl->getDeclName() << Arg->getSourceRange(); 7062 Result = *R; 7063 return false; 7064 } 7065 7066 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7067 /// TheCall is a constant expression in the range [Low, High]. 7068 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7069 int Low, int High, bool RangeIsError) { 7070 if (isConstantEvaluated()) 7071 return false; 7072 llvm::APSInt Result; 7073 7074 // We can't check the value of a dependent argument. 7075 Expr *Arg = TheCall->getArg(ArgNum); 7076 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7077 return false; 7078 7079 // Check constant-ness first. 7080 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7081 return true; 7082 7083 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7084 if (RangeIsError) 7085 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7086 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7087 else 7088 // Defer the warning until we know if the code will be emitted so that 7089 // dead code can ignore this. 7090 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7091 PDiag(diag::warn_argument_invalid_range) 7092 << toString(Result, 10) << Low << High 7093 << Arg->getSourceRange()); 7094 } 7095 7096 return false; 7097 } 7098 7099 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7100 /// TheCall is a constant expression is a multiple of Num.. 7101 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7102 unsigned Num) { 7103 llvm::APSInt Result; 7104 7105 // We can't check the value of a dependent argument. 7106 Expr *Arg = TheCall->getArg(ArgNum); 7107 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7108 return false; 7109 7110 // Check constant-ness first. 7111 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7112 return true; 7113 7114 if (Result.getSExtValue() % Num != 0) 7115 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7116 << Num << Arg->getSourceRange(); 7117 7118 return false; 7119 } 7120 7121 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7122 /// constant expression representing a power of 2. 7123 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7124 llvm::APSInt Result; 7125 7126 // We can't check the value of a dependent argument. 7127 Expr *Arg = TheCall->getArg(ArgNum); 7128 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7129 return false; 7130 7131 // Check constant-ness first. 7132 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7133 return true; 7134 7135 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7136 // and only if x is a power of 2. 7137 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7138 return false; 7139 7140 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7141 << Arg->getSourceRange(); 7142 } 7143 7144 static bool IsShiftedByte(llvm::APSInt Value) { 7145 if (Value.isNegative()) 7146 return false; 7147 7148 // Check if it's a shifted byte, by shifting it down 7149 while (true) { 7150 // If the value fits in the bottom byte, the check passes. 7151 if (Value < 0x100) 7152 return true; 7153 7154 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7155 // fails. 7156 if ((Value & 0xFF) != 0) 7157 return false; 7158 7159 // If the bottom 8 bits are all 0, but something above that is nonzero, 7160 // then shifting the value right by 8 bits won't affect whether it's a 7161 // shifted byte or not. So do that, and go round again. 7162 Value >>= 8; 7163 } 7164 } 7165 7166 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7167 /// a constant expression representing an arbitrary byte value shifted left by 7168 /// a multiple of 8 bits. 7169 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7170 unsigned ArgBits) { 7171 llvm::APSInt Result; 7172 7173 // We can't check the value of a dependent argument. 7174 Expr *Arg = TheCall->getArg(ArgNum); 7175 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7176 return false; 7177 7178 // Check constant-ness first. 7179 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7180 return true; 7181 7182 // Truncate to the given size. 7183 Result = Result.getLoBits(ArgBits); 7184 Result.setIsUnsigned(true); 7185 7186 if (IsShiftedByte(Result)) 7187 return false; 7188 7189 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7190 << Arg->getSourceRange(); 7191 } 7192 7193 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7194 /// TheCall is a constant expression representing either a shifted byte value, 7195 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7196 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7197 /// Arm MVE intrinsics. 7198 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7199 int ArgNum, 7200 unsigned ArgBits) { 7201 llvm::APSInt Result; 7202 7203 // We can't check the value of a dependent argument. 7204 Expr *Arg = TheCall->getArg(ArgNum); 7205 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7206 return false; 7207 7208 // Check constant-ness first. 7209 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7210 return true; 7211 7212 // Truncate to the given size. 7213 Result = Result.getLoBits(ArgBits); 7214 Result.setIsUnsigned(true); 7215 7216 // Check to see if it's in either of the required forms. 7217 if (IsShiftedByte(Result) || 7218 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7219 return false; 7220 7221 return Diag(TheCall->getBeginLoc(), 7222 diag::err_argument_not_shifted_byte_or_xxff) 7223 << Arg->getSourceRange(); 7224 } 7225 7226 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7227 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7228 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7229 if (checkArgCount(*this, TheCall, 2)) 7230 return true; 7231 Expr *Arg0 = TheCall->getArg(0); 7232 Expr *Arg1 = TheCall->getArg(1); 7233 7234 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7235 if (FirstArg.isInvalid()) 7236 return true; 7237 QualType FirstArgType = FirstArg.get()->getType(); 7238 if (!FirstArgType->isAnyPointerType()) 7239 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7240 << "first" << FirstArgType << Arg0->getSourceRange(); 7241 TheCall->setArg(0, FirstArg.get()); 7242 7243 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7244 if (SecArg.isInvalid()) 7245 return true; 7246 QualType SecArgType = SecArg.get()->getType(); 7247 if (!SecArgType->isIntegerType()) 7248 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7249 << "second" << SecArgType << Arg1->getSourceRange(); 7250 7251 // Derive the return type from the pointer argument. 7252 TheCall->setType(FirstArgType); 7253 return false; 7254 } 7255 7256 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7257 if (checkArgCount(*this, TheCall, 2)) 7258 return true; 7259 7260 Expr *Arg0 = TheCall->getArg(0); 7261 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7262 if (FirstArg.isInvalid()) 7263 return true; 7264 QualType FirstArgType = FirstArg.get()->getType(); 7265 if (!FirstArgType->isAnyPointerType()) 7266 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7267 << "first" << FirstArgType << Arg0->getSourceRange(); 7268 TheCall->setArg(0, FirstArg.get()); 7269 7270 // Derive the return type from the pointer argument. 7271 TheCall->setType(FirstArgType); 7272 7273 // Second arg must be an constant in range [0,15] 7274 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7275 } 7276 7277 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7278 if (checkArgCount(*this, TheCall, 2)) 7279 return true; 7280 Expr *Arg0 = TheCall->getArg(0); 7281 Expr *Arg1 = TheCall->getArg(1); 7282 7283 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7284 if (FirstArg.isInvalid()) 7285 return true; 7286 QualType FirstArgType = FirstArg.get()->getType(); 7287 if (!FirstArgType->isAnyPointerType()) 7288 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7289 << "first" << FirstArgType << Arg0->getSourceRange(); 7290 7291 QualType SecArgType = Arg1->getType(); 7292 if (!SecArgType->isIntegerType()) 7293 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7294 << "second" << SecArgType << Arg1->getSourceRange(); 7295 TheCall->setType(Context.IntTy); 7296 return false; 7297 } 7298 7299 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7300 BuiltinID == AArch64::BI__builtin_arm_stg) { 7301 if (checkArgCount(*this, TheCall, 1)) 7302 return true; 7303 Expr *Arg0 = TheCall->getArg(0); 7304 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7305 if (FirstArg.isInvalid()) 7306 return true; 7307 7308 QualType FirstArgType = FirstArg.get()->getType(); 7309 if (!FirstArgType->isAnyPointerType()) 7310 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7311 << "first" << FirstArgType << Arg0->getSourceRange(); 7312 TheCall->setArg(0, FirstArg.get()); 7313 7314 // Derive the return type from the pointer argument. 7315 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7316 TheCall->setType(FirstArgType); 7317 return false; 7318 } 7319 7320 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7321 Expr *ArgA = TheCall->getArg(0); 7322 Expr *ArgB = TheCall->getArg(1); 7323 7324 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7325 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7326 7327 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7328 return true; 7329 7330 QualType ArgTypeA = ArgExprA.get()->getType(); 7331 QualType ArgTypeB = ArgExprB.get()->getType(); 7332 7333 auto isNull = [&] (Expr *E) -> bool { 7334 return E->isNullPointerConstant( 7335 Context, Expr::NPC_ValueDependentIsNotNull); }; 7336 7337 // argument should be either a pointer or null 7338 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7339 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7340 << "first" << ArgTypeA << ArgA->getSourceRange(); 7341 7342 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7343 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7344 << "second" << ArgTypeB << ArgB->getSourceRange(); 7345 7346 // Ensure Pointee types are compatible 7347 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7348 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7349 QualType pointeeA = ArgTypeA->getPointeeType(); 7350 QualType pointeeB = ArgTypeB->getPointeeType(); 7351 if (!Context.typesAreCompatible( 7352 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7353 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7354 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7355 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7356 << ArgB->getSourceRange(); 7357 } 7358 } 7359 7360 // at least one argument should be pointer type 7361 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7362 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7363 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7364 7365 if (isNull(ArgA)) // adopt type of the other pointer 7366 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7367 7368 if (isNull(ArgB)) 7369 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7370 7371 TheCall->setArg(0, ArgExprA.get()); 7372 TheCall->setArg(1, ArgExprB.get()); 7373 TheCall->setType(Context.LongLongTy); 7374 return false; 7375 } 7376 assert(false && "Unhandled ARM MTE intrinsic"); 7377 return true; 7378 } 7379 7380 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7381 /// TheCall is an ARM/AArch64 special register string literal. 7382 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7383 int ArgNum, unsigned ExpectedFieldNum, 7384 bool AllowName) { 7385 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7386 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7387 BuiltinID == ARM::BI__builtin_arm_rsr || 7388 BuiltinID == ARM::BI__builtin_arm_rsrp || 7389 BuiltinID == ARM::BI__builtin_arm_wsr || 7390 BuiltinID == ARM::BI__builtin_arm_wsrp; 7391 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7392 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7393 BuiltinID == AArch64::BI__builtin_arm_rsr || 7394 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7395 BuiltinID == AArch64::BI__builtin_arm_wsr || 7396 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7397 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7398 7399 // We can't check the value of a dependent argument. 7400 Expr *Arg = TheCall->getArg(ArgNum); 7401 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7402 return false; 7403 7404 // Check if the argument is a string literal. 7405 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7406 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7407 << Arg->getSourceRange(); 7408 7409 // Check the type of special register given. 7410 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7411 SmallVector<StringRef, 6> Fields; 7412 Reg.split(Fields, ":"); 7413 7414 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7415 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7416 << Arg->getSourceRange(); 7417 7418 // If the string is the name of a register then we cannot check that it is 7419 // valid here but if the string is of one the forms described in ACLE then we 7420 // can check that the supplied fields are integers and within the valid 7421 // ranges. 7422 if (Fields.size() > 1) { 7423 bool FiveFields = Fields.size() == 5; 7424 7425 bool ValidString = true; 7426 if (IsARMBuiltin) { 7427 ValidString &= Fields[0].startswith_insensitive("cp") || 7428 Fields[0].startswith_insensitive("p"); 7429 if (ValidString) 7430 Fields[0] = Fields[0].drop_front( 7431 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7432 7433 ValidString &= Fields[2].startswith_insensitive("c"); 7434 if (ValidString) 7435 Fields[2] = Fields[2].drop_front(1); 7436 7437 if (FiveFields) { 7438 ValidString &= Fields[3].startswith_insensitive("c"); 7439 if (ValidString) 7440 Fields[3] = Fields[3].drop_front(1); 7441 } 7442 } 7443 7444 SmallVector<int, 5> Ranges; 7445 if (FiveFields) 7446 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7447 else 7448 Ranges.append({15, 7, 15}); 7449 7450 for (unsigned i=0; i<Fields.size(); ++i) { 7451 int IntField; 7452 ValidString &= !Fields[i].getAsInteger(10, IntField); 7453 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7454 } 7455 7456 if (!ValidString) 7457 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7458 << Arg->getSourceRange(); 7459 } else if (IsAArch64Builtin && Fields.size() == 1) { 7460 // If the register name is one of those that appear in the condition below 7461 // and the special register builtin being used is one of the write builtins, 7462 // then we require that the argument provided for writing to the register 7463 // is an integer constant expression. This is because it will be lowered to 7464 // an MSR (immediate) instruction, so we need to know the immediate at 7465 // compile time. 7466 if (TheCall->getNumArgs() != 2) 7467 return false; 7468 7469 std::string RegLower = Reg.lower(); 7470 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7471 RegLower != "pan" && RegLower != "uao") 7472 return false; 7473 7474 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7475 } 7476 7477 return false; 7478 } 7479 7480 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7481 /// Emit an error and return true on failure; return false on success. 7482 /// TypeStr is a string containing the type descriptor of the value returned by 7483 /// the builtin and the descriptors of the expected type of the arguments. 7484 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 7485 7486 assert((TypeStr[0] != '\0') && 7487 "Invalid types in PPC MMA builtin declaration"); 7488 7489 unsigned Mask = 0; 7490 unsigned ArgNum = 0; 7491 7492 // The first type in TypeStr is the type of the value returned by the 7493 // builtin. So we first read that type and change the type of TheCall. 7494 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7495 TheCall->setType(type); 7496 7497 while (*TypeStr != '\0') { 7498 Mask = 0; 7499 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7500 if (ArgNum >= TheCall->getNumArgs()) { 7501 ArgNum++; 7502 break; 7503 } 7504 7505 Expr *Arg = TheCall->getArg(ArgNum); 7506 QualType ArgType = Arg->getType(); 7507 7508 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7509 (!ExpectedType->isVoidPointerType() && 7510 ArgType.getCanonicalType() != ExpectedType)) 7511 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7512 << ArgType << ExpectedType << 1 << 0 << 0; 7513 7514 // If the value of the Mask is not 0, we have a constraint in the size of 7515 // the integer argument so here we ensure the argument is a constant that 7516 // is in the valid range. 7517 if (Mask != 0 && 7518 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7519 return true; 7520 7521 ArgNum++; 7522 } 7523 7524 // In case we exited early from the previous loop, there are other types to 7525 // read from TypeStr. So we need to read them all to ensure we have the right 7526 // number of arguments in TheCall and if it is not the case, to display a 7527 // better error message. 7528 while (*TypeStr != '\0') { 7529 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7530 ArgNum++; 7531 } 7532 if (checkArgCount(*this, TheCall, ArgNum)) 7533 return true; 7534 7535 return false; 7536 } 7537 7538 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7539 /// This checks that the target supports __builtin_longjmp and 7540 /// that val is a constant 1. 7541 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7542 if (!Context.getTargetInfo().hasSjLjLowering()) 7543 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7544 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7545 7546 Expr *Arg = TheCall->getArg(1); 7547 llvm::APSInt Result; 7548 7549 // TODO: This is less than ideal. Overload this to take a value. 7550 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7551 return true; 7552 7553 if (Result != 1) 7554 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7555 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7556 7557 return false; 7558 } 7559 7560 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7561 /// This checks that the target supports __builtin_setjmp. 7562 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7563 if (!Context.getTargetInfo().hasSjLjLowering()) 7564 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7565 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7566 return false; 7567 } 7568 7569 namespace { 7570 7571 class UncoveredArgHandler { 7572 enum { Unknown = -1, AllCovered = -2 }; 7573 7574 signed FirstUncoveredArg = Unknown; 7575 SmallVector<const Expr *, 4> DiagnosticExprs; 7576 7577 public: 7578 UncoveredArgHandler() = default; 7579 7580 bool hasUncoveredArg() const { 7581 return (FirstUncoveredArg >= 0); 7582 } 7583 7584 unsigned getUncoveredArg() const { 7585 assert(hasUncoveredArg() && "no uncovered argument"); 7586 return FirstUncoveredArg; 7587 } 7588 7589 void setAllCovered() { 7590 // A string has been found with all arguments covered, so clear out 7591 // the diagnostics. 7592 DiagnosticExprs.clear(); 7593 FirstUncoveredArg = AllCovered; 7594 } 7595 7596 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7597 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7598 7599 // Don't update if a previous string covers all arguments. 7600 if (FirstUncoveredArg == AllCovered) 7601 return; 7602 7603 // UncoveredArgHandler tracks the highest uncovered argument index 7604 // and with it all the strings that match this index. 7605 if (NewFirstUncoveredArg == FirstUncoveredArg) 7606 DiagnosticExprs.push_back(StrExpr); 7607 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7608 DiagnosticExprs.clear(); 7609 DiagnosticExprs.push_back(StrExpr); 7610 FirstUncoveredArg = NewFirstUncoveredArg; 7611 } 7612 } 7613 7614 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7615 }; 7616 7617 enum StringLiteralCheckType { 7618 SLCT_NotALiteral, 7619 SLCT_UncheckedLiteral, 7620 SLCT_CheckedLiteral 7621 }; 7622 7623 } // namespace 7624 7625 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7626 BinaryOperatorKind BinOpKind, 7627 bool AddendIsRight) { 7628 unsigned BitWidth = Offset.getBitWidth(); 7629 unsigned AddendBitWidth = Addend.getBitWidth(); 7630 // There might be negative interim results. 7631 if (Addend.isUnsigned()) { 7632 Addend = Addend.zext(++AddendBitWidth); 7633 Addend.setIsSigned(true); 7634 } 7635 // Adjust the bit width of the APSInts. 7636 if (AddendBitWidth > BitWidth) { 7637 Offset = Offset.sext(AddendBitWidth); 7638 BitWidth = AddendBitWidth; 7639 } else if (BitWidth > AddendBitWidth) { 7640 Addend = Addend.sext(BitWidth); 7641 } 7642 7643 bool Ov = false; 7644 llvm::APSInt ResOffset = Offset; 7645 if (BinOpKind == BO_Add) 7646 ResOffset = Offset.sadd_ov(Addend, Ov); 7647 else { 7648 assert(AddendIsRight && BinOpKind == BO_Sub && 7649 "operator must be add or sub with addend on the right"); 7650 ResOffset = Offset.ssub_ov(Addend, Ov); 7651 } 7652 7653 // We add an offset to a pointer here so we should support an offset as big as 7654 // possible. 7655 if (Ov) { 7656 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7657 "index (intermediate) result too big"); 7658 Offset = Offset.sext(2 * BitWidth); 7659 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7660 return; 7661 } 7662 7663 Offset = ResOffset; 7664 } 7665 7666 namespace { 7667 7668 // This is a wrapper class around StringLiteral to support offsetted string 7669 // literals as format strings. It takes the offset into account when returning 7670 // the string and its length or the source locations to display notes correctly. 7671 class FormatStringLiteral { 7672 const StringLiteral *FExpr; 7673 int64_t Offset; 7674 7675 public: 7676 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7677 : FExpr(fexpr), Offset(Offset) {} 7678 7679 StringRef getString() const { 7680 return FExpr->getString().drop_front(Offset); 7681 } 7682 7683 unsigned getByteLength() const { 7684 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7685 } 7686 7687 unsigned getLength() const { return FExpr->getLength() - Offset; } 7688 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7689 7690 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7691 7692 QualType getType() const { return FExpr->getType(); } 7693 7694 bool isAscii() const { return FExpr->isAscii(); } 7695 bool isWide() const { return FExpr->isWide(); } 7696 bool isUTF8() const { return FExpr->isUTF8(); } 7697 bool isUTF16() const { return FExpr->isUTF16(); } 7698 bool isUTF32() const { return FExpr->isUTF32(); } 7699 bool isPascal() const { return FExpr->isPascal(); } 7700 7701 SourceLocation getLocationOfByte( 7702 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7703 const TargetInfo &Target, unsigned *StartToken = nullptr, 7704 unsigned *StartTokenByteOffset = nullptr) const { 7705 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7706 StartToken, StartTokenByteOffset); 7707 } 7708 7709 SourceLocation getBeginLoc() const LLVM_READONLY { 7710 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7711 } 7712 7713 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7714 }; 7715 7716 } // namespace 7717 7718 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7719 const Expr *OrigFormatExpr, 7720 ArrayRef<const Expr *> Args, 7721 bool HasVAListArg, unsigned format_idx, 7722 unsigned firstDataArg, 7723 Sema::FormatStringType Type, 7724 bool inFunctionCall, 7725 Sema::VariadicCallType CallType, 7726 llvm::SmallBitVector &CheckedVarArgs, 7727 UncoveredArgHandler &UncoveredArg, 7728 bool IgnoreStringsWithoutSpecifiers); 7729 7730 // Determine if an expression is a string literal or constant string. 7731 // If this function returns false on the arguments to a function expecting a 7732 // format string, we will usually need to emit a warning. 7733 // True string literals are then checked by CheckFormatString. 7734 static StringLiteralCheckType 7735 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7736 bool HasVAListArg, unsigned format_idx, 7737 unsigned firstDataArg, Sema::FormatStringType Type, 7738 Sema::VariadicCallType CallType, bool InFunctionCall, 7739 llvm::SmallBitVector &CheckedVarArgs, 7740 UncoveredArgHandler &UncoveredArg, 7741 llvm::APSInt Offset, 7742 bool IgnoreStringsWithoutSpecifiers = false) { 7743 if (S.isConstantEvaluated()) 7744 return SLCT_NotALiteral; 7745 tryAgain: 7746 assert(Offset.isSigned() && "invalid offset"); 7747 7748 if (E->isTypeDependent() || E->isValueDependent()) 7749 return SLCT_NotALiteral; 7750 7751 E = E->IgnoreParenCasts(); 7752 7753 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7754 // Technically -Wformat-nonliteral does not warn about this case. 7755 // The behavior of printf and friends in this case is implementation 7756 // dependent. Ideally if the format string cannot be null then 7757 // it should have a 'nonnull' attribute in the function prototype. 7758 return SLCT_UncheckedLiteral; 7759 7760 switch (E->getStmtClass()) { 7761 case Stmt::BinaryConditionalOperatorClass: 7762 case Stmt::ConditionalOperatorClass: { 7763 // The expression is a literal if both sub-expressions were, and it was 7764 // completely checked only if both sub-expressions were checked. 7765 const AbstractConditionalOperator *C = 7766 cast<AbstractConditionalOperator>(E); 7767 7768 // Determine whether it is necessary to check both sub-expressions, for 7769 // example, because the condition expression is a constant that can be 7770 // evaluated at compile time. 7771 bool CheckLeft = true, CheckRight = true; 7772 7773 bool Cond; 7774 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7775 S.isConstantEvaluated())) { 7776 if (Cond) 7777 CheckRight = false; 7778 else 7779 CheckLeft = false; 7780 } 7781 7782 // We need to maintain the offsets for the right and the left hand side 7783 // separately to check if every possible indexed expression is a valid 7784 // string literal. They might have different offsets for different string 7785 // literals in the end. 7786 StringLiteralCheckType Left; 7787 if (!CheckLeft) 7788 Left = SLCT_UncheckedLiteral; 7789 else { 7790 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7791 HasVAListArg, format_idx, firstDataArg, 7792 Type, CallType, InFunctionCall, 7793 CheckedVarArgs, UncoveredArg, Offset, 7794 IgnoreStringsWithoutSpecifiers); 7795 if (Left == SLCT_NotALiteral || !CheckRight) { 7796 return Left; 7797 } 7798 } 7799 7800 StringLiteralCheckType Right = checkFormatStringExpr( 7801 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7802 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7803 IgnoreStringsWithoutSpecifiers); 7804 7805 return (CheckLeft && Left < Right) ? Left : Right; 7806 } 7807 7808 case Stmt::ImplicitCastExprClass: 7809 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7810 goto tryAgain; 7811 7812 case Stmt::OpaqueValueExprClass: 7813 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7814 E = src; 7815 goto tryAgain; 7816 } 7817 return SLCT_NotALiteral; 7818 7819 case Stmt::PredefinedExprClass: 7820 // While __func__, etc., are technically not string literals, they 7821 // cannot contain format specifiers and thus are not a security 7822 // liability. 7823 return SLCT_UncheckedLiteral; 7824 7825 case Stmt::DeclRefExprClass: { 7826 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7827 7828 // As an exception, do not flag errors for variables binding to 7829 // const string literals. 7830 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7831 bool isConstant = false; 7832 QualType T = DR->getType(); 7833 7834 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7835 isConstant = AT->getElementType().isConstant(S.Context); 7836 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7837 isConstant = T.isConstant(S.Context) && 7838 PT->getPointeeType().isConstant(S.Context); 7839 } else if (T->isObjCObjectPointerType()) { 7840 // In ObjC, there is usually no "const ObjectPointer" type, 7841 // so don't check if the pointee type is constant. 7842 isConstant = T.isConstant(S.Context); 7843 } 7844 7845 if (isConstant) { 7846 if (const Expr *Init = VD->getAnyInitializer()) { 7847 // Look through initializers like const char c[] = { "foo" } 7848 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7849 if (InitList->isStringLiteralInit()) 7850 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7851 } 7852 return checkFormatStringExpr(S, Init, Args, 7853 HasVAListArg, format_idx, 7854 firstDataArg, Type, CallType, 7855 /*InFunctionCall*/ false, CheckedVarArgs, 7856 UncoveredArg, Offset); 7857 } 7858 } 7859 7860 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7861 // special check to see if the format string is a function parameter 7862 // of the function calling the printf function. If the function 7863 // has an attribute indicating it is a printf-like function, then we 7864 // should suppress warnings concerning non-literals being used in a call 7865 // to a vprintf function. For example: 7866 // 7867 // void 7868 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7869 // va_list ap; 7870 // va_start(ap, fmt); 7871 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7872 // ... 7873 // } 7874 if (HasVAListArg) { 7875 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7876 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7877 int PVIndex = PV->getFunctionScopeIndex() + 1; 7878 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7879 // adjust for implicit parameter 7880 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7881 if (MD->isInstance()) 7882 ++PVIndex; 7883 // We also check if the formats are compatible. 7884 // We can't pass a 'scanf' string to a 'printf' function. 7885 if (PVIndex == PVFormat->getFormatIdx() && 7886 Type == S.GetFormatStringType(PVFormat)) 7887 return SLCT_UncheckedLiteral; 7888 } 7889 } 7890 } 7891 } 7892 } 7893 7894 return SLCT_NotALiteral; 7895 } 7896 7897 case Stmt::CallExprClass: 7898 case Stmt::CXXMemberCallExprClass: { 7899 const CallExpr *CE = cast<CallExpr>(E); 7900 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7901 bool IsFirst = true; 7902 StringLiteralCheckType CommonResult; 7903 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7904 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7905 StringLiteralCheckType Result = checkFormatStringExpr( 7906 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7907 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7908 IgnoreStringsWithoutSpecifiers); 7909 if (IsFirst) { 7910 CommonResult = Result; 7911 IsFirst = false; 7912 } 7913 } 7914 if (!IsFirst) 7915 return CommonResult; 7916 7917 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7918 unsigned BuiltinID = FD->getBuiltinID(); 7919 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7920 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7921 const Expr *Arg = CE->getArg(0); 7922 return checkFormatStringExpr(S, Arg, Args, 7923 HasVAListArg, format_idx, 7924 firstDataArg, Type, CallType, 7925 InFunctionCall, CheckedVarArgs, 7926 UncoveredArg, Offset, 7927 IgnoreStringsWithoutSpecifiers); 7928 } 7929 } 7930 } 7931 7932 return SLCT_NotALiteral; 7933 } 7934 case Stmt::ObjCMessageExprClass: { 7935 const auto *ME = cast<ObjCMessageExpr>(E); 7936 if (const auto *MD = ME->getMethodDecl()) { 7937 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7938 // As a special case heuristic, if we're using the method -[NSBundle 7939 // localizedStringForKey:value:table:], ignore any key strings that lack 7940 // format specifiers. The idea is that if the key doesn't have any 7941 // format specifiers then its probably just a key to map to the 7942 // localized strings. If it does have format specifiers though, then its 7943 // likely that the text of the key is the format string in the 7944 // programmer's language, and should be checked. 7945 const ObjCInterfaceDecl *IFace; 7946 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7947 IFace->getIdentifier()->isStr("NSBundle") && 7948 MD->getSelector().isKeywordSelector( 7949 {"localizedStringForKey", "value", "table"})) { 7950 IgnoreStringsWithoutSpecifiers = true; 7951 } 7952 7953 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7954 return checkFormatStringExpr( 7955 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7956 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7957 IgnoreStringsWithoutSpecifiers); 7958 } 7959 } 7960 7961 return SLCT_NotALiteral; 7962 } 7963 case Stmt::ObjCStringLiteralClass: 7964 case Stmt::StringLiteralClass: { 7965 const StringLiteral *StrE = nullptr; 7966 7967 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7968 StrE = ObjCFExpr->getString(); 7969 else 7970 StrE = cast<StringLiteral>(E); 7971 7972 if (StrE) { 7973 if (Offset.isNegative() || Offset > StrE->getLength()) { 7974 // TODO: It would be better to have an explicit warning for out of 7975 // bounds literals. 7976 return SLCT_NotALiteral; 7977 } 7978 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7979 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7980 firstDataArg, Type, InFunctionCall, CallType, 7981 CheckedVarArgs, UncoveredArg, 7982 IgnoreStringsWithoutSpecifiers); 7983 return SLCT_CheckedLiteral; 7984 } 7985 7986 return SLCT_NotALiteral; 7987 } 7988 case Stmt::BinaryOperatorClass: { 7989 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7990 7991 // A string literal + an int offset is still a string literal. 7992 if (BinOp->isAdditiveOp()) { 7993 Expr::EvalResult LResult, RResult; 7994 7995 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7996 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7997 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7998 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7999 8000 if (LIsInt != RIsInt) { 8001 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8002 8003 if (LIsInt) { 8004 if (BinOpKind == BO_Add) { 8005 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8006 E = BinOp->getRHS(); 8007 goto tryAgain; 8008 } 8009 } else { 8010 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8011 E = BinOp->getLHS(); 8012 goto tryAgain; 8013 } 8014 } 8015 } 8016 8017 return SLCT_NotALiteral; 8018 } 8019 case Stmt::UnaryOperatorClass: { 8020 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8021 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8022 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8023 Expr::EvalResult IndexResult; 8024 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8025 Expr::SE_NoSideEffects, 8026 S.isConstantEvaluated())) { 8027 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8028 /*RHS is int*/ true); 8029 E = ASE->getBase(); 8030 goto tryAgain; 8031 } 8032 } 8033 8034 return SLCT_NotALiteral; 8035 } 8036 8037 default: 8038 return SLCT_NotALiteral; 8039 } 8040 } 8041 8042 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8043 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8044 .Case("scanf", FST_Scanf) 8045 .Cases("printf", "printf0", FST_Printf) 8046 .Cases("NSString", "CFString", FST_NSString) 8047 .Case("strftime", FST_Strftime) 8048 .Case("strfmon", FST_Strfmon) 8049 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8050 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8051 .Case("os_trace", FST_OSLog) 8052 .Case("os_log", FST_OSLog) 8053 .Default(FST_Unknown); 8054 } 8055 8056 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8057 /// functions) for correct use of format strings. 8058 /// Returns true if a format string has been fully checked. 8059 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8060 ArrayRef<const Expr *> Args, 8061 bool IsCXXMember, 8062 VariadicCallType CallType, 8063 SourceLocation Loc, SourceRange Range, 8064 llvm::SmallBitVector &CheckedVarArgs) { 8065 FormatStringInfo FSI; 8066 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8067 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8068 FSI.FirstDataArg, GetFormatStringType(Format), 8069 CallType, Loc, Range, CheckedVarArgs); 8070 return false; 8071 } 8072 8073 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8074 bool HasVAListArg, unsigned format_idx, 8075 unsigned firstDataArg, FormatStringType Type, 8076 VariadicCallType CallType, 8077 SourceLocation Loc, SourceRange Range, 8078 llvm::SmallBitVector &CheckedVarArgs) { 8079 // CHECK: printf/scanf-like function is called with no format string. 8080 if (format_idx >= Args.size()) { 8081 Diag(Loc, diag::warn_missing_format_string) << Range; 8082 return false; 8083 } 8084 8085 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8086 8087 // CHECK: format string is not a string literal. 8088 // 8089 // Dynamically generated format strings are difficult to 8090 // automatically vet at compile time. Requiring that format strings 8091 // are string literals: (1) permits the checking of format strings by 8092 // the compiler and thereby (2) can practically remove the source of 8093 // many format string exploits. 8094 8095 // Format string can be either ObjC string (e.g. @"%d") or 8096 // C string (e.g. "%d") 8097 // ObjC string uses the same format specifiers as C string, so we can use 8098 // the same format string checking logic for both ObjC and C strings. 8099 UncoveredArgHandler UncoveredArg; 8100 StringLiteralCheckType CT = 8101 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8102 format_idx, firstDataArg, Type, CallType, 8103 /*IsFunctionCall*/ true, CheckedVarArgs, 8104 UncoveredArg, 8105 /*no string offset*/ llvm::APSInt(64, false) = 0); 8106 8107 // Generate a diagnostic where an uncovered argument is detected. 8108 if (UncoveredArg.hasUncoveredArg()) { 8109 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8110 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8111 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8112 } 8113 8114 if (CT != SLCT_NotALiteral) 8115 // Literal format string found, check done! 8116 return CT == SLCT_CheckedLiteral; 8117 8118 // Strftime is particular as it always uses a single 'time' argument, 8119 // so it is safe to pass a non-literal string. 8120 if (Type == FST_Strftime) 8121 return false; 8122 8123 // Do not emit diag when the string param is a macro expansion and the 8124 // format is either NSString or CFString. This is a hack to prevent 8125 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8126 // which are usually used in place of NS and CF string literals. 8127 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8128 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8129 return false; 8130 8131 // If there are no arguments specified, warn with -Wformat-security, otherwise 8132 // warn only with -Wformat-nonliteral. 8133 if (Args.size() == firstDataArg) { 8134 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8135 << OrigFormatExpr->getSourceRange(); 8136 switch (Type) { 8137 default: 8138 break; 8139 case FST_Kprintf: 8140 case FST_FreeBSDKPrintf: 8141 case FST_Printf: 8142 Diag(FormatLoc, diag::note_format_security_fixit) 8143 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8144 break; 8145 case FST_NSString: 8146 Diag(FormatLoc, diag::note_format_security_fixit) 8147 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8148 break; 8149 } 8150 } else { 8151 Diag(FormatLoc, diag::warn_format_nonliteral) 8152 << OrigFormatExpr->getSourceRange(); 8153 } 8154 return false; 8155 } 8156 8157 namespace { 8158 8159 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8160 protected: 8161 Sema &S; 8162 const FormatStringLiteral *FExpr; 8163 const Expr *OrigFormatExpr; 8164 const Sema::FormatStringType FSType; 8165 const unsigned FirstDataArg; 8166 const unsigned NumDataArgs; 8167 const char *Beg; // Start of format string. 8168 const bool HasVAListArg; 8169 ArrayRef<const Expr *> Args; 8170 unsigned FormatIdx; 8171 llvm::SmallBitVector CoveredArgs; 8172 bool usesPositionalArgs = false; 8173 bool atFirstArg = true; 8174 bool inFunctionCall; 8175 Sema::VariadicCallType CallType; 8176 llvm::SmallBitVector &CheckedVarArgs; 8177 UncoveredArgHandler &UncoveredArg; 8178 8179 public: 8180 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8181 const Expr *origFormatExpr, 8182 const Sema::FormatStringType type, unsigned firstDataArg, 8183 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8184 ArrayRef<const Expr *> Args, unsigned formatIdx, 8185 bool inFunctionCall, Sema::VariadicCallType callType, 8186 llvm::SmallBitVector &CheckedVarArgs, 8187 UncoveredArgHandler &UncoveredArg) 8188 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8189 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8190 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8191 inFunctionCall(inFunctionCall), CallType(callType), 8192 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8193 CoveredArgs.resize(numDataArgs); 8194 CoveredArgs.reset(); 8195 } 8196 8197 void DoneProcessing(); 8198 8199 void HandleIncompleteSpecifier(const char *startSpecifier, 8200 unsigned specifierLen) override; 8201 8202 void HandleInvalidLengthModifier( 8203 const analyze_format_string::FormatSpecifier &FS, 8204 const analyze_format_string::ConversionSpecifier &CS, 8205 const char *startSpecifier, unsigned specifierLen, 8206 unsigned DiagID); 8207 8208 void HandleNonStandardLengthModifier( 8209 const analyze_format_string::FormatSpecifier &FS, 8210 const char *startSpecifier, unsigned specifierLen); 8211 8212 void HandleNonStandardConversionSpecifier( 8213 const analyze_format_string::ConversionSpecifier &CS, 8214 const char *startSpecifier, unsigned specifierLen); 8215 8216 void HandlePosition(const char *startPos, unsigned posLen) override; 8217 8218 void HandleInvalidPosition(const char *startSpecifier, 8219 unsigned specifierLen, 8220 analyze_format_string::PositionContext p) override; 8221 8222 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8223 8224 void HandleNullChar(const char *nullCharacter) override; 8225 8226 template <typename Range> 8227 static void 8228 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8229 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8230 bool IsStringLocation, Range StringRange, 8231 ArrayRef<FixItHint> Fixit = None); 8232 8233 protected: 8234 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8235 const char *startSpec, 8236 unsigned specifierLen, 8237 const char *csStart, unsigned csLen); 8238 8239 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8240 const char *startSpec, 8241 unsigned specifierLen); 8242 8243 SourceRange getFormatStringRange(); 8244 CharSourceRange getSpecifierRange(const char *startSpecifier, 8245 unsigned specifierLen); 8246 SourceLocation getLocationOfByte(const char *x); 8247 8248 const Expr *getDataArg(unsigned i) const; 8249 8250 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8251 const analyze_format_string::ConversionSpecifier &CS, 8252 const char *startSpecifier, unsigned specifierLen, 8253 unsigned argIndex); 8254 8255 template <typename Range> 8256 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8257 bool IsStringLocation, Range StringRange, 8258 ArrayRef<FixItHint> Fixit = None); 8259 }; 8260 8261 } // namespace 8262 8263 SourceRange CheckFormatHandler::getFormatStringRange() { 8264 return OrigFormatExpr->getSourceRange(); 8265 } 8266 8267 CharSourceRange CheckFormatHandler:: 8268 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8269 SourceLocation Start = getLocationOfByte(startSpecifier); 8270 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8271 8272 // Advance the end SourceLocation by one due to half-open ranges. 8273 End = End.getLocWithOffset(1); 8274 8275 return CharSourceRange::getCharRange(Start, End); 8276 } 8277 8278 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8279 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8280 S.getLangOpts(), S.Context.getTargetInfo()); 8281 } 8282 8283 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8284 unsigned specifierLen){ 8285 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8286 getLocationOfByte(startSpecifier), 8287 /*IsStringLocation*/true, 8288 getSpecifierRange(startSpecifier, specifierLen)); 8289 } 8290 8291 void CheckFormatHandler::HandleInvalidLengthModifier( 8292 const analyze_format_string::FormatSpecifier &FS, 8293 const analyze_format_string::ConversionSpecifier &CS, 8294 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8295 using namespace analyze_format_string; 8296 8297 const LengthModifier &LM = FS.getLengthModifier(); 8298 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8299 8300 // See if we know how to fix this length modifier. 8301 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8302 if (FixedLM) { 8303 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8304 getLocationOfByte(LM.getStart()), 8305 /*IsStringLocation*/true, 8306 getSpecifierRange(startSpecifier, specifierLen)); 8307 8308 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8309 << FixedLM->toString() 8310 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8311 8312 } else { 8313 FixItHint Hint; 8314 if (DiagID == diag::warn_format_nonsensical_length) 8315 Hint = FixItHint::CreateRemoval(LMRange); 8316 8317 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8318 getLocationOfByte(LM.getStart()), 8319 /*IsStringLocation*/true, 8320 getSpecifierRange(startSpecifier, specifierLen), 8321 Hint); 8322 } 8323 } 8324 8325 void CheckFormatHandler::HandleNonStandardLengthModifier( 8326 const analyze_format_string::FormatSpecifier &FS, 8327 const char *startSpecifier, unsigned specifierLen) { 8328 using namespace analyze_format_string; 8329 8330 const LengthModifier &LM = FS.getLengthModifier(); 8331 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8332 8333 // See if we know how to fix this length modifier. 8334 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8335 if (FixedLM) { 8336 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8337 << LM.toString() << 0, 8338 getLocationOfByte(LM.getStart()), 8339 /*IsStringLocation*/true, 8340 getSpecifierRange(startSpecifier, specifierLen)); 8341 8342 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8343 << FixedLM->toString() 8344 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8345 8346 } else { 8347 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8348 << LM.toString() << 0, 8349 getLocationOfByte(LM.getStart()), 8350 /*IsStringLocation*/true, 8351 getSpecifierRange(startSpecifier, specifierLen)); 8352 } 8353 } 8354 8355 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8356 const analyze_format_string::ConversionSpecifier &CS, 8357 const char *startSpecifier, unsigned specifierLen) { 8358 using namespace analyze_format_string; 8359 8360 // See if we know how to fix this conversion specifier. 8361 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8362 if (FixedCS) { 8363 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8364 << CS.toString() << /*conversion specifier*/1, 8365 getLocationOfByte(CS.getStart()), 8366 /*IsStringLocation*/true, 8367 getSpecifierRange(startSpecifier, specifierLen)); 8368 8369 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8370 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8371 << FixedCS->toString() 8372 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8373 } else { 8374 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8375 << CS.toString() << /*conversion specifier*/1, 8376 getLocationOfByte(CS.getStart()), 8377 /*IsStringLocation*/true, 8378 getSpecifierRange(startSpecifier, specifierLen)); 8379 } 8380 } 8381 8382 void CheckFormatHandler::HandlePosition(const char *startPos, 8383 unsigned posLen) { 8384 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8385 getLocationOfByte(startPos), 8386 /*IsStringLocation*/true, 8387 getSpecifierRange(startPos, posLen)); 8388 } 8389 8390 void 8391 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8392 analyze_format_string::PositionContext p) { 8393 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8394 << (unsigned) p, 8395 getLocationOfByte(startPos), /*IsStringLocation*/true, 8396 getSpecifierRange(startPos, posLen)); 8397 } 8398 8399 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8400 unsigned posLen) { 8401 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8402 getLocationOfByte(startPos), 8403 /*IsStringLocation*/true, 8404 getSpecifierRange(startPos, posLen)); 8405 } 8406 8407 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8408 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8409 // The presence of a null character is likely an error. 8410 EmitFormatDiagnostic( 8411 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8412 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8413 getFormatStringRange()); 8414 } 8415 } 8416 8417 // Note that this may return NULL if there was an error parsing or building 8418 // one of the argument expressions. 8419 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8420 return Args[FirstDataArg + i]; 8421 } 8422 8423 void CheckFormatHandler::DoneProcessing() { 8424 // Does the number of data arguments exceed the number of 8425 // format conversions in the format string? 8426 if (!HasVAListArg) { 8427 // Find any arguments that weren't covered. 8428 CoveredArgs.flip(); 8429 signed notCoveredArg = CoveredArgs.find_first(); 8430 if (notCoveredArg >= 0) { 8431 assert((unsigned)notCoveredArg < NumDataArgs); 8432 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8433 } else { 8434 UncoveredArg.setAllCovered(); 8435 } 8436 } 8437 } 8438 8439 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8440 const Expr *ArgExpr) { 8441 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8442 "Invalid state"); 8443 8444 if (!ArgExpr) 8445 return; 8446 8447 SourceLocation Loc = ArgExpr->getBeginLoc(); 8448 8449 if (S.getSourceManager().isInSystemMacro(Loc)) 8450 return; 8451 8452 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8453 for (auto E : DiagnosticExprs) 8454 PDiag << E->getSourceRange(); 8455 8456 CheckFormatHandler::EmitFormatDiagnostic( 8457 S, IsFunctionCall, DiagnosticExprs[0], 8458 PDiag, Loc, /*IsStringLocation*/false, 8459 DiagnosticExprs[0]->getSourceRange()); 8460 } 8461 8462 bool 8463 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8464 SourceLocation Loc, 8465 const char *startSpec, 8466 unsigned specifierLen, 8467 const char *csStart, 8468 unsigned csLen) { 8469 bool keepGoing = true; 8470 if (argIndex < NumDataArgs) { 8471 // Consider the argument coverered, even though the specifier doesn't 8472 // make sense. 8473 CoveredArgs.set(argIndex); 8474 } 8475 else { 8476 // If argIndex exceeds the number of data arguments we 8477 // don't issue a warning because that is just a cascade of warnings (and 8478 // they may have intended '%%' anyway). We don't want to continue processing 8479 // the format string after this point, however, as we will like just get 8480 // gibberish when trying to match arguments. 8481 keepGoing = false; 8482 } 8483 8484 StringRef Specifier(csStart, csLen); 8485 8486 // If the specifier in non-printable, it could be the first byte of a UTF-8 8487 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8488 // hex value. 8489 std::string CodePointStr; 8490 if (!llvm::sys::locale::isPrint(*csStart)) { 8491 llvm::UTF32 CodePoint; 8492 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8493 const llvm::UTF8 *E = 8494 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8495 llvm::ConversionResult Result = 8496 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8497 8498 if (Result != llvm::conversionOK) { 8499 unsigned char FirstChar = *csStart; 8500 CodePoint = (llvm::UTF32)FirstChar; 8501 } 8502 8503 llvm::raw_string_ostream OS(CodePointStr); 8504 if (CodePoint < 256) 8505 OS << "\\x" << llvm::format("%02x", CodePoint); 8506 else if (CodePoint <= 0xFFFF) 8507 OS << "\\u" << llvm::format("%04x", CodePoint); 8508 else 8509 OS << "\\U" << llvm::format("%08x", CodePoint); 8510 OS.flush(); 8511 Specifier = CodePointStr; 8512 } 8513 8514 EmitFormatDiagnostic( 8515 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8516 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8517 8518 return keepGoing; 8519 } 8520 8521 void 8522 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8523 const char *startSpec, 8524 unsigned specifierLen) { 8525 EmitFormatDiagnostic( 8526 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8527 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8528 } 8529 8530 bool 8531 CheckFormatHandler::CheckNumArgs( 8532 const analyze_format_string::FormatSpecifier &FS, 8533 const analyze_format_string::ConversionSpecifier &CS, 8534 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8535 8536 if (argIndex >= NumDataArgs) { 8537 PartialDiagnostic PDiag = FS.usesPositionalArg() 8538 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8539 << (argIndex+1) << NumDataArgs) 8540 : S.PDiag(diag::warn_printf_insufficient_data_args); 8541 EmitFormatDiagnostic( 8542 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8543 getSpecifierRange(startSpecifier, specifierLen)); 8544 8545 // Since more arguments than conversion tokens are given, by extension 8546 // all arguments are covered, so mark this as so. 8547 UncoveredArg.setAllCovered(); 8548 return false; 8549 } 8550 return true; 8551 } 8552 8553 template<typename Range> 8554 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8555 SourceLocation Loc, 8556 bool IsStringLocation, 8557 Range StringRange, 8558 ArrayRef<FixItHint> FixIt) { 8559 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8560 Loc, IsStringLocation, StringRange, FixIt); 8561 } 8562 8563 /// If the format string is not within the function call, emit a note 8564 /// so that the function call and string are in diagnostic messages. 8565 /// 8566 /// \param InFunctionCall if true, the format string is within the function 8567 /// call and only one diagnostic message will be produced. Otherwise, an 8568 /// extra note will be emitted pointing to location of the format string. 8569 /// 8570 /// \param ArgumentExpr the expression that is passed as the format string 8571 /// argument in the function call. Used for getting locations when two 8572 /// diagnostics are emitted. 8573 /// 8574 /// \param PDiag the callee should already have provided any strings for the 8575 /// diagnostic message. This function only adds locations and fixits 8576 /// to diagnostics. 8577 /// 8578 /// \param Loc primary location for diagnostic. If two diagnostics are 8579 /// required, one will be at Loc and a new SourceLocation will be created for 8580 /// the other one. 8581 /// 8582 /// \param IsStringLocation if true, Loc points to the format string should be 8583 /// used for the note. Otherwise, Loc points to the argument list and will 8584 /// be used with PDiag. 8585 /// 8586 /// \param StringRange some or all of the string to highlight. This is 8587 /// templated so it can accept either a CharSourceRange or a SourceRange. 8588 /// 8589 /// \param FixIt optional fix it hint for the format string. 8590 template <typename Range> 8591 void CheckFormatHandler::EmitFormatDiagnostic( 8592 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8593 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8594 Range StringRange, ArrayRef<FixItHint> FixIt) { 8595 if (InFunctionCall) { 8596 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8597 D << StringRange; 8598 D << FixIt; 8599 } else { 8600 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8601 << ArgumentExpr->getSourceRange(); 8602 8603 const Sema::SemaDiagnosticBuilder &Note = 8604 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8605 diag::note_format_string_defined); 8606 8607 Note << StringRange; 8608 Note << FixIt; 8609 } 8610 } 8611 8612 //===--- CHECK: Printf format string checking ------------------------------===// 8613 8614 namespace { 8615 8616 class CheckPrintfHandler : public CheckFormatHandler { 8617 public: 8618 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8619 const Expr *origFormatExpr, 8620 const Sema::FormatStringType type, unsigned firstDataArg, 8621 unsigned numDataArgs, bool isObjC, const char *beg, 8622 bool hasVAListArg, ArrayRef<const Expr *> Args, 8623 unsigned formatIdx, bool inFunctionCall, 8624 Sema::VariadicCallType CallType, 8625 llvm::SmallBitVector &CheckedVarArgs, 8626 UncoveredArgHandler &UncoveredArg) 8627 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8628 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8629 inFunctionCall, CallType, CheckedVarArgs, 8630 UncoveredArg) {} 8631 8632 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8633 8634 /// Returns true if '%@' specifiers are allowed in the format string. 8635 bool allowsObjCArg() const { 8636 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8637 FSType == Sema::FST_OSTrace; 8638 } 8639 8640 bool HandleInvalidPrintfConversionSpecifier( 8641 const analyze_printf::PrintfSpecifier &FS, 8642 const char *startSpecifier, 8643 unsigned specifierLen) override; 8644 8645 void handleInvalidMaskType(StringRef MaskType) override; 8646 8647 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8648 const char *startSpecifier, 8649 unsigned specifierLen) override; 8650 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8651 const char *StartSpecifier, 8652 unsigned SpecifierLen, 8653 const Expr *E); 8654 8655 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8656 const char *startSpecifier, unsigned specifierLen); 8657 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8658 const analyze_printf::OptionalAmount &Amt, 8659 unsigned type, 8660 const char *startSpecifier, unsigned specifierLen); 8661 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8662 const analyze_printf::OptionalFlag &flag, 8663 const char *startSpecifier, unsigned specifierLen); 8664 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8665 const analyze_printf::OptionalFlag &ignoredFlag, 8666 const analyze_printf::OptionalFlag &flag, 8667 const char *startSpecifier, unsigned specifierLen); 8668 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8669 const Expr *E); 8670 8671 void HandleEmptyObjCModifierFlag(const char *startFlag, 8672 unsigned flagLen) override; 8673 8674 void HandleInvalidObjCModifierFlag(const char *startFlag, 8675 unsigned flagLen) override; 8676 8677 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8678 const char *flagsEnd, 8679 const char *conversionPosition) 8680 override; 8681 }; 8682 8683 } // namespace 8684 8685 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8686 const analyze_printf::PrintfSpecifier &FS, 8687 const char *startSpecifier, 8688 unsigned specifierLen) { 8689 const analyze_printf::PrintfConversionSpecifier &CS = 8690 FS.getConversionSpecifier(); 8691 8692 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8693 getLocationOfByte(CS.getStart()), 8694 startSpecifier, specifierLen, 8695 CS.getStart(), CS.getLength()); 8696 } 8697 8698 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8699 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8700 } 8701 8702 bool CheckPrintfHandler::HandleAmount( 8703 const analyze_format_string::OptionalAmount &Amt, 8704 unsigned k, const char *startSpecifier, 8705 unsigned specifierLen) { 8706 if (Amt.hasDataArgument()) { 8707 if (!HasVAListArg) { 8708 unsigned argIndex = Amt.getArgIndex(); 8709 if (argIndex >= NumDataArgs) { 8710 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8711 << k, 8712 getLocationOfByte(Amt.getStart()), 8713 /*IsStringLocation*/true, 8714 getSpecifierRange(startSpecifier, specifierLen)); 8715 // Don't do any more checking. We will just emit 8716 // spurious errors. 8717 return false; 8718 } 8719 8720 // Type check the data argument. It should be an 'int'. 8721 // Although not in conformance with C99, we also allow the argument to be 8722 // an 'unsigned int' as that is a reasonably safe case. GCC also 8723 // doesn't emit a warning for that case. 8724 CoveredArgs.set(argIndex); 8725 const Expr *Arg = getDataArg(argIndex); 8726 if (!Arg) 8727 return false; 8728 8729 QualType T = Arg->getType(); 8730 8731 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8732 assert(AT.isValid()); 8733 8734 if (!AT.matchesType(S.Context, T)) { 8735 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8736 << k << AT.getRepresentativeTypeName(S.Context) 8737 << T << Arg->getSourceRange(), 8738 getLocationOfByte(Amt.getStart()), 8739 /*IsStringLocation*/true, 8740 getSpecifierRange(startSpecifier, specifierLen)); 8741 // Don't do any more checking. We will just emit 8742 // spurious errors. 8743 return false; 8744 } 8745 } 8746 } 8747 return true; 8748 } 8749 8750 void CheckPrintfHandler::HandleInvalidAmount( 8751 const analyze_printf::PrintfSpecifier &FS, 8752 const analyze_printf::OptionalAmount &Amt, 8753 unsigned type, 8754 const char *startSpecifier, 8755 unsigned specifierLen) { 8756 const analyze_printf::PrintfConversionSpecifier &CS = 8757 FS.getConversionSpecifier(); 8758 8759 FixItHint fixit = 8760 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8761 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8762 Amt.getConstantLength())) 8763 : FixItHint(); 8764 8765 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8766 << type << CS.toString(), 8767 getLocationOfByte(Amt.getStart()), 8768 /*IsStringLocation*/true, 8769 getSpecifierRange(startSpecifier, specifierLen), 8770 fixit); 8771 } 8772 8773 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8774 const analyze_printf::OptionalFlag &flag, 8775 const char *startSpecifier, 8776 unsigned specifierLen) { 8777 // Warn about pointless flag with a fixit removal. 8778 const analyze_printf::PrintfConversionSpecifier &CS = 8779 FS.getConversionSpecifier(); 8780 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8781 << flag.toString() << CS.toString(), 8782 getLocationOfByte(flag.getPosition()), 8783 /*IsStringLocation*/true, 8784 getSpecifierRange(startSpecifier, specifierLen), 8785 FixItHint::CreateRemoval( 8786 getSpecifierRange(flag.getPosition(), 1))); 8787 } 8788 8789 void CheckPrintfHandler::HandleIgnoredFlag( 8790 const analyze_printf::PrintfSpecifier &FS, 8791 const analyze_printf::OptionalFlag &ignoredFlag, 8792 const analyze_printf::OptionalFlag &flag, 8793 const char *startSpecifier, 8794 unsigned specifierLen) { 8795 // Warn about ignored flag with a fixit removal. 8796 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8797 << ignoredFlag.toString() << flag.toString(), 8798 getLocationOfByte(ignoredFlag.getPosition()), 8799 /*IsStringLocation*/true, 8800 getSpecifierRange(startSpecifier, specifierLen), 8801 FixItHint::CreateRemoval( 8802 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8803 } 8804 8805 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8806 unsigned flagLen) { 8807 // Warn about an empty flag. 8808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8809 getLocationOfByte(startFlag), 8810 /*IsStringLocation*/true, 8811 getSpecifierRange(startFlag, flagLen)); 8812 } 8813 8814 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8815 unsigned flagLen) { 8816 // Warn about an invalid flag. 8817 auto Range = getSpecifierRange(startFlag, flagLen); 8818 StringRef flag(startFlag, flagLen); 8819 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8820 getLocationOfByte(startFlag), 8821 /*IsStringLocation*/true, 8822 Range, FixItHint::CreateRemoval(Range)); 8823 } 8824 8825 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8826 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8827 // Warn about using '[...]' without a '@' conversion. 8828 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8829 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8830 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8831 getLocationOfByte(conversionPosition), 8832 /*IsStringLocation*/true, 8833 Range, FixItHint::CreateRemoval(Range)); 8834 } 8835 8836 // Determines if the specified is a C++ class or struct containing 8837 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8838 // "c_str()"). 8839 template<typename MemberKind> 8840 static llvm::SmallPtrSet<MemberKind*, 1> 8841 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8842 const RecordType *RT = Ty->getAs<RecordType>(); 8843 llvm::SmallPtrSet<MemberKind*, 1> Results; 8844 8845 if (!RT) 8846 return Results; 8847 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8848 if (!RD || !RD->getDefinition()) 8849 return Results; 8850 8851 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8852 Sema::LookupMemberName); 8853 R.suppressDiagnostics(); 8854 8855 // We just need to include all members of the right kind turned up by the 8856 // filter, at this point. 8857 if (S.LookupQualifiedName(R, RT->getDecl())) 8858 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8859 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8860 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8861 Results.insert(FK); 8862 } 8863 return Results; 8864 } 8865 8866 /// Check if we could call '.c_str()' on an object. 8867 /// 8868 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8869 /// allow the call, or if it would be ambiguous). 8870 bool Sema::hasCStrMethod(const Expr *E) { 8871 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8872 8873 MethodSet Results = 8874 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8875 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8876 MI != ME; ++MI) 8877 if ((*MI)->getMinRequiredArguments() == 0) 8878 return true; 8879 return false; 8880 } 8881 8882 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8883 // better diagnostic if so. AT is assumed to be valid. 8884 // Returns true when a c_str() conversion method is found. 8885 bool CheckPrintfHandler::checkForCStrMembers( 8886 const analyze_printf::ArgType &AT, const Expr *E) { 8887 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8888 8889 MethodSet Results = 8890 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8891 8892 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8893 MI != ME; ++MI) { 8894 const CXXMethodDecl *Method = *MI; 8895 if (Method->getMinRequiredArguments() == 0 && 8896 AT.matchesType(S.Context, Method->getReturnType())) { 8897 // FIXME: Suggest parens if the expression needs them. 8898 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8899 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8900 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8901 return true; 8902 } 8903 } 8904 8905 return false; 8906 } 8907 8908 bool 8909 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8910 &FS, 8911 const char *startSpecifier, 8912 unsigned specifierLen) { 8913 using namespace analyze_format_string; 8914 using namespace analyze_printf; 8915 8916 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8917 8918 if (FS.consumesDataArgument()) { 8919 if (atFirstArg) { 8920 atFirstArg = false; 8921 usesPositionalArgs = FS.usesPositionalArg(); 8922 } 8923 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8924 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8925 startSpecifier, specifierLen); 8926 return false; 8927 } 8928 } 8929 8930 // First check if the field width, precision, and conversion specifier 8931 // have matching data arguments. 8932 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8933 startSpecifier, specifierLen)) { 8934 return false; 8935 } 8936 8937 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8938 startSpecifier, specifierLen)) { 8939 return false; 8940 } 8941 8942 if (!CS.consumesDataArgument()) { 8943 // FIXME: Technically specifying a precision or field width here 8944 // makes no sense. Worth issuing a warning at some point. 8945 return true; 8946 } 8947 8948 // Consume the argument. 8949 unsigned argIndex = FS.getArgIndex(); 8950 if (argIndex < NumDataArgs) { 8951 // The check to see if the argIndex is valid will come later. 8952 // We set the bit here because we may exit early from this 8953 // function if we encounter some other error. 8954 CoveredArgs.set(argIndex); 8955 } 8956 8957 // FreeBSD kernel extensions. 8958 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8959 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8960 // We need at least two arguments. 8961 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8962 return false; 8963 8964 // Claim the second argument. 8965 CoveredArgs.set(argIndex + 1); 8966 8967 // Type check the first argument (int for %b, pointer for %D) 8968 const Expr *Ex = getDataArg(argIndex); 8969 const analyze_printf::ArgType &AT = 8970 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8971 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8972 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8973 EmitFormatDiagnostic( 8974 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8975 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8976 << false << Ex->getSourceRange(), 8977 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8978 getSpecifierRange(startSpecifier, specifierLen)); 8979 8980 // Type check the second argument (char * for both %b and %D) 8981 Ex = getDataArg(argIndex + 1); 8982 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8983 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8984 EmitFormatDiagnostic( 8985 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8986 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8987 << false << Ex->getSourceRange(), 8988 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8989 getSpecifierRange(startSpecifier, specifierLen)); 8990 8991 return true; 8992 } 8993 8994 // Check for using an Objective-C specific conversion specifier 8995 // in a non-ObjC literal. 8996 if (!allowsObjCArg() && CS.isObjCArg()) { 8997 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8998 specifierLen); 8999 } 9000 9001 // %P can only be used with os_log. 9002 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9003 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9004 specifierLen); 9005 } 9006 9007 // %n is not allowed with os_log. 9008 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9009 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9010 getLocationOfByte(CS.getStart()), 9011 /*IsStringLocation*/ false, 9012 getSpecifierRange(startSpecifier, specifierLen)); 9013 9014 return true; 9015 } 9016 9017 // Only scalars are allowed for os_trace. 9018 if (FSType == Sema::FST_OSTrace && 9019 (CS.getKind() == ConversionSpecifier::PArg || 9020 CS.getKind() == ConversionSpecifier::sArg || 9021 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9022 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9023 specifierLen); 9024 } 9025 9026 // Check for use of public/private annotation outside of os_log(). 9027 if (FSType != Sema::FST_OSLog) { 9028 if (FS.isPublic().isSet()) { 9029 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9030 << "public", 9031 getLocationOfByte(FS.isPublic().getPosition()), 9032 /*IsStringLocation*/ false, 9033 getSpecifierRange(startSpecifier, specifierLen)); 9034 } 9035 if (FS.isPrivate().isSet()) { 9036 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9037 << "private", 9038 getLocationOfByte(FS.isPrivate().getPosition()), 9039 /*IsStringLocation*/ false, 9040 getSpecifierRange(startSpecifier, specifierLen)); 9041 } 9042 } 9043 9044 // Check for invalid use of field width 9045 if (!FS.hasValidFieldWidth()) { 9046 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9047 startSpecifier, specifierLen); 9048 } 9049 9050 // Check for invalid use of precision 9051 if (!FS.hasValidPrecision()) { 9052 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9053 startSpecifier, specifierLen); 9054 } 9055 9056 // Precision is mandatory for %P specifier. 9057 if (CS.getKind() == ConversionSpecifier::PArg && 9058 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9059 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9060 getLocationOfByte(startSpecifier), 9061 /*IsStringLocation*/ false, 9062 getSpecifierRange(startSpecifier, specifierLen)); 9063 } 9064 9065 // Check each flag does not conflict with any other component. 9066 if (!FS.hasValidThousandsGroupingPrefix()) 9067 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9068 if (!FS.hasValidLeadingZeros()) 9069 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9070 if (!FS.hasValidPlusPrefix()) 9071 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9072 if (!FS.hasValidSpacePrefix()) 9073 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9074 if (!FS.hasValidAlternativeForm()) 9075 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9076 if (!FS.hasValidLeftJustified()) 9077 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9078 9079 // Check that flags are not ignored by another flag 9080 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9081 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9082 startSpecifier, specifierLen); 9083 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9084 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9085 startSpecifier, specifierLen); 9086 9087 // Check the length modifier is valid with the given conversion specifier. 9088 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9089 S.getLangOpts())) 9090 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9091 diag::warn_format_nonsensical_length); 9092 else if (!FS.hasStandardLengthModifier()) 9093 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9094 else if (!FS.hasStandardLengthConversionCombination()) 9095 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9096 diag::warn_format_non_standard_conversion_spec); 9097 9098 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9099 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9100 9101 // The remaining checks depend on the data arguments. 9102 if (HasVAListArg) 9103 return true; 9104 9105 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9106 return false; 9107 9108 const Expr *Arg = getDataArg(argIndex); 9109 if (!Arg) 9110 return true; 9111 9112 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9113 } 9114 9115 static bool requiresParensToAddCast(const Expr *E) { 9116 // FIXME: We should have a general way to reason about operator 9117 // precedence and whether parens are actually needed here. 9118 // Take care of a few common cases where they aren't. 9119 const Expr *Inside = E->IgnoreImpCasts(); 9120 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9121 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9122 9123 switch (Inside->getStmtClass()) { 9124 case Stmt::ArraySubscriptExprClass: 9125 case Stmt::CallExprClass: 9126 case Stmt::CharacterLiteralClass: 9127 case Stmt::CXXBoolLiteralExprClass: 9128 case Stmt::DeclRefExprClass: 9129 case Stmt::FloatingLiteralClass: 9130 case Stmt::IntegerLiteralClass: 9131 case Stmt::MemberExprClass: 9132 case Stmt::ObjCArrayLiteralClass: 9133 case Stmt::ObjCBoolLiteralExprClass: 9134 case Stmt::ObjCBoxedExprClass: 9135 case Stmt::ObjCDictionaryLiteralClass: 9136 case Stmt::ObjCEncodeExprClass: 9137 case Stmt::ObjCIvarRefExprClass: 9138 case Stmt::ObjCMessageExprClass: 9139 case Stmt::ObjCPropertyRefExprClass: 9140 case Stmt::ObjCStringLiteralClass: 9141 case Stmt::ObjCSubscriptRefExprClass: 9142 case Stmt::ParenExprClass: 9143 case Stmt::StringLiteralClass: 9144 case Stmt::UnaryOperatorClass: 9145 return false; 9146 default: 9147 return true; 9148 } 9149 } 9150 9151 static std::pair<QualType, StringRef> 9152 shouldNotPrintDirectly(const ASTContext &Context, 9153 QualType IntendedTy, 9154 const Expr *E) { 9155 // Use a 'while' to peel off layers of typedefs. 9156 QualType TyTy = IntendedTy; 9157 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9158 StringRef Name = UserTy->getDecl()->getName(); 9159 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9160 .Case("CFIndex", Context.getNSIntegerType()) 9161 .Case("NSInteger", Context.getNSIntegerType()) 9162 .Case("NSUInteger", Context.getNSUIntegerType()) 9163 .Case("SInt32", Context.IntTy) 9164 .Case("UInt32", Context.UnsignedIntTy) 9165 .Default(QualType()); 9166 9167 if (!CastTy.isNull()) 9168 return std::make_pair(CastTy, Name); 9169 9170 TyTy = UserTy->desugar(); 9171 } 9172 9173 // Strip parens if necessary. 9174 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9175 return shouldNotPrintDirectly(Context, 9176 PE->getSubExpr()->getType(), 9177 PE->getSubExpr()); 9178 9179 // If this is a conditional expression, then its result type is constructed 9180 // via usual arithmetic conversions and thus there might be no necessary 9181 // typedef sugar there. Recurse to operands to check for NSInteger & 9182 // Co. usage condition. 9183 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9184 QualType TrueTy, FalseTy; 9185 StringRef TrueName, FalseName; 9186 9187 std::tie(TrueTy, TrueName) = 9188 shouldNotPrintDirectly(Context, 9189 CO->getTrueExpr()->getType(), 9190 CO->getTrueExpr()); 9191 std::tie(FalseTy, FalseName) = 9192 shouldNotPrintDirectly(Context, 9193 CO->getFalseExpr()->getType(), 9194 CO->getFalseExpr()); 9195 9196 if (TrueTy == FalseTy) 9197 return std::make_pair(TrueTy, TrueName); 9198 else if (TrueTy.isNull()) 9199 return std::make_pair(FalseTy, FalseName); 9200 else if (FalseTy.isNull()) 9201 return std::make_pair(TrueTy, TrueName); 9202 } 9203 9204 return std::make_pair(QualType(), StringRef()); 9205 } 9206 9207 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9208 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9209 /// type do not count. 9210 static bool 9211 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9212 QualType From = ICE->getSubExpr()->getType(); 9213 QualType To = ICE->getType(); 9214 // It's an integer promotion if the destination type is the promoted 9215 // source type. 9216 if (ICE->getCastKind() == CK_IntegralCast && 9217 From->isPromotableIntegerType() && 9218 S.Context.getPromotedIntegerType(From) == To) 9219 return true; 9220 // Look through vector types, since we do default argument promotion for 9221 // those in OpenCL. 9222 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9223 From = VecTy->getElementType(); 9224 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9225 To = VecTy->getElementType(); 9226 // It's a floating promotion if the source type is a lower rank. 9227 return ICE->getCastKind() == CK_FloatingCast && 9228 S.Context.getFloatingTypeOrder(From, To) < 0; 9229 } 9230 9231 bool 9232 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9233 const char *StartSpecifier, 9234 unsigned SpecifierLen, 9235 const Expr *E) { 9236 using namespace analyze_format_string; 9237 using namespace analyze_printf; 9238 9239 // Now type check the data expression that matches the 9240 // format specifier. 9241 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9242 if (!AT.isValid()) 9243 return true; 9244 9245 QualType ExprTy = E->getType(); 9246 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9247 ExprTy = TET->getUnderlyingExpr()->getType(); 9248 } 9249 9250 // Diagnose attempts to print a boolean value as a character. Unlike other 9251 // -Wformat diagnostics, this is fine from a type perspective, but it still 9252 // doesn't make sense. 9253 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9254 E->isKnownToHaveBooleanValue()) { 9255 const CharSourceRange &CSR = 9256 getSpecifierRange(StartSpecifier, SpecifierLen); 9257 SmallString<4> FSString; 9258 llvm::raw_svector_ostream os(FSString); 9259 FS.toString(os); 9260 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9261 << FSString, 9262 E->getExprLoc(), false, CSR); 9263 return true; 9264 } 9265 9266 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9267 if (Match == analyze_printf::ArgType::Match) 9268 return true; 9269 9270 // Look through argument promotions for our error message's reported type. 9271 // This includes the integral and floating promotions, but excludes array 9272 // and function pointer decay (seeing that an argument intended to be a 9273 // string has type 'char [6]' is probably more confusing than 'char *') and 9274 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9275 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9276 if (isArithmeticArgumentPromotion(S, ICE)) { 9277 E = ICE->getSubExpr(); 9278 ExprTy = E->getType(); 9279 9280 // Check if we didn't match because of an implicit cast from a 'char' 9281 // or 'short' to an 'int'. This is done because printf is a varargs 9282 // function. 9283 if (ICE->getType() == S.Context.IntTy || 9284 ICE->getType() == S.Context.UnsignedIntTy) { 9285 // All further checking is done on the subexpression 9286 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9287 AT.matchesType(S.Context, ExprTy); 9288 if (ImplicitMatch == analyze_printf::ArgType::Match) 9289 return true; 9290 if (ImplicitMatch == ArgType::NoMatchPedantic || 9291 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9292 Match = ImplicitMatch; 9293 } 9294 } 9295 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9296 // Special case for 'a', which has type 'int' in C. 9297 // Note, however, that we do /not/ want to treat multibyte constants like 9298 // 'MooV' as characters! This form is deprecated but still exists. In 9299 // addition, don't treat expressions as of type 'char' if one byte length 9300 // modifier is provided. 9301 if (ExprTy == S.Context.IntTy && 9302 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9303 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9304 ExprTy = S.Context.CharTy; 9305 } 9306 9307 // Look through enums to their underlying type. 9308 bool IsEnum = false; 9309 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9310 ExprTy = EnumTy->getDecl()->getIntegerType(); 9311 IsEnum = true; 9312 } 9313 9314 // %C in an Objective-C context prints a unichar, not a wchar_t. 9315 // If the argument is an integer of some kind, believe the %C and suggest 9316 // a cast instead of changing the conversion specifier. 9317 QualType IntendedTy = ExprTy; 9318 if (isObjCContext() && 9319 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9320 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9321 !ExprTy->isCharType()) { 9322 // 'unichar' is defined as a typedef of unsigned short, but we should 9323 // prefer using the typedef if it is visible. 9324 IntendedTy = S.Context.UnsignedShortTy; 9325 9326 // While we are here, check if the value is an IntegerLiteral that happens 9327 // to be within the valid range. 9328 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9329 const llvm::APInt &V = IL->getValue(); 9330 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9331 return true; 9332 } 9333 9334 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9335 Sema::LookupOrdinaryName); 9336 if (S.LookupName(Result, S.getCurScope())) { 9337 NamedDecl *ND = Result.getFoundDecl(); 9338 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9339 if (TD->getUnderlyingType() == IntendedTy) 9340 IntendedTy = S.Context.getTypedefType(TD); 9341 } 9342 } 9343 } 9344 9345 // Special-case some of Darwin's platform-independence types by suggesting 9346 // casts to primitive types that are known to be large enough. 9347 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9348 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9349 QualType CastTy; 9350 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9351 if (!CastTy.isNull()) { 9352 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9353 // (long in ASTContext). Only complain to pedants. 9354 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9355 (AT.isSizeT() || AT.isPtrdiffT()) && 9356 AT.matchesType(S.Context, CastTy)) 9357 Match = ArgType::NoMatchPedantic; 9358 IntendedTy = CastTy; 9359 ShouldNotPrintDirectly = true; 9360 } 9361 } 9362 9363 // We may be able to offer a FixItHint if it is a supported type. 9364 PrintfSpecifier fixedFS = FS; 9365 bool Success = 9366 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9367 9368 if (Success) { 9369 // Get the fix string from the fixed format specifier 9370 SmallString<16> buf; 9371 llvm::raw_svector_ostream os(buf); 9372 fixedFS.toString(os); 9373 9374 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9375 9376 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9377 unsigned Diag; 9378 switch (Match) { 9379 case ArgType::Match: llvm_unreachable("expected non-matching"); 9380 case ArgType::NoMatchPedantic: 9381 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9382 break; 9383 case ArgType::NoMatchTypeConfusion: 9384 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9385 break; 9386 case ArgType::NoMatch: 9387 Diag = diag::warn_format_conversion_argument_type_mismatch; 9388 break; 9389 } 9390 9391 // In this case, the specifier is wrong and should be changed to match 9392 // the argument. 9393 EmitFormatDiagnostic(S.PDiag(Diag) 9394 << AT.getRepresentativeTypeName(S.Context) 9395 << IntendedTy << IsEnum << E->getSourceRange(), 9396 E->getBeginLoc(), 9397 /*IsStringLocation*/ false, SpecRange, 9398 FixItHint::CreateReplacement(SpecRange, os.str())); 9399 } else { 9400 // The canonical type for formatting this value is different from the 9401 // actual type of the expression. (This occurs, for example, with Darwin's 9402 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9403 // should be printed as 'long' for 64-bit compatibility.) 9404 // Rather than emitting a normal format/argument mismatch, we want to 9405 // add a cast to the recommended type (and correct the format string 9406 // if necessary). 9407 SmallString<16> CastBuf; 9408 llvm::raw_svector_ostream CastFix(CastBuf); 9409 CastFix << "("; 9410 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9411 CastFix << ")"; 9412 9413 SmallVector<FixItHint,4> Hints; 9414 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9415 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9416 9417 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9418 // If there's already a cast present, just replace it. 9419 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9420 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9421 9422 } else if (!requiresParensToAddCast(E)) { 9423 // If the expression has high enough precedence, 9424 // just write the C-style cast. 9425 Hints.push_back( 9426 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9427 } else { 9428 // Otherwise, add parens around the expression as well as the cast. 9429 CastFix << "("; 9430 Hints.push_back( 9431 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9432 9433 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9434 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9435 } 9436 9437 if (ShouldNotPrintDirectly) { 9438 // The expression has a type that should not be printed directly. 9439 // We extract the name from the typedef because we don't want to show 9440 // the underlying type in the diagnostic. 9441 StringRef Name; 9442 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9443 Name = TypedefTy->getDecl()->getName(); 9444 else 9445 Name = CastTyName; 9446 unsigned Diag = Match == ArgType::NoMatchPedantic 9447 ? diag::warn_format_argument_needs_cast_pedantic 9448 : diag::warn_format_argument_needs_cast; 9449 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9450 << E->getSourceRange(), 9451 E->getBeginLoc(), /*IsStringLocation=*/false, 9452 SpecRange, Hints); 9453 } else { 9454 // In this case, the expression could be printed using a different 9455 // specifier, but we've decided that the specifier is probably correct 9456 // and we should cast instead. Just use the normal warning message. 9457 EmitFormatDiagnostic( 9458 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9459 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9460 << E->getSourceRange(), 9461 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9462 } 9463 } 9464 } else { 9465 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9466 SpecifierLen); 9467 // Since the warning for passing non-POD types to variadic functions 9468 // was deferred until now, we emit a warning for non-POD 9469 // arguments here. 9470 switch (S.isValidVarArgType(ExprTy)) { 9471 case Sema::VAK_Valid: 9472 case Sema::VAK_ValidInCXX11: { 9473 unsigned Diag; 9474 switch (Match) { 9475 case ArgType::Match: llvm_unreachable("expected non-matching"); 9476 case ArgType::NoMatchPedantic: 9477 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9478 break; 9479 case ArgType::NoMatchTypeConfusion: 9480 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9481 break; 9482 case ArgType::NoMatch: 9483 Diag = diag::warn_format_conversion_argument_type_mismatch; 9484 break; 9485 } 9486 9487 EmitFormatDiagnostic( 9488 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9489 << IsEnum << CSR << E->getSourceRange(), 9490 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9491 break; 9492 } 9493 case Sema::VAK_Undefined: 9494 case Sema::VAK_MSVCUndefined: 9495 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9496 << S.getLangOpts().CPlusPlus11 << ExprTy 9497 << CallType 9498 << AT.getRepresentativeTypeName(S.Context) << CSR 9499 << E->getSourceRange(), 9500 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9501 checkForCStrMembers(AT, E); 9502 break; 9503 9504 case Sema::VAK_Invalid: 9505 if (ExprTy->isObjCObjectType()) 9506 EmitFormatDiagnostic( 9507 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9508 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9509 << AT.getRepresentativeTypeName(S.Context) << CSR 9510 << E->getSourceRange(), 9511 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9512 else 9513 // FIXME: If this is an initializer list, suggest removing the braces 9514 // or inserting a cast to the target type. 9515 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9516 << isa<InitListExpr>(E) << ExprTy << CallType 9517 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9518 break; 9519 } 9520 9521 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9522 "format string specifier index out of range"); 9523 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9524 } 9525 9526 return true; 9527 } 9528 9529 //===--- CHECK: Scanf format string checking ------------------------------===// 9530 9531 namespace { 9532 9533 class CheckScanfHandler : public CheckFormatHandler { 9534 public: 9535 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9536 const Expr *origFormatExpr, Sema::FormatStringType type, 9537 unsigned firstDataArg, unsigned numDataArgs, 9538 const char *beg, bool hasVAListArg, 9539 ArrayRef<const Expr *> Args, unsigned formatIdx, 9540 bool inFunctionCall, Sema::VariadicCallType CallType, 9541 llvm::SmallBitVector &CheckedVarArgs, 9542 UncoveredArgHandler &UncoveredArg) 9543 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9544 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9545 inFunctionCall, CallType, CheckedVarArgs, 9546 UncoveredArg) {} 9547 9548 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9549 const char *startSpecifier, 9550 unsigned specifierLen) override; 9551 9552 bool HandleInvalidScanfConversionSpecifier( 9553 const analyze_scanf::ScanfSpecifier &FS, 9554 const char *startSpecifier, 9555 unsigned specifierLen) override; 9556 9557 void HandleIncompleteScanList(const char *start, const char *end) override; 9558 }; 9559 9560 } // namespace 9561 9562 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9563 const char *end) { 9564 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9565 getLocationOfByte(end), /*IsStringLocation*/true, 9566 getSpecifierRange(start, end - start)); 9567 } 9568 9569 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9570 const analyze_scanf::ScanfSpecifier &FS, 9571 const char *startSpecifier, 9572 unsigned specifierLen) { 9573 const analyze_scanf::ScanfConversionSpecifier &CS = 9574 FS.getConversionSpecifier(); 9575 9576 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9577 getLocationOfByte(CS.getStart()), 9578 startSpecifier, specifierLen, 9579 CS.getStart(), CS.getLength()); 9580 } 9581 9582 bool CheckScanfHandler::HandleScanfSpecifier( 9583 const analyze_scanf::ScanfSpecifier &FS, 9584 const char *startSpecifier, 9585 unsigned specifierLen) { 9586 using namespace analyze_scanf; 9587 using namespace analyze_format_string; 9588 9589 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9590 9591 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9592 // be used to decide if we are using positional arguments consistently. 9593 if (FS.consumesDataArgument()) { 9594 if (atFirstArg) { 9595 atFirstArg = false; 9596 usesPositionalArgs = FS.usesPositionalArg(); 9597 } 9598 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9599 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9600 startSpecifier, specifierLen); 9601 return false; 9602 } 9603 } 9604 9605 // Check if the field with is non-zero. 9606 const OptionalAmount &Amt = FS.getFieldWidth(); 9607 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9608 if (Amt.getConstantAmount() == 0) { 9609 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9610 Amt.getConstantLength()); 9611 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9612 getLocationOfByte(Amt.getStart()), 9613 /*IsStringLocation*/true, R, 9614 FixItHint::CreateRemoval(R)); 9615 } 9616 } 9617 9618 if (!FS.consumesDataArgument()) { 9619 // FIXME: Technically specifying a precision or field width here 9620 // makes no sense. Worth issuing a warning at some point. 9621 return true; 9622 } 9623 9624 // Consume the argument. 9625 unsigned argIndex = FS.getArgIndex(); 9626 if (argIndex < NumDataArgs) { 9627 // The check to see if the argIndex is valid will come later. 9628 // We set the bit here because we may exit early from this 9629 // function if we encounter some other error. 9630 CoveredArgs.set(argIndex); 9631 } 9632 9633 // Check the length modifier is valid with the given conversion specifier. 9634 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9635 S.getLangOpts())) 9636 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9637 diag::warn_format_nonsensical_length); 9638 else if (!FS.hasStandardLengthModifier()) 9639 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9640 else if (!FS.hasStandardLengthConversionCombination()) 9641 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9642 diag::warn_format_non_standard_conversion_spec); 9643 9644 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9645 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9646 9647 // The remaining checks depend on the data arguments. 9648 if (HasVAListArg) 9649 return true; 9650 9651 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9652 return false; 9653 9654 // Check that the argument type matches the format specifier. 9655 const Expr *Ex = getDataArg(argIndex); 9656 if (!Ex) 9657 return true; 9658 9659 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9660 9661 if (!AT.isValid()) { 9662 return true; 9663 } 9664 9665 analyze_format_string::ArgType::MatchKind Match = 9666 AT.matchesType(S.Context, Ex->getType()); 9667 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9668 if (Match == analyze_format_string::ArgType::Match) 9669 return true; 9670 9671 ScanfSpecifier fixedFS = FS; 9672 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9673 S.getLangOpts(), S.Context); 9674 9675 unsigned Diag = 9676 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9677 : diag::warn_format_conversion_argument_type_mismatch; 9678 9679 if (Success) { 9680 // Get the fix string from the fixed format specifier. 9681 SmallString<128> buf; 9682 llvm::raw_svector_ostream os(buf); 9683 fixedFS.toString(os); 9684 9685 EmitFormatDiagnostic( 9686 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9687 << Ex->getType() << false << Ex->getSourceRange(), 9688 Ex->getBeginLoc(), 9689 /*IsStringLocation*/ false, 9690 getSpecifierRange(startSpecifier, specifierLen), 9691 FixItHint::CreateReplacement( 9692 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9693 } else { 9694 EmitFormatDiagnostic(S.PDiag(Diag) 9695 << AT.getRepresentativeTypeName(S.Context) 9696 << Ex->getType() << false << Ex->getSourceRange(), 9697 Ex->getBeginLoc(), 9698 /*IsStringLocation*/ false, 9699 getSpecifierRange(startSpecifier, specifierLen)); 9700 } 9701 9702 return true; 9703 } 9704 9705 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9706 const Expr *OrigFormatExpr, 9707 ArrayRef<const Expr *> Args, 9708 bool HasVAListArg, unsigned format_idx, 9709 unsigned firstDataArg, 9710 Sema::FormatStringType Type, 9711 bool inFunctionCall, 9712 Sema::VariadicCallType CallType, 9713 llvm::SmallBitVector &CheckedVarArgs, 9714 UncoveredArgHandler &UncoveredArg, 9715 bool IgnoreStringsWithoutSpecifiers) { 9716 // CHECK: is the format string a wide literal? 9717 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9718 CheckFormatHandler::EmitFormatDiagnostic( 9719 S, inFunctionCall, Args[format_idx], 9720 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9721 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9722 return; 9723 } 9724 9725 // Str - The format string. NOTE: this is NOT null-terminated! 9726 StringRef StrRef = FExpr->getString(); 9727 const char *Str = StrRef.data(); 9728 // Account for cases where the string literal is truncated in a declaration. 9729 const ConstantArrayType *T = 9730 S.Context.getAsConstantArrayType(FExpr->getType()); 9731 assert(T && "String literal not of constant array type!"); 9732 size_t TypeSize = T->getSize().getZExtValue(); 9733 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9734 const unsigned numDataArgs = Args.size() - firstDataArg; 9735 9736 if (IgnoreStringsWithoutSpecifiers && 9737 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9738 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9739 return; 9740 9741 // Emit a warning if the string literal is truncated and does not contain an 9742 // embedded null character. 9743 if (TypeSize <= StrRef.size() && 9744 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9745 CheckFormatHandler::EmitFormatDiagnostic( 9746 S, inFunctionCall, Args[format_idx], 9747 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9748 FExpr->getBeginLoc(), 9749 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9750 return; 9751 } 9752 9753 // CHECK: empty format string? 9754 if (StrLen == 0 && numDataArgs > 0) { 9755 CheckFormatHandler::EmitFormatDiagnostic( 9756 S, inFunctionCall, Args[format_idx], 9757 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9758 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9759 return; 9760 } 9761 9762 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9763 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9764 Type == Sema::FST_OSTrace) { 9765 CheckPrintfHandler H( 9766 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9767 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9768 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9769 CheckedVarArgs, UncoveredArg); 9770 9771 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9772 S.getLangOpts(), 9773 S.Context.getTargetInfo(), 9774 Type == Sema::FST_FreeBSDKPrintf)) 9775 H.DoneProcessing(); 9776 } else if (Type == Sema::FST_Scanf) { 9777 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9778 numDataArgs, Str, HasVAListArg, Args, format_idx, 9779 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9780 9781 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9782 S.getLangOpts(), 9783 S.Context.getTargetInfo())) 9784 H.DoneProcessing(); 9785 } // TODO: handle other formats 9786 } 9787 9788 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9789 // Str - The format string. NOTE: this is NOT null-terminated! 9790 StringRef StrRef = FExpr->getString(); 9791 const char *Str = StrRef.data(); 9792 // Account for cases where the string literal is truncated in a declaration. 9793 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9794 assert(T && "String literal not of constant array type!"); 9795 size_t TypeSize = T->getSize().getZExtValue(); 9796 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9797 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9798 getLangOpts(), 9799 Context.getTargetInfo()); 9800 } 9801 9802 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9803 9804 // Returns the related absolute value function that is larger, of 0 if one 9805 // does not exist. 9806 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9807 switch (AbsFunction) { 9808 default: 9809 return 0; 9810 9811 case Builtin::BI__builtin_abs: 9812 return Builtin::BI__builtin_labs; 9813 case Builtin::BI__builtin_labs: 9814 return Builtin::BI__builtin_llabs; 9815 case Builtin::BI__builtin_llabs: 9816 return 0; 9817 9818 case Builtin::BI__builtin_fabsf: 9819 return Builtin::BI__builtin_fabs; 9820 case Builtin::BI__builtin_fabs: 9821 return Builtin::BI__builtin_fabsl; 9822 case Builtin::BI__builtin_fabsl: 9823 return 0; 9824 9825 case Builtin::BI__builtin_cabsf: 9826 return Builtin::BI__builtin_cabs; 9827 case Builtin::BI__builtin_cabs: 9828 return Builtin::BI__builtin_cabsl; 9829 case Builtin::BI__builtin_cabsl: 9830 return 0; 9831 9832 case Builtin::BIabs: 9833 return Builtin::BIlabs; 9834 case Builtin::BIlabs: 9835 return Builtin::BIllabs; 9836 case Builtin::BIllabs: 9837 return 0; 9838 9839 case Builtin::BIfabsf: 9840 return Builtin::BIfabs; 9841 case Builtin::BIfabs: 9842 return Builtin::BIfabsl; 9843 case Builtin::BIfabsl: 9844 return 0; 9845 9846 case Builtin::BIcabsf: 9847 return Builtin::BIcabs; 9848 case Builtin::BIcabs: 9849 return Builtin::BIcabsl; 9850 case Builtin::BIcabsl: 9851 return 0; 9852 } 9853 } 9854 9855 // Returns the argument type of the absolute value function. 9856 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9857 unsigned AbsType) { 9858 if (AbsType == 0) 9859 return QualType(); 9860 9861 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9862 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9863 if (Error != ASTContext::GE_None) 9864 return QualType(); 9865 9866 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9867 if (!FT) 9868 return QualType(); 9869 9870 if (FT->getNumParams() != 1) 9871 return QualType(); 9872 9873 return FT->getParamType(0); 9874 } 9875 9876 // Returns the best absolute value function, or zero, based on type and 9877 // current absolute value function. 9878 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9879 unsigned AbsFunctionKind) { 9880 unsigned BestKind = 0; 9881 uint64_t ArgSize = Context.getTypeSize(ArgType); 9882 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9883 Kind = getLargerAbsoluteValueFunction(Kind)) { 9884 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9885 if (Context.getTypeSize(ParamType) >= ArgSize) { 9886 if (BestKind == 0) 9887 BestKind = Kind; 9888 else if (Context.hasSameType(ParamType, ArgType)) { 9889 BestKind = Kind; 9890 break; 9891 } 9892 } 9893 } 9894 return BestKind; 9895 } 9896 9897 enum AbsoluteValueKind { 9898 AVK_Integer, 9899 AVK_Floating, 9900 AVK_Complex 9901 }; 9902 9903 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9904 if (T->isIntegralOrEnumerationType()) 9905 return AVK_Integer; 9906 if (T->isRealFloatingType()) 9907 return AVK_Floating; 9908 if (T->isAnyComplexType()) 9909 return AVK_Complex; 9910 9911 llvm_unreachable("Type not integer, floating, or complex"); 9912 } 9913 9914 // Changes the absolute value function to a different type. Preserves whether 9915 // the function is a builtin. 9916 static unsigned changeAbsFunction(unsigned AbsKind, 9917 AbsoluteValueKind ValueKind) { 9918 switch (ValueKind) { 9919 case AVK_Integer: 9920 switch (AbsKind) { 9921 default: 9922 return 0; 9923 case Builtin::BI__builtin_fabsf: 9924 case Builtin::BI__builtin_fabs: 9925 case Builtin::BI__builtin_fabsl: 9926 case Builtin::BI__builtin_cabsf: 9927 case Builtin::BI__builtin_cabs: 9928 case Builtin::BI__builtin_cabsl: 9929 return Builtin::BI__builtin_abs; 9930 case Builtin::BIfabsf: 9931 case Builtin::BIfabs: 9932 case Builtin::BIfabsl: 9933 case Builtin::BIcabsf: 9934 case Builtin::BIcabs: 9935 case Builtin::BIcabsl: 9936 return Builtin::BIabs; 9937 } 9938 case AVK_Floating: 9939 switch (AbsKind) { 9940 default: 9941 return 0; 9942 case Builtin::BI__builtin_abs: 9943 case Builtin::BI__builtin_labs: 9944 case Builtin::BI__builtin_llabs: 9945 case Builtin::BI__builtin_cabsf: 9946 case Builtin::BI__builtin_cabs: 9947 case Builtin::BI__builtin_cabsl: 9948 return Builtin::BI__builtin_fabsf; 9949 case Builtin::BIabs: 9950 case Builtin::BIlabs: 9951 case Builtin::BIllabs: 9952 case Builtin::BIcabsf: 9953 case Builtin::BIcabs: 9954 case Builtin::BIcabsl: 9955 return Builtin::BIfabsf; 9956 } 9957 case AVK_Complex: 9958 switch (AbsKind) { 9959 default: 9960 return 0; 9961 case Builtin::BI__builtin_abs: 9962 case Builtin::BI__builtin_labs: 9963 case Builtin::BI__builtin_llabs: 9964 case Builtin::BI__builtin_fabsf: 9965 case Builtin::BI__builtin_fabs: 9966 case Builtin::BI__builtin_fabsl: 9967 return Builtin::BI__builtin_cabsf; 9968 case Builtin::BIabs: 9969 case Builtin::BIlabs: 9970 case Builtin::BIllabs: 9971 case Builtin::BIfabsf: 9972 case Builtin::BIfabs: 9973 case Builtin::BIfabsl: 9974 return Builtin::BIcabsf; 9975 } 9976 } 9977 llvm_unreachable("Unable to convert function"); 9978 } 9979 9980 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9981 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9982 if (!FnInfo) 9983 return 0; 9984 9985 switch (FDecl->getBuiltinID()) { 9986 default: 9987 return 0; 9988 case Builtin::BI__builtin_abs: 9989 case Builtin::BI__builtin_fabs: 9990 case Builtin::BI__builtin_fabsf: 9991 case Builtin::BI__builtin_fabsl: 9992 case Builtin::BI__builtin_labs: 9993 case Builtin::BI__builtin_llabs: 9994 case Builtin::BI__builtin_cabs: 9995 case Builtin::BI__builtin_cabsf: 9996 case Builtin::BI__builtin_cabsl: 9997 case Builtin::BIabs: 9998 case Builtin::BIlabs: 9999 case Builtin::BIllabs: 10000 case Builtin::BIfabs: 10001 case Builtin::BIfabsf: 10002 case Builtin::BIfabsl: 10003 case Builtin::BIcabs: 10004 case Builtin::BIcabsf: 10005 case Builtin::BIcabsl: 10006 return FDecl->getBuiltinID(); 10007 } 10008 llvm_unreachable("Unknown Builtin type"); 10009 } 10010 10011 // If the replacement is valid, emit a note with replacement function. 10012 // Additionally, suggest including the proper header if not already included. 10013 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10014 unsigned AbsKind, QualType ArgType) { 10015 bool EmitHeaderHint = true; 10016 const char *HeaderName = nullptr; 10017 const char *FunctionName = nullptr; 10018 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10019 FunctionName = "std::abs"; 10020 if (ArgType->isIntegralOrEnumerationType()) { 10021 HeaderName = "cstdlib"; 10022 } else if (ArgType->isRealFloatingType()) { 10023 HeaderName = "cmath"; 10024 } else { 10025 llvm_unreachable("Invalid Type"); 10026 } 10027 10028 // Lookup all std::abs 10029 if (NamespaceDecl *Std = S.getStdNamespace()) { 10030 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10031 R.suppressDiagnostics(); 10032 S.LookupQualifiedName(R, Std); 10033 10034 for (const auto *I : R) { 10035 const FunctionDecl *FDecl = nullptr; 10036 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10037 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10038 } else { 10039 FDecl = dyn_cast<FunctionDecl>(I); 10040 } 10041 if (!FDecl) 10042 continue; 10043 10044 // Found std::abs(), check that they are the right ones. 10045 if (FDecl->getNumParams() != 1) 10046 continue; 10047 10048 // Check that the parameter type can handle the argument. 10049 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10050 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10051 S.Context.getTypeSize(ArgType) <= 10052 S.Context.getTypeSize(ParamType)) { 10053 // Found a function, don't need the header hint. 10054 EmitHeaderHint = false; 10055 break; 10056 } 10057 } 10058 } 10059 } else { 10060 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10061 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10062 10063 if (HeaderName) { 10064 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10065 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10066 R.suppressDiagnostics(); 10067 S.LookupName(R, S.getCurScope()); 10068 10069 if (R.isSingleResult()) { 10070 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10071 if (FD && FD->getBuiltinID() == AbsKind) { 10072 EmitHeaderHint = false; 10073 } else { 10074 return; 10075 } 10076 } else if (!R.empty()) { 10077 return; 10078 } 10079 } 10080 } 10081 10082 S.Diag(Loc, diag::note_replace_abs_function) 10083 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10084 10085 if (!HeaderName) 10086 return; 10087 10088 if (!EmitHeaderHint) 10089 return; 10090 10091 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10092 << FunctionName; 10093 } 10094 10095 template <std::size_t StrLen> 10096 static bool IsStdFunction(const FunctionDecl *FDecl, 10097 const char (&Str)[StrLen]) { 10098 if (!FDecl) 10099 return false; 10100 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10101 return false; 10102 if (!FDecl->isInStdNamespace()) 10103 return false; 10104 10105 return true; 10106 } 10107 10108 // Warn when using the wrong abs() function. 10109 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10110 const FunctionDecl *FDecl) { 10111 if (Call->getNumArgs() != 1) 10112 return; 10113 10114 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10115 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10116 if (AbsKind == 0 && !IsStdAbs) 10117 return; 10118 10119 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10120 QualType ParamType = Call->getArg(0)->getType(); 10121 10122 // Unsigned types cannot be negative. Suggest removing the absolute value 10123 // function call. 10124 if (ArgType->isUnsignedIntegerType()) { 10125 const char *FunctionName = 10126 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10127 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10128 Diag(Call->getExprLoc(), diag::note_remove_abs) 10129 << FunctionName 10130 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10131 return; 10132 } 10133 10134 // Taking the absolute value of a pointer is very suspicious, they probably 10135 // wanted to index into an array, dereference a pointer, call a function, etc. 10136 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10137 unsigned DiagType = 0; 10138 if (ArgType->isFunctionType()) 10139 DiagType = 1; 10140 else if (ArgType->isArrayType()) 10141 DiagType = 2; 10142 10143 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10144 return; 10145 } 10146 10147 // std::abs has overloads which prevent most of the absolute value problems 10148 // from occurring. 10149 if (IsStdAbs) 10150 return; 10151 10152 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10153 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10154 10155 // The argument and parameter are the same kind. Check if they are the right 10156 // size. 10157 if (ArgValueKind == ParamValueKind) { 10158 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10159 return; 10160 10161 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10162 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10163 << FDecl << ArgType << ParamType; 10164 10165 if (NewAbsKind == 0) 10166 return; 10167 10168 emitReplacement(*this, Call->getExprLoc(), 10169 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10170 return; 10171 } 10172 10173 // ArgValueKind != ParamValueKind 10174 // The wrong type of absolute value function was used. Attempt to find the 10175 // proper one. 10176 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10177 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10178 if (NewAbsKind == 0) 10179 return; 10180 10181 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10182 << FDecl << ParamValueKind << ArgValueKind; 10183 10184 emitReplacement(*this, Call->getExprLoc(), 10185 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10186 } 10187 10188 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10189 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10190 const FunctionDecl *FDecl) { 10191 if (!Call || !FDecl) return; 10192 10193 // Ignore template specializations and macros. 10194 if (inTemplateInstantiation()) return; 10195 if (Call->getExprLoc().isMacroID()) return; 10196 10197 // Only care about the one template argument, two function parameter std::max 10198 if (Call->getNumArgs() != 2) return; 10199 if (!IsStdFunction(FDecl, "max")) return; 10200 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10201 if (!ArgList) return; 10202 if (ArgList->size() != 1) return; 10203 10204 // Check that template type argument is unsigned integer. 10205 const auto& TA = ArgList->get(0); 10206 if (TA.getKind() != TemplateArgument::Type) return; 10207 QualType ArgType = TA.getAsType(); 10208 if (!ArgType->isUnsignedIntegerType()) return; 10209 10210 // See if either argument is a literal zero. 10211 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10212 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10213 if (!MTE) return false; 10214 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10215 if (!Num) return false; 10216 if (Num->getValue() != 0) return false; 10217 return true; 10218 }; 10219 10220 const Expr *FirstArg = Call->getArg(0); 10221 const Expr *SecondArg = Call->getArg(1); 10222 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10223 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10224 10225 // Only warn when exactly one argument is zero. 10226 if (IsFirstArgZero == IsSecondArgZero) return; 10227 10228 SourceRange FirstRange = FirstArg->getSourceRange(); 10229 SourceRange SecondRange = SecondArg->getSourceRange(); 10230 10231 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10232 10233 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10234 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10235 10236 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10237 SourceRange RemovalRange; 10238 if (IsFirstArgZero) { 10239 RemovalRange = SourceRange(FirstRange.getBegin(), 10240 SecondRange.getBegin().getLocWithOffset(-1)); 10241 } else { 10242 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10243 SecondRange.getEnd()); 10244 } 10245 10246 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10247 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10248 << FixItHint::CreateRemoval(RemovalRange); 10249 } 10250 10251 //===--- CHECK: Standard memory functions ---------------------------------===// 10252 10253 /// Takes the expression passed to the size_t parameter of functions 10254 /// such as memcmp, strncat, etc and warns if it's a comparison. 10255 /// 10256 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10257 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10258 IdentifierInfo *FnName, 10259 SourceLocation FnLoc, 10260 SourceLocation RParenLoc) { 10261 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10262 if (!Size) 10263 return false; 10264 10265 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10266 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10267 return false; 10268 10269 SourceRange SizeRange = Size->getSourceRange(); 10270 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10271 << SizeRange << FnName; 10272 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10273 << FnName 10274 << FixItHint::CreateInsertion( 10275 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10276 << FixItHint::CreateRemoval(RParenLoc); 10277 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10278 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10279 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10280 ")"); 10281 10282 return true; 10283 } 10284 10285 /// Determine whether the given type is or contains a dynamic class type 10286 /// (e.g., whether it has a vtable). 10287 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10288 bool &IsContained) { 10289 // Look through array types while ignoring qualifiers. 10290 const Type *Ty = T->getBaseElementTypeUnsafe(); 10291 IsContained = false; 10292 10293 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10294 RD = RD ? RD->getDefinition() : nullptr; 10295 if (!RD || RD->isInvalidDecl()) 10296 return nullptr; 10297 10298 if (RD->isDynamicClass()) 10299 return RD; 10300 10301 // Check all the fields. If any bases were dynamic, the class is dynamic. 10302 // It's impossible for a class to transitively contain itself by value, so 10303 // infinite recursion is impossible. 10304 for (auto *FD : RD->fields()) { 10305 bool SubContained; 10306 if (const CXXRecordDecl *ContainedRD = 10307 getContainedDynamicClass(FD->getType(), SubContained)) { 10308 IsContained = true; 10309 return ContainedRD; 10310 } 10311 } 10312 10313 return nullptr; 10314 } 10315 10316 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10317 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10318 if (Unary->getKind() == UETT_SizeOf) 10319 return Unary; 10320 return nullptr; 10321 } 10322 10323 /// If E is a sizeof expression, returns its argument expression, 10324 /// otherwise returns NULL. 10325 static const Expr *getSizeOfExprArg(const Expr *E) { 10326 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10327 if (!SizeOf->isArgumentType()) 10328 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10329 return nullptr; 10330 } 10331 10332 /// If E is a sizeof expression, returns its argument type. 10333 static QualType getSizeOfArgType(const Expr *E) { 10334 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10335 return SizeOf->getTypeOfArgument(); 10336 return QualType(); 10337 } 10338 10339 namespace { 10340 10341 struct SearchNonTrivialToInitializeField 10342 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10343 using Super = 10344 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10345 10346 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10347 10348 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10349 SourceLocation SL) { 10350 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10351 asDerived().visitArray(PDIK, AT, SL); 10352 return; 10353 } 10354 10355 Super::visitWithKind(PDIK, FT, SL); 10356 } 10357 10358 void visitARCStrong(QualType FT, SourceLocation SL) { 10359 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10360 } 10361 void visitARCWeak(QualType FT, SourceLocation SL) { 10362 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10363 } 10364 void visitStruct(QualType FT, SourceLocation SL) { 10365 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10366 visit(FD->getType(), FD->getLocation()); 10367 } 10368 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10369 const ArrayType *AT, SourceLocation SL) { 10370 visit(getContext().getBaseElementType(AT), SL); 10371 } 10372 void visitTrivial(QualType FT, SourceLocation SL) {} 10373 10374 static void diag(QualType RT, const Expr *E, Sema &S) { 10375 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10376 } 10377 10378 ASTContext &getContext() { return S.getASTContext(); } 10379 10380 const Expr *E; 10381 Sema &S; 10382 }; 10383 10384 struct SearchNonTrivialToCopyField 10385 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10386 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10387 10388 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10389 10390 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10391 SourceLocation SL) { 10392 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10393 asDerived().visitArray(PCK, AT, SL); 10394 return; 10395 } 10396 10397 Super::visitWithKind(PCK, FT, SL); 10398 } 10399 10400 void visitARCStrong(QualType FT, SourceLocation SL) { 10401 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10402 } 10403 void visitARCWeak(QualType FT, SourceLocation SL) { 10404 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10405 } 10406 void visitStruct(QualType FT, SourceLocation SL) { 10407 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10408 visit(FD->getType(), FD->getLocation()); 10409 } 10410 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10411 SourceLocation SL) { 10412 visit(getContext().getBaseElementType(AT), SL); 10413 } 10414 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10415 SourceLocation SL) {} 10416 void visitTrivial(QualType FT, SourceLocation SL) {} 10417 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10418 10419 static void diag(QualType RT, const Expr *E, Sema &S) { 10420 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10421 } 10422 10423 ASTContext &getContext() { return S.getASTContext(); } 10424 10425 const Expr *E; 10426 Sema &S; 10427 }; 10428 10429 } 10430 10431 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10432 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10433 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10434 10435 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10436 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10437 return false; 10438 10439 return doesExprLikelyComputeSize(BO->getLHS()) || 10440 doesExprLikelyComputeSize(BO->getRHS()); 10441 } 10442 10443 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10444 } 10445 10446 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10447 /// 10448 /// \code 10449 /// #define MACRO 0 10450 /// foo(MACRO); 10451 /// foo(0); 10452 /// \endcode 10453 /// 10454 /// This should return true for the first call to foo, but not for the second 10455 /// (regardless of whether foo is a macro or function). 10456 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10457 SourceLocation CallLoc, 10458 SourceLocation ArgLoc) { 10459 if (!CallLoc.isMacroID()) 10460 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10461 10462 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10463 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10464 } 10465 10466 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10467 /// last two arguments transposed. 10468 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10469 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10470 return; 10471 10472 const Expr *SizeArg = 10473 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10474 10475 auto isLiteralZero = [](const Expr *E) { 10476 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10477 }; 10478 10479 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10480 SourceLocation CallLoc = Call->getRParenLoc(); 10481 SourceManager &SM = S.getSourceManager(); 10482 if (isLiteralZero(SizeArg) && 10483 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10484 10485 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10486 10487 // Some platforms #define bzero to __builtin_memset. See if this is the 10488 // case, and if so, emit a better diagnostic. 10489 if (BId == Builtin::BIbzero || 10490 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10491 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10492 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10493 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10494 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10495 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10496 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10497 } 10498 return; 10499 } 10500 10501 // If the second argument to a memset is a sizeof expression and the third 10502 // isn't, this is also likely an error. This should catch 10503 // 'memset(buf, sizeof(buf), 0xff)'. 10504 if (BId == Builtin::BImemset && 10505 doesExprLikelyComputeSize(Call->getArg(1)) && 10506 !doesExprLikelyComputeSize(Call->getArg(2))) { 10507 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10508 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10509 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10510 return; 10511 } 10512 } 10513 10514 /// Check for dangerous or invalid arguments to memset(). 10515 /// 10516 /// This issues warnings on known problematic, dangerous or unspecified 10517 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10518 /// function calls. 10519 /// 10520 /// \param Call The call expression to diagnose. 10521 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10522 unsigned BId, 10523 IdentifierInfo *FnName) { 10524 assert(BId != 0); 10525 10526 // It is possible to have a non-standard definition of memset. Validate 10527 // we have enough arguments, and if not, abort further checking. 10528 unsigned ExpectedNumArgs = 10529 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10530 if (Call->getNumArgs() < ExpectedNumArgs) 10531 return; 10532 10533 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10534 BId == Builtin::BIstrndup ? 1 : 2); 10535 unsigned LenArg = 10536 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10537 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10538 10539 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10540 Call->getBeginLoc(), Call->getRParenLoc())) 10541 return; 10542 10543 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10544 CheckMemaccessSize(*this, BId, Call); 10545 10546 // We have special checking when the length is a sizeof expression. 10547 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10548 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10549 llvm::FoldingSetNodeID SizeOfArgID; 10550 10551 // Although widely used, 'bzero' is not a standard function. Be more strict 10552 // with the argument types before allowing diagnostics and only allow the 10553 // form bzero(ptr, sizeof(...)). 10554 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10555 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10556 return; 10557 10558 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10559 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10560 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10561 10562 QualType DestTy = Dest->getType(); 10563 QualType PointeeTy; 10564 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10565 PointeeTy = DestPtrTy->getPointeeType(); 10566 10567 // Never warn about void type pointers. This can be used to suppress 10568 // false positives. 10569 if (PointeeTy->isVoidType()) 10570 continue; 10571 10572 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10573 // actually comparing the expressions for equality. Because computing the 10574 // expression IDs can be expensive, we only do this if the diagnostic is 10575 // enabled. 10576 if (SizeOfArg && 10577 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10578 SizeOfArg->getExprLoc())) { 10579 // We only compute IDs for expressions if the warning is enabled, and 10580 // cache the sizeof arg's ID. 10581 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10582 SizeOfArg->Profile(SizeOfArgID, Context, true); 10583 llvm::FoldingSetNodeID DestID; 10584 Dest->Profile(DestID, Context, true); 10585 if (DestID == SizeOfArgID) { 10586 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10587 // over sizeof(src) as well. 10588 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10589 StringRef ReadableName = FnName->getName(); 10590 10591 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10592 if (UnaryOp->getOpcode() == UO_AddrOf) 10593 ActionIdx = 1; // If its an address-of operator, just remove it. 10594 if (!PointeeTy->isIncompleteType() && 10595 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10596 ActionIdx = 2; // If the pointee's size is sizeof(char), 10597 // suggest an explicit length. 10598 10599 // If the function is defined as a builtin macro, do not show macro 10600 // expansion. 10601 SourceLocation SL = SizeOfArg->getExprLoc(); 10602 SourceRange DSR = Dest->getSourceRange(); 10603 SourceRange SSR = SizeOfArg->getSourceRange(); 10604 SourceManager &SM = getSourceManager(); 10605 10606 if (SM.isMacroArgExpansion(SL)) { 10607 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10608 SL = SM.getSpellingLoc(SL); 10609 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10610 SM.getSpellingLoc(DSR.getEnd())); 10611 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10612 SM.getSpellingLoc(SSR.getEnd())); 10613 } 10614 10615 DiagRuntimeBehavior(SL, SizeOfArg, 10616 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10617 << ReadableName 10618 << PointeeTy 10619 << DestTy 10620 << DSR 10621 << SSR); 10622 DiagRuntimeBehavior(SL, SizeOfArg, 10623 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10624 << ActionIdx 10625 << SSR); 10626 10627 break; 10628 } 10629 } 10630 10631 // Also check for cases where the sizeof argument is the exact same 10632 // type as the memory argument, and where it points to a user-defined 10633 // record type. 10634 if (SizeOfArgTy != QualType()) { 10635 if (PointeeTy->isRecordType() && 10636 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10637 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10638 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10639 << FnName << SizeOfArgTy << ArgIdx 10640 << PointeeTy << Dest->getSourceRange() 10641 << LenExpr->getSourceRange()); 10642 break; 10643 } 10644 } 10645 } else if (DestTy->isArrayType()) { 10646 PointeeTy = DestTy; 10647 } 10648 10649 if (PointeeTy == QualType()) 10650 continue; 10651 10652 // Always complain about dynamic classes. 10653 bool IsContained; 10654 if (const CXXRecordDecl *ContainedRD = 10655 getContainedDynamicClass(PointeeTy, IsContained)) { 10656 10657 unsigned OperationType = 0; 10658 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10659 // "overwritten" if we're warning about the destination for any call 10660 // but memcmp; otherwise a verb appropriate to the call. 10661 if (ArgIdx != 0 || IsCmp) { 10662 if (BId == Builtin::BImemcpy) 10663 OperationType = 1; 10664 else if(BId == Builtin::BImemmove) 10665 OperationType = 2; 10666 else if (IsCmp) 10667 OperationType = 3; 10668 } 10669 10670 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10671 PDiag(diag::warn_dyn_class_memaccess) 10672 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10673 << IsContained << ContainedRD << OperationType 10674 << Call->getCallee()->getSourceRange()); 10675 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10676 BId != Builtin::BImemset) 10677 DiagRuntimeBehavior( 10678 Dest->getExprLoc(), Dest, 10679 PDiag(diag::warn_arc_object_memaccess) 10680 << ArgIdx << FnName << PointeeTy 10681 << Call->getCallee()->getSourceRange()); 10682 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10683 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10684 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10685 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10686 PDiag(diag::warn_cstruct_memaccess) 10687 << ArgIdx << FnName << PointeeTy << 0); 10688 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10689 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10690 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10691 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10692 PDiag(diag::warn_cstruct_memaccess) 10693 << ArgIdx << FnName << PointeeTy << 1); 10694 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10695 } else { 10696 continue; 10697 } 10698 } else 10699 continue; 10700 10701 DiagRuntimeBehavior( 10702 Dest->getExprLoc(), Dest, 10703 PDiag(diag::note_bad_memaccess_silence) 10704 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10705 break; 10706 } 10707 } 10708 10709 // A little helper routine: ignore addition and subtraction of integer literals. 10710 // This intentionally does not ignore all integer constant expressions because 10711 // we don't want to remove sizeof(). 10712 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10713 Ex = Ex->IgnoreParenCasts(); 10714 10715 while (true) { 10716 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10717 if (!BO || !BO->isAdditiveOp()) 10718 break; 10719 10720 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10721 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10722 10723 if (isa<IntegerLiteral>(RHS)) 10724 Ex = LHS; 10725 else if (isa<IntegerLiteral>(LHS)) 10726 Ex = RHS; 10727 else 10728 break; 10729 } 10730 10731 return Ex; 10732 } 10733 10734 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10735 ASTContext &Context) { 10736 // Only handle constant-sized or VLAs, but not flexible members. 10737 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10738 // Only issue the FIXIT for arrays of size > 1. 10739 if (CAT->getSize().getSExtValue() <= 1) 10740 return false; 10741 } else if (!Ty->isVariableArrayType()) { 10742 return false; 10743 } 10744 return true; 10745 } 10746 10747 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10748 // be the size of the source, instead of the destination. 10749 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10750 IdentifierInfo *FnName) { 10751 10752 // Don't crash if the user has the wrong number of arguments 10753 unsigned NumArgs = Call->getNumArgs(); 10754 if ((NumArgs != 3) && (NumArgs != 4)) 10755 return; 10756 10757 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10758 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10759 const Expr *CompareWithSrc = nullptr; 10760 10761 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10762 Call->getBeginLoc(), Call->getRParenLoc())) 10763 return; 10764 10765 // Look for 'strlcpy(dst, x, sizeof(x))' 10766 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10767 CompareWithSrc = Ex; 10768 else { 10769 // Look for 'strlcpy(dst, x, strlen(x))' 10770 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10771 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10772 SizeCall->getNumArgs() == 1) 10773 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10774 } 10775 } 10776 10777 if (!CompareWithSrc) 10778 return; 10779 10780 // Determine if the argument to sizeof/strlen is equal to the source 10781 // argument. In principle there's all kinds of things you could do 10782 // here, for instance creating an == expression and evaluating it with 10783 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10784 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10785 if (!SrcArgDRE) 10786 return; 10787 10788 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10789 if (!CompareWithSrcDRE || 10790 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10791 return; 10792 10793 const Expr *OriginalSizeArg = Call->getArg(2); 10794 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10795 << OriginalSizeArg->getSourceRange() << FnName; 10796 10797 // Output a FIXIT hint if the destination is an array (rather than a 10798 // pointer to an array). This could be enhanced to handle some 10799 // pointers if we know the actual size, like if DstArg is 'array+2' 10800 // we could say 'sizeof(array)-2'. 10801 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10802 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10803 return; 10804 10805 SmallString<128> sizeString; 10806 llvm::raw_svector_ostream OS(sizeString); 10807 OS << "sizeof("; 10808 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10809 OS << ")"; 10810 10811 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10812 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10813 OS.str()); 10814 } 10815 10816 /// Check if two expressions refer to the same declaration. 10817 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10818 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10819 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10820 return D1->getDecl() == D2->getDecl(); 10821 return false; 10822 } 10823 10824 static const Expr *getStrlenExprArg(const Expr *E) { 10825 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10826 const FunctionDecl *FD = CE->getDirectCallee(); 10827 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10828 return nullptr; 10829 return CE->getArg(0)->IgnoreParenCasts(); 10830 } 10831 return nullptr; 10832 } 10833 10834 // Warn on anti-patterns as the 'size' argument to strncat. 10835 // The correct size argument should look like following: 10836 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10837 void Sema::CheckStrncatArguments(const CallExpr *CE, 10838 IdentifierInfo *FnName) { 10839 // Don't crash if the user has the wrong number of arguments. 10840 if (CE->getNumArgs() < 3) 10841 return; 10842 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10843 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10844 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10845 10846 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10847 CE->getRParenLoc())) 10848 return; 10849 10850 // Identify common expressions, which are wrongly used as the size argument 10851 // to strncat and may lead to buffer overflows. 10852 unsigned PatternType = 0; 10853 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10854 // - sizeof(dst) 10855 if (referToTheSameDecl(SizeOfArg, DstArg)) 10856 PatternType = 1; 10857 // - sizeof(src) 10858 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10859 PatternType = 2; 10860 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10861 if (BE->getOpcode() == BO_Sub) { 10862 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10863 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10864 // - sizeof(dst) - strlen(dst) 10865 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10866 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10867 PatternType = 1; 10868 // - sizeof(src) - (anything) 10869 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10870 PatternType = 2; 10871 } 10872 } 10873 10874 if (PatternType == 0) 10875 return; 10876 10877 // Generate the diagnostic. 10878 SourceLocation SL = LenArg->getBeginLoc(); 10879 SourceRange SR = LenArg->getSourceRange(); 10880 SourceManager &SM = getSourceManager(); 10881 10882 // If the function is defined as a builtin macro, do not show macro expansion. 10883 if (SM.isMacroArgExpansion(SL)) { 10884 SL = SM.getSpellingLoc(SL); 10885 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10886 SM.getSpellingLoc(SR.getEnd())); 10887 } 10888 10889 // Check if the destination is an array (rather than a pointer to an array). 10890 QualType DstTy = DstArg->getType(); 10891 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10892 Context); 10893 if (!isKnownSizeArray) { 10894 if (PatternType == 1) 10895 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10896 else 10897 Diag(SL, diag::warn_strncat_src_size) << SR; 10898 return; 10899 } 10900 10901 if (PatternType == 1) 10902 Diag(SL, diag::warn_strncat_large_size) << SR; 10903 else 10904 Diag(SL, diag::warn_strncat_src_size) << SR; 10905 10906 SmallString<128> sizeString; 10907 llvm::raw_svector_ostream OS(sizeString); 10908 OS << "sizeof("; 10909 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10910 OS << ") - "; 10911 OS << "strlen("; 10912 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10913 OS << ") - 1"; 10914 10915 Diag(SL, diag::note_strncat_wrong_size) 10916 << FixItHint::CreateReplacement(SR, OS.str()); 10917 } 10918 10919 namespace { 10920 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10921 const UnaryOperator *UnaryExpr, const Decl *D) { 10922 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10923 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10924 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10925 return; 10926 } 10927 } 10928 10929 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10930 const UnaryOperator *UnaryExpr) { 10931 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10932 const Decl *D = Lvalue->getDecl(); 10933 if (isa<DeclaratorDecl>(D)) 10934 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10935 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10936 } 10937 10938 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10939 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10940 Lvalue->getMemberDecl()); 10941 } 10942 10943 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10944 const UnaryOperator *UnaryExpr) { 10945 const auto *Lambda = dyn_cast<LambdaExpr>( 10946 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10947 if (!Lambda) 10948 return; 10949 10950 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10951 << CalleeName << 2 /*object: lambda expression*/; 10952 } 10953 10954 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10955 const DeclRefExpr *Lvalue) { 10956 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10957 if (Var == nullptr) 10958 return; 10959 10960 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10961 << CalleeName << 0 /*object: */ << Var; 10962 } 10963 10964 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10965 const CastExpr *Cast) { 10966 SmallString<128> SizeString; 10967 llvm::raw_svector_ostream OS(SizeString); 10968 10969 clang::CastKind Kind = Cast->getCastKind(); 10970 if (Kind == clang::CK_BitCast && 10971 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10972 return; 10973 if (Kind == clang::CK_IntegralToPointer && 10974 !isa<IntegerLiteral>( 10975 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10976 return; 10977 10978 switch (Cast->getCastKind()) { 10979 case clang::CK_BitCast: 10980 case clang::CK_IntegralToPointer: 10981 case clang::CK_FunctionToPointerDecay: 10982 OS << '\''; 10983 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10984 OS << '\''; 10985 break; 10986 default: 10987 return; 10988 } 10989 10990 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10991 << CalleeName << 0 /*object: */ << OS.str(); 10992 } 10993 } // namespace 10994 10995 /// Alerts the user that they are attempting to free a non-malloc'd object. 10996 void Sema::CheckFreeArguments(const CallExpr *E) { 10997 const std::string CalleeName = 10998 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10999 11000 { // Prefer something that doesn't involve a cast to make things simpler. 11001 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11002 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11003 switch (UnaryExpr->getOpcode()) { 11004 case UnaryOperator::Opcode::UO_AddrOf: 11005 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11006 case UnaryOperator::Opcode::UO_Plus: 11007 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11008 default: 11009 break; 11010 } 11011 11012 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11013 if (Lvalue->getType()->isArrayType()) 11014 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11015 11016 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11017 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11018 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11019 return; 11020 } 11021 11022 if (isa<BlockExpr>(Arg)) { 11023 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11024 << CalleeName << 1 /*object: block*/; 11025 return; 11026 } 11027 } 11028 // Maybe the cast was important, check after the other cases. 11029 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11030 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11031 } 11032 11033 void 11034 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11035 SourceLocation ReturnLoc, 11036 bool isObjCMethod, 11037 const AttrVec *Attrs, 11038 const FunctionDecl *FD) { 11039 // Check if the return value is null but should not be. 11040 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11041 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11042 CheckNonNullExpr(*this, RetValExp)) 11043 Diag(ReturnLoc, diag::warn_null_ret) 11044 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11045 11046 // C++11 [basic.stc.dynamic.allocation]p4: 11047 // If an allocation function declared with a non-throwing 11048 // exception-specification fails to allocate storage, it shall return 11049 // a null pointer. Any other allocation function that fails to allocate 11050 // storage shall indicate failure only by throwing an exception [...] 11051 if (FD) { 11052 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11053 if (Op == OO_New || Op == OO_Array_New) { 11054 const FunctionProtoType *Proto 11055 = FD->getType()->castAs<FunctionProtoType>(); 11056 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11057 CheckNonNullExpr(*this, RetValExp)) 11058 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11059 << FD << getLangOpts().CPlusPlus11; 11060 } 11061 } 11062 11063 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11064 // here prevent the user from using a PPC MMA type as trailing return type. 11065 if (Context.getTargetInfo().getTriple().isPPC64()) 11066 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11067 } 11068 11069 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11070 11071 /// Check for comparisons of floating point operands using != and ==. 11072 /// Issue a warning if these are no self-comparisons, as they are not likely 11073 /// to do what the programmer intended. 11074 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11075 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11076 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11077 11078 // Special case: check for x == x (which is OK). 11079 // Do not emit warnings for such cases. 11080 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11081 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11082 if (DRL->getDecl() == DRR->getDecl()) 11083 return; 11084 11085 // Special case: check for comparisons against literals that can be exactly 11086 // represented by APFloat. In such cases, do not emit a warning. This 11087 // is a heuristic: often comparison against such literals are used to 11088 // detect if a value in a variable has not changed. This clearly can 11089 // lead to false negatives. 11090 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11091 if (FLL->isExact()) 11092 return; 11093 } else 11094 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11095 if (FLR->isExact()) 11096 return; 11097 11098 // Check for comparisons with builtin types. 11099 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11100 if (CL->getBuiltinCallee()) 11101 return; 11102 11103 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11104 if (CR->getBuiltinCallee()) 11105 return; 11106 11107 // Emit the diagnostic. 11108 Diag(Loc, diag::warn_floatingpoint_eq) 11109 << LHS->getSourceRange() << RHS->getSourceRange(); 11110 } 11111 11112 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11113 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11114 11115 namespace { 11116 11117 /// Structure recording the 'active' range of an integer-valued 11118 /// expression. 11119 struct IntRange { 11120 /// The number of bits active in the int. Note that this includes exactly one 11121 /// sign bit if !NonNegative. 11122 unsigned Width; 11123 11124 /// True if the int is known not to have negative values. If so, all leading 11125 /// bits before Width are known zero, otherwise they are known to be the 11126 /// same as the MSB within Width. 11127 bool NonNegative; 11128 11129 IntRange(unsigned Width, bool NonNegative) 11130 : Width(Width), NonNegative(NonNegative) {} 11131 11132 /// Number of bits excluding the sign bit. 11133 unsigned valueBits() const { 11134 return NonNegative ? Width : Width - 1; 11135 } 11136 11137 /// Returns the range of the bool type. 11138 static IntRange forBoolType() { 11139 return IntRange(1, true); 11140 } 11141 11142 /// Returns the range of an opaque value of the given integral type. 11143 static IntRange forValueOfType(ASTContext &C, QualType T) { 11144 return forValueOfCanonicalType(C, 11145 T->getCanonicalTypeInternal().getTypePtr()); 11146 } 11147 11148 /// Returns the range of an opaque value of a canonical integral type. 11149 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11150 assert(T->isCanonicalUnqualified()); 11151 11152 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11153 T = VT->getElementType().getTypePtr(); 11154 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11155 T = CT->getElementType().getTypePtr(); 11156 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11157 T = AT->getValueType().getTypePtr(); 11158 11159 if (!C.getLangOpts().CPlusPlus) { 11160 // For enum types in C code, use the underlying datatype. 11161 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11162 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11163 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11164 // For enum types in C++, use the known bit width of the enumerators. 11165 EnumDecl *Enum = ET->getDecl(); 11166 // In C++11, enums can have a fixed underlying type. Use this type to 11167 // compute the range. 11168 if (Enum->isFixed()) { 11169 return IntRange(C.getIntWidth(QualType(T, 0)), 11170 !ET->isSignedIntegerOrEnumerationType()); 11171 } 11172 11173 unsigned NumPositive = Enum->getNumPositiveBits(); 11174 unsigned NumNegative = Enum->getNumNegativeBits(); 11175 11176 if (NumNegative == 0) 11177 return IntRange(NumPositive, true/*NonNegative*/); 11178 else 11179 return IntRange(std::max(NumPositive + 1, NumNegative), 11180 false/*NonNegative*/); 11181 } 11182 11183 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11184 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11185 11186 const BuiltinType *BT = cast<BuiltinType>(T); 11187 assert(BT->isInteger()); 11188 11189 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11190 } 11191 11192 /// Returns the "target" range of a canonical integral type, i.e. 11193 /// the range of values expressible in the type. 11194 /// 11195 /// This matches forValueOfCanonicalType except that enums have the 11196 /// full range of their type, not the range of their enumerators. 11197 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11198 assert(T->isCanonicalUnqualified()); 11199 11200 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11201 T = VT->getElementType().getTypePtr(); 11202 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11203 T = CT->getElementType().getTypePtr(); 11204 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11205 T = AT->getValueType().getTypePtr(); 11206 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11207 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11208 11209 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11210 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11211 11212 const BuiltinType *BT = cast<BuiltinType>(T); 11213 assert(BT->isInteger()); 11214 11215 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11216 } 11217 11218 /// Returns the supremum of two ranges: i.e. their conservative merge. 11219 static IntRange join(IntRange L, IntRange R) { 11220 bool Unsigned = L.NonNegative && R.NonNegative; 11221 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11222 L.NonNegative && R.NonNegative); 11223 } 11224 11225 /// Return the range of a bitwise-AND of the two ranges. 11226 static IntRange bit_and(IntRange L, IntRange R) { 11227 unsigned Bits = std::max(L.Width, R.Width); 11228 bool NonNegative = false; 11229 if (L.NonNegative) { 11230 Bits = std::min(Bits, L.Width); 11231 NonNegative = true; 11232 } 11233 if (R.NonNegative) { 11234 Bits = std::min(Bits, R.Width); 11235 NonNegative = true; 11236 } 11237 return IntRange(Bits, NonNegative); 11238 } 11239 11240 /// Return the range of a sum of the two ranges. 11241 static IntRange sum(IntRange L, IntRange R) { 11242 bool Unsigned = L.NonNegative && R.NonNegative; 11243 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11244 Unsigned); 11245 } 11246 11247 /// Return the range of a difference of the two ranges. 11248 static IntRange difference(IntRange L, IntRange R) { 11249 // We need a 1-bit-wider range if: 11250 // 1) LHS can be negative: least value can be reduced. 11251 // 2) RHS can be negative: greatest value can be increased. 11252 bool CanWiden = !L.NonNegative || !R.NonNegative; 11253 bool Unsigned = L.NonNegative && R.Width == 0; 11254 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11255 !Unsigned, 11256 Unsigned); 11257 } 11258 11259 /// Return the range of a product of the two ranges. 11260 static IntRange product(IntRange L, IntRange R) { 11261 // If both LHS and RHS can be negative, we can form 11262 // -2^L * -2^R = 2^(L + R) 11263 // which requires L + R + 1 value bits to represent. 11264 bool CanWiden = !L.NonNegative && !R.NonNegative; 11265 bool Unsigned = L.NonNegative && R.NonNegative; 11266 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11267 Unsigned); 11268 } 11269 11270 /// Return the range of a remainder operation between the two ranges. 11271 static IntRange rem(IntRange L, IntRange R) { 11272 // The result of a remainder can't be larger than the result of 11273 // either side. The sign of the result is the sign of the LHS. 11274 bool Unsigned = L.NonNegative; 11275 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11276 Unsigned); 11277 } 11278 }; 11279 11280 } // namespace 11281 11282 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11283 unsigned MaxWidth) { 11284 if (value.isSigned() && value.isNegative()) 11285 return IntRange(value.getMinSignedBits(), false); 11286 11287 if (value.getBitWidth() > MaxWidth) 11288 value = value.trunc(MaxWidth); 11289 11290 // isNonNegative() just checks the sign bit without considering 11291 // signedness. 11292 return IntRange(value.getActiveBits(), true); 11293 } 11294 11295 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11296 unsigned MaxWidth) { 11297 if (result.isInt()) 11298 return GetValueRange(C, result.getInt(), MaxWidth); 11299 11300 if (result.isVector()) { 11301 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11302 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11303 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11304 R = IntRange::join(R, El); 11305 } 11306 return R; 11307 } 11308 11309 if (result.isComplexInt()) { 11310 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11311 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11312 return IntRange::join(R, I); 11313 } 11314 11315 // This can happen with lossless casts to intptr_t of "based" lvalues. 11316 // Assume it might use arbitrary bits. 11317 // FIXME: The only reason we need to pass the type in here is to get 11318 // the sign right on this one case. It would be nice if APValue 11319 // preserved this. 11320 assert(result.isLValue() || result.isAddrLabelDiff()); 11321 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11322 } 11323 11324 static QualType GetExprType(const Expr *E) { 11325 QualType Ty = E->getType(); 11326 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11327 Ty = AtomicRHS->getValueType(); 11328 return Ty; 11329 } 11330 11331 /// Pseudo-evaluate the given integer expression, estimating the 11332 /// range of values it might take. 11333 /// 11334 /// \param MaxWidth The width to which the value will be truncated. 11335 /// \param Approximate If \c true, return a likely range for the result: in 11336 /// particular, assume that arithmetic on narrower types doesn't leave 11337 /// those types. If \c false, return a range including all possible 11338 /// result values. 11339 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11340 bool InConstantContext, bool Approximate) { 11341 E = E->IgnoreParens(); 11342 11343 // Try a full evaluation first. 11344 Expr::EvalResult result; 11345 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11346 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11347 11348 // I think we only want to look through implicit casts here; if the 11349 // user has an explicit widening cast, we should treat the value as 11350 // being of the new, wider type. 11351 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11352 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11353 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11354 Approximate); 11355 11356 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11357 11358 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11359 CE->getCastKind() == CK_BooleanToSignedIntegral; 11360 11361 // Assume that non-integer casts can span the full range of the type. 11362 if (!isIntegerCast) 11363 return OutputTypeRange; 11364 11365 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11366 std::min(MaxWidth, OutputTypeRange.Width), 11367 InConstantContext, Approximate); 11368 11369 // Bail out if the subexpr's range is as wide as the cast type. 11370 if (SubRange.Width >= OutputTypeRange.Width) 11371 return OutputTypeRange; 11372 11373 // Otherwise, we take the smaller width, and we're non-negative if 11374 // either the output type or the subexpr is. 11375 return IntRange(SubRange.Width, 11376 SubRange.NonNegative || OutputTypeRange.NonNegative); 11377 } 11378 11379 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11380 // If we can fold the condition, just take that operand. 11381 bool CondResult; 11382 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11383 return GetExprRange(C, 11384 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11385 MaxWidth, InConstantContext, Approximate); 11386 11387 // Otherwise, conservatively merge. 11388 // GetExprRange requires an integer expression, but a throw expression 11389 // results in a void type. 11390 Expr *E = CO->getTrueExpr(); 11391 IntRange L = E->getType()->isVoidType() 11392 ? IntRange{0, true} 11393 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11394 E = CO->getFalseExpr(); 11395 IntRange R = E->getType()->isVoidType() 11396 ? IntRange{0, true} 11397 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11398 return IntRange::join(L, R); 11399 } 11400 11401 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11402 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11403 11404 switch (BO->getOpcode()) { 11405 case BO_Cmp: 11406 llvm_unreachable("builtin <=> should have class type"); 11407 11408 // Boolean-valued operations are single-bit and positive. 11409 case BO_LAnd: 11410 case BO_LOr: 11411 case BO_LT: 11412 case BO_GT: 11413 case BO_LE: 11414 case BO_GE: 11415 case BO_EQ: 11416 case BO_NE: 11417 return IntRange::forBoolType(); 11418 11419 // The type of the assignments is the type of the LHS, so the RHS 11420 // is not necessarily the same type. 11421 case BO_MulAssign: 11422 case BO_DivAssign: 11423 case BO_RemAssign: 11424 case BO_AddAssign: 11425 case BO_SubAssign: 11426 case BO_XorAssign: 11427 case BO_OrAssign: 11428 // TODO: bitfields? 11429 return IntRange::forValueOfType(C, GetExprType(E)); 11430 11431 // Simple assignments just pass through the RHS, which will have 11432 // been coerced to the LHS type. 11433 case BO_Assign: 11434 // TODO: bitfields? 11435 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11436 Approximate); 11437 11438 // Operations with opaque sources are black-listed. 11439 case BO_PtrMemD: 11440 case BO_PtrMemI: 11441 return IntRange::forValueOfType(C, GetExprType(E)); 11442 11443 // Bitwise-and uses the *infinum* of the two source ranges. 11444 case BO_And: 11445 case BO_AndAssign: 11446 Combine = IntRange::bit_and; 11447 break; 11448 11449 // Left shift gets black-listed based on a judgement call. 11450 case BO_Shl: 11451 // ...except that we want to treat '1 << (blah)' as logically 11452 // positive. It's an important idiom. 11453 if (IntegerLiteral *I 11454 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11455 if (I->getValue() == 1) { 11456 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11457 return IntRange(R.Width, /*NonNegative*/ true); 11458 } 11459 } 11460 LLVM_FALLTHROUGH; 11461 11462 case BO_ShlAssign: 11463 return IntRange::forValueOfType(C, GetExprType(E)); 11464 11465 // Right shift by a constant can narrow its left argument. 11466 case BO_Shr: 11467 case BO_ShrAssign: { 11468 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11469 Approximate); 11470 11471 // If the shift amount is a positive constant, drop the width by 11472 // that much. 11473 if (Optional<llvm::APSInt> shift = 11474 BO->getRHS()->getIntegerConstantExpr(C)) { 11475 if (shift->isNonNegative()) { 11476 unsigned zext = shift->getZExtValue(); 11477 if (zext >= L.Width) 11478 L.Width = (L.NonNegative ? 0 : 1); 11479 else 11480 L.Width -= zext; 11481 } 11482 } 11483 11484 return L; 11485 } 11486 11487 // Comma acts as its right operand. 11488 case BO_Comma: 11489 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11490 Approximate); 11491 11492 case BO_Add: 11493 if (!Approximate) 11494 Combine = IntRange::sum; 11495 break; 11496 11497 case BO_Sub: 11498 if (BO->getLHS()->getType()->isPointerType()) 11499 return IntRange::forValueOfType(C, GetExprType(E)); 11500 if (!Approximate) 11501 Combine = IntRange::difference; 11502 break; 11503 11504 case BO_Mul: 11505 if (!Approximate) 11506 Combine = IntRange::product; 11507 break; 11508 11509 // The width of a division result is mostly determined by the size 11510 // of the LHS. 11511 case BO_Div: { 11512 // Don't 'pre-truncate' the operands. 11513 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11514 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11515 Approximate); 11516 11517 // If the divisor is constant, use that. 11518 if (Optional<llvm::APSInt> divisor = 11519 BO->getRHS()->getIntegerConstantExpr(C)) { 11520 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11521 if (log2 >= L.Width) 11522 L.Width = (L.NonNegative ? 0 : 1); 11523 else 11524 L.Width = std::min(L.Width - log2, MaxWidth); 11525 return L; 11526 } 11527 11528 // Otherwise, just use the LHS's width. 11529 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11530 // could be -1. 11531 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11532 Approximate); 11533 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11534 } 11535 11536 case BO_Rem: 11537 Combine = IntRange::rem; 11538 break; 11539 11540 // The default behavior is okay for these. 11541 case BO_Xor: 11542 case BO_Or: 11543 break; 11544 } 11545 11546 // Combine the two ranges, but limit the result to the type in which we 11547 // performed the computation. 11548 QualType T = GetExprType(E); 11549 unsigned opWidth = C.getIntWidth(T); 11550 IntRange L = 11551 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11552 IntRange R = 11553 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11554 IntRange C = Combine(L, R); 11555 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11556 C.Width = std::min(C.Width, MaxWidth); 11557 return C; 11558 } 11559 11560 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11561 switch (UO->getOpcode()) { 11562 // Boolean-valued operations are white-listed. 11563 case UO_LNot: 11564 return IntRange::forBoolType(); 11565 11566 // Operations with opaque sources are black-listed. 11567 case UO_Deref: 11568 case UO_AddrOf: // should be impossible 11569 return IntRange::forValueOfType(C, GetExprType(E)); 11570 11571 default: 11572 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11573 Approximate); 11574 } 11575 } 11576 11577 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11578 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11579 Approximate); 11580 11581 if (const auto *BitField = E->getSourceBitField()) 11582 return IntRange(BitField->getBitWidthValue(C), 11583 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11584 11585 return IntRange::forValueOfType(C, GetExprType(E)); 11586 } 11587 11588 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11589 bool InConstantContext, bool Approximate) { 11590 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11591 Approximate); 11592 } 11593 11594 /// Checks whether the given value, which currently has the given 11595 /// source semantics, has the same value when coerced through the 11596 /// target semantics. 11597 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11598 const llvm::fltSemantics &Src, 11599 const llvm::fltSemantics &Tgt) { 11600 llvm::APFloat truncated = value; 11601 11602 bool ignored; 11603 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11604 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11605 11606 return truncated.bitwiseIsEqual(value); 11607 } 11608 11609 /// Checks whether the given value, which currently has the given 11610 /// source semantics, has the same value when coerced through the 11611 /// target semantics. 11612 /// 11613 /// The value might be a vector of floats (or a complex number). 11614 static bool IsSameFloatAfterCast(const APValue &value, 11615 const llvm::fltSemantics &Src, 11616 const llvm::fltSemantics &Tgt) { 11617 if (value.isFloat()) 11618 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11619 11620 if (value.isVector()) { 11621 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11622 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11623 return false; 11624 return true; 11625 } 11626 11627 assert(value.isComplexFloat()); 11628 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11629 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11630 } 11631 11632 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11633 bool IsListInit = false); 11634 11635 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11636 // Suppress cases where we are comparing against an enum constant. 11637 if (const DeclRefExpr *DR = 11638 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11639 if (isa<EnumConstantDecl>(DR->getDecl())) 11640 return true; 11641 11642 // Suppress cases where the value is expanded from a macro, unless that macro 11643 // is how a language represents a boolean literal. This is the case in both C 11644 // and Objective-C. 11645 SourceLocation BeginLoc = E->getBeginLoc(); 11646 if (BeginLoc.isMacroID()) { 11647 StringRef MacroName = Lexer::getImmediateMacroName( 11648 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11649 return MacroName != "YES" && MacroName != "NO" && 11650 MacroName != "true" && MacroName != "false"; 11651 } 11652 11653 return false; 11654 } 11655 11656 static bool isKnownToHaveUnsignedValue(Expr *E) { 11657 return E->getType()->isIntegerType() && 11658 (!E->getType()->isSignedIntegerType() || 11659 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11660 } 11661 11662 namespace { 11663 /// The promoted range of values of a type. In general this has the 11664 /// following structure: 11665 /// 11666 /// |-----------| . . . |-----------| 11667 /// ^ ^ ^ ^ 11668 /// Min HoleMin HoleMax Max 11669 /// 11670 /// ... where there is only a hole if a signed type is promoted to unsigned 11671 /// (in which case Min and Max are the smallest and largest representable 11672 /// values). 11673 struct PromotedRange { 11674 // Min, or HoleMax if there is a hole. 11675 llvm::APSInt PromotedMin; 11676 // Max, or HoleMin if there is a hole. 11677 llvm::APSInt PromotedMax; 11678 11679 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11680 if (R.Width == 0) 11681 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11682 else if (R.Width >= BitWidth && !Unsigned) { 11683 // Promotion made the type *narrower*. This happens when promoting 11684 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11685 // Treat all values of 'signed int' as being in range for now. 11686 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11687 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11688 } else { 11689 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11690 .extOrTrunc(BitWidth); 11691 PromotedMin.setIsUnsigned(Unsigned); 11692 11693 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11694 .extOrTrunc(BitWidth); 11695 PromotedMax.setIsUnsigned(Unsigned); 11696 } 11697 } 11698 11699 // Determine whether this range is contiguous (has no hole). 11700 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11701 11702 // Where a constant value is within the range. 11703 enum ComparisonResult { 11704 LT = 0x1, 11705 LE = 0x2, 11706 GT = 0x4, 11707 GE = 0x8, 11708 EQ = 0x10, 11709 NE = 0x20, 11710 InRangeFlag = 0x40, 11711 11712 Less = LE | LT | NE, 11713 Min = LE | InRangeFlag, 11714 InRange = InRangeFlag, 11715 Max = GE | InRangeFlag, 11716 Greater = GE | GT | NE, 11717 11718 OnlyValue = LE | GE | EQ | InRangeFlag, 11719 InHole = NE 11720 }; 11721 11722 ComparisonResult compare(const llvm::APSInt &Value) const { 11723 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11724 Value.isUnsigned() == PromotedMin.isUnsigned()); 11725 if (!isContiguous()) { 11726 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11727 if (Value.isMinValue()) return Min; 11728 if (Value.isMaxValue()) return Max; 11729 if (Value >= PromotedMin) return InRange; 11730 if (Value <= PromotedMax) return InRange; 11731 return InHole; 11732 } 11733 11734 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11735 case -1: return Less; 11736 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11737 case 1: 11738 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11739 case -1: return InRange; 11740 case 0: return Max; 11741 case 1: return Greater; 11742 } 11743 } 11744 11745 llvm_unreachable("impossible compare result"); 11746 } 11747 11748 static llvm::Optional<StringRef> 11749 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11750 if (Op == BO_Cmp) { 11751 ComparisonResult LTFlag = LT, GTFlag = GT; 11752 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11753 11754 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11755 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11756 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11757 return llvm::None; 11758 } 11759 11760 ComparisonResult TrueFlag, FalseFlag; 11761 if (Op == BO_EQ) { 11762 TrueFlag = EQ; 11763 FalseFlag = NE; 11764 } else if (Op == BO_NE) { 11765 TrueFlag = NE; 11766 FalseFlag = EQ; 11767 } else { 11768 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11769 TrueFlag = LT; 11770 FalseFlag = GE; 11771 } else { 11772 TrueFlag = GT; 11773 FalseFlag = LE; 11774 } 11775 if (Op == BO_GE || Op == BO_LE) 11776 std::swap(TrueFlag, FalseFlag); 11777 } 11778 if (R & TrueFlag) 11779 return StringRef("true"); 11780 if (R & FalseFlag) 11781 return StringRef("false"); 11782 return llvm::None; 11783 } 11784 }; 11785 } 11786 11787 static bool HasEnumType(Expr *E) { 11788 // Strip off implicit integral promotions. 11789 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11790 if (ICE->getCastKind() != CK_IntegralCast && 11791 ICE->getCastKind() != CK_NoOp) 11792 break; 11793 E = ICE->getSubExpr(); 11794 } 11795 11796 return E->getType()->isEnumeralType(); 11797 } 11798 11799 static int classifyConstantValue(Expr *Constant) { 11800 // The values of this enumeration are used in the diagnostics 11801 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11802 enum ConstantValueKind { 11803 Miscellaneous = 0, 11804 LiteralTrue, 11805 LiteralFalse 11806 }; 11807 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11808 return BL->getValue() ? ConstantValueKind::LiteralTrue 11809 : ConstantValueKind::LiteralFalse; 11810 return ConstantValueKind::Miscellaneous; 11811 } 11812 11813 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11814 Expr *Constant, Expr *Other, 11815 const llvm::APSInt &Value, 11816 bool RhsConstant) { 11817 if (S.inTemplateInstantiation()) 11818 return false; 11819 11820 Expr *OriginalOther = Other; 11821 11822 Constant = Constant->IgnoreParenImpCasts(); 11823 Other = Other->IgnoreParenImpCasts(); 11824 11825 // Suppress warnings on tautological comparisons between values of the same 11826 // enumeration type. There are only two ways we could warn on this: 11827 // - If the constant is outside the range of representable values of 11828 // the enumeration. In such a case, we should warn about the cast 11829 // to enumeration type, not about the comparison. 11830 // - If the constant is the maximum / minimum in-range value. For an 11831 // enumeratin type, such comparisons can be meaningful and useful. 11832 if (Constant->getType()->isEnumeralType() && 11833 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11834 return false; 11835 11836 IntRange OtherValueRange = GetExprRange( 11837 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11838 11839 QualType OtherT = Other->getType(); 11840 if (const auto *AT = OtherT->getAs<AtomicType>()) 11841 OtherT = AT->getValueType(); 11842 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11843 11844 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11845 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11846 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11847 S.NSAPIObj->isObjCBOOLType(OtherT) && 11848 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11849 11850 // Whether we're treating Other as being a bool because of the form of 11851 // expression despite it having another type (typically 'int' in C). 11852 bool OtherIsBooleanDespiteType = 11853 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11854 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11855 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11856 11857 // Check if all values in the range of possible values of this expression 11858 // lead to the same comparison outcome. 11859 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11860 Value.isUnsigned()); 11861 auto Cmp = OtherPromotedValueRange.compare(Value); 11862 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11863 if (!Result) 11864 return false; 11865 11866 // Also consider the range determined by the type alone. This allows us to 11867 // classify the warning under the proper diagnostic group. 11868 bool TautologicalTypeCompare = false; 11869 { 11870 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11871 Value.isUnsigned()); 11872 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11873 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11874 RhsConstant)) { 11875 TautologicalTypeCompare = true; 11876 Cmp = TypeCmp; 11877 Result = TypeResult; 11878 } 11879 } 11880 11881 // Don't warn if the non-constant operand actually always evaluates to the 11882 // same value. 11883 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11884 return false; 11885 11886 // Suppress the diagnostic for an in-range comparison if the constant comes 11887 // from a macro or enumerator. We don't want to diagnose 11888 // 11889 // some_long_value <= INT_MAX 11890 // 11891 // when sizeof(int) == sizeof(long). 11892 bool InRange = Cmp & PromotedRange::InRangeFlag; 11893 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11894 return false; 11895 11896 // A comparison of an unsigned bit-field against 0 is really a type problem, 11897 // even though at the type level the bit-field might promote to 'signed int'. 11898 if (Other->refersToBitField() && InRange && Value == 0 && 11899 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11900 TautologicalTypeCompare = true; 11901 11902 // If this is a comparison to an enum constant, include that 11903 // constant in the diagnostic. 11904 const EnumConstantDecl *ED = nullptr; 11905 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11906 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11907 11908 // Should be enough for uint128 (39 decimal digits) 11909 SmallString<64> PrettySourceValue; 11910 llvm::raw_svector_ostream OS(PrettySourceValue); 11911 if (ED) { 11912 OS << '\'' << *ED << "' (" << Value << ")"; 11913 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11914 Constant->IgnoreParenImpCasts())) { 11915 OS << (BL->getValue() ? "YES" : "NO"); 11916 } else { 11917 OS << Value; 11918 } 11919 11920 if (!TautologicalTypeCompare) { 11921 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11922 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11923 << E->getOpcodeStr() << OS.str() << *Result 11924 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11925 return true; 11926 } 11927 11928 if (IsObjCSignedCharBool) { 11929 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11930 S.PDiag(diag::warn_tautological_compare_objc_bool) 11931 << OS.str() << *Result); 11932 return true; 11933 } 11934 11935 // FIXME: We use a somewhat different formatting for the in-range cases and 11936 // cases involving boolean values for historical reasons. We should pick a 11937 // consistent way of presenting these diagnostics. 11938 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11939 11940 S.DiagRuntimeBehavior( 11941 E->getOperatorLoc(), E, 11942 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11943 : diag::warn_tautological_bool_compare) 11944 << OS.str() << classifyConstantValue(Constant) << OtherT 11945 << OtherIsBooleanDespiteType << *Result 11946 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11947 } else { 11948 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11949 unsigned Diag = 11950 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11951 ? (HasEnumType(OriginalOther) 11952 ? diag::warn_unsigned_enum_always_true_comparison 11953 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11954 : diag::warn_unsigned_always_true_comparison) 11955 : diag::warn_tautological_constant_compare; 11956 11957 S.Diag(E->getOperatorLoc(), Diag) 11958 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11959 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11960 } 11961 11962 return true; 11963 } 11964 11965 /// Analyze the operands of the given comparison. Implements the 11966 /// fallback case from AnalyzeComparison. 11967 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11968 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11969 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11970 } 11971 11972 /// Implements -Wsign-compare. 11973 /// 11974 /// \param E the binary operator to check for warnings 11975 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11976 // The type the comparison is being performed in. 11977 QualType T = E->getLHS()->getType(); 11978 11979 // Only analyze comparison operators where both sides have been converted to 11980 // the same type. 11981 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11982 return AnalyzeImpConvsInComparison(S, E); 11983 11984 // Don't analyze value-dependent comparisons directly. 11985 if (E->isValueDependent()) 11986 return AnalyzeImpConvsInComparison(S, E); 11987 11988 Expr *LHS = E->getLHS(); 11989 Expr *RHS = E->getRHS(); 11990 11991 if (T->isIntegralType(S.Context)) { 11992 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11993 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11994 11995 // We don't care about expressions whose result is a constant. 11996 if (RHSValue && LHSValue) 11997 return AnalyzeImpConvsInComparison(S, E); 11998 11999 // We only care about expressions where just one side is literal 12000 if ((bool)RHSValue ^ (bool)LHSValue) { 12001 // Is the constant on the RHS or LHS? 12002 const bool RhsConstant = (bool)RHSValue; 12003 Expr *Const = RhsConstant ? RHS : LHS; 12004 Expr *Other = RhsConstant ? LHS : RHS; 12005 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12006 12007 // Check whether an integer constant comparison results in a value 12008 // of 'true' or 'false'. 12009 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12010 return AnalyzeImpConvsInComparison(S, E); 12011 } 12012 } 12013 12014 if (!T->hasUnsignedIntegerRepresentation()) { 12015 // We don't do anything special if this isn't an unsigned integral 12016 // comparison: we're only interested in integral comparisons, and 12017 // signed comparisons only happen in cases we don't care to warn about. 12018 return AnalyzeImpConvsInComparison(S, E); 12019 } 12020 12021 LHS = LHS->IgnoreParenImpCasts(); 12022 RHS = RHS->IgnoreParenImpCasts(); 12023 12024 if (!S.getLangOpts().CPlusPlus) { 12025 // Avoid warning about comparison of integers with different signs when 12026 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12027 // the type of `E`. 12028 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12029 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12030 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12031 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12032 } 12033 12034 // Check to see if one of the (unmodified) operands is of different 12035 // signedness. 12036 Expr *signedOperand, *unsignedOperand; 12037 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12038 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12039 "unsigned comparison between two signed integer expressions?"); 12040 signedOperand = LHS; 12041 unsignedOperand = RHS; 12042 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12043 signedOperand = RHS; 12044 unsignedOperand = LHS; 12045 } else { 12046 return AnalyzeImpConvsInComparison(S, E); 12047 } 12048 12049 // Otherwise, calculate the effective range of the signed operand. 12050 IntRange signedRange = GetExprRange( 12051 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12052 12053 // Go ahead and analyze implicit conversions in the operands. Note 12054 // that we skip the implicit conversions on both sides. 12055 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12056 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12057 12058 // If the signed range is non-negative, -Wsign-compare won't fire. 12059 if (signedRange.NonNegative) 12060 return; 12061 12062 // For (in)equality comparisons, if the unsigned operand is a 12063 // constant which cannot collide with a overflowed signed operand, 12064 // then reinterpreting the signed operand as unsigned will not 12065 // change the result of the comparison. 12066 if (E->isEqualityOp()) { 12067 unsigned comparisonWidth = S.Context.getIntWidth(T); 12068 IntRange unsignedRange = 12069 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12070 /*Approximate*/ true); 12071 12072 // We should never be unable to prove that the unsigned operand is 12073 // non-negative. 12074 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12075 12076 if (unsignedRange.Width < comparisonWidth) 12077 return; 12078 } 12079 12080 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12081 S.PDiag(diag::warn_mixed_sign_comparison) 12082 << LHS->getType() << RHS->getType() 12083 << LHS->getSourceRange() << RHS->getSourceRange()); 12084 } 12085 12086 /// Analyzes an attempt to assign the given value to a bitfield. 12087 /// 12088 /// Returns true if there was something fishy about the attempt. 12089 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12090 SourceLocation InitLoc) { 12091 assert(Bitfield->isBitField()); 12092 if (Bitfield->isInvalidDecl()) 12093 return false; 12094 12095 // White-list bool bitfields. 12096 QualType BitfieldType = Bitfield->getType(); 12097 if (BitfieldType->isBooleanType()) 12098 return false; 12099 12100 if (BitfieldType->isEnumeralType()) { 12101 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12102 // If the underlying enum type was not explicitly specified as an unsigned 12103 // type and the enum contain only positive values, MSVC++ will cause an 12104 // inconsistency by storing this as a signed type. 12105 if (S.getLangOpts().CPlusPlus11 && 12106 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12107 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12108 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12109 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12110 << BitfieldEnumDecl; 12111 } 12112 } 12113 12114 if (Bitfield->getType()->isBooleanType()) 12115 return false; 12116 12117 // Ignore value- or type-dependent expressions. 12118 if (Bitfield->getBitWidth()->isValueDependent() || 12119 Bitfield->getBitWidth()->isTypeDependent() || 12120 Init->isValueDependent() || 12121 Init->isTypeDependent()) 12122 return false; 12123 12124 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12125 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12126 12127 Expr::EvalResult Result; 12128 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12129 Expr::SE_AllowSideEffects)) { 12130 // The RHS is not constant. If the RHS has an enum type, make sure the 12131 // bitfield is wide enough to hold all the values of the enum without 12132 // truncation. 12133 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12134 EnumDecl *ED = EnumTy->getDecl(); 12135 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12136 12137 // Enum types are implicitly signed on Windows, so check if there are any 12138 // negative enumerators to see if the enum was intended to be signed or 12139 // not. 12140 bool SignedEnum = ED->getNumNegativeBits() > 0; 12141 12142 // Check for surprising sign changes when assigning enum values to a 12143 // bitfield of different signedness. If the bitfield is signed and we 12144 // have exactly the right number of bits to store this unsigned enum, 12145 // suggest changing the enum to an unsigned type. This typically happens 12146 // on Windows where unfixed enums always use an underlying type of 'int'. 12147 unsigned DiagID = 0; 12148 if (SignedEnum && !SignedBitfield) { 12149 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12150 } else if (SignedBitfield && !SignedEnum && 12151 ED->getNumPositiveBits() == FieldWidth) { 12152 DiagID = diag::warn_signed_bitfield_enum_conversion; 12153 } 12154 12155 if (DiagID) { 12156 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12157 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12158 SourceRange TypeRange = 12159 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12160 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12161 << SignedEnum << TypeRange; 12162 } 12163 12164 // Compute the required bitwidth. If the enum has negative values, we need 12165 // one more bit than the normal number of positive bits to represent the 12166 // sign bit. 12167 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12168 ED->getNumNegativeBits()) 12169 : ED->getNumPositiveBits(); 12170 12171 // Check the bitwidth. 12172 if (BitsNeeded > FieldWidth) { 12173 Expr *WidthExpr = Bitfield->getBitWidth(); 12174 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12175 << Bitfield << ED; 12176 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12177 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12178 } 12179 } 12180 12181 return false; 12182 } 12183 12184 llvm::APSInt Value = Result.Val.getInt(); 12185 12186 unsigned OriginalWidth = Value.getBitWidth(); 12187 12188 if (!Value.isSigned() || Value.isNegative()) 12189 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12190 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12191 OriginalWidth = Value.getMinSignedBits(); 12192 12193 if (OriginalWidth <= FieldWidth) 12194 return false; 12195 12196 // Compute the value which the bitfield will contain. 12197 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12198 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12199 12200 // Check whether the stored value is equal to the original value. 12201 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12202 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12203 return false; 12204 12205 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12206 // therefore don't strictly fit into a signed bitfield of width 1. 12207 if (FieldWidth == 1 && Value == 1) 12208 return false; 12209 12210 std::string PrettyValue = toString(Value, 10); 12211 std::string PrettyTrunc = toString(TruncatedValue, 10); 12212 12213 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12214 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12215 << Init->getSourceRange(); 12216 12217 return true; 12218 } 12219 12220 /// Analyze the given simple or compound assignment for warning-worthy 12221 /// operations. 12222 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12223 // Just recurse on the LHS. 12224 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12225 12226 // We want to recurse on the RHS as normal unless we're assigning to 12227 // a bitfield. 12228 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12229 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12230 E->getOperatorLoc())) { 12231 // Recurse, ignoring any implicit conversions on the RHS. 12232 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12233 E->getOperatorLoc()); 12234 } 12235 } 12236 12237 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12238 12239 // Diagnose implicitly sequentially-consistent atomic assignment. 12240 if (E->getLHS()->getType()->isAtomicType()) 12241 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12242 } 12243 12244 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12245 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12246 SourceLocation CContext, unsigned diag, 12247 bool pruneControlFlow = false) { 12248 if (pruneControlFlow) { 12249 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12250 S.PDiag(diag) 12251 << SourceType << T << E->getSourceRange() 12252 << SourceRange(CContext)); 12253 return; 12254 } 12255 S.Diag(E->getExprLoc(), diag) 12256 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12257 } 12258 12259 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12260 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12261 SourceLocation CContext, 12262 unsigned diag, bool pruneControlFlow = false) { 12263 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12264 } 12265 12266 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12267 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12268 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12269 } 12270 12271 static void adornObjCBoolConversionDiagWithTernaryFixit( 12272 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12273 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12274 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12275 Ignored = OVE->getSourceExpr(); 12276 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12277 isa<BinaryOperator>(Ignored) || 12278 isa<CXXOperatorCallExpr>(Ignored); 12279 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12280 if (NeedsParens) 12281 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12282 << FixItHint::CreateInsertion(EndLoc, ")"); 12283 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12284 } 12285 12286 /// Diagnose an implicit cast from a floating point value to an integer value. 12287 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12288 SourceLocation CContext) { 12289 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12290 const bool PruneWarnings = S.inTemplateInstantiation(); 12291 12292 Expr *InnerE = E->IgnoreParenImpCasts(); 12293 // We also want to warn on, e.g., "int i = -1.234" 12294 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12295 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12296 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12297 12298 const bool IsLiteral = 12299 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12300 12301 llvm::APFloat Value(0.0); 12302 bool IsConstant = 12303 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12304 if (!IsConstant) { 12305 if (isObjCSignedCharBool(S, T)) { 12306 return adornObjCBoolConversionDiagWithTernaryFixit( 12307 S, E, 12308 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12309 << E->getType()); 12310 } 12311 12312 return DiagnoseImpCast(S, E, T, CContext, 12313 diag::warn_impcast_float_integer, PruneWarnings); 12314 } 12315 12316 bool isExact = false; 12317 12318 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12319 T->hasUnsignedIntegerRepresentation()); 12320 llvm::APFloat::opStatus Result = Value.convertToInteger( 12321 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12322 12323 // FIXME: Force the precision of the source value down so we don't print 12324 // digits which are usually useless (we don't really care here if we 12325 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12326 // would automatically print the shortest representation, but it's a bit 12327 // tricky to implement. 12328 SmallString<16> PrettySourceValue; 12329 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12330 precision = (precision * 59 + 195) / 196; 12331 Value.toString(PrettySourceValue, precision); 12332 12333 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12334 return adornObjCBoolConversionDiagWithTernaryFixit( 12335 S, E, 12336 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12337 << PrettySourceValue); 12338 } 12339 12340 if (Result == llvm::APFloat::opOK && isExact) { 12341 if (IsLiteral) return; 12342 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12343 PruneWarnings); 12344 } 12345 12346 // Conversion of a floating-point value to a non-bool integer where the 12347 // integral part cannot be represented by the integer type is undefined. 12348 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12349 return DiagnoseImpCast( 12350 S, E, T, CContext, 12351 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12352 : diag::warn_impcast_float_to_integer_out_of_range, 12353 PruneWarnings); 12354 12355 unsigned DiagID = 0; 12356 if (IsLiteral) { 12357 // Warn on floating point literal to integer. 12358 DiagID = diag::warn_impcast_literal_float_to_integer; 12359 } else if (IntegerValue == 0) { 12360 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12361 return DiagnoseImpCast(S, E, T, CContext, 12362 diag::warn_impcast_float_integer, PruneWarnings); 12363 } 12364 // Warn on non-zero to zero conversion. 12365 DiagID = diag::warn_impcast_float_to_integer_zero; 12366 } else { 12367 if (IntegerValue.isUnsigned()) { 12368 if (!IntegerValue.isMaxValue()) { 12369 return DiagnoseImpCast(S, E, T, CContext, 12370 diag::warn_impcast_float_integer, PruneWarnings); 12371 } 12372 } else { // IntegerValue.isSigned() 12373 if (!IntegerValue.isMaxSignedValue() && 12374 !IntegerValue.isMinSignedValue()) { 12375 return DiagnoseImpCast(S, E, T, CContext, 12376 diag::warn_impcast_float_integer, PruneWarnings); 12377 } 12378 } 12379 // Warn on evaluatable floating point expression to integer conversion. 12380 DiagID = diag::warn_impcast_float_to_integer; 12381 } 12382 12383 SmallString<16> PrettyTargetValue; 12384 if (IsBool) 12385 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12386 else 12387 IntegerValue.toString(PrettyTargetValue); 12388 12389 if (PruneWarnings) { 12390 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12391 S.PDiag(DiagID) 12392 << E->getType() << T.getUnqualifiedType() 12393 << PrettySourceValue << PrettyTargetValue 12394 << E->getSourceRange() << SourceRange(CContext)); 12395 } else { 12396 S.Diag(E->getExprLoc(), DiagID) 12397 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12398 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12399 } 12400 } 12401 12402 /// Analyze the given compound assignment for the possible losing of 12403 /// floating-point precision. 12404 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12405 assert(isa<CompoundAssignOperator>(E) && 12406 "Must be compound assignment operation"); 12407 // Recurse on the LHS and RHS in here 12408 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12409 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12410 12411 if (E->getLHS()->getType()->isAtomicType()) 12412 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12413 12414 // Now check the outermost expression 12415 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12416 const auto *RBT = cast<CompoundAssignOperator>(E) 12417 ->getComputationResultType() 12418 ->getAs<BuiltinType>(); 12419 12420 // The below checks assume source is floating point. 12421 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12422 12423 // If source is floating point but target is an integer. 12424 if (ResultBT->isInteger()) 12425 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12426 E->getExprLoc(), diag::warn_impcast_float_integer); 12427 12428 if (!ResultBT->isFloatingPoint()) 12429 return; 12430 12431 // If both source and target are floating points, warn about losing precision. 12432 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12433 QualType(ResultBT, 0), QualType(RBT, 0)); 12434 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12435 // warn about dropping FP rank. 12436 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12437 diag::warn_impcast_float_result_precision); 12438 } 12439 12440 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12441 IntRange Range) { 12442 if (!Range.Width) return "0"; 12443 12444 llvm::APSInt ValueInRange = Value; 12445 ValueInRange.setIsSigned(!Range.NonNegative); 12446 ValueInRange = ValueInRange.trunc(Range.Width); 12447 return toString(ValueInRange, 10); 12448 } 12449 12450 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12451 if (!isa<ImplicitCastExpr>(Ex)) 12452 return false; 12453 12454 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12455 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12456 const Type *Source = 12457 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12458 if (Target->isDependentType()) 12459 return false; 12460 12461 const BuiltinType *FloatCandidateBT = 12462 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12463 const Type *BoolCandidateType = ToBool ? Target : Source; 12464 12465 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12466 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12467 } 12468 12469 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12470 SourceLocation CC) { 12471 unsigned NumArgs = TheCall->getNumArgs(); 12472 for (unsigned i = 0; i < NumArgs; ++i) { 12473 Expr *CurrA = TheCall->getArg(i); 12474 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12475 continue; 12476 12477 bool IsSwapped = ((i > 0) && 12478 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12479 IsSwapped |= ((i < (NumArgs - 1)) && 12480 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12481 if (IsSwapped) { 12482 // Warn on this floating-point to bool conversion. 12483 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12484 CurrA->getType(), CC, 12485 diag::warn_impcast_floating_point_to_bool); 12486 } 12487 } 12488 } 12489 12490 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12491 SourceLocation CC) { 12492 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12493 E->getExprLoc())) 12494 return; 12495 12496 // Don't warn on functions which have return type nullptr_t. 12497 if (isa<CallExpr>(E)) 12498 return; 12499 12500 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12501 const Expr::NullPointerConstantKind NullKind = 12502 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12503 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12504 return; 12505 12506 // Return if target type is a safe conversion. 12507 if (T->isAnyPointerType() || T->isBlockPointerType() || 12508 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12509 return; 12510 12511 SourceLocation Loc = E->getSourceRange().getBegin(); 12512 12513 // Venture through the macro stacks to get to the source of macro arguments. 12514 // The new location is a better location than the complete location that was 12515 // passed in. 12516 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12517 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12518 12519 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12520 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12521 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12522 Loc, S.SourceMgr, S.getLangOpts()); 12523 if (MacroName == "NULL") 12524 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12525 } 12526 12527 // Only warn if the null and context location are in the same macro expansion. 12528 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12529 return; 12530 12531 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12532 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12533 << FixItHint::CreateReplacement(Loc, 12534 S.getFixItZeroLiteralForType(T, Loc)); 12535 } 12536 12537 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12538 ObjCArrayLiteral *ArrayLiteral); 12539 12540 static void 12541 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12542 ObjCDictionaryLiteral *DictionaryLiteral); 12543 12544 /// Check a single element within a collection literal against the 12545 /// target element type. 12546 static void checkObjCCollectionLiteralElement(Sema &S, 12547 QualType TargetElementType, 12548 Expr *Element, 12549 unsigned ElementKind) { 12550 // Skip a bitcast to 'id' or qualified 'id'. 12551 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12552 if (ICE->getCastKind() == CK_BitCast && 12553 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12554 Element = ICE->getSubExpr(); 12555 } 12556 12557 QualType ElementType = Element->getType(); 12558 ExprResult ElementResult(Element); 12559 if (ElementType->getAs<ObjCObjectPointerType>() && 12560 S.CheckSingleAssignmentConstraints(TargetElementType, 12561 ElementResult, 12562 false, false) 12563 != Sema::Compatible) { 12564 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12565 << ElementType << ElementKind << TargetElementType 12566 << Element->getSourceRange(); 12567 } 12568 12569 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12570 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12571 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12572 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12573 } 12574 12575 /// Check an Objective-C array literal being converted to the given 12576 /// target type. 12577 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12578 ObjCArrayLiteral *ArrayLiteral) { 12579 if (!S.NSArrayDecl) 12580 return; 12581 12582 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12583 if (!TargetObjCPtr) 12584 return; 12585 12586 if (TargetObjCPtr->isUnspecialized() || 12587 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12588 != S.NSArrayDecl->getCanonicalDecl()) 12589 return; 12590 12591 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12592 if (TypeArgs.size() != 1) 12593 return; 12594 12595 QualType TargetElementType = TypeArgs[0]; 12596 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12597 checkObjCCollectionLiteralElement(S, TargetElementType, 12598 ArrayLiteral->getElement(I), 12599 0); 12600 } 12601 } 12602 12603 /// Check an Objective-C dictionary literal being converted to the given 12604 /// target type. 12605 static void 12606 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12607 ObjCDictionaryLiteral *DictionaryLiteral) { 12608 if (!S.NSDictionaryDecl) 12609 return; 12610 12611 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12612 if (!TargetObjCPtr) 12613 return; 12614 12615 if (TargetObjCPtr->isUnspecialized() || 12616 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12617 != S.NSDictionaryDecl->getCanonicalDecl()) 12618 return; 12619 12620 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12621 if (TypeArgs.size() != 2) 12622 return; 12623 12624 QualType TargetKeyType = TypeArgs[0]; 12625 QualType TargetObjectType = TypeArgs[1]; 12626 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12627 auto Element = DictionaryLiteral->getKeyValueElement(I); 12628 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12629 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12630 } 12631 } 12632 12633 // Helper function to filter out cases for constant width constant conversion. 12634 // Don't warn on char array initialization or for non-decimal values. 12635 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12636 SourceLocation CC) { 12637 // If initializing from a constant, and the constant starts with '0', 12638 // then it is a binary, octal, or hexadecimal. Allow these constants 12639 // to fill all the bits, even if there is a sign change. 12640 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12641 const char FirstLiteralCharacter = 12642 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12643 if (FirstLiteralCharacter == '0') 12644 return false; 12645 } 12646 12647 // If the CC location points to a '{', and the type is char, then assume 12648 // assume it is an array initialization. 12649 if (CC.isValid() && T->isCharType()) { 12650 const char FirstContextCharacter = 12651 S.getSourceManager().getCharacterData(CC)[0]; 12652 if (FirstContextCharacter == '{') 12653 return false; 12654 } 12655 12656 return true; 12657 } 12658 12659 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12660 const auto *IL = dyn_cast<IntegerLiteral>(E); 12661 if (!IL) { 12662 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12663 if (UO->getOpcode() == UO_Minus) 12664 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12665 } 12666 } 12667 12668 return IL; 12669 } 12670 12671 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12672 E = E->IgnoreParenImpCasts(); 12673 SourceLocation ExprLoc = E->getExprLoc(); 12674 12675 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12676 BinaryOperator::Opcode Opc = BO->getOpcode(); 12677 Expr::EvalResult Result; 12678 // Do not diagnose unsigned shifts. 12679 if (Opc == BO_Shl) { 12680 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12681 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12682 if (LHS && LHS->getValue() == 0) 12683 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12684 else if (!E->isValueDependent() && LHS && RHS && 12685 RHS->getValue().isNonNegative() && 12686 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12687 S.Diag(ExprLoc, diag::warn_left_shift_always) 12688 << (Result.Val.getInt() != 0); 12689 else if (E->getType()->isSignedIntegerType()) 12690 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12691 } 12692 } 12693 12694 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12695 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12696 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12697 if (!LHS || !RHS) 12698 return; 12699 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12700 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12701 // Do not diagnose common idioms. 12702 return; 12703 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12704 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12705 } 12706 } 12707 12708 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12709 SourceLocation CC, 12710 bool *ICContext = nullptr, 12711 bool IsListInit = false) { 12712 if (E->isTypeDependent() || E->isValueDependent()) return; 12713 12714 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12715 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12716 if (Source == Target) return; 12717 if (Target->isDependentType()) return; 12718 12719 // If the conversion context location is invalid don't complain. We also 12720 // don't want to emit a warning if the issue occurs from the expansion of 12721 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12722 // delay this check as long as possible. Once we detect we are in that 12723 // scenario, we just return. 12724 if (CC.isInvalid()) 12725 return; 12726 12727 if (Source->isAtomicType()) 12728 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12729 12730 // Diagnose implicit casts to bool. 12731 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12732 if (isa<StringLiteral>(E)) 12733 // Warn on string literal to bool. Checks for string literals in logical 12734 // and expressions, for instance, assert(0 && "error here"), are 12735 // prevented by a check in AnalyzeImplicitConversions(). 12736 return DiagnoseImpCast(S, E, T, CC, 12737 diag::warn_impcast_string_literal_to_bool); 12738 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12739 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12740 // This covers the literal expressions that evaluate to Objective-C 12741 // objects. 12742 return DiagnoseImpCast(S, E, T, CC, 12743 diag::warn_impcast_objective_c_literal_to_bool); 12744 } 12745 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12746 // Warn on pointer to bool conversion that is always true. 12747 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12748 SourceRange(CC)); 12749 } 12750 } 12751 12752 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12753 // is a typedef for signed char (macOS), then that constant value has to be 1 12754 // or 0. 12755 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12756 Expr::EvalResult Result; 12757 if (E->EvaluateAsInt(Result, S.getASTContext(), 12758 Expr::SE_AllowSideEffects)) { 12759 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12760 adornObjCBoolConversionDiagWithTernaryFixit( 12761 S, E, 12762 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12763 << toString(Result.Val.getInt(), 10)); 12764 } 12765 return; 12766 } 12767 } 12768 12769 // Check implicit casts from Objective-C collection literals to specialized 12770 // collection types, e.g., NSArray<NSString *> *. 12771 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12772 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12773 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12774 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12775 12776 // Strip vector types. 12777 if (isa<VectorType>(Source)) { 12778 if (Target->isVLSTBuiltinType() && 12779 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12780 QualType(Source, 0)) || 12781 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12782 QualType(Source, 0)))) 12783 return; 12784 12785 if (!isa<VectorType>(Target)) { 12786 if (S.SourceMgr.isInSystemMacro(CC)) 12787 return; 12788 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12789 } 12790 12791 // If the vector cast is cast between two vectors of the same size, it is 12792 // a bitcast, not a conversion. 12793 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12794 return; 12795 12796 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12797 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12798 } 12799 if (auto VecTy = dyn_cast<VectorType>(Target)) 12800 Target = VecTy->getElementType().getTypePtr(); 12801 12802 // Strip complex types. 12803 if (isa<ComplexType>(Source)) { 12804 if (!isa<ComplexType>(Target)) { 12805 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12806 return; 12807 12808 return DiagnoseImpCast(S, E, T, CC, 12809 S.getLangOpts().CPlusPlus 12810 ? diag::err_impcast_complex_scalar 12811 : diag::warn_impcast_complex_scalar); 12812 } 12813 12814 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12815 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12816 } 12817 12818 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12819 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12820 12821 // If the source is floating point... 12822 if (SourceBT && SourceBT->isFloatingPoint()) { 12823 // ...and the target is floating point... 12824 if (TargetBT && TargetBT->isFloatingPoint()) { 12825 // ...then warn if we're dropping FP rank. 12826 12827 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12828 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12829 if (Order > 0) { 12830 // Don't warn about float constants that are precisely 12831 // representable in the target type. 12832 Expr::EvalResult result; 12833 if (E->EvaluateAsRValue(result, S.Context)) { 12834 // Value might be a float, a float vector, or a float complex. 12835 if (IsSameFloatAfterCast(result.Val, 12836 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12837 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12838 return; 12839 } 12840 12841 if (S.SourceMgr.isInSystemMacro(CC)) 12842 return; 12843 12844 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12845 } 12846 // ... or possibly if we're increasing rank, too 12847 else if (Order < 0) { 12848 if (S.SourceMgr.isInSystemMacro(CC)) 12849 return; 12850 12851 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12852 } 12853 return; 12854 } 12855 12856 // If the target is integral, always warn. 12857 if (TargetBT && TargetBT->isInteger()) { 12858 if (S.SourceMgr.isInSystemMacro(CC)) 12859 return; 12860 12861 DiagnoseFloatingImpCast(S, E, T, CC); 12862 } 12863 12864 // Detect the case where a call result is converted from floating-point to 12865 // to bool, and the final argument to the call is converted from bool, to 12866 // discover this typo: 12867 // 12868 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12869 // 12870 // FIXME: This is an incredibly special case; is there some more general 12871 // way to detect this class of misplaced-parentheses bug? 12872 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12873 // Check last argument of function call to see if it is an 12874 // implicit cast from a type matching the type the result 12875 // is being cast to. 12876 CallExpr *CEx = cast<CallExpr>(E); 12877 if (unsigned NumArgs = CEx->getNumArgs()) { 12878 Expr *LastA = CEx->getArg(NumArgs - 1); 12879 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12880 if (isa<ImplicitCastExpr>(LastA) && 12881 InnerE->getType()->isBooleanType()) { 12882 // Warn on this floating-point to bool conversion 12883 DiagnoseImpCast(S, E, T, CC, 12884 diag::warn_impcast_floating_point_to_bool); 12885 } 12886 } 12887 } 12888 return; 12889 } 12890 12891 // Valid casts involving fixed point types should be accounted for here. 12892 if (Source->isFixedPointType()) { 12893 if (Target->isUnsaturatedFixedPointType()) { 12894 Expr::EvalResult Result; 12895 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12896 S.isConstantEvaluated())) { 12897 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12898 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12899 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12900 if (Value > MaxVal || Value < MinVal) { 12901 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12902 S.PDiag(diag::warn_impcast_fixed_point_range) 12903 << Value.toString() << T 12904 << E->getSourceRange() 12905 << clang::SourceRange(CC)); 12906 return; 12907 } 12908 } 12909 } else if (Target->isIntegerType()) { 12910 Expr::EvalResult Result; 12911 if (!S.isConstantEvaluated() && 12912 E->EvaluateAsFixedPoint(Result, S.Context, 12913 Expr::SE_AllowSideEffects)) { 12914 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12915 12916 bool Overflowed; 12917 llvm::APSInt IntResult = FXResult.convertToInt( 12918 S.Context.getIntWidth(T), 12919 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12920 12921 if (Overflowed) { 12922 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12923 S.PDiag(diag::warn_impcast_fixed_point_range) 12924 << FXResult.toString() << T 12925 << E->getSourceRange() 12926 << clang::SourceRange(CC)); 12927 return; 12928 } 12929 } 12930 } 12931 } else if (Target->isUnsaturatedFixedPointType()) { 12932 if (Source->isIntegerType()) { 12933 Expr::EvalResult Result; 12934 if (!S.isConstantEvaluated() && 12935 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12936 llvm::APSInt Value = Result.Val.getInt(); 12937 12938 bool Overflowed; 12939 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12940 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12941 12942 if (Overflowed) { 12943 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12944 S.PDiag(diag::warn_impcast_fixed_point_range) 12945 << toString(Value, /*Radix=*/10) << T 12946 << E->getSourceRange() 12947 << clang::SourceRange(CC)); 12948 return; 12949 } 12950 } 12951 } 12952 } 12953 12954 // If we are casting an integer type to a floating point type without 12955 // initialization-list syntax, we might lose accuracy if the floating 12956 // point type has a narrower significand than the integer type. 12957 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12958 TargetBT->isFloatingType() && !IsListInit) { 12959 // Determine the number of precision bits in the source integer type. 12960 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12961 /*Approximate*/ true); 12962 unsigned int SourcePrecision = SourceRange.Width; 12963 12964 // Determine the number of precision bits in the 12965 // target floating point type. 12966 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12967 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12968 12969 if (SourcePrecision > 0 && TargetPrecision > 0 && 12970 SourcePrecision > TargetPrecision) { 12971 12972 if (Optional<llvm::APSInt> SourceInt = 12973 E->getIntegerConstantExpr(S.Context)) { 12974 // If the source integer is a constant, convert it to the target 12975 // floating point type. Issue a warning if the value changes 12976 // during the whole conversion. 12977 llvm::APFloat TargetFloatValue( 12978 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12979 llvm::APFloat::opStatus ConversionStatus = 12980 TargetFloatValue.convertFromAPInt( 12981 *SourceInt, SourceBT->isSignedInteger(), 12982 llvm::APFloat::rmNearestTiesToEven); 12983 12984 if (ConversionStatus != llvm::APFloat::opOK) { 12985 SmallString<32> PrettySourceValue; 12986 SourceInt->toString(PrettySourceValue, 10); 12987 SmallString<32> PrettyTargetValue; 12988 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12989 12990 S.DiagRuntimeBehavior( 12991 E->getExprLoc(), E, 12992 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12993 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12994 << E->getSourceRange() << clang::SourceRange(CC)); 12995 } 12996 } else { 12997 // Otherwise, the implicit conversion may lose precision. 12998 DiagnoseImpCast(S, E, T, CC, 12999 diag::warn_impcast_integer_float_precision); 13000 } 13001 } 13002 } 13003 13004 DiagnoseNullConversion(S, E, T, CC); 13005 13006 S.DiscardMisalignedMemberAddress(Target, E); 13007 13008 if (Target->isBooleanType()) 13009 DiagnoseIntInBoolContext(S, E); 13010 13011 if (!Source->isIntegerType() || !Target->isIntegerType()) 13012 return; 13013 13014 // TODO: remove this early return once the false positives for constant->bool 13015 // in templates, macros, etc, are reduced or removed. 13016 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13017 return; 13018 13019 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13020 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13021 return adornObjCBoolConversionDiagWithTernaryFixit( 13022 S, E, 13023 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13024 << E->getType()); 13025 } 13026 13027 IntRange SourceTypeRange = 13028 IntRange::forTargetOfCanonicalType(S.Context, Source); 13029 IntRange LikelySourceRange = 13030 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13031 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13032 13033 if (LikelySourceRange.Width > TargetRange.Width) { 13034 // If the source is a constant, use a default-on diagnostic. 13035 // TODO: this should happen for bitfield stores, too. 13036 Expr::EvalResult Result; 13037 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13038 S.isConstantEvaluated())) { 13039 llvm::APSInt Value(32); 13040 Value = Result.Val.getInt(); 13041 13042 if (S.SourceMgr.isInSystemMacro(CC)) 13043 return; 13044 13045 std::string PrettySourceValue = toString(Value, 10); 13046 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13047 13048 S.DiagRuntimeBehavior( 13049 E->getExprLoc(), E, 13050 S.PDiag(diag::warn_impcast_integer_precision_constant) 13051 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13052 << E->getSourceRange() << SourceRange(CC)); 13053 return; 13054 } 13055 13056 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13057 if (S.SourceMgr.isInSystemMacro(CC)) 13058 return; 13059 13060 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13061 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13062 /* pruneControlFlow */ true); 13063 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13064 } 13065 13066 if (TargetRange.Width > SourceTypeRange.Width) { 13067 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13068 if (UO->getOpcode() == UO_Minus) 13069 if (Source->isUnsignedIntegerType()) { 13070 if (Target->isUnsignedIntegerType()) 13071 return DiagnoseImpCast(S, E, T, CC, 13072 diag::warn_impcast_high_order_zero_bits); 13073 if (Target->isSignedIntegerType()) 13074 return DiagnoseImpCast(S, E, T, CC, 13075 diag::warn_impcast_nonnegative_result); 13076 } 13077 } 13078 13079 if (TargetRange.Width == LikelySourceRange.Width && 13080 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13081 Source->isSignedIntegerType()) { 13082 // Warn when doing a signed to signed conversion, warn if the positive 13083 // source value is exactly the width of the target type, which will 13084 // cause a negative value to be stored. 13085 13086 Expr::EvalResult Result; 13087 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13088 !S.SourceMgr.isInSystemMacro(CC)) { 13089 llvm::APSInt Value = Result.Val.getInt(); 13090 if (isSameWidthConstantConversion(S, E, T, CC)) { 13091 std::string PrettySourceValue = toString(Value, 10); 13092 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13093 13094 S.DiagRuntimeBehavior( 13095 E->getExprLoc(), E, 13096 S.PDiag(diag::warn_impcast_integer_precision_constant) 13097 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13098 << E->getSourceRange() << SourceRange(CC)); 13099 return; 13100 } 13101 } 13102 13103 // Fall through for non-constants to give a sign conversion warning. 13104 } 13105 13106 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13107 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13108 LikelySourceRange.Width == TargetRange.Width)) { 13109 if (S.SourceMgr.isInSystemMacro(CC)) 13110 return; 13111 13112 unsigned DiagID = diag::warn_impcast_integer_sign; 13113 13114 // Traditionally, gcc has warned about this under -Wsign-compare. 13115 // We also want to warn about it in -Wconversion. 13116 // So if -Wconversion is off, use a completely identical diagnostic 13117 // in the sign-compare group. 13118 // The conditional-checking code will 13119 if (ICContext) { 13120 DiagID = diag::warn_impcast_integer_sign_conditional; 13121 *ICContext = true; 13122 } 13123 13124 return DiagnoseImpCast(S, E, T, CC, DiagID); 13125 } 13126 13127 // Diagnose conversions between different enumeration types. 13128 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13129 // type, to give us better diagnostics. 13130 QualType SourceType = E->getType(); 13131 if (!S.getLangOpts().CPlusPlus) { 13132 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13133 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13134 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13135 SourceType = S.Context.getTypeDeclType(Enum); 13136 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13137 } 13138 } 13139 13140 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13141 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13142 if (SourceEnum->getDecl()->hasNameForLinkage() && 13143 TargetEnum->getDecl()->hasNameForLinkage() && 13144 SourceEnum != TargetEnum) { 13145 if (S.SourceMgr.isInSystemMacro(CC)) 13146 return; 13147 13148 return DiagnoseImpCast(S, E, SourceType, T, CC, 13149 diag::warn_impcast_different_enum_types); 13150 } 13151 } 13152 13153 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13154 SourceLocation CC, QualType T); 13155 13156 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13157 SourceLocation CC, bool &ICContext) { 13158 E = E->IgnoreParenImpCasts(); 13159 13160 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13161 return CheckConditionalOperator(S, CO, CC, T); 13162 13163 AnalyzeImplicitConversions(S, E, CC); 13164 if (E->getType() != T) 13165 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13166 } 13167 13168 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13169 SourceLocation CC, QualType T) { 13170 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13171 13172 Expr *TrueExpr = E->getTrueExpr(); 13173 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13174 TrueExpr = BCO->getCommon(); 13175 13176 bool Suspicious = false; 13177 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13178 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13179 13180 if (T->isBooleanType()) 13181 DiagnoseIntInBoolContext(S, E); 13182 13183 // If -Wconversion would have warned about either of the candidates 13184 // for a signedness conversion to the context type... 13185 if (!Suspicious) return; 13186 13187 // ...but it's currently ignored... 13188 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13189 return; 13190 13191 // ...then check whether it would have warned about either of the 13192 // candidates for a signedness conversion to the condition type. 13193 if (E->getType() == T) return; 13194 13195 Suspicious = false; 13196 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13197 E->getType(), CC, &Suspicious); 13198 if (!Suspicious) 13199 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13200 E->getType(), CC, &Suspicious); 13201 } 13202 13203 /// Check conversion of given expression to boolean. 13204 /// Input argument E is a logical expression. 13205 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13206 if (S.getLangOpts().Bool) 13207 return; 13208 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13209 return; 13210 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13211 } 13212 13213 namespace { 13214 struct AnalyzeImplicitConversionsWorkItem { 13215 Expr *E; 13216 SourceLocation CC; 13217 bool IsListInit; 13218 }; 13219 } 13220 13221 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13222 /// that should be visited are added to WorkList. 13223 static void AnalyzeImplicitConversions( 13224 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13225 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13226 Expr *OrigE = Item.E; 13227 SourceLocation CC = Item.CC; 13228 13229 QualType T = OrigE->getType(); 13230 Expr *E = OrigE->IgnoreParenImpCasts(); 13231 13232 // Propagate whether we are in a C++ list initialization expression. 13233 // If so, we do not issue warnings for implicit int-float conversion 13234 // precision loss, because C++11 narrowing already handles it. 13235 bool IsListInit = Item.IsListInit || 13236 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13237 13238 if (E->isTypeDependent() || E->isValueDependent()) 13239 return; 13240 13241 Expr *SourceExpr = E; 13242 // Examine, but don't traverse into the source expression of an 13243 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13244 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13245 // evaluate it in the context of checking the specific conversion to T though. 13246 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13247 if (auto *Src = OVE->getSourceExpr()) 13248 SourceExpr = Src; 13249 13250 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13251 if (UO->getOpcode() == UO_Not && 13252 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13253 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13254 << OrigE->getSourceRange() << T->isBooleanType() 13255 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13256 13257 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13258 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13259 BO->getLHS()->isKnownToHaveBooleanValue() && 13260 BO->getRHS()->isKnownToHaveBooleanValue() && 13261 BO->getLHS()->HasSideEffects(S.Context) && 13262 BO->getRHS()->HasSideEffects(S.Context)) { 13263 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13264 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13265 << FixItHint::CreateReplacement( 13266 BO->getOperatorLoc(), 13267 (BO->getOpcode() == BO_And ? "&&" : "||")); 13268 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13269 } 13270 13271 // For conditional operators, we analyze the arguments as if they 13272 // were being fed directly into the output. 13273 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13274 CheckConditionalOperator(S, CO, CC, T); 13275 return; 13276 } 13277 13278 // Check implicit argument conversions for function calls. 13279 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13280 CheckImplicitArgumentConversions(S, Call, CC); 13281 13282 // Go ahead and check any implicit conversions we might have skipped. 13283 // The non-canonical typecheck is just an optimization; 13284 // CheckImplicitConversion will filter out dead implicit conversions. 13285 if (SourceExpr->getType() != T) 13286 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13287 13288 // Now continue drilling into this expression. 13289 13290 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13291 // The bound subexpressions in a PseudoObjectExpr are not reachable 13292 // as transitive children. 13293 // FIXME: Use a more uniform representation for this. 13294 for (auto *SE : POE->semantics()) 13295 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13296 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13297 } 13298 13299 // Skip past explicit casts. 13300 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13301 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13302 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13303 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13304 WorkList.push_back({E, CC, IsListInit}); 13305 return; 13306 } 13307 13308 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13309 // Do a somewhat different check with comparison operators. 13310 if (BO->isComparisonOp()) 13311 return AnalyzeComparison(S, BO); 13312 13313 // And with simple assignments. 13314 if (BO->getOpcode() == BO_Assign) 13315 return AnalyzeAssignment(S, BO); 13316 // And with compound assignments. 13317 if (BO->isAssignmentOp()) 13318 return AnalyzeCompoundAssignment(S, BO); 13319 } 13320 13321 // These break the otherwise-useful invariant below. Fortunately, 13322 // we don't really need to recurse into them, because any internal 13323 // expressions should have been analyzed already when they were 13324 // built into statements. 13325 if (isa<StmtExpr>(E)) return; 13326 13327 // Don't descend into unevaluated contexts. 13328 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13329 13330 // Now just recurse over the expression's children. 13331 CC = E->getExprLoc(); 13332 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13333 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13334 for (Stmt *SubStmt : E->children()) { 13335 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13336 if (!ChildExpr) 13337 continue; 13338 13339 if (IsLogicalAndOperator && 13340 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13341 // Ignore checking string literals that are in logical and operators. 13342 // This is a common pattern for asserts. 13343 continue; 13344 WorkList.push_back({ChildExpr, CC, IsListInit}); 13345 } 13346 13347 if (BO && BO->isLogicalOp()) { 13348 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13349 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13350 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13351 13352 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13353 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13354 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13355 } 13356 13357 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13358 if (U->getOpcode() == UO_LNot) { 13359 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13360 } else if (U->getOpcode() != UO_AddrOf) { 13361 if (U->getSubExpr()->getType()->isAtomicType()) 13362 S.Diag(U->getSubExpr()->getBeginLoc(), 13363 diag::warn_atomic_implicit_seq_cst); 13364 } 13365 } 13366 } 13367 13368 /// AnalyzeImplicitConversions - Find and report any interesting 13369 /// implicit conversions in the given expression. There are a couple 13370 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13371 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13372 bool IsListInit/*= false*/) { 13373 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13374 WorkList.push_back({OrigE, CC, IsListInit}); 13375 while (!WorkList.empty()) 13376 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13377 } 13378 13379 /// Diagnose integer type and any valid implicit conversion to it. 13380 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13381 // Taking into account implicit conversions, 13382 // allow any integer. 13383 if (!E->getType()->isIntegerType()) { 13384 S.Diag(E->getBeginLoc(), 13385 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13386 return true; 13387 } 13388 // Potentially emit standard warnings for implicit conversions if enabled 13389 // using -Wconversion. 13390 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13391 return false; 13392 } 13393 13394 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13395 // Returns true when emitting a warning about taking the address of a reference. 13396 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13397 const PartialDiagnostic &PD) { 13398 E = E->IgnoreParenImpCasts(); 13399 13400 const FunctionDecl *FD = nullptr; 13401 13402 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13403 if (!DRE->getDecl()->getType()->isReferenceType()) 13404 return false; 13405 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13406 if (!M->getMemberDecl()->getType()->isReferenceType()) 13407 return false; 13408 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13409 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13410 return false; 13411 FD = Call->getDirectCallee(); 13412 } else { 13413 return false; 13414 } 13415 13416 SemaRef.Diag(E->getExprLoc(), PD); 13417 13418 // If possible, point to location of function. 13419 if (FD) { 13420 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13421 } 13422 13423 return true; 13424 } 13425 13426 // Returns true if the SourceLocation is expanded from any macro body. 13427 // Returns false if the SourceLocation is invalid, is from not in a macro 13428 // expansion, or is from expanded from a top-level macro argument. 13429 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13430 if (Loc.isInvalid()) 13431 return false; 13432 13433 while (Loc.isMacroID()) { 13434 if (SM.isMacroBodyExpansion(Loc)) 13435 return true; 13436 Loc = SM.getImmediateMacroCallerLoc(Loc); 13437 } 13438 13439 return false; 13440 } 13441 13442 /// Diagnose pointers that are always non-null. 13443 /// \param E the expression containing the pointer 13444 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13445 /// compared to a null pointer 13446 /// \param IsEqual True when the comparison is equal to a null pointer 13447 /// \param Range Extra SourceRange to highlight in the diagnostic 13448 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13449 Expr::NullPointerConstantKind NullKind, 13450 bool IsEqual, SourceRange Range) { 13451 if (!E) 13452 return; 13453 13454 // Don't warn inside macros. 13455 if (E->getExprLoc().isMacroID()) { 13456 const SourceManager &SM = getSourceManager(); 13457 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13458 IsInAnyMacroBody(SM, Range.getBegin())) 13459 return; 13460 } 13461 E = E->IgnoreImpCasts(); 13462 13463 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13464 13465 if (isa<CXXThisExpr>(E)) { 13466 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13467 : diag::warn_this_bool_conversion; 13468 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13469 return; 13470 } 13471 13472 bool IsAddressOf = false; 13473 13474 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13475 if (UO->getOpcode() != UO_AddrOf) 13476 return; 13477 IsAddressOf = true; 13478 E = UO->getSubExpr(); 13479 } 13480 13481 if (IsAddressOf) { 13482 unsigned DiagID = IsCompare 13483 ? diag::warn_address_of_reference_null_compare 13484 : diag::warn_address_of_reference_bool_conversion; 13485 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13486 << IsEqual; 13487 if (CheckForReference(*this, E, PD)) { 13488 return; 13489 } 13490 } 13491 13492 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13493 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13494 std::string Str; 13495 llvm::raw_string_ostream S(Str); 13496 E->printPretty(S, nullptr, getPrintingPolicy()); 13497 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13498 : diag::warn_cast_nonnull_to_bool; 13499 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13500 << E->getSourceRange() << Range << IsEqual; 13501 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13502 }; 13503 13504 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13505 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13506 if (auto *Callee = Call->getDirectCallee()) { 13507 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13508 ComplainAboutNonnullParamOrCall(A); 13509 return; 13510 } 13511 } 13512 } 13513 13514 // Expect to find a single Decl. Skip anything more complicated. 13515 ValueDecl *D = nullptr; 13516 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13517 D = R->getDecl(); 13518 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13519 D = M->getMemberDecl(); 13520 } 13521 13522 // Weak Decls can be null. 13523 if (!D || D->isWeak()) 13524 return; 13525 13526 // Check for parameter decl with nonnull attribute 13527 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13528 if (getCurFunction() && 13529 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13530 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13531 ComplainAboutNonnullParamOrCall(A); 13532 return; 13533 } 13534 13535 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13536 // Skip function template not specialized yet. 13537 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13538 return; 13539 auto ParamIter = llvm::find(FD->parameters(), PV); 13540 assert(ParamIter != FD->param_end()); 13541 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13542 13543 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13544 if (!NonNull->args_size()) { 13545 ComplainAboutNonnullParamOrCall(NonNull); 13546 return; 13547 } 13548 13549 for (const ParamIdx &ArgNo : NonNull->args()) { 13550 if (ArgNo.getASTIndex() == ParamNo) { 13551 ComplainAboutNonnullParamOrCall(NonNull); 13552 return; 13553 } 13554 } 13555 } 13556 } 13557 } 13558 } 13559 13560 QualType T = D->getType(); 13561 const bool IsArray = T->isArrayType(); 13562 const bool IsFunction = T->isFunctionType(); 13563 13564 // Address of function is used to silence the function warning. 13565 if (IsAddressOf && IsFunction) { 13566 return; 13567 } 13568 13569 // Found nothing. 13570 if (!IsAddressOf && !IsFunction && !IsArray) 13571 return; 13572 13573 // Pretty print the expression for the diagnostic. 13574 std::string Str; 13575 llvm::raw_string_ostream S(Str); 13576 E->printPretty(S, nullptr, getPrintingPolicy()); 13577 13578 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13579 : diag::warn_impcast_pointer_to_bool; 13580 enum { 13581 AddressOf, 13582 FunctionPointer, 13583 ArrayPointer 13584 } DiagType; 13585 if (IsAddressOf) 13586 DiagType = AddressOf; 13587 else if (IsFunction) 13588 DiagType = FunctionPointer; 13589 else if (IsArray) 13590 DiagType = ArrayPointer; 13591 else 13592 llvm_unreachable("Could not determine diagnostic."); 13593 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13594 << Range << IsEqual; 13595 13596 if (!IsFunction) 13597 return; 13598 13599 // Suggest '&' to silence the function warning. 13600 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13601 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13602 13603 // Check to see if '()' fixit should be emitted. 13604 QualType ReturnType; 13605 UnresolvedSet<4> NonTemplateOverloads; 13606 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13607 if (ReturnType.isNull()) 13608 return; 13609 13610 if (IsCompare) { 13611 // There are two cases here. If there is null constant, the only suggest 13612 // for a pointer return type. If the null is 0, then suggest if the return 13613 // type is a pointer or an integer type. 13614 if (!ReturnType->isPointerType()) { 13615 if (NullKind == Expr::NPCK_ZeroExpression || 13616 NullKind == Expr::NPCK_ZeroLiteral) { 13617 if (!ReturnType->isIntegerType()) 13618 return; 13619 } else { 13620 return; 13621 } 13622 } 13623 } else { // !IsCompare 13624 // For function to bool, only suggest if the function pointer has bool 13625 // return type. 13626 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13627 return; 13628 } 13629 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13630 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13631 } 13632 13633 /// Diagnoses "dangerous" implicit conversions within the given 13634 /// expression (which is a full expression). Implements -Wconversion 13635 /// and -Wsign-compare. 13636 /// 13637 /// \param CC the "context" location of the implicit conversion, i.e. 13638 /// the most location of the syntactic entity requiring the implicit 13639 /// conversion 13640 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13641 // Don't diagnose in unevaluated contexts. 13642 if (isUnevaluatedContext()) 13643 return; 13644 13645 // Don't diagnose for value- or type-dependent expressions. 13646 if (E->isTypeDependent() || E->isValueDependent()) 13647 return; 13648 13649 // Check for array bounds violations in cases where the check isn't triggered 13650 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13651 // ArraySubscriptExpr is on the RHS of a variable initialization. 13652 CheckArrayAccess(E); 13653 13654 // This is not the right CC for (e.g.) a variable initialization. 13655 AnalyzeImplicitConversions(*this, E, CC); 13656 } 13657 13658 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13659 /// Input argument E is a logical expression. 13660 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13661 ::CheckBoolLikeConversion(*this, E, CC); 13662 } 13663 13664 /// Diagnose when expression is an integer constant expression and its evaluation 13665 /// results in integer overflow 13666 void Sema::CheckForIntOverflow (Expr *E) { 13667 // Use a work list to deal with nested struct initializers. 13668 SmallVector<Expr *, 2> Exprs(1, E); 13669 13670 do { 13671 Expr *OriginalE = Exprs.pop_back_val(); 13672 Expr *E = OriginalE->IgnoreParenCasts(); 13673 13674 if (isa<BinaryOperator>(E)) { 13675 E->EvaluateForOverflow(Context); 13676 continue; 13677 } 13678 13679 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13680 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13681 else if (isa<ObjCBoxedExpr>(OriginalE)) 13682 E->EvaluateForOverflow(Context); 13683 else if (auto Call = dyn_cast<CallExpr>(E)) 13684 Exprs.append(Call->arg_begin(), Call->arg_end()); 13685 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13686 Exprs.append(Message->arg_begin(), Message->arg_end()); 13687 } while (!Exprs.empty()); 13688 } 13689 13690 namespace { 13691 13692 /// Visitor for expressions which looks for unsequenced operations on the 13693 /// same object. 13694 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13695 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13696 13697 /// A tree of sequenced regions within an expression. Two regions are 13698 /// unsequenced if one is an ancestor or a descendent of the other. When we 13699 /// finish processing an expression with sequencing, such as a comma 13700 /// expression, we fold its tree nodes into its parent, since they are 13701 /// unsequenced with respect to nodes we will visit later. 13702 class SequenceTree { 13703 struct Value { 13704 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13705 unsigned Parent : 31; 13706 unsigned Merged : 1; 13707 }; 13708 SmallVector<Value, 8> Values; 13709 13710 public: 13711 /// A region within an expression which may be sequenced with respect 13712 /// to some other region. 13713 class Seq { 13714 friend class SequenceTree; 13715 13716 unsigned Index; 13717 13718 explicit Seq(unsigned N) : Index(N) {} 13719 13720 public: 13721 Seq() : Index(0) {} 13722 }; 13723 13724 SequenceTree() { Values.push_back(Value(0)); } 13725 Seq root() const { return Seq(0); } 13726 13727 /// Create a new sequence of operations, which is an unsequenced 13728 /// subset of \p Parent. This sequence of operations is sequenced with 13729 /// respect to other children of \p Parent. 13730 Seq allocate(Seq Parent) { 13731 Values.push_back(Value(Parent.Index)); 13732 return Seq(Values.size() - 1); 13733 } 13734 13735 /// Merge a sequence of operations into its parent. 13736 void merge(Seq S) { 13737 Values[S.Index].Merged = true; 13738 } 13739 13740 /// Determine whether two operations are unsequenced. This operation 13741 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13742 /// should have been merged into its parent as appropriate. 13743 bool isUnsequenced(Seq Cur, Seq Old) { 13744 unsigned C = representative(Cur.Index); 13745 unsigned Target = representative(Old.Index); 13746 while (C >= Target) { 13747 if (C == Target) 13748 return true; 13749 C = Values[C].Parent; 13750 } 13751 return false; 13752 } 13753 13754 private: 13755 /// Pick a representative for a sequence. 13756 unsigned representative(unsigned K) { 13757 if (Values[K].Merged) 13758 // Perform path compression as we go. 13759 return Values[K].Parent = representative(Values[K].Parent); 13760 return K; 13761 } 13762 }; 13763 13764 /// An object for which we can track unsequenced uses. 13765 using Object = const NamedDecl *; 13766 13767 /// Different flavors of object usage which we track. We only track the 13768 /// least-sequenced usage of each kind. 13769 enum UsageKind { 13770 /// A read of an object. Multiple unsequenced reads are OK. 13771 UK_Use, 13772 13773 /// A modification of an object which is sequenced before the value 13774 /// computation of the expression, such as ++n in C++. 13775 UK_ModAsValue, 13776 13777 /// A modification of an object which is not sequenced before the value 13778 /// computation of the expression, such as n++. 13779 UK_ModAsSideEffect, 13780 13781 UK_Count = UK_ModAsSideEffect + 1 13782 }; 13783 13784 /// Bundle together a sequencing region and the expression corresponding 13785 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13786 struct Usage { 13787 const Expr *UsageExpr; 13788 SequenceTree::Seq Seq; 13789 13790 Usage() : UsageExpr(nullptr), Seq() {} 13791 }; 13792 13793 struct UsageInfo { 13794 Usage Uses[UK_Count]; 13795 13796 /// Have we issued a diagnostic for this object already? 13797 bool Diagnosed; 13798 13799 UsageInfo() : Uses(), Diagnosed(false) {} 13800 }; 13801 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13802 13803 Sema &SemaRef; 13804 13805 /// Sequenced regions within the expression. 13806 SequenceTree Tree; 13807 13808 /// Declaration modifications and references which we have seen. 13809 UsageInfoMap UsageMap; 13810 13811 /// The region we are currently within. 13812 SequenceTree::Seq Region; 13813 13814 /// Filled in with declarations which were modified as a side-effect 13815 /// (that is, post-increment operations). 13816 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13817 13818 /// Expressions to check later. We defer checking these to reduce 13819 /// stack usage. 13820 SmallVectorImpl<const Expr *> &WorkList; 13821 13822 /// RAII object wrapping the visitation of a sequenced subexpression of an 13823 /// expression. At the end of this process, the side-effects of the evaluation 13824 /// become sequenced with respect to the value computation of the result, so 13825 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13826 /// UK_ModAsValue. 13827 struct SequencedSubexpression { 13828 SequencedSubexpression(SequenceChecker &Self) 13829 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13830 Self.ModAsSideEffect = &ModAsSideEffect; 13831 } 13832 13833 ~SequencedSubexpression() { 13834 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13835 // Add a new usage with usage kind UK_ModAsValue, and then restore 13836 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13837 // the previous one was empty). 13838 UsageInfo &UI = Self.UsageMap[M.first]; 13839 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13840 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13841 SideEffectUsage = M.second; 13842 } 13843 Self.ModAsSideEffect = OldModAsSideEffect; 13844 } 13845 13846 SequenceChecker &Self; 13847 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13848 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13849 }; 13850 13851 /// RAII object wrapping the visitation of a subexpression which we might 13852 /// choose to evaluate as a constant. If any subexpression is evaluated and 13853 /// found to be non-constant, this allows us to suppress the evaluation of 13854 /// the outer expression. 13855 class EvaluationTracker { 13856 public: 13857 EvaluationTracker(SequenceChecker &Self) 13858 : Self(Self), Prev(Self.EvalTracker) { 13859 Self.EvalTracker = this; 13860 } 13861 13862 ~EvaluationTracker() { 13863 Self.EvalTracker = Prev; 13864 if (Prev) 13865 Prev->EvalOK &= EvalOK; 13866 } 13867 13868 bool evaluate(const Expr *E, bool &Result) { 13869 if (!EvalOK || E->isValueDependent()) 13870 return false; 13871 EvalOK = E->EvaluateAsBooleanCondition( 13872 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13873 return EvalOK; 13874 } 13875 13876 private: 13877 SequenceChecker &Self; 13878 EvaluationTracker *Prev; 13879 bool EvalOK = true; 13880 } *EvalTracker = nullptr; 13881 13882 /// Find the object which is produced by the specified expression, 13883 /// if any. 13884 Object getObject(const Expr *E, bool Mod) const { 13885 E = E->IgnoreParenCasts(); 13886 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13887 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13888 return getObject(UO->getSubExpr(), Mod); 13889 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13890 if (BO->getOpcode() == BO_Comma) 13891 return getObject(BO->getRHS(), Mod); 13892 if (Mod && BO->isAssignmentOp()) 13893 return getObject(BO->getLHS(), Mod); 13894 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13895 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13896 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13897 return ME->getMemberDecl(); 13898 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13899 // FIXME: If this is a reference, map through to its value. 13900 return DRE->getDecl(); 13901 return nullptr; 13902 } 13903 13904 /// Note that an object \p O was modified or used by an expression 13905 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13906 /// the object \p O as obtained via the \p UsageMap. 13907 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13908 // Get the old usage for the given object and usage kind. 13909 Usage &U = UI.Uses[UK]; 13910 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13911 // If we have a modification as side effect and are in a sequenced 13912 // subexpression, save the old Usage so that we can restore it later 13913 // in SequencedSubexpression::~SequencedSubexpression. 13914 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13915 ModAsSideEffect->push_back(std::make_pair(O, U)); 13916 // Then record the new usage with the current sequencing region. 13917 U.UsageExpr = UsageExpr; 13918 U.Seq = Region; 13919 } 13920 } 13921 13922 /// Check whether a modification or use of an object \p O in an expression 13923 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13924 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13925 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13926 /// usage and false we are checking for a mod-use unsequenced usage. 13927 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13928 UsageKind OtherKind, bool IsModMod) { 13929 if (UI.Diagnosed) 13930 return; 13931 13932 const Usage &U = UI.Uses[OtherKind]; 13933 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13934 return; 13935 13936 const Expr *Mod = U.UsageExpr; 13937 const Expr *ModOrUse = UsageExpr; 13938 if (OtherKind == UK_Use) 13939 std::swap(Mod, ModOrUse); 13940 13941 SemaRef.DiagRuntimeBehavior( 13942 Mod->getExprLoc(), {Mod, ModOrUse}, 13943 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13944 : diag::warn_unsequenced_mod_use) 13945 << O << SourceRange(ModOrUse->getExprLoc())); 13946 UI.Diagnosed = true; 13947 } 13948 13949 // A note on note{Pre, Post}{Use, Mod}: 13950 // 13951 // (It helps to follow the algorithm with an expression such as 13952 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13953 // operations before C++17 and both are well-defined in C++17). 13954 // 13955 // When visiting a node which uses/modify an object we first call notePreUse 13956 // or notePreMod before visiting its sub-expression(s). At this point the 13957 // children of the current node have not yet been visited and so the eventual 13958 // uses/modifications resulting from the children of the current node have not 13959 // been recorded yet. 13960 // 13961 // We then visit the children of the current node. After that notePostUse or 13962 // notePostMod is called. These will 1) detect an unsequenced modification 13963 // as side effect (as in "k++ + k") and 2) add a new usage with the 13964 // appropriate usage kind. 13965 // 13966 // We also have to be careful that some operation sequences modification as 13967 // side effect as well (for example: || or ,). To account for this we wrap 13968 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13969 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13970 // which record usages which are modifications as side effect, and then 13971 // downgrade them (or more accurately restore the previous usage which was a 13972 // modification as side effect) when exiting the scope of the sequenced 13973 // subexpression. 13974 13975 void notePreUse(Object O, const Expr *UseExpr) { 13976 UsageInfo &UI = UsageMap[O]; 13977 // Uses conflict with other modifications. 13978 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13979 } 13980 13981 void notePostUse(Object O, const Expr *UseExpr) { 13982 UsageInfo &UI = UsageMap[O]; 13983 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13984 /*IsModMod=*/false); 13985 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13986 } 13987 13988 void notePreMod(Object O, const Expr *ModExpr) { 13989 UsageInfo &UI = UsageMap[O]; 13990 // Modifications conflict with other modifications and with uses. 13991 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13992 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13993 } 13994 13995 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13996 UsageInfo &UI = UsageMap[O]; 13997 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13998 /*IsModMod=*/true); 13999 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14000 } 14001 14002 public: 14003 SequenceChecker(Sema &S, const Expr *E, 14004 SmallVectorImpl<const Expr *> &WorkList) 14005 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14006 Visit(E); 14007 // Silence a -Wunused-private-field since WorkList is now unused. 14008 // TODO: Evaluate if it can be used, and if not remove it. 14009 (void)this->WorkList; 14010 } 14011 14012 void VisitStmt(const Stmt *S) { 14013 // Skip all statements which aren't expressions for now. 14014 } 14015 14016 void VisitExpr(const Expr *E) { 14017 // By default, just recurse to evaluated subexpressions. 14018 Base::VisitStmt(E); 14019 } 14020 14021 void VisitCastExpr(const CastExpr *E) { 14022 Object O = Object(); 14023 if (E->getCastKind() == CK_LValueToRValue) 14024 O = getObject(E->getSubExpr(), false); 14025 14026 if (O) 14027 notePreUse(O, E); 14028 VisitExpr(E); 14029 if (O) 14030 notePostUse(O, E); 14031 } 14032 14033 void VisitSequencedExpressions(const Expr *SequencedBefore, 14034 const Expr *SequencedAfter) { 14035 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14036 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14037 SequenceTree::Seq OldRegion = Region; 14038 14039 { 14040 SequencedSubexpression SeqBefore(*this); 14041 Region = BeforeRegion; 14042 Visit(SequencedBefore); 14043 } 14044 14045 Region = AfterRegion; 14046 Visit(SequencedAfter); 14047 14048 Region = OldRegion; 14049 14050 Tree.merge(BeforeRegion); 14051 Tree.merge(AfterRegion); 14052 } 14053 14054 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14055 // C++17 [expr.sub]p1: 14056 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14057 // expression E1 is sequenced before the expression E2. 14058 if (SemaRef.getLangOpts().CPlusPlus17) 14059 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14060 else { 14061 Visit(ASE->getLHS()); 14062 Visit(ASE->getRHS()); 14063 } 14064 } 14065 14066 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14067 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14068 void VisitBinPtrMem(const BinaryOperator *BO) { 14069 // C++17 [expr.mptr.oper]p4: 14070 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14071 // the expression E1 is sequenced before the expression E2. 14072 if (SemaRef.getLangOpts().CPlusPlus17) 14073 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14074 else { 14075 Visit(BO->getLHS()); 14076 Visit(BO->getRHS()); 14077 } 14078 } 14079 14080 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14081 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14082 void VisitBinShlShr(const BinaryOperator *BO) { 14083 // C++17 [expr.shift]p4: 14084 // The expression E1 is sequenced before the expression E2. 14085 if (SemaRef.getLangOpts().CPlusPlus17) 14086 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14087 else { 14088 Visit(BO->getLHS()); 14089 Visit(BO->getRHS()); 14090 } 14091 } 14092 14093 void VisitBinComma(const BinaryOperator *BO) { 14094 // C++11 [expr.comma]p1: 14095 // Every value computation and side effect associated with the left 14096 // expression is sequenced before every value computation and side 14097 // effect associated with the right expression. 14098 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14099 } 14100 14101 void VisitBinAssign(const BinaryOperator *BO) { 14102 SequenceTree::Seq RHSRegion; 14103 SequenceTree::Seq LHSRegion; 14104 if (SemaRef.getLangOpts().CPlusPlus17) { 14105 RHSRegion = Tree.allocate(Region); 14106 LHSRegion = Tree.allocate(Region); 14107 } else { 14108 RHSRegion = Region; 14109 LHSRegion = Region; 14110 } 14111 SequenceTree::Seq OldRegion = Region; 14112 14113 // C++11 [expr.ass]p1: 14114 // [...] the assignment is sequenced after the value computation 14115 // of the right and left operands, [...] 14116 // 14117 // so check it before inspecting the operands and update the 14118 // map afterwards. 14119 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14120 if (O) 14121 notePreMod(O, BO); 14122 14123 if (SemaRef.getLangOpts().CPlusPlus17) { 14124 // C++17 [expr.ass]p1: 14125 // [...] The right operand is sequenced before the left operand. [...] 14126 { 14127 SequencedSubexpression SeqBefore(*this); 14128 Region = RHSRegion; 14129 Visit(BO->getRHS()); 14130 } 14131 14132 Region = LHSRegion; 14133 Visit(BO->getLHS()); 14134 14135 if (O && isa<CompoundAssignOperator>(BO)) 14136 notePostUse(O, BO); 14137 14138 } else { 14139 // C++11 does not specify any sequencing between the LHS and RHS. 14140 Region = LHSRegion; 14141 Visit(BO->getLHS()); 14142 14143 if (O && isa<CompoundAssignOperator>(BO)) 14144 notePostUse(O, BO); 14145 14146 Region = RHSRegion; 14147 Visit(BO->getRHS()); 14148 } 14149 14150 // C++11 [expr.ass]p1: 14151 // the assignment is sequenced [...] before the value computation of the 14152 // assignment expression. 14153 // C11 6.5.16/3 has no such rule. 14154 Region = OldRegion; 14155 if (O) 14156 notePostMod(O, BO, 14157 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14158 : UK_ModAsSideEffect); 14159 if (SemaRef.getLangOpts().CPlusPlus17) { 14160 Tree.merge(RHSRegion); 14161 Tree.merge(LHSRegion); 14162 } 14163 } 14164 14165 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14166 VisitBinAssign(CAO); 14167 } 14168 14169 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14170 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14171 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14172 Object O = getObject(UO->getSubExpr(), true); 14173 if (!O) 14174 return VisitExpr(UO); 14175 14176 notePreMod(O, UO); 14177 Visit(UO->getSubExpr()); 14178 // C++11 [expr.pre.incr]p1: 14179 // the expression ++x is equivalent to x+=1 14180 notePostMod(O, UO, 14181 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14182 : UK_ModAsSideEffect); 14183 } 14184 14185 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14186 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14187 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14188 Object O = getObject(UO->getSubExpr(), true); 14189 if (!O) 14190 return VisitExpr(UO); 14191 14192 notePreMod(O, UO); 14193 Visit(UO->getSubExpr()); 14194 notePostMod(O, UO, UK_ModAsSideEffect); 14195 } 14196 14197 void VisitBinLOr(const BinaryOperator *BO) { 14198 // C++11 [expr.log.or]p2: 14199 // If the second expression is evaluated, every value computation and 14200 // side effect associated with the first expression is sequenced before 14201 // every value computation and side effect associated with the 14202 // second expression. 14203 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14204 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14205 SequenceTree::Seq OldRegion = Region; 14206 14207 EvaluationTracker Eval(*this); 14208 { 14209 SequencedSubexpression Sequenced(*this); 14210 Region = LHSRegion; 14211 Visit(BO->getLHS()); 14212 } 14213 14214 // C++11 [expr.log.or]p1: 14215 // [...] the second operand is not evaluated if the first operand 14216 // evaluates to true. 14217 bool EvalResult = false; 14218 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14219 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14220 if (ShouldVisitRHS) { 14221 Region = RHSRegion; 14222 Visit(BO->getRHS()); 14223 } 14224 14225 Region = OldRegion; 14226 Tree.merge(LHSRegion); 14227 Tree.merge(RHSRegion); 14228 } 14229 14230 void VisitBinLAnd(const BinaryOperator *BO) { 14231 // C++11 [expr.log.and]p2: 14232 // If the second expression is evaluated, every value computation and 14233 // side effect associated with the first expression is sequenced before 14234 // every value computation and side effect associated with the 14235 // second expression. 14236 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14237 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14238 SequenceTree::Seq OldRegion = Region; 14239 14240 EvaluationTracker Eval(*this); 14241 { 14242 SequencedSubexpression Sequenced(*this); 14243 Region = LHSRegion; 14244 Visit(BO->getLHS()); 14245 } 14246 14247 // C++11 [expr.log.and]p1: 14248 // [...] the second operand is not evaluated if the first operand is false. 14249 bool EvalResult = false; 14250 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14251 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14252 if (ShouldVisitRHS) { 14253 Region = RHSRegion; 14254 Visit(BO->getRHS()); 14255 } 14256 14257 Region = OldRegion; 14258 Tree.merge(LHSRegion); 14259 Tree.merge(RHSRegion); 14260 } 14261 14262 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14263 // C++11 [expr.cond]p1: 14264 // [...] Every value computation and side effect associated with the first 14265 // expression is sequenced before every value computation and side effect 14266 // associated with the second or third expression. 14267 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14268 14269 // No sequencing is specified between the true and false expression. 14270 // However since exactly one of both is going to be evaluated we can 14271 // consider them to be sequenced. This is needed to avoid warning on 14272 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14273 // both the true and false expressions because we can't evaluate x. 14274 // This will still allow us to detect an expression like (pre C++17) 14275 // "(x ? y += 1 : y += 2) = y". 14276 // 14277 // We don't wrap the visitation of the true and false expression with 14278 // SequencedSubexpression because we don't want to downgrade modifications 14279 // as side effect in the true and false expressions after the visition 14280 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14281 // not warn between the two "y++", but we should warn between the "y++" 14282 // and the "y". 14283 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14284 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14285 SequenceTree::Seq OldRegion = Region; 14286 14287 EvaluationTracker Eval(*this); 14288 { 14289 SequencedSubexpression Sequenced(*this); 14290 Region = ConditionRegion; 14291 Visit(CO->getCond()); 14292 } 14293 14294 // C++11 [expr.cond]p1: 14295 // [...] The first expression is contextually converted to bool (Clause 4). 14296 // It is evaluated and if it is true, the result of the conditional 14297 // expression is the value of the second expression, otherwise that of the 14298 // third expression. Only one of the second and third expressions is 14299 // evaluated. [...] 14300 bool EvalResult = false; 14301 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14302 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14303 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14304 if (ShouldVisitTrueExpr) { 14305 Region = TrueRegion; 14306 Visit(CO->getTrueExpr()); 14307 } 14308 if (ShouldVisitFalseExpr) { 14309 Region = FalseRegion; 14310 Visit(CO->getFalseExpr()); 14311 } 14312 14313 Region = OldRegion; 14314 Tree.merge(ConditionRegion); 14315 Tree.merge(TrueRegion); 14316 Tree.merge(FalseRegion); 14317 } 14318 14319 void VisitCallExpr(const CallExpr *CE) { 14320 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14321 14322 if (CE->isUnevaluatedBuiltinCall(Context)) 14323 return; 14324 14325 // C++11 [intro.execution]p15: 14326 // When calling a function [...], every value computation and side effect 14327 // associated with any argument expression, or with the postfix expression 14328 // designating the called function, is sequenced before execution of every 14329 // expression or statement in the body of the function [and thus before 14330 // the value computation of its result]. 14331 SequencedSubexpression Sequenced(*this); 14332 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14333 // C++17 [expr.call]p5 14334 // The postfix-expression is sequenced before each expression in the 14335 // expression-list and any default argument. [...] 14336 SequenceTree::Seq CalleeRegion; 14337 SequenceTree::Seq OtherRegion; 14338 if (SemaRef.getLangOpts().CPlusPlus17) { 14339 CalleeRegion = Tree.allocate(Region); 14340 OtherRegion = Tree.allocate(Region); 14341 } else { 14342 CalleeRegion = Region; 14343 OtherRegion = Region; 14344 } 14345 SequenceTree::Seq OldRegion = Region; 14346 14347 // Visit the callee expression first. 14348 Region = CalleeRegion; 14349 if (SemaRef.getLangOpts().CPlusPlus17) { 14350 SequencedSubexpression Sequenced(*this); 14351 Visit(CE->getCallee()); 14352 } else { 14353 Visit(CE->getCallee()); 14354 } 14355 14356 // Then visit the argument expressions. 14357 Region = OtherRegion; 14358 for (const Expr *Argument : CE->arguments()) 14359 Visit(Argument); 14360 14361 Region = OldRegion; 14362 if (SemaRef.getLangOpts().CPlusPlus17) { 14363 Tree.merge(CalleeRegion); 14364 Tree.merge(OtherRegion); 14365 } 14366 }); 14367 } 14368 14369 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14370 // C++17 [over.match.oper]p2: 14371 // [...] the operator notation is first transformed to the equivalent 14372 // function-call notation as summarized in Table 12 (where @ denotes one 14373 // of the operators covered in the specified subclause). However, the 14374 // operands are sequenced in the order prescribed for the built-in 14375 // operator (Clause 8). 14376 // 14377 // From the above only overloaded binary operators and overloaded call 14378 // operators have sequencing rules in C++17 that we need to handle 14379 // separately. 14380 if (!SemaRef.getLangOpts().CPlusPlus17 || 14381 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14382 return VisitCallExpr(CXXOCE); 14383 14384 enum { 14385 NoSequencing, 14386 LHSBeforeRHS, 14387 RHSBeforeLHS, 14388 LHSBeforeRest 14389 } SequencingKind; 14390 switch (CXXOCE->getOperator()) { 14391 case OO_Equal: 14392 case OO_PlusEqual: 14393 case OO_MinusEqual: 14394 case OO_StarEqual: 14395 case OO_SlashEqual: 14396 case OO_PercentEqual: 14397 case OO_CaretEqual: 14398 case OO_AmpEqual: 14399 case OO_PipeEqual: 14400 case OO_LessLessEqual: 14401 case OO_GreaterGreaterEqual: 14402 SequencingKind = RHSBeforeLHS; 14403 break; 14404 14405 case OO_LessLess: 14406 case OO_GreaterGreater: 14407 case OO_AmpAmp: 14408 case OO_PipePipe: 14409 case OO_Comma: 14410 case OO_ArrowStar: 14411 case OO_Subscript: 14412 SequencingKind = LHSBeforeRHS; 14413 break; 14414 14415 case OO_Call: 14416 SequencingKind = LHSBeforeRest; 14417 break; 14418 14419 default: 14420 SequencingKind = NoSequencing; 14421 break; 14422 } 14423 14424 if (SequencingKind == NoSequencing) 14425 return VisitCallExpr(CXXOCE); 14426 14427 // This is a call, so all subexpressions are sequenced before the result. 14428 SequencedSubexpression Sequenced(*this); 14429 14430 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14431 assert(SemaRef.getLangOpts().CPlusPlus17 && 14432 "Should only get there with C++17 and above!"); 14433 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14434 "Should only get there with an overloaded binary operator" 14435 " or an overloaded call operator!"); 14436 14437 if (SequencingKind == LHSBeforeRest) { 14438 assert(CXXOCE->getOperator() == OO_Call && 14439 "We should only have an overloaded call operator here!"); 14440 14441 // This is very similar to VisitCallExpr, except that we only have the 14442 // C++17 case. The postfix-expression is the first argument of the 14443 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14444 // are in the following arguments. 14445 // 14446 // Note that we intentionally do not visit the callee expression since 14447 // it is just a decayed reference to a function. 14448 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14449 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14450 SequenceTree::Seq OldRegion = Region; 14451 14452 assert(CXXOCE->getNumArgs() >= 1 && 14453 "An overloaded call operator must have at least one argument" 14454 " for the postfix-expression!"); 14455 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14456 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14457 CXXOCE->getNumArgs() - 1); 14458 14459 // Visit the postfix-expression first. 14460 { 14461 Region = PostfixExprRegion; 14462 SequencedSubexpression Sequenced(*this); 14463 Visit(PostfixExpr); 14464 } 14465 14466 // Then visit the argument expressions. 14467 Region = ArgsRegion; 14468 for (const Expr *Arg : Args) 14469 Visit(Arg); 14470 14471 Region = OldRegion; 14472 Tree.merge(PostfixExprRegion); 14473 Tree.merge(ArgsRegion); 14474 } else { 14475 assert(CXXOCE->getNumArgs() == 2 && 14476 "Should only have two arguments here!"); 14477 assert((SequencingKind == LHSBeforeRHS || 14478 SequencingKind == RHSBeforeLHS) && 14479 "Unexpected sequencing kind!"); 14480 14481 // We do not visit the callee expression since it is just a decayed 14482 // reference to a function. 14483 const Expr *E1 = CXXOCE->getArg(0); 14484 const Expr *E2 = CXXOCE->getArg(1); 14485 if (SequencingKind == RHSBeforeLHS) 14486 std::swap(E1, E2); 14487 14488 return VisitSequencedExpressions(E1, E2); 14489 } 14490 }); 14491 } 14492 14493 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14494 // This is a call, so all subexpressions are sequenced before the result. 14495 SequencedSubexpression Sequenced(*this); 14496 14497 if (!CCE->isListInitialization()) 14498 return VisitExpr(CCE); 14499 14500 // In C++11, list initializations are sequenced. 14501 SmallVector<SequenceTree::Seq, 32> Elts; 14502 SequenceTree::Seq Parent = Region; 14503 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14504 E = CCE->arg_end(); 14505 I != E; ++I) { 14506 Region = Tree.allocate(Parent); 14507 Elts.push_back(Region); 14508 Visit(*I); 14509 } 14510 14511 // Forget that the initializers are sequenced. 14512 Region = Parent; 14513 for (unsigned I = 0; I < Elts.size(); ++I) 14514 Tree.merge(Elts[I]); 14515 } 14516 14517 void VisitInitListExpr(const InitListExpr *ILE) { 14518 if (!SemaRef.getLangOpts().CPlusPlus11) 14519 return VisitExpr(ILE); 14520 14521 // In C++11, list initializations are sequenced. 14522 SmallVector<SequenceTree::Seq, 32> Elts; 14523 SequenceTree::Seq Parent = Region; 14524 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14525 const Expr *E = ILE->getInit(I); 14526 if (!E) 14527 continue; 14528 Region = Tree.allocate(Parent); 14529 Elts.push_back(Region); 14530 Visit(E); 14531 } 14532 14533 // Forget that the initializers are sequenced. 14534 Region = Parent; 14535 for (unsigned I = 0; I < Elts.size(); ++I) 14536 Tree.merge(Elts[I]); 14537 } 14538 }; 14539 14540 } // namespace 14541 14542 void Sema::CheckUnsequencedOperations(const Expr *E) { 14543 SmallVector<const Expr *, 8> WorkList; 14544 WorkList.push_back(E); 14545 while (!WorkList.empty()) { 14546 const Expr *Item = WorkList.pop_back_val(); 14547 SequenceChecker(*this, Item, WorkList); 14548 } 14549 } 14550 14551 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14552 bool IsConstexpr) { 14553 llvm::SaveAndRestore<bool> ConstantContext( 14554 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14555 CheckImplicitConversions(E, CheckLoc); 14556 if (!E->isInstantiationDependent()) 14557 CheckUnsequencedOperations(E); 14558 if (!IsConstexpr && !E->isValueDependent()) 14559 CheckForIntOverflow(E); 14560 DiagnoseMisalignedMembers(); 14561 } 14562 14563 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14564 FieldDecl *BitField, 14565 Expr *Init) { 14566 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14567 } 14568 14569 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14570 SourceLocation Loc) { 14571 if (!PType->isVariablyModifiedType()) 14572 return; 14573 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14574 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14575 return; 14576 } 14577 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14578 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14579 return; 14580 } 14581 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14582 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14583 return; 14584 } 14585 14586 const ArrayType *AT = S.Context.getAsArrayType(PType); 14587 if (!AT) 14588 return; 14589 14590 if (AT->getSizeModifier() != ArrayType::Star) { 14591 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14592 return; 14593 } 14594 14595 S.Diag(Loc, diag::err_array_star_in_function_definition); 14596 } 14597 14598 /// CheckParmsForFunctionDef - Check that the parameters of the given 14599 /// function are appropriate for the definition of a function. This 14600 /// takes care of any checks that cannot be performed on the 14601 /// declaration itself, e.g., that the types of each of the function 14602 /// parameters are complete. 14603 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14604 bool CheckParameterNames) { 14605 bool HasInvalidParm = false; 14606 for (ParmVarDecl *Param : Parameters) { 14607 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14608 // function declarator that is part of a function definition of 14609 // that function shall not have incomplete type. 14610 // 14611 // This is also C++ [dcl.fct]p6. 14612 if (!Param->isInvalidDecl() && 14613 RequireCompleteType(Param->getLocation(), Param->getType(), 14614 diag::err_typecheck_decl_incomplete_type)) { 14615 Param->setInvalidDecl(); 14616 HasInvalidParm = true; 14617 } 14618 14619 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14620 // declaration of each parameter shall include an identifier. 14621 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14622 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14623 // Diagnose this as an extension in C17 and earlier. 14624 if (!getLangOpts().C2x) 14625 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14626 } 14627 14628 // C99 6.7.5.3p12: 14629 // If the function declarator is not part of a definition of that 14630 // function, parameters may have incomplete type and may use the [*] 14631 // notation in their sequences of declarator specifiers to specify 14632 // variable length array types. 14633 QualType PType = Param->getOriginalType(); 14634 // FIXME: This diagnostic should point the '[*]' if source-location 14635 // information is added for it. 14636 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14637 14638 // If the parameter is a c++ class type and it has to be destructed in the 14639 // callee function, declare the destructor so that it can be called by the 14640 // callee function. Do not perform any direct access check on the dtor here. 14641 if (!Param->isInvalidDecl()) { 14642 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14643 if (!ClassDecl->isInvalidDecl() && 14644 !ClassDecl->hasIrrelevantDestructor() && 14645 !ClassDecl->isDependentContext() && 14646 ClassDecl->isParamDestroyedInCallee()) { 14647 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14648 MarkFunctionReferenced(Param->getLocation(), Destructor); 14649 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14650 } 14651 } 14652 } 14653 14654 // Parameters with the pass_object_size attribute only need to be marked 14655 // constant at function definitions. Because we lack information about 14656 // whether we're on a declaration or definition when we're instantiating the 14657 // attribute, we need to check for constness here. 14658 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14659 if (!Param->getType().isConstQualified()) 14660 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14661 << Attr->getSpelling() << 1; 14662 14663 // Check for parameter names shadowing fields from the class. 14664 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14665 // The owning context for the parameter should be the function, but we 14666 // want to see if this function's declaration context is a record. 14667 DeclContext *DC = Param->getDeclContext(); 14668 if (DC && DC->isFunctionOrMethod()) { 14669 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14670 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14671 RD, /*DeclIsField*/ false); 14672 } 14673 } 14674 } 14675 14676 return HasInvalidParm; 14677 } 14678 14679 Optional<std::pair<CharUnits, CharUnits>> 14680 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14681 14682 /// Compute the alignment and offset of the base class object given the 14683 /// derived-to-base cast expression and the alignment and offset of the derived 14684 /// class object. 14685 static std::pair<CharUnits, CharUnits> 14686 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14687 CharUnits BaseAlignment, CharUnits Offset, 14688 ASTContext &Ctx) { 14689 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14690 ++PathI) { 14691 const CXXBaseSpecifier *Base = *PathI; 14692 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14693 if (Base->isVirtual()) { 14694 // The complete object may have a lower alignment than the non-virtual 14695 // alignment of the base, in which case the base may be misaligned. Choose 14696 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14697 // conservative lower bound of the complete object alignment. 14698 CharUnits NonVirtualAlignment = 14699 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14700 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14701 Offset = CharUnits::Zero(); 14702 } else { 14703 const ASTRecordLayout &RL = 14704 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14705 Offset += RL.getBaseClassOffset(BaseDecl); 14706 } 14707 DerivedType = Base->getType(); 14708 } 14709 14710 return std::make_pair(BaseAlignment, Offset); 14711 } 14712 14713 /// Compute the alignment and offset of a binary additive operator. 14714 static Optional<std::pair<CharUnits, CharUnits>> 14715 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14716 bool IsSub, ASTContext &Ctx) { 14717 QualType PointeeType = PtrE->getType()->getPointeeType(); 14718 14719 if (!PointeeType->isConstantSizeType()) 14720 return llvm::None; 14721 14722 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14723 14724 if (!P) 14725 return llvm::None; 14726 14727 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14728 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14729 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14730 if (IsSub) 14731 Offset = -Offset; 14732 return std::make_pair(P->first, P->second + Offset); 14733 } 14734 14735 // If the integer expression isn't a constant expression, compute the lower 14736 // bound of the alignment using the alignment and offset of the pointer 14737 // expression and the element size. 14738 return std::make_pair( 14739 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14740 CharUnits::Zero()); 14741 } 14742 14743 /// This helper function takes an lvalue expression and returns the alignment of 14744 /// a VarDecl and a constant offset from the VarDecl. 14745 Optional<std::pair<CharUnits, CharUnits>> 14746 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14747 E = E->IgnoreParens(); 14748 switch (E->getStmtClass()) { 14749 default: 14750 break; 14751 case Stmt::CStyleCastExprClass: 14752 case Stmt::CXXStaticCastExprClass: 14753 case Stmt::ImplicitCastExprClass: { 14754 auto *CE = cast<CastExpr>(E); 14755 const Expr *From = CE->getSubExpr(); 14756 switch (CE->getCastKind()) { 14757 default: 14758 break; 14759 case CK_NoOp: 14760 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14761 case CK_UncheckedDerivedToBase: 14762 case CK_DerivedToBase: { 14763 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14764 if (!P) 14765 break; 14766 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14767 P->second, Ctx); 14768 } 14769 } 14770 break; 14771 } 14772 case Stmt::ArraySubscriptExprClass: { 14773 auto *ASE = cast<ArraySubscriptExpr>(E); 14774 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14775 false, Ctx); 14776 } 14777 case Stmt::DeclRefExprClass: { 14778 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14779 // FIXME: If VD is captured by copy or is an escaping __block variable, 14780 // use the alignment of VD's type. 14781 if (!VD->getType()->isReferenceType()) 14782 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14783 if (VD->hasInit()) 14784 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14785 } 14786 break; 14787 } 14788 case Stmt::MemberExprClass: { 14789 auto *ME = cast<MemberExpr>(E); 14790 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14791 if (!FD || FD->getType()->isReferenceType() || 14792 FD->getParent()->isInvalidDecl()) 14793 break; 14794 Optional<std::pair<CharUnits, CharUnits>> P; 14795 if (ME->isArrow()) 14796 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14797 else 14798 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14799 if (!P) 14800 break; 14801 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14802 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14803 return std::make_pair(P->first, 14804 P->second + CharUnits::fromQuantity(Offset)); 14805 } 14806 case Stmt::UnaryOperatorClass: { 14807 auto *UO = cast<UnaryOperator>(E); 14808 switch (UO->getOpcode()) { 14809 default: 14810 break; 14811 case UO_Deref: 14812 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14813 } 14814 break; 14815 } 14816 case Stmt::BinaryOperatorClass: { 14817 auto *BO = cast<BinaryOperator>(E); 14818 auto Opcode = BO->getOpcode(); 14819 switch (Opcode) { 14820 default: 14821 break; 14822 case BO_Comma: 14823 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14824 } 14825 break; 14826 } 14827 } 14828 return llvm::None; 14829 } 14830 14831 /// This helper function takes a pointer expression and returns the alignment of 14832 /// a VarDecl and a constant offset from the VarDecl. 14833 Optional<std::pair<CharUnits, CharUnits>> 14834 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14835 E = E->IgnoreParens(); 14836 switch (E->getStmtClass()) { 14837 default: 14838 break; 14839 case Stmt::CStyleCastExprClass: 14840 case Stmt::CXXStaticCastExprClass: 14841 case Stmt::ImplicitCastExprClass: { 14842 auto *CE = cast<CastExpr>(E); 14843 const Expr *From = CE->getSubExpr(); 14844 switch (CE->getCastKind()) { 14845 default: 14846 break; 14847 case CK_NoOp: 14848 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14849 case CK_ArrayToPointerDecay: 14850 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14851 case CK_UncheckedDerivedToBase: 14852 case CK_DerivedToBase: { 14853 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14854 if (!P) 14855 break; 14856 return getDerivedToBaseAlignmentAndOffset( 14857 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14858 } 14859 } 14860 break; 14861 } 14862 case Stmt::CXXThisExprClass: { 14863 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14864 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14865 return std::make_pair(Alignment, CharUnits::Zero()); 14866 } 14867 case Stmt::UnaryOperatorClass: { 14868 auto *UO = cast<UnaryOperator>(E); 14869 if (UO->getOpcode() == UO_AddrOf) 14870 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14871 break; 14872 } 14873 case Stmt::BinaryOperatorClass: { 14874 auto *BO = cast<BinaryOperator>(E); 14875 auto Opcode = BO->getOpcode(); 14876 switch (Opcode) { 14877 default: 14878 break; 14879 case BO_Add: 14880 case BO_Sub: { 14881 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14882 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14883 std::swap(LHS, RHS); 14884 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14885 Ctx); 14886 } 14887 case BO_Comma: 14888 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14889 } 14890 break; 14891 } 14892 } 14893 return llvm::None; 14894 } 14895 14896 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14897 // See if we can compute the alignment of a VarDecl and an offset from it. 14898 Optional<std::pair<CharUnits, CharUnits>> P = 14899 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14900 14901 if (P) 14902 return P->first.alignmentAtOffset(P->second); 14903 14904 // If that failed, return the type's alignment. 14905 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14906 } 14907 14908 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14909 /// pointer cast increases the alignment requirements. 14910 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14911 // This is actually a lot of work to potentially be doing on every 14912 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14913 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14914 return; 14915 14916 // Ignore dependent types. 14917 if (T->isDependentType() || Op->getType()->isDependentType()) 14918 return; 14919 14920 // Require that the destination be a pointer type. 14921 const PointerType *DestPtr = T->getAs<PointerType>(); 14922 if (!DestPtr) return; 14923 14924 // If the destination has alignment 1, we're done. 14925 QualType DestPointee = DestPtr->getPointeeType(); 14926 if (DestPointee->isIncompleteType()) return; 14927 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14928 if (DestAlign.isOne()) return; 14929 14930 // Require that the source be a pointer type. 14931 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14932 if (!SrcPtr) return; 14933 QualType SrcPointee = SrcPtr->getPointeeType(); 14934 14935 // Explicitly allow casts from cv void*. We already implicitly 14936 // allowed casts to cv void*, since they have alignment 1. 14937 // Also allow casts involving incomplete types, which implicitly 14938 // includes 'void'. 14939 if (SrcPointee->isIncompleteType()) return; 14940 14941 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14942 14943 if (SrcAlign >= DestAlign) return; 14944 14945 Diag(TRange.getBegin(), diag::warn_cast_align) 14946 << Op->getType() << T 14947 << static_cast<unsigned>(SrcAlign.getQuantity()) 14948 << static_cast<unsigned>(DestAlign.getQuantity()) 14949 << TRange << Op->getSourceRange(); 14950 } 14951 14952 /// Check whether this array fits the idiom of a size-one tail padded 14953 /// array member of a struct. 14954 /// 14955 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14956 /// commonly used to emulate flexible arrays in C89 code. 14957 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14958 const NamedDecl *ND) { 14959 if (Size != 1 || !ND) return false; 14960 14961 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14962 if (!FD) return false; 14963 14964 // Don't consider sizes resulting from macro expansions or template argument 14965 // substitution to form C89 tail-padded arrays. 14966 14967 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14968 while (TInfo) { 14969 TypeLoc TL = TInfo->getTypeLoc(); 14970 // Look through typedefs. 14971 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14972 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14973 TInfo = TDL->getTypeSourceInfo(); 14974 continue; 14975 } 14976 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14977 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14978 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14979 return false; 14980 } 14981 break; 14982 } 14983 14984 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14985 if (!RD) return false; 14986 if (RD->isUnion()) return false; 14987 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14988 if (!CRD->isStandardLayout()) return false; 14989 } 14990 14991 // See if this is the last field decl in the record. 14992 const Decl *D = FD; 14993 while ((D = D->getNextDeclInContext())) 14994 if (isa<FieldDecl>(D)) 14995 return false; 14996 return true; 14997 } 14998 14999 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15000 const ArraySubscriptExpr *ASE, 15001 bool AllowOnePastEnd, bool IndexNegated) { 15002 // Already diagnosed by the constant evaluator. 15003 if (isConstantEvaluated()) 15004 return; 15005 15006 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15007 if (IndexExpr->isValueDependent()) 15008 return; 15009 15010 const Type *EffectiveType = 15011 BaseExpr->getType()->getPointeeOrArrayElementType(); 15012 BaseExpr = BaseExpr->IgnoreParenCasts(); 15013 const ConstantArrayType *ArrayTy = 15014 Context.getAsConstantArrayType(BaseExpr->getType()); 15015 15016 const Type *BaseType = 15017 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15018 bool IsUnboundedArray = (BaseType == nullptr); 15019 if (EffectiveType->isDependentType() || 15020 (!IsUnboundedArray && BaseType->isDependentType())) 15021 return; 15022 15023 Expr::EvalResult Result; 15024 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15025 return; 15026 15027 llvm::APSInt index = Result.Val.getInt(); 15028 if (IndexNegated) { 15029 index.setIsUnsigned(false); 15030 index = -index; 15031 } 15032 15033 const NamedDecl *ND = nullptr; 15034 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15035 ND = DRE->getDecl(); 15036 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15037 ND = ME->getMemberDecl(); 15038 15039 if (IsUnboundedArray) { 15040 if (index.isUnsigned() || !index.isNegative()) { 15041 const auto &ASTC = getASTContext(); 15042 unsigned AddrBits = 15043 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15044 EffectiveType->getCanonicalTypeInternal())); 15045 if (index.getBitWidth() < AddrBits) 15046 index = index.zext(AddrBits); 15047 Optional<CharUnits> ElemCharUnits = 15048 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15049 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15050 // pointer) bounds-checking isn't meaningful. 15051 if (!ElemCharUnits) 15052 return; 15053 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15054 // If index has more active bits than address space, we already know 15055 // we have a bounds violation to warn about. Otherwise, compute 15056 // address of (index + 1)th element, and warn about bounds violation 15057 // only if that address exceeds address space. 15058 if (index.getActiveBits() <= AddrBits) { 15059 bool Overflow; 15060 llvm::APInt Product(index); 15061 Product += 1; 15062 Product = Product.umul_ov(ElemBytes, Overflow); 15063 if (!Overflow && Product.getActiveBits() <= AddrBits) 15064 return; 15065 } 15066 15067 // Need to compute max possible elements in address space, since that 15068 // is included in diag message. 15069 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15070 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15071 MaxElems += 1; 15072 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15073 MaxElems = MaxElems.udiv(ElemBytes); 15074 15075 unsigned DiagID = 15076 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15077 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15078 15079 // Diag message shows element size in bits and in "bytes" (platform- 15080 // dependent CharUnits) 15081 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15082 PDiag(DiagID) 15083 << toString(index, 10, true) << AddrBits 15084 << (unsigned)ASTC.toBits(*ElemCharUnits) 15085 << toString(ElemBytes, 10, false) 15086 << toString(MaxElems, 10, false) 15087 << (unsigned)MaxElems.getLimitedValue(~0U) 15088 << IndexExpr->getSourceRange()); 15089 15090 if (!ND) { 15091 // Try harder to find a NamedDecl to point at in the note. 15092 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15093 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15094 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15095 ND = DRE->getDecl(); 15096 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15097 ND = ME->getMemberDecl(); 15098 } 15099 15100 if (ND) 15101 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15102 PDiag(diag::note_array_declared_here) << ND); 15103 } 15104 return; 15105 } 15106 15107 if (index.isUnsigned() || !index.isNegative()) { 15108 // It is possible that the type of the base expression after 15109 // IgnoreParenCasts is incomplete, even though the type of the base 15110 // expression before IgnoreParenCasts is complete (see PR39746 for an 15111 // example). In this case we have no information about whether the array 15112 // access exceeds the array bounds. However we can still diagnose an array 15113 // access which precedes the array bounds. 15114 if (BaseType->isIncompleteType()) 15115 return; 15116 15117 llvm::APInt size = ArrayTy->getSize(); 15118 if (!size.isStrictlyPositive()) 15119 return; 15120 15121 if (BaseType != EffectiveType) { 15122 // Make sure we're comparing apples to apples when comparing index to size 15123 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15124 uint64_t array_typesize = Context.getTypeSize(BaseType); 15125 // Handle ptrarith_typesize being zero, such as when casting to void* 15126 if (!ptrarith_typesize) ptrarith_typesize = 1; 15127 if (ptrarith_typesize != array_typesize) { 15128 // There's a cast to a different size type involved 15129 uint64_t ratio = array_typesize / ptrarith_typesize; 15130 // TODO: Be smarter about handling cases where array_typesize is not a 15131 // multiple of ptrarith_typesize 15132 if (ptrarith_typesize * ratio == array_typesize) 15133 size *= llvm::APInt(size.getBitWidth(), ratio); 15134 } 15135 } 15136 15137 if (size.getBitWidth() > index.getBitWidth()) 15138 index = index.zext(size.getBitWidth()); 15139 else if (size.getBitWidth() < index.getBitWidth()) 15140 size = size.zext(index.getBitWidth()); 15141 15142 // For array subscripting the index must be less than size, but for pointer 15143 // arithmetic also allow the index (offset) to be equal to size since 15144 // computing the next address after the end of the array is legal and 15145 // commonly done e.g. in C++ iterators and range-based for loops. 15146 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15147 return; 15148 15149 // Also don't warn for arrays of size 1 which are members of some 15150 // structure. These are often used to approximate flexible arrays in C89 15151 // code. 15152 if (IsTailPaddedMemberArray(*this, size, ND)) 15153 return; 15154 15155 // Suppress the warning if the subscript expression (as identified by the 15156 // ']' location) and the index expression are both from macro expansions 15157 // within a system header. 15158 if (ASE) { 15159 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15160 ASE->getRBracketLoc()); 15161 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15162 SourceLocation IndexLoc = 15163 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15164 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15165 return; 15166 } 15167 } 15168 15169 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15170 : diag::warn_ptr_arith_exceeds_bounds; 15171 15172 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15173 PDiag(DiagID) << toString(index, 10, true) 15174 << toString(size, 10, true) 15175 << (unsigned)size.getLimitedValue(~0U) 15176 << IndexExpr->getSourceRange()); 15177 } else { 15178 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15179 if (!ASE) { 15180 DiagID = diag::warn_ptr_arith_precedes_bounds; 15181 if (index.isNegative()) index = -index; 15182 } 15183 15184 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15185 PDiag(DiagID) << toString(index, 10, true) 15186 << IndexExpr->getSourceRange()); 15187 } 15188 15189 if (!ND) { 15190 // Try harder to find a NamedDecl to point at in the note. 15191 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15192 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15193 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15194 ND = DRE->getDecl(); 15195 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15196 ND = ME->getMemberDecl(); 15197 } 15198 15199 if (ND) 15200 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15201 PDiag(diag::note_array_declared_here) << ND); 15202 } 15203 15204 void Sema::CheckArrayAccess(const Expr *expr) { 15205 int AllowOnePastEnd = 0; 15206 while (expr) { 15207 expr = expr->IgnoreParenImpCasts(); 15208 switch (expr->getStmtClass()) { 15209 case Stmt::ArraySubscriptExprClass: { 15210 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15211 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15212 AllowOnePastEnd > 0); 15213 expr = ASE->getBase(); 15214 break; 15215 } 15216 case Stmt::MemberExprClass: { 15217 expr = cast<MemberExpr>(expr)->getBase(); 15218 break; 15219 } 15220 case Stmt::OMPArraySectionExprClass: { 15221 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15222 if (ASE->getLowerBound()) 15223 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15224 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15225 return; 15226 } 15227 case Stmt::UnaryOperatorClass: { 15228 // Only unwrap the * and & unary operators 15229 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15230 expr = UO->getSubExpr(); 15231 switch (UO->getOpcode()) { 15232 case UO_AddrOf: 15233 AllowOnePastEnd++; 15234 break; 15235 case UO_Deref: 15236 AllowOnePastEnd--; 15237 break; 15238 default: 15239 return; 15240 } 15241 break; 15242 } 15243 case Stmt::ConditionalOperatorClass: { 15244 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15245 if (const Expr *lhs = cond->getLHS()) 15246 CheckArrayAccess(lhs); 15247 if (const Expr *rhs = cond->getRHS()) 15248 CheckArrayAccess(rhs); 15249 return; 15250 } 15251 case Stmt::CXXOperatorCallExprClass: { 15252 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15253 for (const auto *Arg : OCE->arguments()) 15254 CheckArrayAccess(Arg); 15255 return; 15256 } 15257 default: 15258 return; 15259 } 15260 } 15261 } 15262 15263 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15264 15265 namespace { 15266 15267 struct RetainCycleOwner { 15268 VarDecl *Variable = nullptr; 15269 SourceRange Range; 15270 SourceLocation Loc; 15271 bool Indirect = false; 15272 15273 RetainCycleOwner() = default; 15274 15275 void setLocsFrom(Expr *e) { 15276 Loc = e->getExprLoc(); 15277 Range = e->getSourceRange(); 15278 } 15279 }; 15280 15281 } // namespace 15282 15283 /// Consider whether capturing the given variable can possibly lead to 15284 /// a retain cycle. 15285 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15286 // In ARC, it's captured strongly iff the variable has __strong 15287 // lifetime. In MRR, it's captured strongly if the variable is 15288 // __block and has an appropriate type. 15289 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15290 return false; 15291 15292 owner.Variable = var; 15293 if (ref) 15294 owner.setLocsFrom(ref); 15295 return true; 15296 } 15297 15298 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15299 while (true) { 15300 e = e->IgnoreParens(); 15301 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15302 switch (cast->getCastKind()) { 15303 case CK_BitCast: 15304 case CK_LValueBitCast: 15305 case CK_LValueToRValue: 15306 case CK_ARCReclaimReturnedObject: 15307 e = cast->getSubExpr(); 15308 continue; 15309 15310 default: 15311 return false; 15312 } 15313 } 15314 15315 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15316 ObjCIvarDecl *ivar = ref->getDecl(); 15317 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15318 return false; 15319 15320 // Try to find a retain cycle in the base. 15321 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15322 return false; 15323 15324 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15325 owner.Indirect = true; 15326 return true; 15327 } 15328 15329 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15330 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15331 if (!var) return false; 15332 return considerVariable(var, ref, owner); 15333 } 15334 15335 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15336 if (member->isArrow()) return false; 15337 15338 // Don't count this as an indirect ownership. 15339 e = member->getBase(); 15340 continue; 15341 } 15342 15343 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15344 // Only pay attention to pseudo-objects on property references. 15345 ObjCPropertyRefExpr *pre 15346 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15347 ->IgnoreParens()); 15348 if (!pre) return false; 15349 if (pre->isImplicitProperty()) return false; 15350 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15351 if (!property->isRetaining() && 15352 !(property->getPropertyIvarDecl() && 15353 property->getPropertyIvarDecl()->getType() 15354 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15355 return false; 15356 15357 owner.Indirect = true; 15358 if (pre->isSuperReceiver()) { 15359 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15360 if (!owner.Variable) 15361 return false; 15362 owner.Loc = pre->getLocation(); 15363 owner.Range = pre->getSourceRange(); 15364 return true; 15365 } 15366 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15367 ->getSourceExpr()); 15368 continue; 15369 } 15370 15371 // Array ivars? 15372 15373 return false; 15374 } 15375 } 15376 15377 namespace { 15378 15379 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15380 ASTContext &Context; 15381 VarDecl *Variable; 15382 Expr *Capturer = nullptr; 15383 bool VarWillBeReased = false; 15384 15385 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15386 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15387 Context(Context), Variable(variable) {} 15388 15389 void VisitDeclRefExpr(DeclRefExpr *ref) { 15390 if (ref->getDecl() == Variable && !Capturer) 15391 Capturer = ref; 15392 } 15393 15394 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15395 if (Capturer) return; 15396 Visit(ref->getBase()); 15397 if (Capturer && ref->isFreeIvar()) 15398 Capturer = ref; 15399 } 15400 15401 void VisitBlockExpr(BlockExpr *block) { 15402 // Look inside nested blocks 15403 if (block->getBlockDecl()->capturesVariable(Variable)) 15404 Visit(block->getBlockDecl()->getBody()); 15405 } 15406 15407 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15408 if (Capturer) return; 15409 if (OVE->getSourceExpr()) 15410 Visit(OVE->getSourceExpr()); 15411 } 15412 15413 void VisitBinaryOperator(BinaryOperator *BinOp) { 15414 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15415 return; 15416 Expr *LHS = BinOp->getLHS(); 15417 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15418 if (DRE->getDecl() != Variable) 15419 return; 15420 if (Expr *RHS = BinOp->getRHS()) { 15421 RHS = RHS->IgnoreParenCasts(); 15422 Optional<llvm::APSInt> Value; 15423 VarWillBeReased = 15424 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15425 *Value == 0); 15426 } 15427 } 15428 } 15429 }; 15430 15431 } // namespace 15432 15433 /// Check whether the given argument is a block which captures a 15434 /// variable. 15435 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15436 assert(owner.Variable && owner.Loc.isValid()); 15437 15438 e = e->IgnoreParenCasts(); 15439 15440 // Look through [^{...} copy] and Block_copy(^{...}). 15441 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15442 Selector Cmd = ME->getSelector(); 15443 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15444 e = ME->getInstanceReceiver(); 15445 if (!e) 15446 return nullptr; 15447 e = e->IgnoreParenCasts(); 15448 } 15449 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15450 if (CE->getNumArgs() == 1) { 15451 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15452 if (Fn) { 15453 const IdentifierInfo *FnI = Fn->getIdentifier(); 15454 if (FnI && FnI->isStr("_Block_copy")) { 15455 e = CE->getArg(0)->IgnoreParenCasts(); 15456 } 15457 } 15458 } 15459 } 15460 15461 BlockExpr *block = dyn_cast<BlockExpr>(e); 15462 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15463 return nullptr; 15464 15465 FindCaptureVisitor visitor(S.Context, owner.Variable); 15466 visitor.Visit(block->getBlockDecl()->getBody()); 15467 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15468 } 15469 15470 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15471 RetainCycleOwner &owner) { 15472 assert(capturer); 15473 assert(owner.Variable && owner.Loc.isValid()); 15474 15475 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15476 << owner.Variable << capturer->getSourceRange(); 15477 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15478 << owner.Indirect << owner.Range; 15479 } 15480 15481 /// Check for a keyword selector that starts with the word 'add' or 15482 /// 'set'. 15483 static bool isSetterLikeSelector(Selector sel) { 15484 if (sel.isUnarySelector()) return false; 15485 15486 StringRef str = sel.getNameForSlot(0); 15487 while (!str.empty() && str.front() == '_') str = str.substr(1); 15488 if (str.startswith("set")) 15489 str = str.substr(3); 15490 else if (str.startswith("add")) { 15491 // Specially allow 'addOperationWithBlock:'. 15492 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15493 return false; 15494 str = str.substr(3); 15495 } 15496 else 15497 return false; 15498 15499 if (str.empty()) return true; 15500 return !isLowercase(str.front()); 15501 } 15502 15503 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15504 ObjCMessageExpr *Message) { 15505 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15506 Message->getReceiverInterface(), 15507 NSAPI::ClassId_NSMutableArray); 15508 if (!IsMutableArray) { 15509 return None; 15510 } 15511 15512 Selector Sel = Message->getSelector(); 15513 15514 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15515 S.NSAPIObj->getNSArrayMethodKind(Sel); 15516 if (!MKOpt) { 15517 return None; 15518 } 15519 15520 NSAPI::NSArrayMethodKind MK = *MKOpt; 15521 15522 switch (MK) { 15523 case NSAPI::NSMutableArr_addObject: 15524 case NSAPI::NSMutableArr_insertObjectAtIndex: 15525 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15526 return 0; 15527 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15528 return 1; 15529 15530 default: 15531 return None; 15532 } 15533 15534 return None; 15535 } 15536 15537 static 15538 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15539 ObjCMessageExpr *Message) { 15540 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15541 Message->getReceiverInterface(), 15542 NSAPI::ClassId_NSMutableDictionary); 15543 if (!IsMutableDictionary) { 15544 return None; 15545 } 15546 15547 Selector Sel = Message->getSelector(); 15548 15549 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15550 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15551 if (!MKOpt) { 15552 return None; 15553 } 15554 15555 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15556 15557 switch (MK) { 15558 case NSAPI::NSMutableDict_setObjectForKey: 15559 case NSAPI::NSMutableDict_setValueForKey: 15560 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15561 return 0; 15562 15563 default: 15564 return None; 15565 } 15566 15567 return None; 15568 } 15569 15570 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15571 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15572 Message->getReceiverInterface(), 15573 NSAPI::ClassId_NSMutableSet); 15574 15575 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15576 Message->getReceiverInterface(), 15577 NSAPI::ClassId_NSMutableOrderedSet); 15578 if (!IsMutableSet && !IsMutableOrderedSet) { 15579 return None; 15580 } 15581 15582 Selector Sel = Message->getSelector(); 15583 15584 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15585 if (!MKOpt) { 15586 return None; 15587 } 15588 15589 NSAPI::NSSetMethodKind MK = *MKOpt; 15590 15591 switch (MK) { 15592 case NSAPI::NSMutableSet_addObject: 15593 case NSAPI::NSOrderedSet_setObjectAtIndex: 15594 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15595 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15596 return 0; 15597 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15598 return 1; 15599 } 15600 15601 return None; 15602 } 15603 15604 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15605 if (!Message->isInstanceMessage()) { 15606 return; 15607 } 15608 15609 Optional<int> ArgOpt; 15610 15611 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15612 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15613 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15614 return; 15615 } 15616 15617 int ArgIndex = *ArgOpt; 15618 15619 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15620 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15621 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15622 } 15623 15624 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15625 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15626 if (ArgRE->isObjCSelfExpr()) { 15627 Diag(Message->getSourceRange().getBegin(), 15628 diag::warn_objc_circular_container) 15629 << ArgRE->getDecl() << StringRef("'super'"); 15630 } 15631 } 15632 } else { 15633 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15634 15635 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15636 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15637 } 15638 15639 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15640 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15641 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15642 ValueDecl *Decl = ReceiverRE->getDecl(); 15643 Diag(Message->getSourceRange().getBegin(), 15644 diag::warn_objc_circular_container) 15645 << Decl << Decl; 15646 if (!ArgRE->isObjCSelfExpr()) { 15647 Diag(Decl->getLocation(), 15648 diag::note_objc_circular_container_declared_here) 15649 << Decl; 15650 } 15651 } 15652 } 15653 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15654 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15655 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15656 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15657 Diag(Message->getSourceRange().getBegin(), 15658 diag::warn_objc_circular_container) 15659 << Decl << Decl; 15660 Diag(Decl->getLocation(), 15661 diag::note_objc_circular_container_declared_here) 15662 << Decl; 15663 } 15664 } 15665 } 15666 } 15667 } 15668 15669 /// Check a message send to see if it's likely to cause a retain cycle. 15670 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15671 // Only check instance methods whose selector looks like a setter. 15672 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15673 return; 15674 15675 // Try to find a variable that the receiver is strongly owned by. 15676 RetainCycleOwner owner; 15677 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15678 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15679 return; 15680 } else { 15681 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15682 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15683 owner.Loc = msg->getSuperLoc(); 15684 owner.Range = msg->getSuperLoc(); 15685 } 15686 15687 // Check whether the receiver is captured by any of the arguments. 15688 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15689 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15690 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15691 // noescape blocks should not be retained by the method. 15692 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15693 continue; 15694 return diagnoseRetainCycle(*this, capturer, owner); 15695 } 15696 } 15697 } 15698 15699 /// Check a property assign to see if it's likely to cause a retain cycle. 15700 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15701 RetainCycleOwner owner; 15702 if (!findRetainCycleOwner(*this, receiver, owner)) 15703 return; 15704 15705 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15706 diagnoseRetainCycle(*this, capturer, owner); 15707 } 15708 15709 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15710 RetainCycleOwner Owner; 15711 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15712 return; 15713 15714 // Because we don't have an expression for the variable, we have to set the 15715 // location explicitly here. 15716 Owner.Loc = Var->getLocation(); 15717 Owner.Range = Var->getSourceRange(); 15718 15719 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15720 diagnoseRetainCycle(*this, Capturer, Owner); 15721 } 15722 15723 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15724 Expr *RHS, bool isProperty) { 15725 // Check if RHS is an Objective-C object literal, which also can get 15726 // immediately zapped in a weak reference. Note that we explicitly 15727 // allow ObjCStringLiterals, since those are designed to never really die. 15728 RHS = RHS->IgnoreParenImpCasts(); 15729 15730 // This enum needs to match with the 'select' in 15731 // warn_objc_arc_literal_assign (off-by-1). 15732 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15733 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15734 return false; 15735 15736 S.Diag(Loc, diag::warn_arc_literal_assign) 15737 << (unsigned) Kind 15738 << (isProperty ? 0 : 1) 15739 << RHS->getSourceRange(); 15740 15741 return true; 15742 } 15743 15744 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15745 Qualifiers::ObjCLifetime LT, 15746 Expr *RHS, bool isProperty) { 15747 // Strip off any implicit cast added to get to the one ARC-specific. 15748 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15749 if (cast->getCastKind() == CK_ARCConsumeObject) { 15750 S.Diag(Loc, diag::warn_arc_retained_assign) 15751 << (LT == Qualifiers::OCL_ExplicitNone) 15752 << (isProperty ? 0 : 1) 15753 << RHS->getSourceRange(); 15754 return true; 15755 } 15756 RHS = cast->getSubExpr(); 15757 } 15758 15759 if (LT == Qualifiers::OCL_Weak && 15760 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15761 return true; 15762 15763 return false; 15764 } 15765 15766 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15767 QualType LHS, Expr *RHS) { 15768 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15769 15770 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15771 return false; 15772 15773 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15774 return true; 15775 15776 return false; 15777 } 15778 15779 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15780 Expr *LHS, Expr *RHS) { 15781 QualType LHSType; 15782 // PropertyRef on LHS type need be directly obtained from 15783 // its declaration as it has a PseudoType. 15784 ObjCPropertyRefExpr *PRE 15785 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15786 if (PRE && !PRE->isImplicitProperty()) { 15787 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15788 if (PD) 15789 LHSType = PD->getType(); 15790 } 15791 15792 if (LHSType.isNull()) 15793 LHSType = LHS->getType(); 15794 15795 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15796 15797 if (LT == Qualifiers::OCL_Weak) { 15798 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15799 getCurFunction()->markSafeWeakUse(LHS); 15800 } 15801 15802 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15803 return; 15804 15805 // FIXME. Check for other life times. 15806 if (LT != Qualifiers::OCL_None) 15807 return; 15808 15809 if (PRE) { 15810 if (PRE->isImplicitProperty()) 15811 return; 15812 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15813 if (!PD) 15814 return; 15815 15816 unsigned Attributes = PD->getPropertyAttributes(); 15817 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15818 // when 'assign' attribute was not explicitly specified 15819 // by user, ignore it and rely on property type itself 15820 // for lifetime info. 15821 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15822 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15823 LHSType->isObjCRetainableType()) 15824 return; 15825 15826 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15827 if (cast->getCastKind() == CK_ARCConsumeObject) { 15828 Diag(Loc, diag::warn_arc_retained_property_assign) 15829 << RHS->getSourceRange(); 15830 return; 15831 } 15832 RHS = cast->getSubExpr(); 15833 } 15834 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15835 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15836 return; 15837 } 15838 } 15839 } 15840 15841 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15842 15843 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15844 SourceLocation StmtLoc, 15845 const NullStmt *Body) { 15846 // Do not warn if the body is a macro that expands to nothing, e.g: 15847 // 15848 // #define CALL(x) 15849 // if (condition) 15850 // CALL(0); 15851 if (Body->hasLeadingEmptyMacro()) 15852 return false; 15853 15854 // Get line numbers of statement and body. 15855 bool StmtLineInvalid; 15856 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15857 &StmtLineInvalid); 15858 if (StmtLineInvalid) 15859 return false; 15860 15861 bool BodyLineInvalid; 15862 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15863 &BodyLineInvalid); 15864 if (BodyLineInvalid) 15865 return false; 15866 15867 // Warn if null statement and body are on the same line. 15868 if (StmtLine != BodyLine) 15869 return false; 15870 15871 return true; 15872 } 15873 15874 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15875 const Stmt *Body, 15876 unsigned DiagID) { 15877 // Since this is a syntactic check, don't emit diagnostic for template 15878 // instantiations, this just adds noise. 15879 if (CurrentInstantiationScope) 15880 return; 15881 15882 // The body should be a null statement. 15883 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15884 if (!NBody) 15885 return; 15886 15887 // Do the usual checks. 15888 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15889 return; 15890 15891 Diag(NBody->getSemiLoc(), DiagID); 15892 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15893 } 15894 15895 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15896 const Stmt *PossibleBody) { 15897 assert(!CurrentInstantiationScope); // Ensured by caller 15898 15899 SourceLocation StmtLoc; 15900 const Stmt *Body; 15901 unsigned DiagID; 15902 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15903 StmtLoc = FS->getRParenLoc(); 15904 Body = FS->getBody(); 15905 DiagID = diag::warn_empty_for_body; 15906 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15907 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15908 Body = WS->getBody(); 15909 DiagID = diag::warn_empty_while_body; 15910 } else 15911 return; // Neither `for' nor `while'. 15912 15913 // The body should be a null statement. 15914 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15915 if (!NBody) 15916 return; 15917 15918 // Skip expensive checks if diagnostic is disabled. 15919 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15920 return; 15921 15922 // Do the usual checks. 15923 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15924 return; 15925 15926 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15927 // noise level low, emit diagnostics only if for/while is followed by a 15928 // CompoundStmt, e.g.: 15929 // for (int i = 0; i < n; i++); 15930 // { 15931 // a(i); 15932 // } 15933 // or if for/while is followed by a statement with more indentation 15934 // than for/while itself: 15935 // for (int i = 0; i < n; i++); 15936 // a(i); 15937 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15938 if (!ProbableTypo) { 15939 bool BodyColInvalid; 15940 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15941 PossibleBody->getBeginLoc(), &BodyColInvalid); 15942 if (BodyColInvalid) 15943 return; 15944 15945 bool StmtColInvalid; 15946 unsigned StmtCol = 15947 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15948 if (StmtColInvalid) 15949 return; 15950 15951 if (BodyCol > StmtCol) 15952 ProbableTypo = true; 15953 } 15954 15955 if (ProbableTypo) { 15956 Diag(NBody->getSemiLoc(), DiagID); 15957 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15958 } 15959 } 15960 15961 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15962 15963 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15964 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15965 SourceLocation OpLoc) { 15966 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15967 return; 15968 15969 if (inTemplateInstantiation()) 15970 return; 15971 15972 // Strip parens and casts away. 15973 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15974 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15975 15976 // Check for a call expression 15977 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15978 if (!CE || CE->getNumArgs() != 1) 15979 return; 15980 15981 // Check for a call to std::move 15982 if (!CE->isCallToStdMove()) 15983 return; 15984 15985 // Get argument from std::move 15986 RHSExpr = CE->getArg(0); 15987 15988 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15989 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15990 15991 // Two DeclRefExpr's, check that the decls are the same. 15992 if (LHSDeclRef && RHSDeclRef) { 15993 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15994 return; 15995 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15996 RHSDeclRef->getDecl()->getCanonicalDecl()) 15997 return; 15998 15999 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16000 << LHSExpr->getSourceRange() 16001 << RHSExpr->getSourceRange(); 16002 return; 16003 } 16004 16005 // Member variables require a different approach to check for self moves. 16006 // MemberExpr's are the same if every nested MemberExpr refers to the same 16007 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16008 // the base Expr's are CXXThisExpr's. 16009 const Expr *LHSBase = LHSExpr; 16010 const Expr *RHSBase = RHSExpr; 16011 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16012 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16013 if (!LHSME || !RHSME) 16014 return; 16015 16016 while (LHSME && RHSME) { 16017 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16018 RHSME->getMemberDecl()->getCanonicalDecl()) 16019 return; 16020 16021 LHSBase = LHSME->getBase(); 16022 RHSBase = RHSME->getBase(); 16023 LHSME = dyn_cast<MemberExpr>(LHSBase); 16024 RHSME = dyn_cast<MemberExpr>(RHSBase); 16025 } 16026 16027 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16028 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16029 if (LHSDeclRef && RHSDeclRef) { 16030 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16031 return; 16032 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16033 RHSDeclRef->getDecl()->getCanonicalDecl()) 16034 return; 16035 16036 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16037 << LHSExpr->getSourceRange() 16038 << RHSExpr->getSourceRange(); 16039 return; 16040 } 16041 16042 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16043 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16044 << LHSExpr->getSourceRange() 16045 << RHSExpr->getSourceRange(); 16046 } 16047 16048 //===--- Layout compatibility ----------------------------------------------// 16049 16050 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16051 16052 /// Check if two enumeration types are layout-compatible. 16053 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16054 // C++11 [dcl.enum] p8: 16055 // Two enumeration types are layout-compatible if they have the same 16056 // underlying type. 16057 return ED1->isComplete() && ED2->isComplete() && 16058 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16059 } 16060 16061 /// Check if two fields are layout-compatible. 16062 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16063 FieldDecl *Field2) { 16064 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16065 return false; 16066 16067 if (Field1->isBitField() != Field2->isBitField()) 16068 return false; 16069 16070 if (Field1->isBitField()) { 16071 // Make sure that the bit-fields are the same length. 16072 unsigned Bits1 = Field1->getBitWidthValue(C); 16073 unsigned Bits2 = Field2->getBitWidthValue(C); 16074 16075 if (Bits1 != Bits2) 16076 return false; 16077 } 16078 16079 return true; 16080 } 16081 16082 /// Check if two standard-layout structs are layout-compatible. 16083 /// (C++11 [class.mem] p17) 16084 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16085 RecordDecl *RD2) { 16086 // If both records are C++ classes, check that base classes match. 16087 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16088 // If one of records is a CXXRecordDecl we are in C++ mode, 16089 // thus the other one is a CXXRecordDecl, too. 16090 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16091 // Check number of base classes. 16092 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16093 return false; 16094 16095 // Check the base classes. 16096 for (CXXRecordDecl::base_class_const_iterator 16097 Base1 = D1CXX->bases_begin(), 16098 BaseEnd1 = D1CXX->bases_end(), 16099 Base2 = D2CXX->bases_begin(); 16100 Base1 != BaseEnd1; 16101 ++Base1, ++Base2) { 16102 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16103 return false; 16104 } 16105 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16106 // If only RD2 is a C++ class, it should have zero base classes. 16107 if (D2CXX->getNumBases() > 0) 16108 return false; 16109 } 16110 16111 // Check the fields. 16112 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16113 Field2End = RD2->field_end(), 16114 Field1 = RD1->field_begin(), 16115 Field1End = RD1->field_end(); 16116 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16117 if (!isLayoutCompatible(C, *Field1, *Field2)) 16118 return false; 16119 } 16120 if (Field1 != Field1End || Field2 != Field2End) 16121 return false; 16122 16123 return true; 16124 } 16125 16126 /// Check if two standard-layout unions are layout-compatible. 16127 /// (C++11 [class.mem] p18) 16128 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16129 RecordDecl *RD2) { 16130 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16131 for (auto *Field2 : RD2->fields()) 16132 UnmatchedFields.insert(Field2); 16133 16134 for (auto *Field1 : RD1->fields()) { 16135 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16136 I = UnmatchedFields.begin(), 16137 E = UnmatchedFields.end(); 16138 16139 for ( ; I != E; ++I) { 16140 if (isLayoutCompatible(C, Field1, *I)) { 16141 bool Result = UnmatchedFields.erase(*I); 16142 (void) Result; 16143 assert(Result); 16144 break; 16145 } 16146 } 16147 if (I == E) 16148 return false; 16149 } 16150 16151 return UnmatchedFields.empty(); 16152 } 16153 16154 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16155 RecordDecl *RD2) { 16156 if (RD1->isUnion() != RD2->isUnion()) 16157 return false; 16158 16159 if (RD1->isUnion()) 16160 return isLayoutCompatibleUnion(C, RD1, RD2); 16161 else 16162 return isLayoutCompatibleStruct(C, RD1, RD2); 16163 } 16164 16165 /// Check if two types are layout-compatible in C++11 sense. 16166 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16167 if (T1.isNull() || T2.isNull()) 16168 return false; 16169 16170 // C++11 [basic.types] p11: 16171 // If two types T1 and T2 are the same type, then T1 and T2 are 16172 // layout-compatible types. 16173 if (C.hasSameType(T1, T2)) 16174 return true; 16175 16176 T1 = T1.getCanonicalType().getUnqualifiedType(); 16177 T2 = T2.getCanonicalType().getUnqualifiedType(); 16178 16179 const Type::TypeClass TC1 = T1->getTypeClass(); 16180 const Type::TypeClass TC2 = T2->getTypeClass(); 16181 16182 if (TC1 != TC2) 16183 return false; 16184 16185 if (TC1 == Type::Enum) { 16186 return isLayoutCompatible(C, 16187 cast<EnumType>(T1)->getDecl(), 16188 cast<EnumType>(T2)->getDecl()); 16189 } else if (TC1 == Type::Record) { 16190 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16191 return false; 16192 16193 return isLayoutCompatible(C, 16194 cast<RecordType>(T1)->getDecl(), 16195 cast<RecordType>(T2)->getDecl()); 16196 } 16197 16198 return false; 16199 } 16200 16201 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16202 16203 /// Given a type tag expression find the type tag itself. 16204 /// 16205 /// \param TypeExpr Type tag expression, as it appears in user's code. 16206 /// 16207 /// \param VD Declaration of an identifier that appears in a type tag. 16208 /// 16209 /// \param MagicValue Type tag magic value. 16210 /// 16211 /// \param isConstantEvaluated whether the evalaution should be performed in 16212 16213 /// constant context. 16214 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16215 const ValueDecl **VD, uint64_t *MagicValue, 16216 bool isConstantEvaluated) { 16217 while(true) { 16218 if (!TypeExpr) 16219 return false; 16220 16221 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16222 16223 switch (TypeExpr->getStmtClass()) { 16224 case Stmt::UnaryOperatorClass: { 16225 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16226 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16227 TypeExpr = UO->getSubExpr(); 16228 continue; 16229 } 16230 return false; 16231 } 16232 16233 case Stmt::DeclRefExprClass: { 16234 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16235 *VD = DRE->getDecl(); 16236 return true; 16237 } 16238 16239 case Stmt::IntegerLiteralClass: { 16240 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16241 llvm::APInt MagicValueAPInt = IL->getValue(); 16242 if (MagicValueAPInt.getActiveBits() <= 64) { 16243 *MagicValue = MagicValueAPInt.getZExtValue(); 16244 return true; 16245 } else 16246 return false; 16247 } 16248 16249 case Stmt::BinaryConditionalOperatorClass: 16250 case Stmt::ConditionalOperatorClass: { 16251 const AbstractConditionalOperator *ACO = 16252 cast<AbstractConditionalOperator>(TypeExpr); 16253 bool Result; 16254 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16255 isConstantEvaluated)) { 16256 if (Result) 16257 TypeExpr = ACO->getTrueExpr(); 16258 else 16259 TypeExpr = ACO->getFalseExpr(); 16260 continue; 16261 } 16262 return false; 16263 } 16264 16265 case Stmt::BinaryOperatorClass: { 16266 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16267 if (BO->getOpcode() == BO_Comma) { 16268 TypeExpr = BO->getRHS(); 16269 continue; 16270 } 16271 return false; 16272 } 16273 16274 default: 16275 return false; 16276 } 16277 } 16278 } 16279 16280 /// Retrieve the C type corresponding to type tag TypeExpr. 16281 /// 16282 /// \param TypeExpr Expression that specifies a type tag. 16283 /// 16284 /// \param MagicValues Registered magic values. 16285 /// 16286 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16287 /// kind. 16288 /// 16289 /// \param TypeInfo Information about the corresponding C type. 16290 /// 16291 /// \param isConstantEvaluated whether the evalaution should be performed in 16292 /// constant context. 16293 /// 16294 /// \returns true if the corresponding C type was found. 16295 static bool GetMatchingCType( 16296 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16297 const ASTContext &Ctx, 16298 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16299 *MagicValues, 16300 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16301 bool isConstantEvaluated) { 16302 FoundWrongKind = false; 16303 16304 // Variable declaration that has type_tag_for_datatype attribute. 16305 const ValueDecl *VD = nullptr; 16306 16307 uint64_t MagicValue; 16308 16309 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16310 return false; 16311 16312 if (VD) { 16313 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16314 if (I->getArgumentKind() != ArgumentKind) { 16315 FoundWrongKind = true; 16316 return false; 16317 } 16318 TypeInfo.Type = I->getMatchingCType(); 16319 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16320 TypeInfo.MustBeNull = I->getMustBeNull(); 16321 return true; 16322 } 16323 return false; 16324 } 16325 16326 if (!MagicValues) 16327 return false; 16328 16329 llvm::DenseMap<Sema::TypeTagMagicValue, 16330 Sema::TypeTagData>::const_iterator I = 16331 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16332 if (I == MagicValues->end()) 16333 return false; 16334 16335 TypeInfo = I->second; 16336 return true; 16337 } 16338 16339 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16340 uint64_t MagicValue, QualType Type, 16341 bool LayoutCompatible, 16342 bool MustBeNull) { 16343 if (!TypeTagForDatatypeMagicValues) 16344 TypeTagForDatatypeMagicValues.reset( 16345 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16346 16347 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16348 (*TypeTagForDatatypeMagicValues)[Magic] = 16349 TypeTagData(Type, LayoutCompatible, MustBeNull); 16350 } 16351 16352 static bool IsSameCharType(QualType T1, QualType T2) { 16353 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16354 if (!BT1) 16355 return false; 16356 16357 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16358 if (!BT2) 16359 return false; 16360 16361 BuiltinType::Kind T1Kind = BT1->getKind(); 16362 BuiltinType::Kind T2Kind = BT2->getKind(); 16363 16364 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16365 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16366 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16367 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16368 } 16369 16370 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16371 const ArrayRef<const Expr *> ExprArgs, 16372 SourceLocation CallSiteLoc) { 16373 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16374 bool IsPointerAttr = Attr->getIsPointer(); 16375 16376 // Retrieve the argument representing the 'type_tag'. 16377 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16378 if (TypeTagIdxAST >= ExprArgs.size()) { 16379 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16380 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16381 return; 16382 } 16383 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16384 bool FoundWrongKind; 16385 TypeTagData TypeInfo; 16386 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16387 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16388 TypeInfo, isConstantEvaluated())) { 16389 if (FoundWrongKind) 16390 Diag(TypeTagExpr->getExprLoc(), 16391 diag::warn_type_tag_for_datatype_wrong_kind) 16392 << TypeTagExpr->getSourceRange(); 16393 return; 16394 } 16395 16396 // Retrieve the argument representing the 'arg_idx'. 16397 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16398 if (ArgumentIdxAST >= ExprArgs.size()) { 16399 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16400 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16401 return; 16402 } 16403 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16404 if (IsPointerAttr) { 16405 // Skip implicit cast of pointer to `void *' (as a function argument). 16406 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16407 if (ICE->getType()->isVoidPointerType() && 16408 ICE->getCastKind() == CK_BitCast) 16409 ArgumentExpr = ICE->getSubExpr(); 16410 } 16411 QualType ArgumentType = ArgumentExpr->getType(); 16412 16413 // Passing a `void*' pointer shouldn't trigger a warning. 16414 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16415 return; 16416 16417 if (TypeInfo.MustBeNull) { 16418 // Type tag with matching void type requires a null pointer. 16419 if (!ArgumentExpr->isNullPointerConstant(Context, 16420 Expr::NPC_ValueDependentIsNotNull)) { 16421 Diag(ArgumentExpr->getExprLoc(), 16422 diag::warn_type_safety_null_pointer_required) 16423 << ArgumentKind->getName() 16424 << ArgumentExpr->getSourceRange() 16425 << TypeTagExpr->getSourceRange(); 16426 } 16427 return; 16428 } 16429 16430 QualType RequiredType = TypeInfo.Type; 16431 if (IsPointerAttr) 16432 RequiredType = Context.getPointerType(RequiredType); 16433 16434 bool mismatch = false; 16435 if (!TypeInfo.LayoutCompatible) { 16436 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16437 16438 // C++11 [basic.fundamental] p1: 16439 // Plain char, signed char, and unsigned char are three distinct types. 16440 // 16441 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16442 // char' depending on the current char signedness mode. 16443 if (mismatch) 16444 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16445 RequiredType->getPointeeType())) || 16446 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16447 mismatch = false; 16448 } else 16449 if (IsPointerAttr) 16450 mismatch = !isLayoutCompatible(Context, 16451 ArgumentType->getPointeeType(), 16452 RequiredType->getPointeeType()); 16453 else 16454 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16455 16456 if (mismatch) 16457 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16458 << ArgumentType << ArgumentKind 16459 << TypeInfo.LayoutCompatible << RequiredType 16460 << ArgumentExpr->getSourceRange() 16461 << TypeTagExpr->getSourceRange(); 16462 } 16463 16464 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16465 CharUnits Alignment) { 16466 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16467 } 16468 16469 void Sema::DiagnoseMisalignedMembers() { 16470 for (MisalignedMember &m : MisalignedMembers) { 16471 const NamedDecl *ND = m.RD; 16472 if (ND->getName().empty()) { 16473 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16474 ND = TD; 16475 } 16476 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16477 << m.MD << ND << m.E->getSourceRange(); 16478 } 16479 MisalignedMembers.clear(); 16480 } 16481 16482 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16483 E = E->IgnoreParens(); 16484 if (!T->isPointerType() && !T->isIntegerType()) 16485 return; 16486 if (isa<UnaryOperator>(E) && 16487 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16488 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16489 if (isa<MemberExpr>(Op)) { 16490 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16491 if (MA != MisalignedMembers.end() && 16492 (T->isIntegerType() || 16493 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16494 Context.getTypeAlignInChars( 16495 T->getPointeeType()) <= MA->Alignment)))) 16496 MisalignedMembers.erase(MA); 16497 } 16498 } 16499 } 16500 16501 void Sema::RefersToMemberWithReducedAlignment( 16502 Expr *E, 16503 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16504 Action) { 16505 const auto *ME = dyn_cast<MemberExpr>(E); 16506 if (!ME) 16507 return; 16508 16509 // No need to check expressions with an __unaligned-qualified type. 16510 if (E->getType().getQualifiers().hasUnaligned()) 16511 return; 16512 16513 // For a chain of MemberExpr like "a.b.c.d" this list 16514 // will keep FieldDecl's like [d, c, b]. 16515 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16516 const MemberExpr *TopME = nullptr; 16517 bool AnyIsPacked = false; 16518 do { 16519 QualType BaseType = ME->getBase()->getType(); 16520 if (BaseType->isDependentType()) 16521 return; 16522 if (ME->isArrow()) 16523 BaseType = BaseType->getPointeeType(); 16524 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16525 if (RD->isInvalidDecl()) 16526 return; 16527 16528 ValueDecl *MD = ME->getMemberDecl(); 16529 auto *FD = dyn_cast<FieldDecl>(MD); 16530 // We do not care about non-data members. 16531 if (!FD || FD->isInvalidDecl()) 16532 return; 16533 16534 AnyIsPacked = 16535 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16536 ReverseMemberChain.push_back(FD); 16537 16538 TopME = ME; 16539 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16540 } while (ME); 16541 assert(TopME && "We did not compute a topmost MemberExpr!"); 16542 16543 // Not the scope of this diagnostic. 16544 if (!AnyIsPacked) 16545 return; 16546 16547 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16548 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16549 // TODO: The innermost base of the member expression may be too complicated. 16550 // For now, just disregard these cases. This is left for future 16551 // improvement. 16552 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16553 return; 16554 16555 // Alignment expected by the whole expression. 16556 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16557 16558 // No need to do anything else with this case. 16559 if (ExpectedAlignment.isOne()) 16560 return; 16561 16562 // Synthesize offset of the whole access. 16563 CharUnits Offset; 16564 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16565 I++) { 16566 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16567 } 16568 16569 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16570 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16571 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16572 16573 // The base expression of the innermost MemberExpr may give 16574 // stronger guarantees than the class containing the member. 16575 if (DRE && !TopME->isArrow()) { 16576 const ValueDecl *VD = DRE->getDecl(); 16577 if (!VD->getType()->isReferenceType()) 16578 CompleteObjectAlignment = 16579 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16580 } 16581 16582 // Check if the synthesized offset fulfills the alignment. 16583 if (Offset % ExpectedAlignment != 0 || 16584 // It may fulfill the offset it but the effective alignment may still be 16585 // lower than the expected expression alignment. 16586 CompleteObjectAlignment < ExpectedAlignment) { 16587 // If this happens, we want to determine a sensible culprit of this. 16588 // Intuitively, watching the chain of member expressions from right to 16589 // left, we start with the required alignment (as required by the field 16590 // type) but some packed attribute in that chain has reduced the alignment. 16591 // It may happen that another packed structure increases it again. But if 16592 // we are here such increase has not been enough. So pointing the first 16593 // FieldDecl that either is packed or else its RecordDecl is, 16594 // seems reasonable. 16595 FieldDecl *FD = nullptr; 16596 CharUnits Alignment; 16597 for (FieldDecl *FDI : ReverseMemberChain) { 16598 if (FDI->hasAttr<PackedAttr>() || 16599 FDI->getParent()->hasAttr<PackedAttr>()) { 16600 FD = FDI; 16601 Alignment = std::min( 16602 Context.getTypeAlignInChars(FD->getType()), 16603 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16604 break; 16605 } 16606 } 16607 assert(FD && "We did not find a packed FieldDecl!"); 16608 Action(E, FD->getParent(), FD, Alignment); 16609 } 16610 } 16611 16612 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16613 using namespace std::placeholders; 16614 16615 RefersToMemberWithReducedAlignment( 16616 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16617 _2, _3, _4)); 16618 } 16619 16620 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16621 ExprResult CallResult) { 16622 if (checkArgCount(*this, TheCall, 1)) 16623 return ExprError(); 16624 16625 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16626 if (MatrixArg.isInvalid()) 16627 return MatrixArg; 16628 Expr *Matrix = MatrixArg.get(); 16629 16630 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16631 if (!MType) { 16632 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16633 return ExprError(); 16634 } 16635 16636 // Create returned matrix type by swapping rows and columns of the argument 16637 // matrix type. 16638 QualType ResultType = Context.getConstantMatrixType( 16639 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16640 16641 // Change the return type to the type of the returned matrix. 16642 TheCall->setType(ResultType); 16643 16644 // Update call argument to use the possibly converted matrix argument. 16645 TheCall->setArg(0, Matrix); 16646 return CallResult; 16647 } 16648 16649 // Get and verify the matrix dimensions. 16650 static llvm::Optional<unsigned> 16651 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16652 SourceLocation ErrorPos; 16653 Optional<llvm::APSInt> Value = 16654 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16655 if (!Value) { 16656 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16657 << Name; 16658 return {}; 16659 } 16660 uint64_t Dim = Value->getZExtValue(); 16661 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16662 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16663 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16664 return {}; 16665 } 16666 return Dim; 16667 } 16668 16669 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16670 ExprResult CallResult) { 16671 if (!getLangOpts().MatrixTypes) { 16672 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16673 return ExprError(); 16674 } 16675 16676 if (checkArgCount(*this, TheCall, 4)) 16677 return ExprError(); 16678 16679 unsigned PtrArgIdx = 0; 16680 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16681 Expr *RowsExpr = TheCall->getArg(1); 16682 Expr *ColumnsExpr = TheCall->getArg(2); 16683 Expr *StrideExpr = TheCall->getArg(3); 16684 16685 bool ArgError = false; 16686 16687 // Check pointer argument. 16688 { 16689 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16690 if (PtrConv.isInvalid()) 16691 return PtrConv; 16692 PtrExpr = PtrConv.get(); 16693 TheCall->setArg(0, PtrExpr); 16694 if (PtrExpr->isTypeDependent()) { 16695 TheCall->setType(Context.DependentTy); 16696 return TheCall; 16697 } 16698 } 16699 16700 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16701 QualType ElementTy; 16702 if (!PtrTy) { 16703 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16704 << PtrArgIdx + 1; 16705 ArgError = true; 16706 } else { 16707 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16708 16709 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16710 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16711 << PtrArgIdx + 1; 16712 ArgError = true; 16713 } 16714 } 16715 16716 // Apply default Lvalue conversions and convert the expression to size_t. 16717 auto ApplyArgumentConversions = [this](Expr *E) { 16718 ExprResult Conv = DefaultLvalueConversion(E); 16719 if (Conv.isInvalid()) 16720 return Conv; 16721 16722 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16723 }; 16724 16725 // Apply conversion to row and column expressions. 16726 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16727 if (!RowsConv.isInvalid()) { 16728 RowsExpr = RowsConv.get(); 16729 TheCall->setArg(1, RowsExpr); 16730 } else 16731 RowsExpr = nullptr; 16732 16733 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16734 if (!ColumnsConv.isInvalid()) { 16735 ColumnsExpr = ColumnsConv.get(); 16736 TheCall->setArg(2, ColumnsExpr); 16737 } else 16738 ColumnsExpr = nullptr; 16739 16740 // If any any part of the result matrix type is still pending, just use 16741 // Context.DependentTy, until all parts are resolved. 16742 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16743 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16744 TheCall->setType(Context.DependentTy); 16745 return CallResult; 16746 } 16747 16748 // Check row and column dimensions. 16749 llvm::Optional<unsigned> MaybeRows; 16750 if (RowsExpr) 16751 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16752 16753 llvm::Optional<unsigned> MaybeColumns; 16754 if (ColumnsExpr) 16755 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16756 16757 // Check stride argument. 16758 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16759 if (StrideConv.isInvalid()) 16760 return ExprError(); 16761 StrideExpr = StrideConv.get(); 16762 TheCall->setArg(3, StrideExpr); 16763 16764 if (MaybeRows) { 16765 if (Optional<llvm::APSInt> Value = 16766 StrideExpr->getIntegerConstantExpr(Context)) { 16767 uint64_t Stride = Value->getZExtValue(); 16768 if (Stride < *MaybeRows) { 16769 Diag(StrideExpr->getBeginLoc(), 16770 diag::err_builtin_matrix_stride_too_small); 16771 ArgError = true; 16772 } 16773 } 16774 } 16775 16776 if (ArgError || !MaybeRows || !MaybeColumns) 16777 return ExprError(); 16778 16779 TheCall->setType( 16780 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16781 return CallResult; 16782 } 16783 16784 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16785 ExprResult CallResult) { 16786 if (checkArgCount(*this, TheCall, 3)) 16787 return ExprError(); 16788 16789 unsigned PtrArgIdx = 1; 16790 Expr *MatrixExpr = TheCall->getArg(0); 16791 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16792 Expr *StrideExpr = TheCall->getArg(2); 16793 16794 bool ArgError = false; 16795 16796 { 16797 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16798 if (MatrixConv.isInvalid()) 16799 return MatrixConv; 16800 MatrixExpr = MatrixConv.get(); 16801 TheCall->setArg(0, MatrixExpr); 16802 } 16803 if (MatrixExpr->isTypeDependent()) { 16804 TheCall->setType(Context.DependentTy); 16805 return TheCall; 16806 } 16807 16808 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16809 if (!MatrixTy) { 16810 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16811 ArgError = true; 16812 } 16813 16814 { 16815 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16816 if (PtrConv.isInvalid()) 16817 return PtrConv; 16818 PtrExpr = PtrConv.get(); 16819 TheCall->setArg(1, PtrExpr); 16820 if (PtrExpr->isTypeDependent()) { 16821 TheCall->setType(Context.DependentTy); 16822 return TheCall; 16823 } 16824 } 16825 16826 // Check pointer argument. 16827 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16828 if (!PtrTy) { 16829 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16830 << PtrArgIdx + 1; 16831 ArgError = true; 16832 } else { 16833 QualType ElementTy = PtrTy->getPointeeType(); 16834 if (ElementTy.isConstQualified()) { 16835 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16836 ArgError = true; 16837 } 16838 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16839 if (MatrixTy && 16840 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16841 Diag(PtrExpr->getBeginLoc(), 16842 diag::err_builtin_matrix_pointer_arg_mismatch) 16843 << ElementTy << MatrixTy->getElementType(); 16844 ArgError = true; 16845 } 16846 } 16847 16848 // Apply default Lvalue conversions and convert the stride expression to 16849 // size_t. 16850 { 16851 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16852 if (StrideConv.isInvalid()) 16853 return StrideConv; 16854 16855 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16856 if (StrideConv.isInvalid()) 16857 return StrideConv; 16858 StrideExpr = StrideConv.get(); 16859 TheCall->setArg(2, StrideExpr); 16860 } 16861 16862 // Check stride argument. 16863 if (MatrixTy) { 16864 if (Optional<llvm::APSInt> Value = 16865 StrideExpr->getIntegerConstantExpr(Context)) { 16866 uint64_t Stride = Value->getZExtValue(); 16867 if (Stride < MatrixTy->getNumRows()) { 16868 Diag(StrideExpr->getBeginLoc(), 16869 diag::err_builtin_matrix_stride_too_small); 16870 ArgError = true; 16871 } 16872 } 16873 } 16874 16875 if (ArgError) 16876 return ExprError(); 16877 16878 return CallResult; 16879 } 16880 16881 /// \brief Enforce the bounds of a TCB 16882 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16883 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16884 /// and enforce_tcb_leaf attributes. 16885 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16886 const FunctionDecl *Callee) { 16887 const FunctionDecl *Caller = getCurFunctionDecl(); 16888 16889 // Calls to builtins are not enforced. 16890 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16891 Callee->getBuiltinID() != 0) 16892 return; 16893 16894 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16895 // all TCBs the callee is a part of. 16896 llvm::StringSet<> CalleeTCBs; 16897 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16898 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16899 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16900 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16901 16902 // Go through the TCBs the caller is a part of and emit warnings if Caller 16903 // is in a TCB that the Callee is not. 16904 for_each( 16905 Caller->specific_attrs<EnforceTCBAttr>(), 16906 [&](const auto *A) { 16907 StringRef CallerTCB = A->getTCBName(); 16908 if (CalleeTCBs.count(CallerTCB) == 0) { 16909 this->Diag(TheCall->getExprLoc(), 16910 diag::warn_tcb_enforcement_violation) << Callee 16911 << CallerTCB; 16912 } 16913 }); 16914 } 16915