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 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 592 /// __builtin_*_chk function, then use the object size argument specified in the 593 /// source. Otherwise, infer the object size using __builtin_object_size. 594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 595 CallExpr *TheCall) { 596 // FIXME: There are some more useful checks we could be doing here: 597 // - Evaluate strlen of strcpy arguments, use as object size. 598 599 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 600 isConstantEvaluated()) 601 return; 602 603 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 604 if (!BuiltinID) 605 return; 606 607 const TargetInfo &TI = getASTContext().getTargetInfo(); 608 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 609 610 unsigned DiagID = 0; 611 bool IsChkVariant = false; 612 Optional<llvm::APSInt> UsedSize; 613 unsigned SizeIndex, ObjectIndex; 614 switch (BuiltinID) { 615 default: 616 return; 617 case Builtin::BIsprintf: 618 case Builtin::BI__builtin___sprintf_chk: { 619 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 620 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 621 622 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 623 624 if (!Format->isAscii() && !Format->isUTF8()) 625 return; 626 627 StringRef FormatStrRef = Format->getString(); 628 EstimateSizeFormatHandler H(FormatStrRef); 629 const char *FormatBytes = FormatStrRef.data(); 630 const ConstantArrayType *T = 631 Context.getAsConstantArrayType(Format->getType()); 632 assert(T && "String literal not of constant array type!"); 633 size_t TypeSize = T->getSize().getZExtValue(); 634 635 // In case there's a null byte somewhere. 636 size_t StrLen = 637 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 638 if (!analyze_format_string::ParsePrintfString( 639 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 640 Context.getTargetInfo(), false)) { 641 DiagID = diag::warn_fortify_source_format_overflow; 642 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 643 .extOrTrunc(SizeTypeWidth); 644 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 645 IsChkVariant = true; 646 ObjectIndex = 2; 647 } else { 648 IsChkVariant = false; 649 ObjectIndex = 0; 650 } 651 break; 652 } 653 } 654 return; 655 } 656 case Builtin::BI__builtin___memcpy_chk: 657 case Builtin::BI__builtin___memmove_chk: 658 case Builtin::BI__builtin___memset_chk: 659 case Builtin::BI__builtin___strlcat_chk: 660 case Builtin::BI__builtin___strlcpy_chk: 661 case Builtin::BI__builtin___strncat_chk: 662 case Builtin::BI__builtin___strncpy_chk: 663 case Builtin::BI__builtin___stpncpy_chk: 664 case Builtin::BI__builtin___memccpy_chk: 665 case Builtin::BI__builtin___mempcpy_chk: { 666 DiagID = diag::warn_builtin_chk_overflow; 667 IsChkVariant = true; 668 SizeIndex = TheCall->getNumArgs() - 2; 669 ObjectIndex = TheCall->getNumArgs() - 1; 670 break; 671 } 672 673 case Builtin::BI__builtin___snprintf_chk: 674 case Builtin::BI__builtin___vsnprintf_chk: { 675 DiagID = diag::warn_builtin_chk_overflow; 676 IsChkVariant = true; 677 SizeIndex = 1; 678 ObjectIndex = 3; 679 break; 680 } 681 682 case Builtin::BIstrncat: 683 case Builtin::BI__builtin_strncat: 684 case Builtin::BIstrncpy: 685 case Builtin::BI__builtin_strncpy: 686 case Builtin::BIstpncpy: 687 case Builtin::BI__builtin_stpncpy: { 688 // Whether these functions overflow depends on the runtime strlen of the 689 // string, not just the buffer size, so emitting the "always overflow" 690 // diagnostic isn't quite right. We should still diagnose passing a buffer 691 // size larger than the destination buffer though; this is a runtime abort 692 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 693 DiagID = diag::warn_fortify_source_size_mismatch; 694 SizeIndex = TheCall->getNumArgs() - 1; 695 ObjectIndex = 0; 696 break; 697 } 698 699 case Builtin::BImemcpy: 700 case Builtin::BI__builtin_memcpy: 701 case Builtin::BImemmove: 702 case Builtin::BI__builtin_memmove: 703 case Builtin::BImemset: 704 case Builtin::BI__builtin_memset: 705 case Builtin::BImempcpy: 706 case Builtin::BI__builtin_mempcpy: { 707 DiagID = diag::warn_fortify_source_overflow; 708 SizeIndex = TheCall->getNumArgs() - 1; 709 ObjectIndex = 0; 710 break; 711 } 712 case Builtin::BIsnprintf: 713 case Builtin::BI__builtin_snprintf: 714 case Builtin::BIvsnprintf: 715 case Builtin::BI__builtin_vsnprintf: { 716 DiagID = diag::warn_fortify_source_size_mismatch; 717 SizeIndex = 1; 718 ObjectIndex = 0; 719 break; 720 } 721 } 722 723 llvm::APSInt ObjectSize; 724 // For __builtin___*_chk, the object size is explicitly provided by the caller 725 // (usually using __builtin_object_size). Use that value to check this call. 726 if (IsChkVariant) { 727 Expr::EvalResult Result; 728 Expr *SizeArg = TheCall->getArg(ObjectIndex); 729 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 730 return; 731 ObjectSize = Result.Val.getInt(); 732 733 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 734 } else { 735 // If the parameter has a pass_object_size attribute, then we should use its 736 // (potentially) more strict checking mode. Otherwise, conservatively assume 737 // type 0. 738 int BOSType = 0; 739 if (const auto *POS = 740 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 741 BOSType = POS->getType(); 742 743 Expr *ObjArg = TheCall->getArg(ObjectIndex); 744 uint64_t Result; 745 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 746 return; 747 // Get the object size in the target's size_t width. 748 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 749 } 750 751 // Evaluate the number of bytes of the object that this call will use. 752 if (!UsedSize) { 753 Expr::EvalResult Result; 754 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 755 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 756 return; 757 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 758 } 759 760 if (UsedSize.getValue().ule(ObjectSize)) 761 return; 762 763 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 764 // Skim off the details of whichever builtin was called to produce a better 765 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 766 if (IsChkVariant) { 767 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 768 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 769 } else if (FunctionName.startswith("__builtin_")) { 770 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 771 } 772 773 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 774 PDiag(DiagID) 775 << FunctionName << toString(ObjectSize, /*Radix=*/10) 776 << toString(UsedSize.getValue(), /*Radix=*/10)); 777 } 778 779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 780 Scope::ScopeFlags NeededScopeFlags, 781 unsigned DiagID) { 782 // Scopes aren't available during instantiation. Fortunately, builtin 783 // functions cannot be template args so they cannot be formed through template 784 // instantiation. Therefore checking once during the parse is sufficient. 785 if (SemaRef.inTemplateInstantiation()) 786 return false; 787 788 Scope *S = SemaRef.getCurScope(); 789 while (S && !S->isSEHExceptScope()) 790 S = S->getParent(); 791 if (!S || !(S->getFlags() & NeededScopeFlags)) { 792 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 793 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 794 << DRE->getDecl()->getIdentifier(); 795 return true; 796 } 797 798 return false; 799 } 800 801 static inline bool isBlockPointer(Expr *Arg) { 802 return Arg->getType()->isBlockPointerType(); 803 } 804 805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 806 /// void*, which is a requirement of device side enqueue. 807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 808 const BlockPointerType *BPT = 809 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 810 ArrayRef<QualType> Params = 811 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 812 unsigned ArgCounter = 0; 813 bool IllegalParams = false; 814 // Iterate through the block parameters until either one is found that is not 815 // a local void*, or the block is valid. 816 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 817 I != E; ++I, ++ArgCounter) { 818 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 819 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 820 LangAS::opencl_local) { 821 // Get the location of the error. If a block literal has been passed 822 // (BlockExpr) then we can point straight to the offending argument, 823 // else we just point to the variable reference. 824 SourceLocation ErrorLoc; 825 if (isa<BlockExpr>(BlockArg)) { 826 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 827 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 828 } else if (isa<DeclRefExpr>(BlockArg)) { 829 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 830 } 831 S.Diag(ErrorLoc, 832 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 833 IllegalParams = true; 834 } 835 } 836 837 return IllegalParams; 838 } 839 840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 841 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 843 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 844 return true; 845 } 846 return false; 847 } 848 849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 850 if (checkArgCount(S, TheCall, 2)) 851 return true; 852 853 if (checkOpenCLSubgroupExt(S, TheCall)) 854 return true; 855 856 // First argument is an ndrange_t type. 857 Expr *NDRangeArg = TheCall->getArg(0); 858 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 859 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 860 << TheCall->getDirectCallee() << "'ndrange_t'"; 861 return true; 862 } 863 864 Expr *BlockArg = TheCall->getArg(1); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 874 /// get_kernel_work_group_size 875 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 877 if (checkArgCount(S, TheCall, 1)) 878 return true; 879 880 Expr *BlockArg = TheCall->getArg(0); 881 if (!isBlockPointer(BlockArg)) { 882 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 883 << TheCall->getDirectCallee() << "block"; 884 return true; 885 } 886 return checkOpenCLBlockArgs(S, BlockArg); 887 } 888 889 /// Diagnose integer type and any valid implicit conversion to it. 890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 891 const QualType &IntType); 892 893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 894 unsigned Start, unsigned End) { 895 bool IllegalParams = false; 896 for (unsigned I = Start; I <= End; ++I) 897 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 898 S.Context.getSizeType()); 899 return IllegalParams; 900 } 901 902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 903 /// 'local void*' parameter of passed block. 904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 905 Expr *BlockArg, 906 unsigned NumNonVarArgs) { 907 const BlockPointerType *BPT = 908 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 909 unsigned NumBlockParams = 910 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 911 unsigned TotalNumArgs = TheCall->getNumArgs(); 912 913 // For each argument passed to the block, a corresponding uint needs to 914 // be passed to describe the size of the local memory. 915 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 916 S.Diag(TheCall->getBeginLoc(), 917 diag::err_opencl_enqueue_kernel_local_size_args); 918 return true; 919 } 920 921 // Check that the sizes of the local memory are specified by integers. 922 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 923 TotalNumArgs - 1); 924 } 925 926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 927 /// overload formats specified in Table 6.13.17.1. 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// void (^block)(void)) 932 /// int enqueue_kernel(queue_t queue, 933 /// kernel_enqueue_flags_t flags, 934 /// const ndrange_t ndrange, 935 /// uint num_events_in_wait_list, 936 /// clk_event_t *event_wait_list, 937 /// clk_event_t *event_ret, 938 /// void (^block)(void)) 939 /// int enqueue_kernel(queue_t queue, 940 /// kernel_enqueue_flags_t flags, 941 /// const ndrange_t ndrange, 942 /// void (^block)(local void*, ...), 943 /// uint size0, ...) 944 /// int enqueue_kernel(queue_t queue, 945 /// kernel_enqueue_flags_t flags, 946 /// const ndrange_t ndrange, 947 /// uint num_events_in_wait_list, 948 /// clk_event_t *event_wait_list, 949 /// clk_event_t *event_ret, 950 /// void (^block)(local void*, ...), 951 /// uint size0, ...) 952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 953 unsigned NumArgs = TheCall->getNumArgs(); 954 955 if (NumArgs < 4) { 956 S.Diag(TheCall->getBeginLoc(), 957 diag::err_typecheck_call_too_few_args_at_least) 958 << 0 << 4 << NumArgs; 959 return true; 960 } 961 962 Expr *Arg0 = TheCall->getArg(0); 963 Expr *Arg1 = TheCall->getArg(1); 964 Expr *Arg2 = TheCall->getArg(2); 965 Expr *Arg3 = TheCall->getArg(3); 966 967 // First argument always needs to be a queue_t type. 968 if (!Arg0->getType()->isQueueT()) { 969 S.Diag(TheCall->getArg(0)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 972 return true; 973 } 974 975 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 976 if (!Arg1->getType()->isIntegerType()) { 977 S.Diag(TheCall->getArg(1)->getBeginLoc(), 978 diag::err_opencl_builtin_expected_type) 979 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 980 return true; 981 } 982 983 // Third argument is always an ndrange_t type. 984 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 985 S.Diag(TheCall->getArg(2)->getBeginLoc(), 986 diag::err_opencl_builtin_expected_type) 987 << TheCall->getDirectCallee() << "'ndrange_t'"; 988 return true; 989 } 990 991 // With four arguments, there is only one form that the function could be 992 // called in: no events and no variable arguments. 993 if (NumArgs == 4) { 994 // check that the last argument is the right block type. 995 if (!isBlockPointer(Arg3)) { 996 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 997 << TheCall->getDirectCallee() << "block"; 998 return true; 999 } 1000 // we have a block type, check the prototype 1001 const BlockPointerType *BPT = 1002 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1003 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1004 S.Diag(Arg3->getBeginLoc(), 1005 diag::err_opencl_enqueue_kernel_blocks_no_args); 1006 return true; 1007 } 1008 return false; 1009 } 1010 // we can have block + varargs. 1011 if (isBlockPointer(Arg3)) 1012 return (checkOpenCLBlockArgs(S, Arg3) || 1013 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1014 // last two cases with either exactly 7 args or 7 args and varargs. 1015 if (NumArgs >= 7) { 1016 // check common block argument. 1017 Expr *Arg6 = TheCall->getArg(6); 1018 if (!isBlockPointer(Arg6)) { 1019 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1020 << TheCall->getDirectCallee() << "block"; 1021 return true; 1022 } 1023 if (checkOpenCLBlockArgs(S, Arg6)) 1024 return true; 1025 1026 // Forth argument has to be any integer type. 1027 if (!Arg3->getType()->isIntegerType()) { 1028 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1029 diag::err_opencl_builtin_expected_type) 1030 << TheCall->getDirectCallee() << "integer"; 1031 return true; 1032 } 1033 // check remaining common arguments. 1034 Expr *Arg4 = TheCall->getArg(4); 1035 Expr *Arg5 = TheCall->getArg(5); 1036 1037 // Fifth argument is always passed as a pointer to clk_event_t. 1038 if (!Arg4->isNullPointerConstant(S.Context, 1039 Expr::NPC_ValueDependentIsNotNull) && 1040 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1041 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1042 diag::err_opencl_builtin_expected_type) 1043 << TheCall->getDirectCallee() 1044 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1045 return true; 1046 } 1047 1048 // Sixth argument is always passed as a pointer to clk_event_t. 1049 if (!Arg5->isNullPointerConstant(S.Context, 1050 Expr::NPC_ValueDependentIsNotNull) && 1051 !(Arg5->getType()->isPointerType() && 1052 Arg5->getType()->getPointeeType()->isClkEventT())) { 1053 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1054 diag::err_opencl_builtin_expected_type) 1055 << TheCall->getDirectCallee() 1056 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1057 return true; 1058 } 1059 1060 if (NumArgs == 7) 1061 return false; 1062 1063 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1064 } 1065 1066 // None of the specific case has been detected, give generic error 1067 S.Diag(TheCall->getBeginLoc(), 1068 diag::err_opencl_enqueue_kernel_incorrect_args); 1069 return true; 1070 } 1071 1072 /// Returns OpenCL access qual. 1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1074 return D->getAttr<OpenCLAccessAttr>(); 1075 } 1076 1077 /// Returns true if pipe element type is different from the pointer. 1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1079 const Expr *Arg0 = Call->getArg(0); 1080 // First argument type should always be pipe. 1081 if (!Arg0->getType()->isPipeType()) { 1082 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1083 << Call->getDirectCallee() << Arg0->getSourceRange(); 1084 return true; 1085 } 1086 OpenCLAccessAttr *AccessQual = 1087 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1088 // Validates the access qualifier is compatible with the call. 1089 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1090 // read_only and write_only, and assumed to be read_only if no qualifier is 1091 // specified. 1092 switch (Call->getDirectCallee()->getBuiltinID()) { 1093 case Builtin::BIread_pipe: 1094 case Builtin::BIreserve_read_pipe: 1095 case Builtin::BIcommit_read_pipe: 1096 case Builtin::BIwork_group_reserve_read_pipe: 1097 case Builtin::BIsub_group_reserve_read_pipe: 1098 case Builtin::BIwork_group_commit_read_pipe: 1099 case Builtin::BIsub_group_commit_read_pipe: 1100 if (!(!AccessQual || AccessQual->isReadOnly())) { 1101 S.Diag(Arg0->getBeginLoc(), 1102 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1103 << "read_only" << Arg0->getSourceRange(); 1104 return true; 1105 } 1106 break; 1107 case Builtin::BIwrite_pipe: 1108 case Builtin::BIreserve_write_pipe: 1109 case Builtin::BIcommit_write_pipe: 1110 case Builtin::BIwork_group_reserve_write_pipe: 1111 case Builtin::BIsub_group_reserve_write_pipe: 1112 case Builtin::BIwork_group_commit_write_pipe: 1113 case Builtin::BIsub_group_commit_write_pipe: 1114 if (!(AccessQual && AccessQual->isWriteOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "write_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 default: 1122 break; 1123 } 1124 return false; 1125 } 1126 1127 /// Returns true if pipe element type is different from the pointer. 1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1129 const Expr *Arg0 = Call->getArg(0); 1130 const Expr *ArgIdx = Call->getArg(Idx); 1131 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1132 const QualType EltTy = PipeTy->getElementType(); 1133 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1134 // The Idx argument should be a pointer and the type of the pointer and 1135 // the type of pipe element should also be the same. 1136 if (!ArgTy || 1137 !S.Context.hasSameType( 1138 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1139 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1140 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1141 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1142 return true; 1143 } 1144 return false; 1145 } 1146 1147 // Performs semantic analysis for the read/write_pipe call. 1148 // \param S Reference to the semantic analyzer. 1149 // \param Call A pointer to the builtin call. 1150 // \return True if a semantic error has been found, false otherwise. 1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1152 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1153 // functions have two forms. 1154 switch (Call->getNumArgs()) { 1155 case 2: 1156 if (checkOpenCLPipeArg(S, Call)) 1157 return true; 1158 // The call with 2 arguments should be 1159 // read/write_pipe(pipe T, T*). 1160 // Check packet type T. 1161 if (checkOpenCLPipePacketType(S, Call, 1)) 1162 return true; 1163 break; 1164 1165 case 4: { 1166 if (checkOpenCLPipeArg(S, Call)) 1167 return true; 1168 // The call with 4 arguments should be 1169 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1170 // Check reserve_id_t. 1171 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1172 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1173 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1174 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1175 return true; 1176 } 1177 1178 // Check the index. 1179 const Expr *Arg2 = Call->getArg(2); 1180 if (!Arg2->getType()->isIntegerType() && 1181 !Arg2->getType()->isUnsignedIntegerType()) { 1182 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1183 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1184 << Arg2->getType() << Arg2->getSourceRange(); 1185 return true; 1186 } 1187 1188 // Check packet type T. 1189 if (checkOpenCLPipePacketType(S, Call, 3)) 1190 return true; 1191 } break; 1192 default: 1193 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1194 << Call->getDirectCallee() << Call->getSourceRange(); 1195 return true; 1196 } 1197 1198 return false; 1199 } 1200 1201 // Performs a semantic analysis on the {work_group_/sub_group_ 1202 // /_}reserve_{read/write}_pipe 1203 // \param S Reference to the semantic analyzer. 1204 // \param Call The call to the builtin function to be analyzed. 1205 // \return True if a semantic error was found, false otherwise. 1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1207 if (checkArgCount(S, Call, 2)) 1208 return true; 1209 1210 if (checkOpenCLPipeArg(S, Call)) 1211 return true; 1212 1213 // Check the reserve size. 1214 if (!Call->getArg(1)->getType()->isIntegerType() && 1215 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1216 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1217 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1218 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1219 return true; 1220 } 1221 1222 // Since return type of reserve_read/write_pipe built-in function is 1223 // reserve_id_t, which is not defined in the builtin def file , we used int 1224 // as return type and need to override the return type of these functions. 1225 Call->setType(S.Context.OCLReserveIDTy); 1226 1227 return false; 1228 } 1229 1230 // Performs a semantic analysis on {work_group_/sub_group_ 1231 // /_}commit_{read/write}_pipe 1232 // \param S Reference to the semantic analyzer. 1233 // \param Call The call to the builtin function to be analyzed. 1234 // \return True if a semantic error was found, false otherwise. 1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1236 if (checkArgCount(S, Call, 2)) 1237 return true; 1238 1239 if (checkOpenCLPipeArg(S, Call)) 1240 return true; 1241 1242 // Check reserve_id_t. 1243 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1244 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1245 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1246 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1247 return true; 1248 } 1249 1250 return false; 1251 } 1252 1253 // Performs a semantic analysis on the call to built-in Pipe 1254 // Query Functions. 1255 // \param S Reference to the semantic analyzer. 1256 // \param Call The call to the builtin function to be analyzed. 1257 // \return True if a semantic error was found, false otherwise. 1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1259 if (checkArgCount(S, Call, 1)) 1260 return true; 1261 1262 if (!Call->getArg(0)->getType()->isPipeType()) { 1263 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1264 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1265 return true; 1266 } 1267 1268 return false; 1269 } 1270 1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1272 // Performs semantic analysis for the to_global/local/private call. 1273 // \param S Reference to the semantic analyzer. 1274 // \param BuiltinID ID of the builtin function. 1275 // \param Call A pointer to the builtin call. 1276 // \return True if a semantic error has been found, false otherwise. 1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1278 CallExpr *Call) { 1279 if (checkArgCount(S, Call, 1)) 1280 return true; 1281 1282 auto RT = Call->getArg(0)->getType(); 1283 if (!RT->isPointerType() || RT->getPointeeType() 1284 .getAddressSpace() == LangAS::opencl_constant) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1287 return true; 1288 } 1289 1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1291 S.Diag(Call->getArg(0)->getBeginLoc(), 1292 diag::warn_opencl_generic_address_space_arg) 1293 << Call->getDirectCallee()->getNameInfo().getAsString() 1294 << Call->getArg(0)->getSourceRange(); 1295 } 1296 1297 RT = RT->getPointeeType(); 1298 auto Qual = RT.getQualifiers(); 1299 switch (BuiltinID) { 1300 case Builtin::BIto_global: 1301 Qual.setAddressSpace(LangAS::opencl_global); 1302 break; 1303 case Builtin::BIto_local: 1304 Qual.setAddressSpace(LangAS::opencl_local); 1305 break; 1306 case Builtin::BIto_private: 1307 Qual.setAddressSpace(LangAS::opencl_private); 1308 break; 1309 default: 1310 llvm_unreachable("Invalid builtin function"); 1311 } 1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1313 RT.getUnqualifiedType(), Qual))); 1314 1315 return false; 1316 } 1317 1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1319 if (checkArgCount(S, TheCall, 1)) 1320 return ExprError(); 1321 1322 // Compute __builtin_launder's parameter type from the argument. 1323 // The parameter type is: 1324 // * The type of the argument if it's not an array or function type, 1325 // Otherwise, 1326 // * The decayed argument type. 1327 QualType ParamTy = [&]() { 1328 QualType ArgTy = TheCall->getArg(0)->getType(); 1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1330 return S.Context.getPointerType(Ty->getElementType()); 1331 if (ArgTy->isFunctionType()) { 1332 return S.Context.getPointerType(ArgTy); 1333 } 1334 return ArgTy; 1335 }(); 1336 1337 TheCall->setType(ParamTy); 1338 1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1340 if (!ParamTy->isPointerType()) 1341 return 0; 1342 if (ParamTy->isFunctionPointerType()) 1343 return 1; 1344 if (ParamTy->isVoidPointerType()) 1345 return 2; 1346 return llvm::Optional<unsigned>{}; 1347 }(); 1348 if (DiagSelect.hasValue()) { 1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1350 << DiagSelect.getValue() << TheCall->getSourceRange(); 1351 return ExprError(); 1352 } 1353 1354 // We either have an incomplete class type, or we have a class template 1355 // whose instantiation has not been forced. Example: 1356 // 1357 // template <class T> struct Foo { T value; }; 1358 // Foo<int> *p = nullptr; 1359 // auto *d = __builtin_launder(p); 1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1361 diag::err_incomplete_type)) 1362 return ExprError(); 1363 1364 assert(ParamTy->getPointeeType()->isObjectType() && 1365 "Unhandled non-object pointer case"); 1366 1367 InitializedEntity Entity = 1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1369 ExprResult Arg = 1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1371 if (Arg.isInvalid()) 1372 return ExprError(); 1373 TheCall->setArg(0, Arg.get()); 1374 1375 return TheCall; 1376 } 1377 1378 // Emit an error and return true if the current architecture is not in the list 1379 // of supported architectures. 1380 static bool 1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1383 llvm::Triple::ArchType CurArch = 1384 S.getASTContext().getTargetInfo().getTriple().getArch(); 1385 if (llvm::is_contained(SupportedArchs, CurArch)) 1386 return false; 1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1388 << TheCall->getSourceRange(); 1389 return true; 1390 } 1391 1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1393 SourceLocation CallSiteLoc); 1394 1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1396 CallExpr *TheCall) { 1397 switch (TI.getTriple().getArch()) { 1398 default: 1399 // Some builtins don't require additional checking, so just consider these 1400 // acceptable. 1401 return false; 1402 case llvm::Triple::arm: 1403 case llvm::Triple::armeb: 1404 case llvm::Triple::thumb: 1405 case llvm::Triple::thumbeb: 1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1407 case llvm::Triple::aarch64: 1408 case llvm::Triple::aarch64_32: 1409 case llvm::Triple::aarch64_be: 1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1411 case llvm::Triple::bpfeb: 1412 case llvm::Triple::bpfel: 1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::hexagon: 1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1416 case llvm::Triple::mips: 1417 case llvm::Triple::mipsel: 1418 case llvm::Triple::mips64: 1419 case llvm::Triple::mips64el: 1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::systemz: 1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1423 case llvm::Triple::x86: 1424 case llvm::Triple::x86_64: 1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1426 case llvm::Triple::ppc: 1427 case llvm::Triple::ppcle: 1428 case llvm::Triple::ppc64: 1429 case llvm::Triple::ppc64le: 1430 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1431 case llvm::Triple::amdgcn: 1432 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1433 case llvm::Triple::riscv32: 1434 case llvm::Triple::riscv64: 1435 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1436 } 1437 } 1438 1439 ExprResult 1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1441 CallExpr *TheCall) { 1442 ExprResult TheCallResult(TheCall); 1443 1444 // Find out if any arguments are required to be integer constant expressions. 1445 unsigned ICEArguments = 0; 1446 ASTContext::GetBuiltinTypeError Error; 1447 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1448 if (Error != ASTContext::GE_None) 1449 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1450 1451 // If any arguments are required to be ICE's, check and diagnose. 1452 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1453 // Skip arguments not required to be ICE's. 1454 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1455 1456 llvm::APSInt Result; 1457 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1458 return true; 1459 ICEArguments &= ~(1 << ArgNo); 1460 } 1461 1462 switch (BuiltinID) { 1463 case Builtin::BI__builtin___CFStringMakeConstantString: 1464 assert(TheCall->getNumArgs() == 1 && 1465 "Wrong # arguments to builtin CFStringMakeConstantString"); 1466 if (CheckObjCString(TheCall->getArg(0))) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_ms_va_start: 1470 case Builtin::BI__builtin_stdarg_start: 1471 case Builtin::BI__builtin_va_start: 1472 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BI__va_start: { 1476 switch (Context.getTargetInfo().getTriple().getArch()) { 1477 case llvm::Triple::aarch64: 1478 case llvm::Triple::arm: 1479 case llvm::Triple::thumb: 1480 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1481 return ExprError(); 1482 break; 1483 default: 1484 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1485 return ExprError(); 1486 break; 1487 } 1488 break; 1489 } 1490 1491 // The acquire, release, and no fence variants are ARM and AArch64 only. 1492 case Builtin::BI_interlockedbittestandset_acq: 1493 case Builtin::BI_interlockedbittestandset_rel: 1494 case Builtin::BI_interlockedbittestandset_nf: 1495 case Builtin::BI_interlockedbittestandreset_acq: 1496 case Builtin::BI_interlockedbittestandreset_rel: 1497 case Builtin::BI_interlockedbittestandreset_nf: 1498 if (CheckBuiltinTargetSupport( 1499 *this, BuiltinID, TheCall, 1500 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1501 return ExprError(); 1502 break; 1503 1504 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1505 case Builtin::BI_bittest64: 1506 case Builtin::BI_bittestandcomplement64: 1507 case Builtin::BI_bittestandreset64: 1508 case Builtin::BI_bittestandset64: 1509 case Builtin::BI_interlockedbittestandreset64: 1510 case Builtin::BI_interlockedbittestandset64: 1511 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1512 {llvm::Triple::x86_64, llvm::Triple::arm, 1513 llvm::Triple::thumb, llvm::Triple::aarch64})) 1514 return ExprError(); 1515 break; 1516 1517 case Builtin::BI__builtin_isgreater: 1518 case Builtin::BI__builtin_isgreaterequal: 1519 case Builtin::BI__builtin_isless: 1520 case Builtin::BI__builtin_islessequal: 1521 case Builtin::BI__builtin_islessgreater: 1522 case Builtin::BI__builtin_isunordered: 1523 if (SemaBuiltinUnorderedCompare(TheCall)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__builtin_fpclassify: 1527 if (SemaBuiltinFPClassification(TheCall, 6)) 1528 return ExprError(); 1529 break; 1530 case Builtin::BI__builtin_isfinite: 1531 case Builtin::BI__builtin_isinf: 1532 case Builtin::BI__builtin_isinf_sign: 1533 case Builtin::BI__builtin_isnan: 1534 case Builtin::BI__builtin_isnormal: 1535 case Builtin::BI__builtin_signbit: 1536 case Builtin::BI__builtin_signbitf: 1537 case Builtin::BI__builtin_signbitl: 1538 if (SemaBuiltinFPClassification(TheCall, 1)) 1539 return ExprError(); 1540 break; 1541 case Builtin::BI__builtin_shufflevector: 1542 return SemaBuiltinShuffleVector(TheCall); 1543 // TheCall will be freed by the smart pointer here, but that's fine, since 1544 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1545 case Builtin::BI__builtin_prefetch: 1546 if (SemaBuiltinPrefetch(TheCall)) 1547 return ExprError(); 1548 break; 1549 case Builtin::BI__builtin_alloca_with_align: 1550 if (SemaBuiltinAllocaWithAlign(TheCall)) 1551 return ExprError(); 1552 LLVM_FALLTHROUGH; 1553 case Builtin::BI__builtin_alloca: 1554 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1555 << TheCall->getDirectCallee(); 1556 break; 1557 case Builtin::BI__arithmetic_fence: 1558 if (SemaBuiltinArithmeticFence(TheCall)) 1559 return ExprError(); 1560 break; 1561 case Builtin::BI__assume: 1562 case Builtin::BI__builtin_assume: 1563 if (SemaBuiltinAssume(TheCall)) 1564 return ExprError(); 1565 break; 1566 case Builtin::BI__builtin_assume_aligned: 1567 if (SemaBuiltinAssumeAligned(TheCall)) 1568 return ExprError(); 1569 break; 1570 case Builtin::BI__builtin_dynamic_object_size: 1571 case Builtin::BI__builtin_object_size: 1572 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__builtin_longjmp: 1576 if (SemaBuiltinLongjmp(TheCall)) 1577 return ExprError(); 1578 break; 1579 case Builtin::BI__builtin_setjmp: 1580 if (SemaBuiltinSetjmp(TheCall)) 1581 return ExprError(); 1582 break; 1583 case Builtin::BI__builtin_classify_type: 1584 if (checkArgCount(*this, TheCall, 1)) return true; 1585 TheCall->setType(Context.IntTy); 1586 break; 1587 case Builtin::BI__builtin_complex: 1588 if (SemaBuiltinComplex(TheCall)) 1589 return ExprError(); 1590 break; 1591 case Builtin::BI__builtin_constant_p: { 1592 if (checkArgCount(*this, TheCall, 1)) return true; 1593 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1594 if (Arg.isInvalid()) return true; 1595 TheCall->setArg(0, Arg.get()); 1596 TheCall->setType(Context.IntTy); 1597 break; 1598 } 1599 case Builtin::BI__builtin_launder: 1600 return SemaBuiltinLaunder(*this, TheCall); 1601 case Builtin::BI__sync_fetch_and_add: 1602 case Builtin::BI__sync_fetch_and_add_1: 1603 case Builtin::BI__sync_fetch_and_add_2: 1604 case Builtin::BI__sync_fetch_and_add_4: 1605 case Builtin::BI__sync_fetch_and_add_8: 1606 case Builtin::BI__sync_fetch_and_add_16: 1607 case Builtin::BI__sync_fetch_and_sub: 1608 case Builtin::BI__sync_fetch_and_sub_1: 1609 case Builtin::BI__sync_fetch_and_sub_2: 1610 case Builtin::BI__sync_fetch_and_sub_4: 1611 case Builtin::BI__sync_fetch_and_sub_8: 1612 case Builtin::BI__sync_fetch_and_sub_16: 1613 case Builtin::BI__sync_fetch_and_or: 1614 case Builtin::BI__sync_fetch_and_or_1: 1615 case Builtin::BI__sync_fetch_and_or_2: 1616 case Builtin::BI__sync_fetch_and_or_4: 1617 case Builtin::BI__sync_fetch_and_or_8: 1618 case Builtin::BI__sync_fetch_and_or_16: 1619 case Builtin::BI__sync_fetch_and_and: 1620 case Builtin::BI__sync_fetch_and_and_1: 1621 case Builtin::BI__sync_fetch_and_and_2: 1622 case Builtin::BI__sync_fetch_and_and_4: 1623 case Builtin::BI__sync_fetch_and_and_8: 1624 case Builtin::BI__sync_fetch_and_and_16: 1625 case Builtin::BI__sync_fetch_and_xor: 1626 case Builtin::BI__sync_fetch_and_xor_1: 1627 case Builtin::BI__sync_fetch_and_xor_2: 1628 case Builtin::BI__sync_fetch_and_xor_4: 1629 case Builtin::BI__sync_fetch_and_xor_8: 1630 case Builtin::BI__sync_fetch_and_xor_16: 1631 case Builtin::BI__sync_fetch_and_nand: 1632 case Builtin::BI__sync_fetch_and_nand_1: 1633 case Builtin::BI__sync_fetch_and_nand_2: 1634 case Builtin::BI__sync_fetch_and_nand_4: 1635 case Builtin::BI__sync_fetch_and_nand_8: 1636 case Builtin::BI__sync_fetch_and_nand_16: 1637 case Builtin::BI__sync_add_and_fetch: 1638 case Builtin::BI__sync_add_and_fetch_1: 1639 case Builtin::BI__sync_add_and_fetch_2: 1640 case Builtin::BI__sync_add_and_fetch_4: 1641 case Builtin::BI__sync_add_and_fetch_8: 1642 case Builtin::BI__sync_add_and_fetch_16: 1643 case Builtin::BI__sync_sub_and_fetch: 1644 case Builtin::BI__sync_sub_and_fetch_1: 1645 case Builtin::BI__sync_sub_and_fetch_2: 1646 case Builtin::BI__sync_sub_and_fetch_4: 1647 case Builtin::BI__sync_sub_and_fetch_8: 1648 case Builtin::BI__sync_sub_and_fetch_16: 1649 case Builtin::BI__sync_and_and_fetch: 1650 case Builtin::BI__sync_and_and_fetch_1: 1651 case Builtin::BI__sync_and_and_fetch_2: 1652 case Builtin::BI__sync_and_and_fetch_4: 1653 case Builtin::BI__sync_and_and_fetch_8: 1654 case Builtin::BI__sync_and_and_fetch_16: 1655 case Builtin::BI__sync_or_and_fetch: 1656 case Builtin::BI__sync_or_and_fetch_1: 1657 case Builtin::BI__sync_or_and_fetch_2: 1658 case Builtin::BI__sync_or_and_fetch_4: 1659 case Builtin::BI__sync_or_and_fetch_8: 1660 case Builtin::BI__sync_or_and_fetch_16: 1661 case Builtin::BI__sync_xor_and_fetch: 1662 case Builtin::BI__sync_xor_and_fetch_1: 1663 case Builtin::BI__sync_xor_and_fetch_2: 1664 case Builtin::BI__sync_xor_and_fetch_4: 1665 case Builtin::BI__sync_xor_and_fetch_8: 1666 case Builtin::BI__sync_xor_and_fetch_16: 1667 case Builtin::BI__sync_nand_and_fetch: 1668 case Builtin::BI__sync_nand_and_fetch_1: 1669 case Builtin::BI__sync_nand_and_fetch_2: 1670 case Builtin::BI__sync_nand_and_fetch_4: 1671 case Builtin::BI__sync_nand_and_fetch_8: 1672 case Builtin::BI__sync_nand_and_fetch_16: 1673 case Builtin::BI__sync_val_compare_and_swap: 1674 case Builtin::BI__sync_val_compare_and_swap_1: 1675 case Builtin::BI__sync_val_compare_and_swap_2: 1676 case Builtin::BI__sync_val_compare_and_swap_4: 1677 case Builtin::BI__sync_val_compare_and_swap_8: 1678 case Builtin::BI__sync_val_compare_and_swap_16: 1679 case Builtin::BI__sync_bool_compare_and_swap: 1680 case Builtin::BI__sync_bool_compare_and_swap_1: 1681 case Builtin::BI__sync_bool_compare_and_swap_2: 1682 case Builtin::BI__sync_bool_compare_and_swap_4: 1683 case Builtin::BI__sync_bool_compare_and_swap_8: 1684 case Builtin::BI__sync_bool_compare_and_swap_16: 1685 case Builtin::BI__sync_lock_test_and_set: 1686 case Builtin::BI__sync_lock_test_and_set_1: 1687 case Builtin::BI__sync_lock_test_and_set_2: 1688 case Builtin::BI__sync_lock_test_and_set_4: 1689 case Builtin::BI__sync_lock_test_and_set_8: 1690 case Builtin::BI__sync_lock_test_and_set_16: 1691 case Builtin::BI__sync_lock_release: 1692 case Builtin::BI__sync_lock_release_1: 1693 case Builtin::BI__sync_lock_release_2: 1694 case Builtin::BI__sync_lock_release_4: 1695 case Builtin::BI__sync_lock_release_8: 1696 case Builtin::BI__sync_lock_release_16: 1697 case Builtin::BI__sync_swap: 1698 case Builtin::BI__sync_swap_1: 1699 case Builtin::BI__sync_swap_2: 1700 case Builtin::BI__sync_swap_4: 1701 case Builtin::BI__sync_swap_8: 1702 case Builtin::BI__sync_swap_16: 1703 return SemaBuiltinAtomicOverloaded(TheCallResult); 1704 case Builtin::BI__sync_synchronize: 1705 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1706 << TheCall->getCallee()->getSourceRange(); 1707 break; 1708 case Builtin::BI__builtin_nontemporal_load: 1709 case Builtin::BI__builtin_nontemporal_store: 1710 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1711 case Builtin::BI__builtin_memcpy_inline: { 1712 clang::Expr *SizeOp = TheCall->getArg(2); 1713 // We warn about copying to or from `nullptr` pointers when `size` is 1714 // greater than 0. When `size` is value dependent we cannot evaluate its 1715 // value so we bail out. 1716 if (SizeOp->isValueDependent()) 1717 break; 1718 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1719 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1720 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1721 } 1722 break; 1723 } 1724 #define BUILTIN(ID, TYPE, ATTRS) 1725 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1726 case Builtin::BI##ID: \ 1727 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1728 #include "clang/Basic/Builtins.def" 1729 case Builtin::BI__annotation: 1730 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1731 return ExprError(); 1732 break; 1733 case Builtin::BI__builtin_annotation: 1734 if (SemaBuiltinAnnotation(*this, TheCall)) 1735 return ExprError(); 1736 break; 1737 case Builtin::BI__builtin_addressof: 1738 if (SemaBuiltinAddressof(*this, TheCall)) 1739 return ExprError(); 1740 break; 1741 case Builtin::BI__builtin_is_aligned: 1742 case Builtin::BI__builtin_align_up: 1743 case Builtin::BI__builtin_align_down: 1744 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_add_overflow: 1748 case Builtin::BI__builtin_sub_overflow: 1749 case Builtin::BI__builtin_mul_overflow: 1750 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1751 return ExprError(); 1752 break; 1753 case Builtin::BI__builtin_operator_new: 1754 case Builtin::BI__builtin_operator_delete: { 1755 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1756 ExprResult Res = 1757 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1758 if (Res.isInvalid()) 1759 CorrectDelayedTyposInExpr(TheCallResult.get()); 1760 return Res; 1761 } 1762 case Builtin::BI__builtin_dump_struct: { 1763 // We first want to ensure we are called with 2 arguments 1764 if (checkArgCount(*this, TheCall, 2)) 1765 return ExprError(); 1766 // Ensure that the first argument is of type 'struct XX *' 1767 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1768 const QualType PtrArgType = PtrArg->getType(); 1769 if (!PtrArgType->isPointerType() || 1770 !PtrArgType->getPointeeType()->isRecordType()) { 1771 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1772 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1773 << "structure pointer"; 1774 return ExprError(); 1775 } 1776 1777 // Ensure that the second argument is of type 'FunctionType' 1778 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1779 const QualType FnPtrArgType = FnPtrArg->getType(); 1780 if (!FnPtrArgType->isPointerType()) { 1781 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1782 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1783 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1784 return ExprError(); 1785 } 1786 1787 const auto *FuncType = 1788 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1789 1790 if (!FuncType) { 1791 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1792 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1793 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1794 return ExprError(); 1795 } 1796 1797 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1798 if (!FT->getNumParams()) { 1799 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1800 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1801 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1802 return ExprError(); 1803 } 1804 QualType PT = FT->getParamType(0); 1805 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1806 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1807 !PT->getPointeeType().isConstQualified()) { 1808 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1809 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1810 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1811 return ExprError(); 1812 } 1813 } 1814 1815 TheCall->setType(Context.IntTy); 1816 break; 1817 } 1818 case Builtin::BI__builtin_expect_with_probability: { 1819 // We first want to ensure we are called with 3 arguments 1820 if (checkArgCount(*this, TheCall, 3)) 1821 return ExprError(); 1822 // then check probability is constant float in range [0.0, 1.0] 1823 const Expr *ProbArg = TheCall->getArg(2); 1824 SmallVector<PartialDiagnosticAt, 8> Notes; 1825 Expr::EvalResult Eval; 1826 Eval.Diag = &Notes; 1827 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1828 !Eval.Val.isFloat()) { 1829 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1830 << ProbArg->getSourceRange(); 1831 for (const PartialDiagnosticAt &PDiag : Notes) 1832 Diag(PDiag.first, PDiag.second); 1833 return ExprError(); 1834 } 1835 llvm::APFloat Probability = Eval.Val.getFloat(); 1836 bool LoseInfo = false; 1837 Probability.convert(llvm::APFloat::IEEEdouble(), 1838 llvm::RoundingMode::Dynamic, &LoseInfo); 1839 if (!(Probability >= llvm::APFloat(0.0) && 1840 Probability <= llvm::APFloat(1.0))) { 1841 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1842 << ProbArg->getSourceRange(); 1843 return ExprError(); 1844 } 1845 break; 1846 } 1847 case Builtin::BI__builtin_preserve_access_index: 1848 if (SemaBuiltinPreserveAI(*this, TheCall)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__builtin_call_with_static_chain: 1852 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1853 return ExprError(); 1854 break; 1855 case Builtin::BI__exception_code: 1856 case Builtin::BI_exception_code: 1857 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1858 diag::err_seh___except_block)) 1859 return ExprError(); 1860 break; 1861 case Builtin::BI__exception_info: 1862 case Builtin::BI_exception_info: 1863 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1864 diag::err_seh___except_filter)) 1865 return ExprError(); 1866 break; 1867 case Builtin::BI__GetExceptionInfo: 1868 if (checkArgCount(*this, TheCall, 1)) 1869 return ExprError(); 1870 1871 if (CheckCXXThrowOperand( 1872 TheCall->getBeginLoc(), 1873 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1874 TheCall)) 1875 return ExprError(); 1876 1877 TheCall->setType(Context.VoidPtrTy); 1878 break; 1879 // OpenCL v2.0, s6.13.16 - Pipe functions 1880 case Builtin::BIread_pipe: 1881 case Builtin::BIwrite_pipe: 1882 // Since those two functions are declared with var args, we need a semantic 1883 // check for the argument. 1884 if (SemaBuiltinRWPipe(*this, TheCall)) 1885 return ExprError(); 1886 break; 1887 case Builtin::BIreserve_read_pipe: 1888 case Builtin::BIreserve_write_pipe: 1889 case Builtin::BIwork_group_reserve_read_pipe: 1890 case Builtin::BIwork_group_reserve_write_pipe: 1891 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1892 return ExprError(); 1893 break; 1894 case Builtin::BIsub_group_reserve_read_pipe: 1895 case Builtin::BIsub_group_reserve_write_pipe: 1896 if (checkOpenCLSubgroupExt(*this, TheCall) || 1897 SemaBuiltinReserveRWPipe(*this, TheCall)) 1898 return ExprError(); 1899 break; 1900 case Builtin::BIcommit_read_pipe: 1901 case Builtin::BIcommit_write_pipe: 1902 case Builtin::BIwork_group_commit_read_pipe: 1903 case Builtin::BIwork_group_commit_write_pipe: 1904 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1905 return ExprError(); 1906 break; 1907 case Builtin::BIsub_group_commit_read_pipe: 1908 case Builtin::BIsub_group_commit_write_pipe: 1909 if (checkOpenCLSubgroupExt(*this, TheCall) || 1910 SemaBuiltinCommitRWPipe(*this, TheCall)) 1911 return ExprError(); 1912 break; 1913 case Builtin::BIget_pipe_num_packets: 1914 case Builtin::BIget_pipe_max_packets: 1915 if (SemaBuiltinPipePackets(*this, TheCall)) 1916 return ExprError(); 1917 break; 1918 case Builtin::BIto_global: 1919 case Builtin::BIto_local: 1920 case Builtin::BIto_private: 1921 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1922 return ExprError(); 1923 break; 1924 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1925 case Builtin::BIenqueue_kernel: 1926 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1927 return ExprError(); 1928 break; 1929 case Builtin::BIget_kernel_work_group_size: 1930 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1931 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1932 return ExprError(); 1933 break; 1934 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1935 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1936 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1937 return ExprError(); 1938 break; 1939 case Builtin::BI__builtin_os_log_format: 1940 Cleanup.setExprNeedsCleanups(true); 1941 LLVM_FALLTHROUGH; 1942 case Builtin::BI__builtin_os_log_format_buffer_size: 1943 if (SemaBuiltinOSLogFormat(TheCall)) 1944 return ExprError(); 1945 break; 1946 case Builtin::BI__builtin_frame_address: 1947 case Builtin::BI__builtin_return_address: { 1948 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1949 return ExprError(); 1950 1951 // -Wframe-address warning if non-zero passed to builtin 1952 // return/frame address. 1953 Expr::EvalResult Result; 1954 if (!TheCall->getArg(0)->isValueDependent() && 1955 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1956 Result.Val.getInt() != 0) 1957 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1958 << ((BuiltinID == Builtin::BI__builtin_return_address) 1959 ? "__builtin_return_address" 1960 : "__builtin_frame_address") 1961 << TheCall->getSourceRange(); 1962 break; 1963 } 1964 1965 case Builtin::BI__builtin_matrix_transpose: 1966 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1967 1968 case Builtin::BI__builtin_matrix_column_major_load: 1969 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1970 1971 case Builtin::BI__builtin_matrix_column_major_store: 1972 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1973 1974 case Builtin::BI__builtin_get_device_side_mangled_name: { 1975 auto Check = [](CallExpr *TheCall) { 1976 if (TheCall->getNumArgs() != 1) 1977 return false; 1978 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1979 if (!DRE) 1980 return false; 1981 auto *D = DRE->getDecl(); 1982 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1983 return false; 1984 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1985 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 1986 }; 1987 if (!Check(TheCall)) { 1988 Diag(TheCall->getBeginLoc(), 1989 diag::err_hip_invalid_args_builtin_mangled_name); 1990 return ExprError(); 1991 } 1992 } 1993 } 1994 1995 // Since the target specific builtins for each arch overlap, only check those 1996 // of the arch we are compiling for. 1997 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1998 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1999 assert(Context.getAuxTargetInfo() && 2000 "Aux Target Builtin, but not an aux target?"); 2001 2002 if (CheckTSBuiltinFunctionCall( 2003 *Context.getAuxTargetInfo(), 2004 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2005 return ExprError(); 2006 } else { 2007 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2008 TheCall)) 2009 return ExprError(); 2010 } 2011 } 2012 2013 return TheCallResult; 2014 } 2015 2016 // Get the valid immediate range for the specified NEON type code. 2017 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2018 NeonTypeFlags Type(t); 2019 int IsQuad = ForceQuad ? true : Type.isQuad(); 2020 switch (Type.getEltType()) { 2021 case NeonTypeFlags::Int8: 2022 case NeonTypeFlags::Poly8: 2023 return shift ? 7 : (8 << IsQuad) - 1; 2024 case NeonTypeFlags::Int16: 2025 case NeonTypeFlags::Poly16: 2026 return shift ? 15 : (4 << IsQuad) - 1; 2027 case NeonTypeFlags::Int32: 2028 return shift ? 31 : (2 << IsQuad) - 1; 2029 case NeonTypeFlags::Int64: 2030 case NeonTypeFlags::Poly64: 2031 return shift ? 63 : (1 << IsQuad) - 1; 2032 case NeonTypeFlags::Poly128: 2033 return shift ? 127 : (1 << IsQuad) - 1; 2034 case NeonTypeFlags::Float16: 2035 assert(!shift && "cannot shift float types!"); 2036 return (4 << IsQuad) - 1; 2037 case NeonTypeFlags::Float32: 2038 assert(!shift && "cannot shift float types!"); 2039 return (2 << IsQuad) - 1; 2040 case NeonTypeFlags::Float64: 2041 assert(!shift && "cannot shift float types!"); 2042 return (1 << IsQuad) - 1; 2043 case NeonTypeFlags::BFloat16: 2044 assert(!shift && "cannot shift float types!"); 2045 return (4 << IsQuad) - 1; 2046 } 2047 llvm_unreachable("Invalid NeonTypeFlag!"); 2048 } 2049 2050 /// getNeonEltType - Return the QualType corresponding to the elements of 2051 /// the vector type specified by the NeonTypeFlags. This is used to check 2052 /// the pointer arguments for Neon load/store intrinsics. 2053 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2054 bool IsPolyUnsigned, bool IsInt64Long) { 2055 switch (Flags.getEltType()) { 2056 case NeonTypeFlags::Int8: 2057 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2058 case NeonTypeFlags::Int16: 2059 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2060 case NeonTypeFlags::Int32: 2061 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2062 case NeonTypeFlags::Int64: 2063 if (IsInt64Long) 2064 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2065 else 2066 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2067 : Context.LongLongTy; 2068 case NeonTypeFlags::Poly8: 2069 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2070 case NeonTypeFlags::Poly16: 2071 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2072 case NeonTypeFlags::Poly64: 2073 if (IsInt64Long) 2074 return Context.UnsignedLongTy; 2075 else 2076 return Context.UnsignedLongLongTy; 2077 case NeonTypeFlags::Poly128: 2078 break; 2079 case NeonTypeFlags::Float16: 2080 return Context.HalfTy; 2081 case NeonTypeFlags::Float32: 2082 return Context.FloatTy; 2083 case NeonTypeFlags::Float64: 2084 return Context.DoubleTy; 2085 case NeonTypeFlags::BFloat16: 2086 return Context.BFloat16Ty; 2087 } 2088 llvm_unreachable("Invalid NeonTypeFlag!"); 2089 } 2090 2091 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2092 // Range check SVE intrinsics that take immediate values. 2093 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2094 2095 switch (BuiltinID) { 2096 default: 2097 return false; 2098 #define GET_SVE_IMMEDIATE_CHECK 2099 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2100 #undef GET_SVE_IMMEDIATE_CHECK 2101 } 2102 2103 // Perform all the immediate checks for this builtin call. 2104 bool HasError = false; 2105 for (auto &I : ImmChecks) { 2106 int ArgNum, CheckTy, ElementSizeInBits; 2107 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2108 2109 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2110 2111 // Function that checks whether the operand (ArgNum) is an immediate 2112 // that is one of the predefined values. 2113 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2114 int ErrDiag) -> bool { 2115 // We can't check the value of a dependent argument. 2116 Expr *Arg = TheCall->getArg(ArgNum); 2117 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2118 return false; 2119 2120 // Check constant-ness first. 2121 llvm::APSInt Imm; 2122 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2123 return true; 2124 2125 if (!CheckImm(Imm.getSExtValue())) 2126 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2127 return false; 2128 }; 2129 2130 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2131 case SVETypeFlags::ImmCheck0_31: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2133 HasError = true; 2134 break; 2135 case SVETypeFlags::ImmCheck0_13: 2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2137 HasError = true; 2138 break; 2139 case SVETypeFlags::ImmCheck1_16: 2140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2141 HasError = true; 2142 break; 2143 case SVETypeFlags::ImmCheck0_7: 2144 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2145 HasError = true; 2146 break; 2147 case SVETypeFlags::ImmCheckExtract: 2148 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2149 (2048 / ElementSizeInBits) - 1)) 2150 HasError = true; 2151 break; 2152 case SVETypeFlags::ImmCheckShiftRight: 2153 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2154 HasError = true; 2155 break; 2156 case SVETypeFlags::ImmCheckShiftRightNarrow: 2157 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2158 ElementSizeInBits / 2)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckShiftLeft: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 ElementSizeInBits - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckLaneIndex: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2168 (128 / (1 * ElementSizeInBits)) - 1)) 2169 HasError = true; 2170 break; 2171 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2172 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2173 (128 / (2 * ElementSizeInBits)) - 1)) 2174 HasError = true; 2175 break; 2176 case SVETypeFlags::ImmCheckLaneIndexDot: 2177 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2178 (128 / (4 * ElementSizeInBits)) - 1)) 2179 HasError = true; 2180 break; 2181 case SVETypeFlags::ImmCheckComplexRot90_270: 2182 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2183 diag::err_rotation_argument_to_cadd)) 2184 HasError = true; 2185 break; 2186 case SVETypeFlags::ImmCheckComplexRotAll90: 2187 if (CheckImmediateInSet( 2188 [](int64_t V) { 2189 return V == 0 || V == 90 || V == 180 || V == 270; 2190 }, 2191 diag::err_rotation_argument_to_cmla)) 2192 HasError = true; 2193 break; 2194 case SVETypeFlags::ImmCheck0_1: 2195 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2196 HasError = true; 2197 break; 2198 case SVETypeFlags::ImmCheck0_2: 2199 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2200 HasError = true; 2201 break; 2202 case SVETypeFlags::ImmCheck0_3: 2203 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2204 HasError = true; 2205 break; 2206 } 2207 } 2208 2209 return HasError; 2210 } 2211 2212 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2213 unsigned BuiltinID, CallExpr *TheCall) { 2214 llvm::APSInt Result; 2215 uint64_t mask = 0; 2216 unsigned TV = 0; 2217 int PtrArgNum = -1; 2218 bool HasConstPtr = false; 2219 switch (BuiltinID) { 2220 #define GET_NEON_OVERLOAD_CHECK 2221 #include "clang/Basic/arm_neon.inc" 2222 #include "clang/Basic/arm_fp16.inc" 2223 #undef GET_NEON_OVERLOAD_CHECK 2224 } 2225 2226 // For NEON intrinsics which are overloaded on vector element type, validate 2227 // the immediate which specifies which variant to emit. 2228 unsigned ImmArg = TheCall->getNumArgs()-1; 2229 if (mask) { 2230 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2231 return true; 2232 2233 TV = Result.getLimitedValue(64); 2234 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2235 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2236 << TheCall->getArg(ImmArg)->getSourceRange(); 2237 } 2238 2239 if (PtrArgNum >= 0) { 2240 // Check that pointer arguments have the specified type. 2241 Expr *Arg = TheCall->getArg(PtrArgNum); 2242 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2243 Arg = ICE->getSubExpr(); 2244 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2245 QualType RHSTy = RHS.get()->getType(); 2246 2247 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2248 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2249 Arch == llvm::Triple::aarch64_32 || 2250 Arch == llvm::Triple::aarch64_be; 2251 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2252 QualType EltTy = 2253 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2254 if (HasConstPtr) 2255 EltTy = EltTy.withConst(); 2256 QualType LHSTy = Context.getPointerType(EltTy); 2257 AssignConvertType ConvTy; 2258 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2259 if (RHS.isInvalid()) 2260 return true; 2261 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2262 RHS.get(), AA_Assigning)) 2263 return true; 2264 } 2265 2266 // For NEON intrinsics which take an immediate value as part of the 2267 // instruction, range check them here. 2268 unsigned i = 0, l = 0, u = 0; 2269 switch (BuiltinID) { 2270 default: 2271 return false; 2272 #define GET_NEON_IMMEDIATE_CHECK 2273 #include "clang/Basic/arm_neon.inc" 2274 #include "clang/Basic/arm_fp16.inc" 2275 #undef GET_NEON_IMMEDIATE_CHECK 2276 } 2277 2278 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2279 } 2280 2281 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2282 switch (BuiltinID) { 2283 default: 2284 return false; 2285 #include "clang/Basic/arm_mve_builtin_sema.inc" 2286 } 2287 } 2288 2289 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2290 CallExpr *TheCall) { 2291 bool Err = false; 2292 switch (BuiltinID) { 2293 default: 2294 return false; 2295 #include "clang/Basic/arm_cde_builtin_sema.inc" 2296 } 2297 2298 if (Err) 2299 return true; 2300 2301 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2302 } 2303 2304 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2305 const Expr *CoprocArg, bool WantCDE) { 2306 if (isConstantEvaluated()) 2307 return false; 2308 2309 // We can't check the value of a dependent argument. 2310 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2311 return false; 2312 2313 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2314 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2315 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2316 2317 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2318 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2319 2320 if (IsCDECoproc != WantCDE) 2321 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2322 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2323 2324 return false; 2325 } 2326 2327 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2328 unsigned MaxWidth) { 2329 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2330 BuiltinID == ARM::BI__builtin_arm_ldaex || 2331 BuiltinID == ARM::BI__builtin_arm_strex || 2332 BuiltinID == ARM::BI__builtin_arm_stlex || 2333 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2334 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2335 BuiltinID == AArch64::BI__builtin_arm_strex || 2336 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2337 "unexpected ARM builtin"); 2338 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2339 BuiltinID == ARM::BI__builtin_arm_ldaex || 2340 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2341 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2342 2343 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2344 2345 // Ensure that we have the proper number of arguments. 2346 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2347 return true; 2348 2349 // Inspect the pointer argument of the atomic builtin. This should always be 2350 // a pointer type, whose element is an integral scalar or pointer type. 2351 // Because it is a pointer type, we don't have to worry about any implicit 2352 // casts here. 2353 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2354 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2355 if (PointerArgRes.isInvalid()) 2356 return true; 2357 PointerArg = PointerArgRes.get(); 2358 2359 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2360 if (!pointerType) { 2361 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2362 << PointerArg->getType() << PointerArg->getSourceRange(); 2363 return true; 2364 } 2365 2366 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2367 // task is to insert the appropriate casts into the AST. First work out just 2368 // what the appropriate type is. 2369 QualType ValType = pointerType->getPointeeType(); 2370 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2371 if (IsLdrex) 2372 AddrType.addConst(); 2373 2374 // Issue a warning if the cast is dodgy. 2375 CastKind CastNeeded = CK_NoOp; 2376 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2377 CastNeeded = CK_BitCast; 2378 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2379 << PointerArg->getType() << Context.getPointerType(AddrType) 2380 << AA_Passing << PointerArg->getSourceRange(); 2381 } 2382 2383 // Finally, do the cast and replace the argument with the corrected version. 2384 AddrType = Context.getPointerType(AddrType); 2385 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2386 if (PointerArgRes.isInvalid()) 2387 return true; 2388 PointerArg = PointerArgRes.get(); 2389 2390 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2391 2392 // In general, we allow ints, floats and pointers to be loaded and stored. 2393 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2394 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2395 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2396 << PointerArg->getType() << PointerArg->getSourceRange(); 2397 return true; 2398 } 2399 2400 // But ARM doesn't have instructions to deal with 128-bit versions. 2401 if (Context.getTypeSize(ValType) > MaxWidth) { 2402 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2403 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2404 << PointerArg->getType() << PointerArg->getSourceRange(); 2405 return true; 2406 } 2407 2408 switch (ValType.getObjCLifetime()) { 2409 case Qualifiers::OCL_None: 2410 case Qualifiers::OCL_ExplicitNone: 2411 // okay 2412 break; 2413 2414 case Qualifiers::OCL_Weak: 2415 case Qualifiers::OCL_Strong: 2416 case Qualifiers::OCL_Autoreleasing: 2417 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2418 << ValType << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 if (IsLdrex) { 2423 TheCall->setType(ValType); 2424 return false; 2425 } 2426 2427 // Initialize the argument to be stored. 2428 ExprResult ValArg = TheCall->getArg(0); 2429 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2430 Context, ValType, /*consume*/ false); 2431 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2432 if (ValArg.isInvalid()) 2433 return true; 2434 TheCall->setArg(0, ValArg.get()); 2435 2436 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2437 // but the custom checker bypasses all default analysis. 2438 TheCall->setType(Context.IntTy); 2439 return false; 2440 } 2441 2442 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2443 CallExpr *TheCall) { 2444 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2445 BuiltinID == ARM::BI__builtin_arm_ldaex || 2446 BuiltinID == ARM::BI__builtin_arm_strex || 2447 BuiltinID == ARM::BI__builtin_arm_stlex) { 2448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2449 } 2450 2451 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2454 } 2455 2456 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2457 BuiltinID == ARM::BI__builtin_arm_wsr64) 2458 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2459 2460 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2461 BuiltinID == ARM::BI__builtin_arm_rsrp || 2462 BuiltinID == ARM::BI__builtin_arm_wsr || 2463 BuiltinID == ARM::BI__builtin_arm_wsrp) 2464 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2465 2466 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2467 return true; 2468 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2469 return true; 2470 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2471 return true; 2472 2473 // For intrinsics which take an immediate value as part of the instruction, 2474 // range check them here. 2475 // FIXME: VFP Intrinsics should error if VFP not present. 2476 switch (BuiltinID) { 2477 default: return false; 2478 case ARM::BI__builtin_arm_ssat: 2479 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2480 case ARM::BI__builtin_arm_usat: 2481 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2482 case ARM::BI__builtin_arm_ssat16: 2483 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2484 case ARM::BI__builtin_arm_usat16: 2485 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2486 case ARM::BI__builtin_arm_vcvtr_f: 2487 case ARM::BI__builtin_arm_vcvtr_d: 2488 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2489 case ARM::BI__builtin_arm_dmb: 2490 case ARM::BI__builtin_arm_dsb: 2491 case ARM::BI__builtin_arm_isb: 2492 case ARM::BI__builtin_arm_dbg: 2493 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2494 case ARM::BI__builtin_arm_cdp: 2495 case ARM::BI__builtin_arm_cdp2: 2496 case ARM::BI__builtin_arm_mcr: 2497 case ARM::BI__builtin_arm_mcr2: 2498 case ARM::BI__builtin_arm_mrc: 2499 case ARM::BI__builtin_arm_mrc2: 2500 case ARM::BI__builtin_arm_mcrr: 2501 case ARM::BI__builtin_arm_mcrr2: 2502 case ARM::BI__builtin_arm_mrrc: 2503 case ARM::BI__builtin_arm_mrrc2: 2504 case ARM::BI__builtin_arm_ldc: 2505 case ARM::BI__builtin_arm_ldcl: 2506 case ARM::BI__builtin_arm_ldc2: 2507 case ARM::BI__builtin_arm_ldc2l: 2508 case ARM::BI__builtin_arm_stc: 2509 case ARM::BI__builtin_arm_stcl: 2510 case ARM::BI__builtin_arm_stc2: 2511 case ARM::BI__builtin_arm_stc2l: 2512 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2513 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2514 /*WantCDE*/ false); 2515 } 2516 } 2517 2518 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2519 unsigned BuiltinID, 2520 CallExpr *TheCall) { 2521 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2522 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2523 BuiltinID == AArch64::BI__builtin_arm_strex || 2524 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2525 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2526 } 2527 2528 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2529 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2530 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2531 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2532 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2533 } 2534 2535 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2536 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2537 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2538 2539 // Memory Tagging Extensions (MTE) Intrinsics 2540 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2541 BuiltinID == AArch64::BI__builtin_arm_addg || 2542 BuiltinID == AArch64::BI__builtin_arm_gmi || 2543 BuiltinID == AArch64::BI__builtin_arm_ldg || 2544 BuiltinID == AArch64::BI__builtin_arm_stg || 2545 BuiltinID == AArch64::BI__builtin_arm_subp) { 2546 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2550 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2551 BuiltinID == AArch64::BI__builtin_arm_wsr || 2552 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2553 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2554 2555 // Only check the valid encoding range. Any constant in this range would be 2556 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2557 // an exception for incorrect registers. This matches MSVC behavior. 2558 if (BuiltinID == AArch64::BI_ReadStatusReg || 2559 BuiltinID == AArch64::BI_WriteStatusReg) 2560 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2561 2562 if (BuiltinID == AArch64::BI__getReg) 2563 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2564 2565 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2566 return true; 2567 2568 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2569 return true; 2570 2571 // For intrinsics which take an immediate value as part of the instruction, 2572 // range check them here. 2573 unsigned i = 0, l = 0, u = 0; 2574 switch (BuiltinID) { 2575 default: return false; 2576 case AArch64::BI__builtin_arm_dmb: 2577 case AArch64::BI__builtin_arm_dsb: 2578 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2579 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2580 } 2581 2582 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2583 } 2584 2585 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2586 if (Arg->getType()->getAsPlaceholderType()) 2587 return false; 2588 2589 // The first argument needs to be a record field access. 2590 // If it is an array element access, we delay decision 2591 // to BPF backend to check whether the access is a 2592 // field access or not. 2593 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2594 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2595 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2596 } 2597 2598 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2599 QualType VectorTy, QualType EltTy) { 2600 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2601 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2602 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2603 << Call->getSourceRange() << VectorEltTy << EltTy; 2604 return false; 2605 } 2606 return true; 2607 } 2608 2609 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2610 QualType ArgType = Arg->getType(); 2611 if (ArgType->getAsPlaceholderType()) 2612 return false; 2613 2614 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2615 // format: 2616 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2617 // 2. <type> var; 2618 // __builtin_preserve_type_info(var, flag); 2619 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2620 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2621 return false; 2622 2623 // Typedef type. 2624 if (ArgType->getAs<TypedefType>()) 2625 return true; 2626 2627 // Record type or Enum type. 2628 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2629 if (const auto *RT = Ty->getAs<RecordType>()) { 2630 if (!RT->getDecl()->getDeclName().isEmpty()) 2631 return true; 2632 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2633 if (!ET->getDecl()->getDeclName().isEmpty()) 2634 return true; 2635 } 2636 2637 return false; 2638 } 2639 2640 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2641 QualType ArgType = Arg->getType(); 2642 if (ArgType->getAsPlaceholderType()) 2643 return false; 2644 2645 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2646 // format: 2647 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2648 // flag); 2649 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2650 if (!UO) 2651 return false; 2652 2653 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2654 if (!CE) 2655 return false; 2656 if (CE->getCastKind() != CK_IntegralToPointer && 2657 CE->getCastKind() != CK_NullToPointer) 2658 return false; 2659 2660 // The integer must be from an EnumConstantDecl. 2661 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2662 if (!DR) 2663 return false; 2664 2665 const EnumConstantDecl *Enumerator = 2666 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2667 if (!Enumerator) 2668 return false; 2669 2670 // The type must be EnumType. 2671 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2672 const auto *ET = Ty->getAs<EnumType>(); 2673 if (!ET) 2674 return false; 2675 2676 // The enum value must be supported. 2677 for (auto *EDI : ET->getDecl()->enumerators()) { 2678 if (EDI == Enumerator) 2679 return true; 2680 } 2681 2682 return false; 2683 } 2684 2685 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2686 CallExpr *TheCall) { 2687 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2688 BuiltinID == BPF::BI__builtin_btf_type_id || 2689 BuiltinID == BPF::BI__builtin_preserve_type_info || 2690 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2691 "unexpected BPF builtin"); 2692 2693 if (checkArgCount(*this, TheCall, 2)) 2694 return true; 2695 2696 // The second argument needs to be a constant int 2697 Expr *Arg = TheCall->getArg(1); 2698 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2699 diag::kind kind; 2700 if (!Value) { 2701 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2702 kind = diag::err_preserve_field_info_not_const; 2703 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2704 kind = diag::err_btf_type_id_not_const; 2705 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2706 kind = diag::err_preserve_type_info_not_const; 2707 else 2708 kind = diag::err_preserve_enum_value_not_const; 2709 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2710 return true; 2711 } 2712 2713 // The first argument 2714 Arg = TheCall->getArg(0); 2715 bool InvalidArg = false; 2716 bool ReturnUnsignedInt = true; 2717 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2718 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2719 InvalidArg = true; 2720 kind = diag::err_preserve_field_info_not_field; 2721 } 2722 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2723 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2724 InvalidArg = true; 2725 kind = diag::err_preserve_type_info_invalid; 2726 } 2727 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2728 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2729 InvalidArg = true; 2730 kind = diag::err_preserve_enum_value_invalid; 2731 } 2732 ReturnUnsignedInt = false; 2733 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2734 ReturnUnsignedInt = false; 2735 } 2736 2737 if (InvalidArg) { 2738 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2739 return true; 2740 } 2741 2742 if (ReturnUnsignedInt) 2743 TheCall->setType(Context.UnsignedIntTy); 2744 else 2745 TheCall->setType(Context.UnsignedLongTy); 2746 return false; 2747 } 2748 2749 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2750 struct ArgInfo { 2751 uint8_t OpNum; 2752 bool IsSigned; 2753 uint8_t BitWidth; 2754 uint8_t Align; 2755 }; 2756 struct BuiltinInfo { 2757 unsigned BuiltinID; 2758 ArgInfo Infos[2]; 2759 }; 2760 2761 static BuiltinInfo Infos[] = { 2762 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2763 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2764 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2765 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2766 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2767 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2768 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2769 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2770 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2771 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2772 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2773 2774 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2785 2786 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2838 {{ 1, false, 6, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2846 {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2853 { 2, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2855 { 2, false, 6, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2857 { 3, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2859 { 3, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2876 {{ 2, false, 4, 0 }, 2877 { 3, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2879 {{ 2, false, 4, 0 }, 2880 { 3, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2882 {{ 2, false, 4, 0 }, 2883 { 3, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2885 {{ 2, false, 4, 0 }, 2886 { 3, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2898 { 2, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2900 { 2, false, 6, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2910 {{ 1, false, 4, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2913 {{ 1, false, 4, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2934 {{ 3, false, 1, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2939 {{ 3, false, 1, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2944 {{ 3, false, 1, 0 }} }, 2945 }; 2946 2947 // Use a dynamically initialized static to sort the table exactly once on 2948 // first run. 2949 static const bool SortOnce = 2950 (llvm::sort(Infos, 2951 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2952 return LHS.BuiltinID < RHS.BuiltinID; 2953 }), 2954 true); 2955 (void)SortOnce; 2956 2957 const BuiltinInfo *F = llvm::partition_point( 2958 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2959 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2960 return false; 2961 2962 bool Error = false; 2963 2964 for (const ArgInfo &A : F->Infos) { 2965 // Ignore empty ArgInfo elements. 2966 if (A.BitWidth == 0) 2967 continue; 2968 2969 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2970 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2971 if (!A.Align) { 2972 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2973 } else { 2974 unsigned M = 1 << A.Align; 2975 Min *= M; 2976 Max *= M; 2977 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2978 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2979 } 2980 } 2981 return Error; 2982 } 2983 2984 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2985 CallExpr *TheCall) { 2986 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2987 } 2988 2989 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2990 unsigned BuiltinID, CallExpr *TheCall) { 2991 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2992 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2993 } 2994 2995 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2996 CallExpr *TheCall) { 2997 2998 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2999 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3000 if (!TI.hasFeature("dsp")) 3001 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3002 } 3003 3004 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3005 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3006 if (!TI.hasFeature("dspr2")) 3007 return Diag(TheCall->getBeginLoc(), 3008 diag::err_mips_builtin_requires_dspr2); 3009 } 3010 3011 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3012 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3013 if (!TI.hasFeature("msa")) 3014 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3015 } 3016 3017 return false; 3018 } 3019 3020 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3021 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3022 // ordering for DSP is unspecified. MSA is ordered by the data format used 3023 // by the underlying instruction i.e., df/m, df/n and then by size. 3024 // 3025 // FIXME: The size tests here should instead be tablegen'd along with the 3026 // definitions from include/clang/Basic/BuiltinsMips.def. 3027 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3028 // be too. 3029 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3030 unsigned i = 0, l = 0, u = 0, m = 0; 3031 switch (BuiltinID) { 3032 default: return false; 3033 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3034 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3035 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3036 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3037 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3038 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3039 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3040 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3041 // df/m field. 3042 // These intrinsics take an unsigned 3 bit immediate. 3043 case Mips::BI__builtin_msa_bclri_b: 3044 case Mips::BI__builtin_msa_bnegi_b: 3045 case Mips::BI__builtin_msa_bseti_b: 3046 case Mips::BI__builtin_msa_sat_s_b: 3047 case Mips::BI__builtin_msa_sat_u_b: 3048 case Mips::BI__builtin_msa_slli_b: 3049 case Mips::BI__builtin_msa_srai_b: 3050 case Mips::BI__builtin_msa_srari_b: 3051 case Mips::BI__builtin_msa_srli_b: 3052 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3053 case Mips::BI__builtin_msa_binsli_b: 3054 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3055 // These intrinsics take an unsigned 4 bit immediate. 3056 case Mips::BI__builtin_msa_bclri_h: 3057 case Mips::BI__builtin_msa_bnegi_h: 3058 case Mips::BI__builtin_msa_bseti_h: 3059 case Mips::BI__builtin_msa_sat_s_h: 3060 case Mips::BI__builtin_msa_sat_u_h: 3061 case Mips::BI__builtin_msa_slli_h: 3062 case Mips::BI__builtin_msa_srai_h: 3063 case Mips::BI__builtin_msa_srari_h: 3064 case Mips::BI__builtin_msa_srli_h: 3065 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3066 case Mips::BI__builtin_msa_binsli_h: 3067 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3068 // These intrinsics take an unsigned 5 bit immediate. 3069 // The first block of intrinsics actually have an unsigned 5 bit field, 3070 // not a df/n field. 3071 case Mips::BI__builtin_msa_cfcmsa: 3072 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3073 case Mips::BI__builtin_msa_clei_u_b: 3074 case Mips::BI__builtin_msa_clei_u_h: 3075 case Mips::BI__builtin_msa_clei_u_w: 3076 case Mips::BI__builtin_msa_clei_u_d: 3077 case Mips::BI__builtin_msa_clti_u_b: 3078 case Mips::BI__builtin_msa_clti_u_h: 3079 case Mips::BI__builtin_msa_clti_u_w: 3080 case Mips::BI__builtin_msa_clti_u_d: 3081 case Mips::BI__builtin_msa_maxi_u_b: 3082 case Mips::BI__builtin_msa_maxi_u_h: 3083 case Mips::BI__builtin_msa_maxi_u_w: 3084 case Mips::BI__builtin_msa_maxi_u_d: 3085 case Mips::BI__builtin_msa_mini_u_b: 3086 case Mips::BI__builtin_msa_mini_u_h: 3087 case Mips::BI__builtin_msa_mini_u_w: 3088 case Mips::BI__builtin_msa_mini_u_d: 3089 case Mips::BI__builtin_msa_addvi_b: 3090 case Mips::BI__builtin_msa_addvi_h: 3091 case Mips::BI__builtin_msa_addvi_w: 3092 case Mips::BI__builtin_msa_addvi_d: 3093 case Mips::BI__builtin_msa_bclri_w: 3094 case Mips::BI__builtin_msa_bnegi_w: 3095 case Mips::BI__builtin_msa_bseti_w: 3096 case Mips::BI__builtin_msa_sat_s_w: 3097 case Mips::BI__builtin_msa_sat_u_w: 3098 case Mips::BI__builtin_msa_slli_w: 3099 case Mips::BI__builtin_msa_srai_w: 3100 case Mips::BI__builtin_msa_srari_w: 3101 case Mips::BI__builtin_msa_srli_w: 3102 case Mips::BI__builtin_msa_srlri_w: 3103 case Mips::BI__builtin_msa_subvi_b: 3104 case Mips::BI__builtin_msa_subvi_h: 3105 case Mips::BI__builtin_msa_subvi_w: 3106 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3107 case Mips::BI__builtin_msa_binsli_w: 3108 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3109 // These intrinsics take an unsigned 6 bit immediate. 3110 case Mips::BI__builtin_msa_bclri_d: 3111 case Mips::BI__builtin_msa_bnegi_d: 3112 case Mips::BI__builtin_msa_bseti_d: 3113 case Mips::BI__builtin_msa_sat_s_d: 3114 case Mips::BI__builtin_msa_sat_u_d: 3115 case Mips::BI__builtin_msa_slli_d: 3116 case Mips::BI__builtin_msa_srai_d: 3117 case Mips::BI__builtin_msa_srari_d: 3118 case Mips::BI__builtin_msa_srli_d: 3119 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3120 case Mips::BI__builtin_msa_binsli_d: 3121 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3122 // These intrinsics take a signed 5 bit immediate. 3123 case Mips::BI__builtin_msa_ceqi_b: 3124 case Mips::BI__builtin_msa_ceqi_h: 3125 case Mips::BI__builtin_msa_ceqi_w: 3126 case Mips::BI__builtin_msa_ceqi_d: 3127 case Mips::BI__builtin_msa_clti_s_b: 3128 case Mips::BI__builtin_msa_clti_s_h: 3129 case Mips::BI__builtin_msa_clti_s_w: 3130 case Mips::BI__builtin_msa_clti_s_d: 3131 case Mips::BI__builtin_msa_clei_s_b: 3132 case Mips::BI__builtin_msa_clei_s_h: 3133 case Mips::BI__builtin_msa_clei_s_w: 3134 case Mips::BI__builtin_msa_clei_s_d: 3135 case Mips::BI__builtin_msa_maxi_s_b: 3136 case Mips::BI__builtin_msa_maxi_s_h: 3137 case Mips::BI__builtin_msa_maxi_s_w: 3138 case Mips::BI__builtin_msa_maxi_s_d: 3139 case Mips::BI__builtin_msa_mini_s_b: 3140 case Mips::BI__builtin_msa_mini_s_h: 3141 case Mips::BI__builtin_msa_mini_s_w: 3142 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3143 // These intrinsics take an unsigned 8 bit immediate. 3144 case Mips::BI__builtin_msa_andi_b: 3145 case Mips::BI__builtin_msa_nori_b: 3146 case Mips::BI__builtin_msa_ori_b: 3147 case Mips::BI__builtin_msa_shf_b: 3148 case Mips::BI__builtin_msa_shf_h: 3149 case Mips::BI__builtin_msa_shf_w: 3150 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3151 case Mips::BI__builtin_msa_bseli_b: 3152 case Mips::BI__builtin_msa_bmnzi_b: 3153 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3154 // df/n format 3155 // These intrinsics take an unsigned 4 bit immediate. 3156 case Mips::BI__builtin_msa_copy_s_b: 3157 case Mips::BI__builtin_msa_copy_u_b: 3158 case Mips::BI__builtin_msa_insve_b: 3159 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3160 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3161 // These intrinsics take an unsigned 3 bit immediate. 3162 case Mips::BI__builtin_msa_copy_s_h: 3163 case Mips::BI__builtin_msa_copy_u_h: 3164 case Mips::BI__builtin_msa_insve_h: 3165 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3166 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3167 // These intrinsics take an unsigned 2 bit immediate. 3168 case Mips::BI__builtin_msa_copy_s_w: 3169 case Mips::BI__builtin_msa_copy_u_w: 3170 case Mips::BI__builtin_msa_insve_w: 3171 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3172 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3173 // These intrinsics take an unsigned 1 bit immediate. 3174 case Mips::BI__builtin_msa_copy_s_d: 3175 case Mips::BI__builtin_msa_copy_u_d: 3176 case Mips::BI__builtin_msa_insve_d: 3177 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3178 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3179 // Memory offsets and immediate loads. 3180 // These intrinsics take a signed 10 bit immediate. 3181 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3182 case Mips::BI__builtin_msa_ldi_h: 3183 case Mips::BI__builtin_msa_ldi_w: 3184 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3185 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3186 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3187 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3188 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3189 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3190 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3191 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3192 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3193 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3194 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3195 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3196 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3197 } 3198 3199 if (!m) 3200 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3201 3202 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3203 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3204 } 3205 3206 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3207 /// advancing the pointer over the consumed characters. The decoded type is 3208 /// returned. If the decoded type represents a constant integer with a 3209 /// constraint on its value then Mask is set to that value. The type descriptors 3210 /// used in Str are specific to PPC MMA builtins and are documented in the file 3211 /// defining the PPC builtins. 3212 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3213 unsigned &Mask) { 3214 bool RequireICE = false; 3215 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3216 switch (*Str++) { 3217 case 'V': 3218 return Context.getVectorType(Context.UnsignedCharTy, 16, 3219 VectorType::VectorKind::AltiVecVector); 3220 case 'i': { 3221 char *End; 3222 unsigned size = strtoul(Str, &End, 10); 3223 assert(End != Str && "Missing constant parameter constraint"); 3224 Str = End; 3225 Mask = size; 3226 return Context.IntTy; 3227 } 3228 case 'W': { 3229 char *End; 3230 unsigned size = strtoul(Str, &End, 10); 3231 assert(End != Str && "Missing PowerPC MMA type size"); 3232 Str = End; 3233 QualType Type; 3234 switch (size) { 3235 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3236 case size: Type = Context.Id##Ty; break; 3237 #include "clang/Basic/PPCTypes.def" 3238 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3239 } 3240 bool CheckVectorArgs = false; 3241 while (!CheckVectorArgs) { 3242 switch (*Str++) { 3243 case '*': 3244 Type = Context.getPointerType(Type); 3245 break; 3246 case 'C': 3247 Type = Type.withConst(); 3248 break; 3249 default: 3250 CheckVectorArgs = true; 3251 --Str; 3252 break; 3253 } 3254 } 3255 return Type; 3256 } 3257 default: 3258 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3259 } 3260 } 3261 3262 static bool isPPC_64Builtin(unsigned BuiltinID) { 3263 // These builtins only work on PPC 64bit targets. 3264 switch (BuiltinID) { 3265 case PPC::BI__builtin_divde: 3266 case PPC::BI__builtin_divdeu: 3267 case PPC::BI__builtin_bpermd: 3268 return true; 3269 } 3270 return false; 3271 } 3272 3273 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3274 StringRef FeatureToCheck, unsigned DiagID) { 3275 if (!S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3276 return S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3277 return false; 3278 } 3279 3280 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3281 CallExpr *TheCall) { 3282 unsigned i = 0, l = 0, u = 0; 3283 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3284 3285 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3286 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3287 << TheCall->getSourceRange(); 3288 3289 switch (BuiltinID) { 3290 default: return false; 3291 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3292 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3293 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3294 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3295 case PPC::BI__builtin_altivec_dss: 3296 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3297 case PPC::BI__builtin_tbegin: 3298 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3299 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3300 case PPC::BI__builtin_tabortwc: 3301 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3302 case PPC::BI__builtin_tabortwci: 3303 case PPC::BI__builtin_tabortdci: 3304 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3305 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3306 case PPC::BI__builtin_altivec_dst: 3307 case PPC::BI__builtin_altivec_dstt: 3308 case PPC::BI__builtin_altivec_dstst: 3309 case PPC::BI__builtin_altivec_dststt: 3310 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3311 case PPC::BI__builtin_vsx_xxpermdi: 3312 case PPC::BI__builtin_vsx_xxsldwi: 3313 return SemaBuiltinVSX(TheCall); 3314 case PPC::BI__builtin_divwe: 3315 case PPC::BI__builtin_divweu: 3316 case PPC::BI__builtin_divde: 3317 case PPC::BI__builtin_divdeu: 3318 return SemaFeatureCheck(*this, TheCall, "extdiv", 3319 diag::err_ppc_builtin_only_on_pwr7); 3320 case PPC::BI__builtin_bpermd: 3321 return SemaFeatureCheck(*this, TheCall, "bpermd", 3322 diag::err_ppc_builtin_only_on_pwr7); 3323 case PPC::BI__builtin_unpack_vector_int128: 3324 return SemaFeatureCheck(*this, TheCall, "vsx", 3325 diag::err_ppc_builtin_only_on_pwr7) || 3326 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3327 case PPC::BI__builtin_pack_vector_int128: 3328 return SemaFeatureCheck(*this, TheCall, "vsx", 3329 diag::err_ppc_builtin_only_on_pwr7); 3330 case PPC::BI__builtin_altivec_vgnb: 3331 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3332 case PPC::BI__builtin_altivec_vec_replace_elt: 3333 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3334 QualType VecTy = TheCall->getArg(0)->getType(); 3335 QualType EltTy = TheCall->getArg(1)->getType(); 3336 unsigned Width = Context.getIntWidth(EltTy); 3337 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3338 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3339 } 3340 case PPC::BI__builtin_vsx_xxeval: 3341 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3342 case PPC::BI__builtin_altivec_vsldbi: 3343 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3344 case PPC::BI__builtin_altivec_vsrdbi: 3345 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3346 case PPC::BI__builtin_vsx_xxpermx: 3347 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3348 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3349 case PPC::BI__builtin_##Name: \ 3350 return SemaBuiltinPPCMMACall(TheCall, Types); 3351 #include "clang/Basic/BuiltinsPPC.def" 3352 } 3353 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3354 } 3355 3356 // Check if the given type is a non-pointer PPC MMA type. This function is used 3357 // in Sema to prevent invalid uses of restricted PPC MMA types. 3358 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3359 if (Type->isPointerType() || Type->isArrayType()) 3360 return false; 3361 3362 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3363 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3364 if (false 3365 #include "clang/Basic/PPCTypes.def" 3366 ) { 3367 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3368 return true; 3369 } 3370 return false; 3371 } 3372 3373 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3374 CallExpr *TheCall) { 3375 // position of memory order and scope arguments in the builtin 3376 unsigned OrderIndex, ScopeIndex; 3377 switch (BuiltinID) { 3378 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3379 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3380 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3381 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3382 OrderIndex = 2; 3383 ScopeIndex = 3; 3384 break; 3385 case AMDGPU::BI__builtin_amdgcn_fence: 3386 OrderIndex = 0; 3387 ScopeIndex = 1; 3388 break; 3389 default: 3390 return false; 3391 } 3392 3393 ExprResult Arg = TheCall->getArg(OrderIndex); 3394 auto ArgExpr = Arg.get(); 3395 Expr::EvalResult ArgResult; 3396 3397 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3398 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3399 << ArgExpr->getType(); 3400 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3401 3402 // Check valididty of memory ordering as per C11 / C++11's memody model. 3403 // Only fence needs check. Atomic dec/inc allow all memory orders. 3404 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3405 return Diag(ArgExpr->getBeginLoc(), 3406 diag::warn_atomic_op_has_invalid_memory_order) 3407 << ArgExpr->getSourceRange(); 3408 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3409 case llvm::AtomicOrderingCABI::relaxed: 3410 case llvm::AtomicOrderingCABI::consume: 3411 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3412 return Diag(ArgExpr->getBeginLoc(), 3413 diag::warn_atomic_op_has_invalid_memory_order) 3414 << ArgExpr->getSourceRange(); 3415 break; 3416 case llvm::AtomicOrderingCABI::acquire: 3417 case llvm::AtomicOrderingCABI::release: 3418 case llvm::AtomicOrderingCABI::acq_rel: 3419 case llvm::AtomicOrderingCABI::seq_cst: 3420 break; 3421 } 3422 3423 Arg = TheCall->getArg(ScopeIndex); 3424 ArgExpr = Arg.get(); 3425 Expr::EvalResult ArgResult1; 3426 // Check that sync scope is a constant literal 3427 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3428 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3429 << ArgExpr->getType(); 3430 3431 return false; 3432 } 3433 3434 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3435 llvm::APSInt Result; 3436 3437 // We can't check the value of a dependent argument. 3438 Expr *Arg = TheCall->getArg(ArgNum); 3439 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3440 return false; 3441 3442 // Check constant-ness first. 3443 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3444 return true; 3445 3446 int64_t Val = Result.getSExtValue(); 3447 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3448 return false; 3449 3450 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3451 << Arg->getSourceRange(); 3452 } 3453 3454 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3455 unsigned BuiltinID, 3456 CallExpr *TheCall) { 3457 // CodeGenFunction can also detect this, but this gives a better error 3458 // message. 3459 bool FeatureMissing = false; 3460 SmallVector<StringRef> ReqFeatures; 3461 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3462 Features.split(ReqFeatures, ','); 3463 3464 // Check if each required feature is included 3465 for (StringRef F : ReqFeatures) { 3466 if (TI.hasFeature(F)) 3467 continue; 3468 3469 // If the feature is 64bit, alter the string so it will print better in 3470 // the diagnostic. 3471 if (F == "64bit") 3472 F = "RV64"; 3473 3474 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3475 F.consume_front("experimental-"); 3476 std::string FeatureStr = F.str(); 3477 FeatureStr[0] = std::toupper(FeatureStr[0]); 3478 3479 // Error message 3480 FeatureMissing = true; 3481 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3482 << TheCall->getSourceRange() << StringRef(FeatureStr); 3483 } 3484 3485 if (FeatureMissing) 3486 return true; 3487 3488 switch (BuiltinID) { 3489 case RISCV::BI__builtin_rvv_vsetvli: 3490 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3491 CheckRISCVLMUL(TheCall, 2); 3492 case RISCV::BI__builtin_rvv_vsetvlimax: 3493 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3494 CheckRISCVLMUL(TheCall, 1); 3495 case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1: 3496 case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1: 3497 case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1: 3498 case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1: 3499 case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1: 3500 case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1: 3501 case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1: 3502 case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1: 3503 case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1: 3504 case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1: 3505 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2: 3506 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2: 3507 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2: 3508 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2: 3509 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2: 3510 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2: 3511 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2: 3512 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2: 3513 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2: 3514 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2: 3515 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4: 3516 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4: 3517 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4: 3518 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4: 3519 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4: 3520 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4: 3521 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4: 3522 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4: 3523 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4: 3524 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4: 3525 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3526 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1: 3527 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1: 3528 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1: 3529 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1: 3530 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1: 3531 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1: 3532 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1: 3533 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1: 3534 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1: 3535 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1: 3536 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2: 3537 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2: 3538 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2: 3539 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2: 3540 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2: 3541 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2: 3542 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2: 3543 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2: 3544 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2: 3545 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2: 3546 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3547 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1: 3548 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1: 3549 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1: 3550 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1: 3551 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1: 3552 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1: 3553 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1: 3554 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1: 3555 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1: 3556 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1: 3557 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3558 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2: 3559 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2: 3560 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2: 3561 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2: 3562 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2: 3563 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2: 3564 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2: 3565 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2: 3566 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2: 3567 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2: 3568 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4: 3569 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4: 3570 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4: 3571 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4: 3572 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4: 3573 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4: 3574 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4: 3575 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4: 3576 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4: 3577 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4: 3578 case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8: 3579 case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8: 3580 case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8: 3581 case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8: 3582 case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8: 3583 case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8: 3584 case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8: 3585 case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8: 3586 case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8: 3587 case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8: 3588 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3589 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4: 3590 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4: 3591 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4: 3592 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4: 3593 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4: 3594 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4: 3595 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4: 3596 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4: 3597 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4: 3598 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4: 3599 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8: 3600 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8: 3601 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8: 3602 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8: 3603 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8: 3604 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8: 3605 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8: 3606 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8: 3607 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8: 3608 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8: 3609 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3610 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8: 3611 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8: 3612 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8: 3613 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8: 3614 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8: 3615 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8: 3616 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8: 3617 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8: 3618 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8: 3619 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8: 3620 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3621 } 3622 3623 return false; 3624 } 3625 3626 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3627 CallExpr *TheCall) { 3628 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3629 Expr *Arg = TheCall->getArg(0); 3630 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3631 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3632 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3633 << Arg->getSourceRange(); 3634 } 3635 3636 // For intrinsics which take an immediate value as part of the instruction, 3637 // range check them here. 3638 unsigned i = 0, l = 0, u = 0; 3639 switch (BuiltinID) { 3640 default: return false; 3641 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3642 case SystemZ::BI__builtin_s390_verimb: 3643 case SystemZ::BI__builtin_s390_verimh: 3644 case SystemZ::BI__builtin_s390_verimf: 3645 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3646 case SystemZ::BI__builtin_s390_vfaeb: 3647 case SystemZ::BI__builtin_s390_vfaeh: 3648 case SystemZ::BI__builtin_s390_vfaef: 3649 case SystemZ::BI__builtin_s390_vfaebs: 3650 case SystemZ::BI__builtin_s390_vfaehs: 3651 case SystemZ::BI__builtin_s390_vfaefs: 3652 case SystemZ::BI__builtin_s390_vfaezb: 3653 case SystemZ::BI__builtin_s390_vfaezh: 3654 case SystemZ::BI__builtin_s390_vfaezf: 3655 case SystemZ::BI__builtin_s390_vfaezbs: 3656 case SystemZ::BI__builtin_s390_vfaezhs: 3657 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3658 case SystemZ::BI__builtin_s390_vfisb: 3659 case SystemZ::BI__builtin_s390_vfidb: 3660 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3661 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3662 case SystemZ::BI__builtin_s390_vftcisb: 3663 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3664 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3665 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3666 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3667 case SystemZ::BI__builtin_s390_vstrcb: 3668 case SystemZ::BI__builtin_s390_vstrch: 3669 case SystemZ::BI__builtin_s390_vstrcf: 3670 case SystemZ::BI__builtin_s390_vstrczb: 3671 case SystemZ::BI__builtin_s390_vstrczh: 3672 case SystemZ::BI__builtin_s390_vstrczf: 3673 case SystemZ::BI__builtin_s390_vstrcbs: 3674 case SystemZ::BI__builtin_s390_vstrchs: 3675 case SystemZ::BI__builtin_s390_vstrcfs: 3676 case SystemZ::BI__builtin_s390_vstrczbs: 3677 case SystemZ::BI__builtin_s390_vstrczhs: 3678 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3679 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3680 case SystemZ::BI__builtin_s390_vfminsb: 3681 case SystemZ::BI__builtin_s390_vfmaxsb: 3682 case SystemZ::BI__builtin_s390_vfmindb: 3683 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3684 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3685 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3686 } 3687 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3688 } 3689 3690 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3691 /// This checks that the target supports __builtin_cpu_supports and 3692 /// that the string argument is constant and valid. 3693 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3694 CallExpr *TheCall) { 3695 Expr *Arg = TheCall->getArg(0); 3696 3697 // Check if the argument is a string literal. 3698 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3699 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3700 << Arg->getSourceRange(); 3701 3702 // Check the contents of the string. 3703 StringRef Feature = 3704 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3705 if (!TI.validateCpuSupports(Feature)) 3706 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3707 << Arg->getSourceRange(); 3708 return false; 3709 } 3710 3711 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3712 /// This checks that the target supports __builtin_cpu_is and 3713 /// that the string argument is constant and valid. 3714 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3715 Expr *Arg = TheCall->getArg(0); 3716 3717 // Check if the argument is a string literal. 3718 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3719 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3720 << Arg->getSourceRange(); 3721 3722 // Check the contents of the string. 3723 StringRef Feature = 3724 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3725 if (!TI.validateCpuIs(Feature)) 3726 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3727 << Arg->getSourceRange(); 3728 return false; 3729 } 3730 3731 // Check if the rounding mode is legal. 3732 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3733 // Indicates if this instruction has rounding control or just SAE. 3734 bool HasRC = false; 3735 3736 unsigned ArgNum = 0; 3737 switch (BuiltinID) { 3738 default: 3739 return false; 3740 case X86::BI__builtin_ia32_vcvttsd2si32: 3741 case X86::BI__builtin_ia32_vcvttsd2si64: 3742 case X86::BI__builtin_ia32_vcvttsd2usi32: 3743 case X86::BI__builtin_ia32_vcvttsd2usi64: 3744 case X86::BI__builtin_ia32_vcvttss2si32: 3745 case X86::BI__builtin_ia32_vcvttss2si64: 3746 case X86::BI__builtin_ia32_vcvttss2usi32: 3747 case X86::BI__builtin_ia32_vcvttss2usi64: 3748 ArgNum = 1; 3749 break; 3750 case X86::BI__builtin_ia32_maxpd512: 3751 case X86::BI__builtin_ia32_maxps512: 3752 case X86::BI__builtin_ia32_minpd512: 3753 case X86::BI__builtin_ia32_minps512: 3754 ArgNum = 2; 3755 break; 3756 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3757 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3758 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3759 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3760 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3761 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3762 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3763 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3764 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3765 case X86::BI__builtin_ia32_exp2pd_mask: 3766 case X86::BI__builtin_ia32_exp2ps_mask: 3767 case X86::BI__builtin_ia32_getexppd512_mask: 3768 case X86::BI__builtin_ia32_getexpps512_mask: 3769 case X86::BI__builtin_ia32_rcp28pd_mask: 3770 case X86::BI__builtin_ia32_rcp28ps_mask: 3771 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3772 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3773 case X86::BI__builtin_ia32_vcomisd: 3774 case X86::BI__builtin_ia32_vcomiss: 3775 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3776 ArgNum = 3; 3777 break; 3778 case X86::BI__builtin_ia32_cmppd512_mask: 3779 case X86::BI__builtin_ia32_cmpps512_mask: 3780 case X86::BI__builtin_ia32_cmpsd_mask: 3781 case X86::BI__builtin_ia32_cmpss_mask: 3782 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3783 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3784 case X86::BI__builtin_ia32_getexpss128_round_mask: 3785 case X86::BI__builtin_ia32_getmantpd512_mask: 3786 case X86::BI__builtin_ia32_getmantps512_mask: 3787 case X86::BI__builtin_ia32_maxsd_round_mask: 3788 case X86::BI__builtin_ia32_maxss_round_mask: 3789 case X86::BI__builtin_ia32_minsd_round_mask: 3790 case X86::BI__builtin_ia32_minss_round_mask: 3791 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3792 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3793 case X86::BI__builtin_ia32_reducepd512_mask: 3794 case X86::BI__builtin_ia32_reduceps512_mask: 3795 case X86::BI__builtin_ia32_rndscalepd_mask: 3796 case X86::BI__builtin_ia32_rndscaleps_mask: 3797 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3798 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3799 ArgNum = 4; 3800 break; 3801 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3802 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3803 case X86::BI__builtin_ia32_fixupimmps512_mask: 3804 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3805 case X86::BI__builtin_ia32_fixupimmsd_mask: 3806 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3807 case X86::BI__builtin_ia32_fixupimmss_mask: 3808 case X86::BI__builtin_ia32_fixupimmss_maskz: 3809 case X86::BI__builtin_ia32_getmantsd_round_mask: 3810 case X86::BI__builtin_ia32_getmantss_round_mask: 3811 case X86::BI__builtin_ia32_rangepd512_mask: 3812 case X86::BI__builtin_ia32_rangeps512_mask: 3813 case X86::BI__builtin_ia32_rangesd128_round_mask: 3814 case X86::BI__builtin_ia32_rangess128_round_mask: 3815 case X86::BI__builtin_ia32_reducesd_mask: 3816 case X86::BI__builtin_ia32_reducess_mask: 3817 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3818 case X86::BI__builtin_ia32_rndscaless_round_mask: 3819 ArgNum = 5; 3820 break; 3821 case X86::BI__builtin_ia32_vcvtsd2si64: 3822 case X86::BI__builtin_ia32_vcvtsd2si32: 3823 case X86::BI__builtin_ia32_vcvtsd2usi32: 3824 case X86::BI__builtin_ia32_vcvtsd2usi64: 3825 case X86::BI__builtin_ia32_vcvtss2si32: 3826 case X86::BI__builtin_ia32_vcvtss2si64: 3827 case X86::BI__builtin_ia32_vcvtss2usi32: 3828 case X86::BI__builtin_ia32_vcvtss2usi64: 3829 case X86::BI__builtin_ia32_sqrtpd512: 3830 case X86::BI__builtin_ia32_sqrtps512: 3831 ArgNum = 1; 3832 HasRC = true; 3833 break; 3834 case X86::BI__builtin_ia32_addpd512: 3835 case X86::BI__builtin_ia32_addps512: 3836 case X86::BI__builtin_ia32_divpd512: 3837 case X86::BI__builtin_ia32_divps512: 3838 case X86::BI__builtin_ia32_mulpd512: 3839 case X86::BI__builtin_ia32_mulps512: 3840 case X86::BI__builtin_ia32_subpd512: 3841 case X86::BI__builtin_ia32_subps512: 3842 case X86::BI__builtin_ia32_cvtsi2sd64: 3843 case X86::BI__builtin_ia32_cvtsi2ss32: 3844 case X86::BI__builtin_ia32_cvtsi2ss64: 3845 case X86::BI__builtin_ia32_cvtusi2sd64: 3846 case X86::BI__builtin_ia32_cvtusi2ss32: 3847 case X86::BI__builtin_ia32_cvtusi2ss64: 3848 ArgNum = 2; 3849 HasRC = true; 3850 break; 3851 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3852 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3853 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3854 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3855 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3856 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3857 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3858 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3859 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3860 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3861 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3862 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3863 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3864 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3865 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3866 ArgNum = 3; 3867 HasRC = true; 3868 break; 3869 case X86::BI__builtin_ia32_addss_round_mask: 3870 case X86::BI__builtin_ia32_addsd_round_mask: 3871 case X86::BI__builtin_ia32_divss_round_mask: 3872 case X86::BI__builtin_ia32_divsd_round_mask: 3873 case X86::BI__builtin_ia32_mulss_round_mask: 3874 case X86::BI__builtin_ia32_mulsd_round_mask: 3875 case X86::BI__builtin_ia32_subss_round_mask: 3876 case X86::BI__builtin_ia32_subsd_round_mask: 3877 case X86::BI__builtin_ia32_scalefpd512_mask: 3878 case X86::BI__builtin_ia32_scalefps512_mask: 3879 case X86::BI__builtin_ia32_scalefsd_round_mask: 3880 case X86::BI__builtin_ia32_scalefss_round_mask: 3881 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3882 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3883 case X86::BI__builtin_ia32_sqrtss_round_mask: 3884 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3885 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3886 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3887 case X86::BI__builtin_ia32_vfmaddss3_mask: 3888 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3889 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3890 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3891 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3892 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3893 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3894 case X86::BI__builtin_ia32_vfmaddps512_mask: 3895 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3896 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3897 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3898 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3899 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3900 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3901 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3902 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3903 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3904 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3905 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3906 ArgNum = 4; 3907 HasRC = true; 3908 break; 3909 } 3910 3911 llvm::APSInt Result; 3912 3913 // We can't check the value of a dependent argument. 3914 Expr *Arg = TheCall->getArg(ArgNum); 3915 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3916 return false; 3917 3918 // Check constant-ness first. 3919 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3920 return true; 3921 3922 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3923 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3924 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3925 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3926 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3927 Result == 8/*ROUND_NO_EXC*/ || 3928 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3929 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3930 return false; 3931 3932 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3933 << Arg->getSourceRange(); 3934 } 3935 3936 // Check if the gather/scatter scale is legal. 3937 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3938 CallExpr *TheCall) { 3939 unsigned ArgNum = 0; 3940 switch (BuiltinID) { 3941 default: 3942 return false; 3943 case X86::BI__builtin_ia32_gatherpfdpd: 3944 case X86::BI__builtin_ia32_gatherpfdps: 3945 case X86::BI__builtin_ia32_gatherpfqpd: 3946 case X86::BI__builtin_ia32_gatherpfqps: 3947 case X86::BI__builtin_ia32_scatterpfdpd: 3948 case X86::BI__builtin_ia32_scatterpfdps: 3949 case X86::BI__builtin_ia32_scatterpfqpd: 3950 case X86::BI__builtin_ia32_scatterpfqps: 3951 ArgNum = 3; 3952 break; 3953 case X86::BI__builtin_ia32_gatherd_pd: 3954 case X86::BI__builtin_ia32_gatherd_pd256: 3955 case X86::BI__builtin_ia32_gatherq_pd: 3956 case X86::BI__builtin_ia32_gatherq_pd256: 3957 case X86::BI__builtin_ia32_gatherd_ps: 3958 case X86::BI__builtin_ia32_gatherd_ps256: 3959 case X86::BI__builtin_ia32_gatherq_ps: 3960 case X86::BI__builtin_ia32_gatherq_ps256: 3961 case X86::BI__builtin_ia32_gatherd_q: 3962 case X86::BI__builtin_ia32_gatherd_q256: 3963 case X86::BI__builtin_ia32_gatherq_q: 3964 case X86::BI__builtin_ia32_gatherq_q256: 3965 case X86::BI__builtin_ia32_gatherd_d: 3966 case X86::BI__builtin_ia32_gatherd_d256: 3967 case X86::BI__builtin_ia32_gatherq_d: 3968 case X86::BI__builtin_ia32_gatherq_d256: 3969 case X86::BI__builtin_ia32_gather3div2df: 3970 case X86::BI__builtin_ia32_gather3div2di: 3971 case X86::BI__builtin_ia32_gather3div4df: 3972 case X86::BI__builtin_ia32_gather3div4di: 3973 case X86::BI__builtin_ia32_gather3div4sf: 3974 case X86::BI__builtin_ia32_gather3div4si: 3975 case X86::BI__builtin_ia32_gather3div8sf: 3976 case X86::BI__builtin_ia32_gather3div8si: 3977 case X86::BI__builtin_ia32_gather3siv2df: 3978 case X86::BI__builtin_ia32_gather3siv2di: 3979 case X86::BI__builtin_ia32_gather3siv4df: 3980 case X86::BI__builtin_ia32_gather3siv4di: 3981 case X86::BI__builtin_ia32_gather3siv4sf: 3982 case X86::BI__builtin_ia32_gather3siv4si: 3983 case X86::BI__builtin_ia32_gather3siv8sf: 3984 case X86::BI__builtin_ia32_gather3siv8si: 3985 case X86::BI__builtin_ia32_gathersiv8df: 3986 case X86::BI__builtin_ia32_gathersiv16sf: 3987 case X86::BI__builtin_ia32_gatherdiv8df: 3988 case X86::BI__builtin_ia32_gatherdiv16sf: 3989 case X86::BI__builtin_ia32_gathersiv8di: 3990 case X86::BI__builtin_ia32_gathersiv16si: 3991 case X86::BI__builtin_ia32_gatherdiv8di: 3992 case X86::BI__builtin_ia32_gatherdiv16si: 3993 case X86::BI__builtin_ia32_scatterdiv2df: 3994 case X86::BI__builtin_ia32_scatterdiv2di: 3995 case X86::BI__builtin_ia32_scatterdiv4df: 3996 case X86::BI__builtin_ia32_scatterdiv4di: 3997 case X86::BI__builtin_ia32_scatterdiv4sf: 3998 case X86::BI__builtin_ia32_scatterdiv4si: 3999 case X86::BI__builtin_ia32_scatterdiv8sf: 4000 case X86::BI__builtin_ia32_scatterdiv8si: 4001 case X86::BI__builtin_ia32_scattersiv2df: 4002 case X86::BI__builtin_ia32_scattersiv2di: 4003 case X86::BI__builtin_ia32_scattersiv4df: 4004 case X86::BI__builtin_ia32_scattersiv4di: 4005 case X86::BI__builtin_ia32_scattersiv4sf: 4006 case X86::BI__builtin_ia32_scattersiv4si: 4007 case X86::BI__builtin_ia32_scattersiv8sf: 4008 case X86::BI__builtin_ia32_scattersiv8si: 4009 case X86::BI__builtin_ia32_scattersiv8df: 4010 case X86::BI__builtin_ia32_scattersiv16sf: 4011 case X86::BI__builtin_ia32_scatterdiv8df: 4012 case X86::BI__builtin_ia32_scatterdiv16sf: 4013 case X86::BI__builtin_ia32_scattersiv8di: 4014 case X86::BI__builtin_ia32_scattersiv16si: 4015 case X86::BI__builtin_ia32_scatterdiv8di: 4016 case X86::BI__builtin_ia32_scatterdiv16si: 4017 ArgNum = 4; 4018 break; 4019 } 4020 4021 llvm::APSInt Result; 4022 4023 // We can't check the value of a dependent argument. 4024 Expr *Arg = TheCall->getArg(ArgNum); 4025 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4026 return false; 4027 4028 // Check constant-ness first. 4029 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4030 return true; 4031 4032 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4033 return false; 4034 4035 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4036 << Arg->getSourceRange(); 4037 } 4038 4039 enum { TileRegLow = 0, TileRegHigh = 7 }; 4040 4041 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4042 ArrayRef<int> ArgNums) { 4043 for (int ArgNum : ArgNums) { 4044 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4045 return true; 4046 } 4047 return false; 4048 } 4049 4050 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4051 ArrayRef<int> ArgNums) { 4052 // Because the max number of tile register is TileRegHigh + 1, so here we use 4053 // each bit to represent the usage of them in bitset. 4054 std::bitset<TileRegHigh + 1> ArgValues; 4055 for (int ArgNum : ArgNums) { 4056 Expr *Arg = TheCall->getArg(ArgNum); 4057 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4058 continue; 4059 4060 llvm::APSInt Result; 4061 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4062 return true; 4063 int ArgExtValue = Result.getExtValue(); 4064 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4065 "Incorrect tile register num."); 4066 if (ArgValues.test(ArgExtValue)) 4067 return Diag(TheCall->getBeginLoc(), 4068 diag::err_x86_builtin_tile_arg_duplicate) 4069 << TheCall->getArg(ArgNum)->getSourceRange(); 4070 ArgValues.set(ArgExtValue); 4071 } 4072 return false; 4073 } 4074 4075 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4076 ArrayRef<int> ArgNums) { 4077 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4078 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4079 } 4080 4081 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4082 switch (BuiltinID) { 4083 default: 4084 return false; 4085 case X86::BI__builtin_ia32_tileloadd64: 4086 case X86::BI__builtin_ia32_tileloaddt164: 4087 case X86::BI__builtin_ia32_tilestored64: 4088 case X86::BI__builtin_ia32_tilezero: 4089 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4090 case X86::BI__builtin_ia32_tdpbssd: 4091 case X86::BI__builtin_ia32_tdpbsud: 4092 case X86::BI__builtin_ia32_tdpbusd: 4093 case X86::BI__builtin_ia32_tdpbuud: 4094 case X86::BI__builtin_ia32_tdpbf16ps: 4095 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4096 } 4097 } 4098 static bool isX86_32Builtin(unsigned BuiltinID) { 4099 // These builtins only work on x86-32 targets. 4100 switch (BuiltinID) { 4101 case X86::BI__builtin_ia32_readeflags_u32: 4102 case X86::BI__builtin_ia32_writeeflags_u32: 4103 return true; 4104 } 4105 4106 return false; 4107 } 4108 4109 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4110 CallExpr *TheCall) { 4111 if (BuiltinID == X86::BI__builtin_cpu_supports) 4112 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4113 4114 if (BuiltinID == X86::BI__builtin_cpu_is) 4115 return SemaBuiltinCpuIs(*this, TI, TheCall); 4116 4117 // Check for 32-bit only builtins on a 64-bit target. 4118 const llvm::Triple &TT = TI.getTriple(); 4119 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4120 return Diag(TheCall->getCallee()->getBeginLoc(), 4121 diag::err_32_bit_builtin_64_bit_tgt); 4122 4123 // If the intrinsic has rounding or SAE make sure its valid. 4124 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4125 return true; 4126 4127 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4128 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4129 return true; 4130 4131 // If the intrinsic has a tile arguments, make sure they are valid. 4132 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4133 return true; 4134 4135 // For intrinsics which take an immediate value as part of the instruction, 4136 // range check them here. 4137 int i = 0, l = 0, u = 0; 4138 switch (BuiltinID) { 4139 default: 4140 return false; 4141 case X86::BI__builtin_ia32_vec_ext_v2si: 4142 case X86::BI__builtin_ia32_vec_ext_v2di: 4143 case X86::BI__builtin_ia32_vextractf128_pd256: 4144 case X86::BI__builtin_ia32_vextractf128_ps256: 4145 case X86::BI__builtin_ia32_vextractf128_si256: 4146 case X86::BI__builtin_ia32_extract128i256: 4147 case X86::BI__builtin_ia32_extractf64x4_mask: 4148 case X86::BI__builtin_ia32_extracti64x4_mask: 4149 case X86::BI__builtin_ia32_extractf32x8_mask: 4150 case X86::BI__builtin_ia32_extracti32x8_mask: 4151 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4152 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4153 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4154 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4155 i = 1; l = 0; u = 1; 4156 break; 4157 case X86::BI__builtin_ia32_vec_set_v2di: 4158 case X86::BI__builtin_ia32_vinsertf128_pd256: 4159 case X86::BI__builtin_ia32_vinsertf128_ps256: 4160 case X86::BI__builtin_ia32_vinsertf128_si256: 4161 case X86::BI__builtin_ia32_insert128i256: 4162 case X86::BI__builtin_ia32_insertf32x8: 4163 case X86::BI__builtin_ia32_inserti32x8: 4164 case X86::BI__builtin_ia32_insertf64x4: 4165 case X86::BI__builtin_ia32_inserti64x4: 4166 case X86::BI__builtin_ia32_insertf64x2_256: 4167 case X86::BI__builtin_ia32_inserti64x2_256: 4168 case X86::BI__builtin_ia32_insertf32x4_256: 4169 case X86::BI__builtin_ia32_inserti32x4_256: 4170 i = 2; l = 0; u = 1; 4171 break; 4172 case X86::BI__builtin_ia32_vpermilpd: 4173 case X86::BI__builtin_ia32_vec_ext_v4hi: 4174 case X86::BI__builtin_ia32_vec_ext_v4si: 4175 case X86::BI__builtin_ia32_vec_ext_v4sf: 4176 case X86::BI__builtin_ia32_vec_ext_v4di: 4177 case X86::BI__builtin_ia32_extractf32x4_mask: 4178 case X86::BI__builtin_ia32_extracti32x4_mask: 4179 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4180 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4181 i = 1; l = 0; u = 3; 4182 break; 4183 case X86::BI_mm_prefetch: 4184 case X86::BI__builtin_ia32_vec_ext_v8hi: 4185 case X86::BI__builtin_ia32_vec_ext_v8si: 4186 i = 1; l = 0; u = 7; 4187 break; 4188 case X86::BI__builtin_ia32_sha1rnds4: 4189 case X86::BI__builtin_ia32_blendpd: 4190 case X86::BI__builtin_ia32_shufpd: 4191 case X86::BI__builtin_ia32_vec_set_v4hi: 4192 case X86::BI__builtin_ia32_vec_set_v4si: 4193 case X86::BI__builtin_ia32_vec_set_v4di: 4194 case X86::BI__builtin_ia32_shuf_f32x4_256: 4195 case X86::BI__builtin_ia32_shuf_f64x2_256: 4196 case X86::BI__builtin_ia32_shuf_i32x4_256: 4197 case X86::BI__builtin_ia32_shuf_i64x2_256: 4198 case X86::BI__builtin_ia32_insertf64x2_512: 4199 case X86::BI__builtin_ia32_inserti64x2_512: 4200 case X86::BI__builtin_ia32_insertf32x4: 4201 case X86::BI__builtin_ia32_inserti32x4: 4202 i = 2; l = 0; u = 3; 4203 break; 4204 case X86::BI__builtin_ia32_vpermil2pd: 4205 case X86::BI__builtin_ia32_vpermil2pd256: 4206 case X86::BI__builtin_ia32_vpermil2ps: 4207 case X86::BI__builtin_ia32_vpermil2ps256: 4208 i = 3; l = 0; u = 3; 4209 break; 4210 case X86::BI__builtin_ia32_cmpb128_mask: 4211 case X86::BI__builtin_ia32_cmpw128_mask: 4212 case X86::BI__builtin_ia32_cmpd128_mask: 4213 case X86::BI__builtin_ia32_cmpq128_mask: 4214 case X86::BI__builtin_ia32_cmpb256_mask: 4215 case X86::BI__builtin_ia32_cmpw256_mask: 4216 case X86::BI__builtin_ia32_cmpd256_mask: 4217 case X86::BI__builtin_ia32_cmpq256_mask: 4218 case X86::BI__builtin_ia32_cmpb512_mask: 4219 case X86::BI__builtin_ia32_cmpw512_mask: 4220 case X86::BI__builtin_ia32_cmpd512_mask: 4221 case X86::BI__builtin_ia32_cmpq512_mask: 4222 case X86::BI__builtin_ia32_ucmpb128_mask: 4223 case X86::BI__builtin_ia32_ucmpw128_mask: 4224 case X86::BI__builtin_ia32_ucmpd128_mask: 4225 case X86::BI__builtin_ia32_ucmpq128_mask: 4226 case X86::BI__builtin_ia32_ucmpb256_mask: 4227 case X86::BI__builtin_ia32_ucmpw256_mask: 4228 case X86::BI__builtin_ia32_ucmpd256_mask: 4229 case X86::BI__builtin_ia32_ucmpq256_mask: 4230 case X86::BI__builtin_ia32_ucmpb512_mask: 4231 case X86::BI__builtin_ia32_ucmpw512_mask: 4232 case X86::BI__builtin_ia32_ucmpd512_mask: 4233 case X86::BI__builtin_ia32_ucmpq512_mask: 4234 case X86::BI__builtin_ia32_vpcomub: 4235 case X86::BI__builtin_ia32_vpcomuw: 4236 case X86::BI__builtin_ia32_vpcomud: 4237 case X86::BI__builtin_ia32_vpcomuq: 4238 case X86::BI__builtin_ia32_vpcomb: 4239 case X86::BI__builtin_ia32_vpcomw: 4240 case X86::BI__builtin_ia32_vpcomd: 4241 case X86::BI__builtin_ia32_vpcomq: 4242 case X86::BI__builtin_ia32_vec_set_v8hi: 4243 case X86::BI__builtin_ia32_vec_set_v8si: 4244 i = 2; l = 0; u = 7; 4245 break; 4246 case X86::BI__builtin_ia32_vpermilpd256: 4247 case X86::BI__builtin_ia32_roundps: 4248 case X86::BI__builtin_ia32_roundpd: 4249 case X86::BI__builtin_ia32_roundps256: 4250 case X86::BI__builtin_ia32_roundpd256: 4251 case X86::BI__builtin_ia32_getmantpd128_mask: 4252 case X86::BI__builtin_ia32_getmantpd256_mask: 4253 case X86::BI__builtin_ia32_getmantps128_mask: 4254 case X86::BI__builtin_ia32_getmantps256_mask: 4255 case X86::BI__builtin_ia32_getmantpd512_mask: 4256 case X86::BI__builtin_ia32_getmantps512_mask: 4257 case X86::BI__builtin_ia32_vec_ext_v16qi: 4258 case X86::BI__builtin_ia32_vec_ext_v16hi: 4259 i = 1; l = 0; u = 15; 4260 break; 4261 case X86::BI__builtin_ia32_pblendd128: 4262 case X86::BI__builtin_ia32_blendps: 4263 case X86::BI__builtin_ia32_blendpd256: 4264 case X86::BI__builtin_ia32_shufpd256: 4265 case X86::BI__builtin_ia32_roundss: 4266 case X86::BI__builtin_ia32_roundsd: 4267 case X86::BI__builtin_ia32_rangepd128_mask: 4268 case X86::BI__builtin_ia32_rangepd256_mask: 4269 case X86::BI__builtin_ia32_rangepd512_mask: 4270 case X86::BI__builtin_ia32_rangeps128_mask: 4271 case X86::BI__builtin_ia32_rangeps256_mask: 4272 case X86::BI__builtin_ia32_rangeps512_mask: 4273 case X86::BI__builtin_ia32_getmantsd_round_mask: 4274 case X86::BI__builtin_ia32_getmantss_round_mask: 4275 case X86::BI__builtin_ia32_vec_set_v16qi: 4276 case X86::BI__builtin_ia32_vec_set_v16hi: 4277 i = 2; l = 0; u = 15; 4278 break; 4279 case X86::BI__builtin_ia32_vec_ext_v32qi: 4280 i = 1; l = 0; u = 31; 4281 break; 4282 case X86::BI__builtin_ia32_cmpps: 4283 case X86::BI__builtin_ia32_cmpss: 4284 case X86::BI__builtin_ia32_cmppd: 4285 case X86::BI__builtin_ia32_cmpsd: 4286 case X86::BI__builtin_ia32_cmpps256: 4287 case X86::BI__builtin_ia32_cmppd256: 4288 case X86::BI__builtin_ia32_cmpps128_mask: 4289 case X86::BI__builtin_ia32_cmppd128_mask: 4290 case X86::BI__builtin_ia32_cmpps256_mask: 4291 case X86::BI__builtin_ia32_cmppd256_mask: 4292 case X86::BI__builtin_ia32_cmpps512_mask: 4293 case X86::BI__builtin_ia32_cmppd512_mask: 4294 case X86::BI__builtin_ia32_cmpsd_mask: 4295 case X86::BI__builtin_ia32_cmpss_mask: 4296 case X86::BI__builtin_ia32_vec_set_v32qi: 4297 i = 2; l = 0; u = 31; 4298 break; 4299 case X86::BI__builtin_ia32_permdf256: 4300 case X86::BI__builtin_ia32_permdi256: 4301 case X86::BI__builtin_ia32_permdf512: 4302 case X86::BI__builtin_ia32_permdi512: 4303 case X86::BI__builtin_ia32_vpermilps: 4304 case X86::BI__builtin_ia32_vpermilps256: 4305 case X86::BI__builtin_ia32_vpermilpd512: 4306 case X86::BI__builtin_ia32_vpermilps512: 4307 case X86::BI__builtin_ia32_pshufd: 4308 case X86::BI__builtin_ia32_pshufd256: 4309 case X86::BI__builtin_ia32_pshufd512: 4310 case X86::BI__builtin_ia32_pshufhw: 4311 case X86::BI__builtin_ia32_pshufhw256: 4312 case X86::BI__builtin_ia32_pshufhw512: 4313 case X86::BI__builtin_ia32_pshuflw: 4314 case X86::BI__builtin_ia32_pshuflw256: 4315 case X86::BI__builtin_ia32_pshuflw512: 4316 case X86::BI__builtin_ia32_vcvtps2ph: 4317 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4318 case X86::BI__builtin_ia32_vcvtps2ph256: 4319 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4320 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4321 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4322 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4323 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4324 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4325 case X86::BI__builtin_ia32_rndscaleps_mask: 4326 case X86::BI__builtin_ia32_rndscalepd_mask: 4327 case X86::BI__builtin_ia32_reducepd128_mask: 4328 case X86::BI__builtin_ia32_reducepd256_mask: 4329 case X86::BI__builtin_ia32_reducepd512_mask: 4330 case X86::BI__builtin_ia32_reduceps128_mask: 4331 case X86::BI__builtin_ia32_reduceps256_mask: 4332 case X86::BI__builtin_ia32_reduceps512_mask: 4333 case X86::BI__builtin_ia32_prold512: 4334 case X86::BI__builtin_ia32_prolq512: 4335 case X86::BI__builtin_ia32_prold128: 4336 case X86::BI__builtin_ia32_prold256: 4337 case X86::BI__builtin_ia32_prolq128: 4338 case X86::BI__builtin_ia32_prolq256: 4339 case X86::BI__builtin_ia32_prord512: 4340 case X86::BI__builtin_ia32_prorq512: 4341 case X86::BI__builtin_ia32_prord128: 4342 case X86::BI__builtin_ia32_prord256: 4343 case X86::BI__builtin_ia32_prorq128: 4344 case X86::BI__builtin_ia32_prorq256: 4345 case X86::BI__builtin_ia32_fpclasspd128_mask: 4346 case X86::BI__builtin_ia32_fpclasspd256_mask: 4347 case X86::BI__builtin_ia32_fpclassps128_mask: 4348 case X86::BI__builtin_ia32_fpclassps256_mask: 4349 case X86::BI__builtin_ia32_fpclassps512_mask: 4350 case X86::BI__builtin_ia32_fpclasspd512_mask: 4351 case X86::BI__builtin_ia32_fpclasssd_mask: 4352 case X86::BI__builtin_ia32_fpclassss_mask: 4353 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4354 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4355 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4356 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4357 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4358 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4359 case X86::BI__builtin_ia32_kshiftliqi: 4360 case X86::BI__builtin_ia32_kshiftlihi: 4361 case X86::BI__builtin_ia32_kshiftlisi: 4362 case X86::BI__builtin_ia32_kshiftlidi: 4363 case X86::BI__builtin_ia32_kshiftriqi: 4364 case X86::BI__builtin_ia32_kshiftrihi: 4365 case X86::BI__builtin_ia32_kshiftrisi: 4366 case X86::BI__builtin_ia32_kshiftridi: 4367 i = 1; l = 0; u = 255; 4368 break; 4369 case X86::BI__builtin_ia32_vperm2f128_pd256: 4370 case X86::BI__builtin_ia32_vperm2f128_ps256: 4371 case X86::BI__builtin_ia32_vperm2f128_si256: 4372 case X86::BI__builtin_ia32_permti256: 4373 case X86::BI__builtin_ia32_pblendw128: 4374 case X86::BI__builtin_ia32_pblendw256: 4375 case X86::BI__builtin_ia32_blendps256: 4376 case X86::BI__builtin_ia32_pblendd256: 4377 case X86::BI__builtin_ia32_palignr128: 4378 case X86::BI__builtin_ia32_palignr256: 4379 case X86::BI__builtin_ia32_palignr512: 4380 case X86::BI__builtin_ia32_alignq512: 4381 case X86::BI__builtin_ia32_alignd512: 4382 case X86::BI__builtin_ia32_alignd128: 4383 case X86::BI__builtin_ia32_alignd256: 4384 case X86::BI__builtin_ia32_alignq128: 4385 case X86::BI__builtin_ia32_alignq256: 4386 case X86::BI__builtin_ia32_vcomisd: 4387 case X86::BI__builtin_ia32_vcomiss: 4388 case X86::BI__builtin_ia32_shuf_f32x4: 4389 case X86::BI__builtin_ia32_shuf_f64x2: 4390 case X86::BI__builtin_ia32_shuf_i32x4: 4391 case X86::BI__builtin_ia32_shuf_i64x2: 4392 case X86::BI__builtin_ia32_shufpd512: 4393 case X86::BI__builtin_ia32_shufps: 4394 case X86::BI__builtin_ia32_shufps256: 4395 case X86::BI__builtin_ia32_shufps512: 4396 case X86::BI__builtin_ia32_dbpsadbw128: 4397 case X86::BI__builtin_ia32_dbpsadbw256: 4398 case X86::BI__builtin_ia32_dbpsadbw512: 4399 case X86::BI__builtin_ia32_vpshldd128: 4400 case X86::BI__builtin_ia32_vpshldd256: 4401 case X86::BI__builtin_ia32_vpshldd512: 4402 case X86::BI__builtin_ia32_vpshldq128: 4403 case X86::BI__builtin_ia32_vpshldq256: 4404 case X86::BI__builtin_ia32_vpshldq512: 4405 case X86::BI__builtin_ia32_vpshldw128: 4406 case X86::BI__builtin_ia32_vpshldw256: 4407 case X86::BI__builtin_ia32_vpshldw512: 4408 case X86::BI__builtin_ia32_vpshrdd128: 4409 case X86::BI__builtin_ia32_vpshrdd256: 4410 case X86::BI__builtin_ia32_vpshrdd512: 4411 case X86::BI__builtin_ia32_vpshrdq128: 4412 case X86::BI__builtin_ia32_vpshrdq256: 4413 case X86::BI__builtin_ia32_vpshrdq512: 4414 case X86::BI__builtin_ia32_vpshrdw128: 4415 case X86::BI__builtin_ia32_vpshrdw256: 4416 case X86::BI__builtin_ia32_vpshrdw512: 4417 i = 2; l = 0; u = 255; 4418 break; 4419 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4420 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4421 case X86::BI__builtin_ia32_fixupimmps512_mask: 4422 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4423 case X86::BI__builtin_ia32_fixupimmsd_mask: 4424 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4425 case X86::BI__builtin_ia32_fixupimmss_mask: 4426 case X86::BI__builtin_ia32_fixupimmss_maskz: 4427 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4428 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4429 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4430 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4431 case X86::BI__builtin_ia32_fixupimmps128_mask: 4432 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4433 case X86::BI__builtin_ia32_fixupimmps256_mask: 4434 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4435 case X86::BI__builtin_ia32_pternlogd512_mask: 4436 case X86::BI__builtin_ia32_pternlogd512_maskz: 4437 case X86::BI__builtin_ia32_pternlogq512_mask: 4438 case X86::BI__builtin_ia32_pternlogq512_maskz: 4439 case X86::BI__builtin_ia32_pternlogd128_mask: 4440 case X86::BI__builtin_ia32_pternlogd128_maskz: 4441 case X86::BI__builtin_ia32_pternlogd256_mask: 4442 case X86::BI__builtin_ia32_pternlogd256_maskz: 4443 case X86::BI__builtin_ia32_pternlogq128_mask: 4444 case X86::BI__builtin_ia32_pternlogq128_maskz: 4445 case X86::BI__builtin_ia32_pternlogq256_mask: 4446 case X86::BI__builtin_ia32_pternlogq256_maskz: 4447 i = 3; l = 0; u = 255; 4448 break; 4449 case X86::BI__builtin_ia32_gatherpfdpd: 4450 case X86::BI__builtin_ia32_gatherpfdps: 4451 case X86::BI__builtin_ia32_gatherpfqpd: 4452 case X86::BI__builtin_ia32_gatherpfqps: 4453 case X86::BI__builtin_ia32_scatterpfdpd: 4454 case X86::BI__builtin_ia32_scatterpfdps: 4455 case X86::BI__builtin_ia32_scatterpfqpd: 4456 case X86::BI__builtin_ia32_scatterpfqps: 4457 i = 4; l = 2; u = 3; 4458 break; 4459 case X86::BI__builtin_ia32_reducesd_mask: 4460 case X86::BI__builtin_ia32_reducess_mask: 4461 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4462 case X86::BI__builtin_ia32_rndscaless_round_mask: 4463 i = 4; l = 0; u = 255; 4464 break; 4465 } 4466 4467 // Note that we don't force a hard error on the range check here, allowing 4468 // template-generated or macro-generated dead code to potentially have out-of- 4469 // range values. These need to code generate, but don't need to necessarily 4470 // make any sense. We use a warning that defaults to an error. 4471 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4472 } 4473 4474 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4475 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4476 /// Returns true when the format fits the function and the FormatStringInfo has 4477 /// been populated. 4478 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4479 FormatStringInfo *FSI) { 4480 FSI->HasVAListArg = Format->getFirstArg() == 0; 4481 FSI->FormatIdx = Format->getFormatIdx() - 1; 4482 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4483 4484 // The way the format attribute works in GCC, the implicit this argument 4485 // of member functions is counted. However, it doesn't appear in our own 4486 // lists, so decrement format_idx in that case. 4487 if (IsCXXMember) { 4488 if(FSI->FormatIdx == 0) 4489 return false; 4490 --FSI->FormatIdx; 4491 if (FSI->FirstDataArg != 0) 4492 --FSI->FirstDataArg; 4493 } 4494 return true; 4495 } 4496 4497 /// Checks if a the given expression evaluates to null. 4498 /// 4499 /// Returns true if the value evaluates to null. 4500 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4501 // If the expression has non-null type, it doesn't evaluate to null. 4502 if (auto nullability 4503 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4504 if (*nullability == NullabilityKind::NonNull) 4505 return false; 4506 } 4507 4508 // As a special case, transparent unions initialized with zero are 4509 // considered null for the purposes of the nonnull attribute. 4510 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4511 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4512 if (const CompoundLiteralExpr *CLE = 4513 dyn_cast<CompoundLiteralExpr>(Expr)) 4514 if (const InitListExpr *ILE = 4515 dyn_cast<InitListExpr>(CLE->getInitializer())) 4516 Expr = ILE->getInit(0); 4517 } 4518 4519 bool Result; 4520 return (!Expr->isValueDependent() && 4521 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4522 !Result); 4523 } 4524 4525 static void CheckNonNullArgument(Sema &S, 4526 const Expr *ArgExpr, 4527 SourceLocation CallSiteLoc) { 4528 if (CheckNonNullExpr(S, ArgExpr)) 4529 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4530 S.PDiag(diag::warn_null_arg) 4531 << ArgExpr->getSourceRange()); 4532 } 4533 4534 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4535 FormatStringInfo FSI; 4536 if ((GetFormatStringType(Format) == FST_NSString) && 4537 getFormatStringInfo(Format, false, &FSI)) { 4538 Idx = FSI.FormatIdx; 4539 return true; 4540 } 4541 return false; 4542 } 4543 4544 /// Diagnose use of %s directive in an NSString which is being passed 4545 /// as formatting string to formatting method. 4546 static void 4547 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4548 const NamedDecl *FDecl, 4549 Expr **Args, 4550 unsigned NumArgs) { 4551 unsigned Idx = 0; 4552 bool Format = false; 4553 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4554 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4555 Idx = 2; 4556 Format = true; 4557 } 4558 else 4559 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4560 if (S.GetFormatNSStringIdx(I, Idx)) { 4561 Format = true; 4562 break; 4563 } 4564 } 4565 if (!Format || NumArgs <= Idx) 4566 return; 4567 const Expr *FormatExpr = Args[Idx]; 4568 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4569 FormatExpr = CSCE->getSubExpr(); 4570 const StringLiteral *FormatString; 4571 if (const ObjCStringLiteral *OSL = 4572 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4573 FormatString = OSL->getString(); 4574 else 4575 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4576 if (!FormatString) 4577 return; 4578 if (S.FormatStringHasSArg(FormatString)) { 4579 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4580 << "%s" << 1 << 1; 4581 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4582 << FDecl->getDeclName(); 4583 } 4584 } 4585 4586 /// Determine whether the given type has a non-null nullability annotation. 4587 static bool isNonNullType(ASTContext &ctx, QualType type) { 4588 if (auto nullability = type->getNullability(ctx)) 4589 return *nullability == NullabilityKind::NonNull; 4590 4591 return false; 4592 } 4593 4594 static void CheckNonNullArguments(Sema &S, 4595 const NamedDecl *FDecl, 4596 const FunctionProtoType *Proto, 4597 ArrayRef<const Expr *> Args, 4598 SourceLocation CallSiteLoc) { 4599 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4600 4601 // Already checked by by constant evaluator. 4602 if (S.isConstantEvaluated()) 4603 return; 4604 // Check the attributes attached to the method/function itself. 4605 llvm::SmallBitVector NonNullArgs; 4606 if (FDecl) { 4607 // Handle the nonnull attribute on the function/method declaration itself. 4608 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4609 if (!NonNull->args_size()) { 4610 // Easy case: all pointer arguments are nonnull. 4611 for (const auto *Arg : Args) 4612 if (S.isValidPointerAttrType(Arg->getType())) 4613 CheckNonNullArgument(S, Arg, CallSiteLoc); 4614 return; 4615 } 4616 4617 for (const ParamIdx &Idx : NonNull->args()) { 4618 unsigned IdxAST = Idx.getASTIndex(); 4619 if (IdxAST >= Args.size()) 4620 continue; 4621 if (NonNullArgs.empty()) 4622 NonNullArgs.resize(Args.size()); 4623 NonNullArgs.set(IdxAST); 4624 } 4625 } 4626 } 4627 4628 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4629 // Handle the nonnull attribute on the parameters of the 4630 // function/method. 4631 ArrayRef<ParmVarDecl*> parms; 4632 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4633 parms = FD->parameters(); 4634 else 4635 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4636 4637 unsigned ParamIndex = 0; 4638 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4639 I != E; ++I, ++ParamIndex) { 4640 const ParmVarDecl *PVD = *I; 4641 if (PVD->hasAttr<NonNullAttr>() || 4642 isNonNullType(S.Context, PVD->getType())) { 4643 if (NonNullArgs.empty()) 4644 NonNullArgs.resize(Args.size()); 4645 4646 NonNullArgs.set(ParamIndex); 4647 } 4648 } 4649 } else { 4650 // If we have a non-function, non-method declaration but no 4651 // function prototype, try to dig out the function prototype. 4652 if (!Proto) { 4653 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4654 QualType type = VD->getType().getNonReferenceType(); 4655 if (auto pointerType = type->getAs<PointerType>()) 4656 type = pointerType->getPointeeType(); 4657 else if (auto blockType = type->getAs<BlockPointerType>()) 4658 type = blockType->getPointeeType(); 4659 // FIXME: data member pointers? 4660 4661 // Dig out the function prototype, if there is one. 4662 Proto = type->getAs<FunctionProtoType>(); 4663 } 4664 } 4665 4666 // Fill in non-null argument information from the nullability 4667 // information on the parameter types (if we have them). 4668 if (Proto) { 4669 unsigned Index = 0; 4670 for (auto paramType : Proto->getParamTypes()) { 4671 if (isNonNullType(S.Context, paramType)) { 4672 if (NonNullArgs.empty()) 4673 NonNullArgs.resize(Args.size()); 4674 4675 NonNullArgs.set(Index); 4676 } 4677 4678 ++Index; 4679 } 4680 } 4681 } 4682 4683 // Check for non-null arguments. 4684 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4685 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4686 if (NonNullArgs[ArgIndex]) 4687 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4688 } 4689 } 4690 4691 /// Warn if a pointer or reference argument passed to a function points to an 4692 /// object that is less aligned than the parameter. This can happen when 4693 /// creating a typedef with a lower alignment than the original type and then 4694 /// calling functions defined in terms of the original type. 4695 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4696 StringRef ParamName, QualType ArgTy, 4697 QualType ParamTy) { 4698 4699 // If a function accepts a pointer or reference type 4700 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4701 return; 4702 4703 // If the parameter is a pointer type, get the pointee type for the 4704 // argument too. If the parameter is a reference type, don't try to get 4705 // the pointee type for the argument. 4706 if (ParamTy->isPointerType()) 4707 ArgTy = ArgTy->getPointeeType(); 4708 4709 // Remove reference or pointer 4710 ParamTy = ParamTy->getPointeeType(); 4711 4712 // Find expected alignment, and the actual alignment of the passed object. 4713 // getTypeAlignInChars requires complete types 4714 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4715 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4716 ArgTy->isUndeducedType()) 4717 return; 4718 4719 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4720 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4721 4722 // If the argument is less aligned than the parameter, there is a 4723 // potential alignment issue. 4724 if (ArgAlign < ParamAlign) 4725 Diag(Loc, diag::warn_param_mismatched_alignment) 4726 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4727 << ParamName << FDecl; 4728 } 4729 4730 /// Handles the checks for format strings, non-POD arguments to vararg 4731 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4732 /// attributes. 4733 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4734 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4735 bool IsMemberFunction, SourceLocation Loc, 4736 SourceRange Range, VariadicCallType CallType) { 4737 // FIXME: We should check as much as we can in the template definition. 4738 if (CurContext->isDependentContext()) 4739 return; 4740 4741 // Printf and scanf checking. 4742 llvm::SmallBitVector CheckedVarArgs; 4743 if (FDecl) { 4744 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4745 // Only create vector if there are format attributes. 4746 CheckedVarArgs.resize(Args.size()); 4747 4748 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4749 CheckedVarArgs); 4750 } 4751 } 4752 4753 // Refuse POD arguments that weren't caught by the format string 4754 // checks above. 4755 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4756 if (CallType != VariadicDoesNotApply && 4757 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4758 unsigned NumParams = Proto ? Proto->getNumParams() 4759 : FDecl && isa<FunctionDecl>(FDecl) 4760 ? cast<FunctionDecl>(FDecl)->getNumParams() 4761 : FDecl && isa<ObjCMethodDecl>(FDecl) 4762 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4763 : 0; 4764 4765 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4766 // Args[ArgIdx] can be null in malformed code. 4767 if (const Expr *Arg = Args[ArgIdx]) { 4768 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4769 checkVariadicArgument(Arg, CallType); 4770 } 4771 } 4772 } 4773 4774 if (FDecl || Proto) { 4775 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4776 4777 // Type safety checking. 4778 if (FDecl) { 4779 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4780 CheckArgumentWithTypeTag(I, Args, Loc); 4781 } 4782 } 4783 4784 // Check that passed arguments match the alignment of original arguments. 4785 // Try to get the missing prototype from the declaration. 4786 if (!Proto && FDecl) { 4787 const auto *FT = FDecl->getFunctionType(); 4788 if (isa_and_nonnull<FunctionProtoType>(FT)) 4789 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4790 } 4791 if (Proto) { 4792 // For variadic functions, we may have more args than parameters. 4793 // For some K&R functions, we may have less args than parameters. 4794 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4795 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4796 // Args[ArgIdx] can be null in malformed code. 4797 if (const Expr *Arg = Args[ArgIdx]) { 4798 if (Arg->containsErrors()) 4799 continue; 4800 4801 QualType ParamTy = Proto->getParamType(ArgIdx); 4802 QualType ArgTy = Arg->getType(); 4803 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4804 ArgTy, ParamTy); 4805 } 4806 } 4807 } 4808 4809 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4810 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4811 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4812 if (!Arg->isValueDependent()) { 4813 Expr::EvalResult Align; 4814 if (Arg->EvaluateAsInt(Align, Context)) { 4815 const llvm::APSInt &I = Align.Val.getInt(); 4816 if (!I.isPowerOf2()) 4817 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4818 << Arg->getSourceRange(); 4819 4820 if (I > Sema::MaximumAlignment) 4821 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4822 << Arg->getSourceRange() << Sema::MaximumAlignment; 4823 } 4824 } 4825 } 4826 4827 if (FD) 4828 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4829 } 4830 4831 /// CheckConstructorCall - Check a constructor call for correctness and safety 4832 /// properties not enforced by the C type system. 4833 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4834 ArrayRef<const Expr *> Args, 4835 const FunctionProtoType *Proto, 4836 SourceLocation Loc) { 4837 VariadicCallType CallType = 4838 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4839 4840 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4841 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4842 Context.getPointerType(Ctor->getThisObjectType())); 4843 4844 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4845 Loc, SourceRange(), CallType); 4846 } 4847 4848 /// CheckFunctionCall - Check a direct function call for various correctness 4849 /// and safety properties not strictly enforced by the C type system. 4850 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4851 const FunctionProtoType *Proto) { 4852 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4853 isa<CXXMethodDecl>(FDecl); 4854 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4855 IsMemberOperatorCall; 4856 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4857 TheCall->getCallee()); 4858 Expr** Args = TheCall->getArgs(); 4859 unsigned NumArgs = TheCall->getNumArgs(); 4860 4861 Expr *ImplicitThis = nullptr; 4862 if (IsMemberOperatorCall) { 4863 // If this is a call to a member operator, hide the first argument 4864 // from checkCall. 4865 // FIXME: Our choice of AST representation here is less than ideal. 4866 ImplicitThis = Args[0]; 4867 ++Args; 4868 --NumArgs; 4869 } else if (IsMemberFunction) 4870 ImplicitThis = 4871 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4872 4873 if (ImplicitThis) { 4874 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4875 // used. 4876 QualType ThisType = ImplicitThis->getType(); 4877 if (!ThisType->isPointerType()) { 4878 assert(!ThisType->isReferenceType()); 4879 ThisType = Context.getPointerType(ThisType); 4880 } 4881 4882 QualType ThisTypeFromDecl = 4883 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 4884 4885 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 4886 ThisTypeFromDecl); 4887 } 4888 4889 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4890 IsMemberFunction, TheCall->getRParenLoc(), 4891 TheCall->getCallee()->getSourceRange(), CallType); 4892 4893 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4894 // None of the checks below are needed for functions that don't have 4895 // simple names (e.g., C++ conversion functions). 4896 if (!FnInfo) 4897 return false; 4898 4899 CheckTCBEnforcement(TheCall, FDecl); 4900 4901 CheckAbsoluteValueFunction(TheCall, FDecl); 4902 CheckMaxUnsignedZero(TheCall, FDecl); 4903 4904 if (getLangOpts().ObjC) 4905 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4906 4907 unsigned CMId = FDecl->getMemoryFunctionKind(); 4908 4909 // Handle memory setting and copying functions. 4910 switch (CMId) { 4911 case 0: 4912 return false; 4913 case Builtin::BIstrlcpy: // fallthrough 4914 case Builtin::BIstrlcat: 4915 CheckStrlcpycatArguments(TheCall, FnInfo); 4916 break; 4917 case Builtin::BIstrncat: 4918 CheckStrncatArguments(TheCall, FnInfo); 4919 break; 4920 case Builtin::BIfree: 4921 CheckFreeArguments(TheCall); 4922 break; 4923 default: 4924 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4925 } 4926 4927 return false; 4928 } 4929 4930 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4931 ArrayRef<const Expr *> Args) { 4932 VariadicCallType CallType = 4933 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4934 4935 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4936 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4937 CallType); 4938 4939 return false; 4940 } 4941 4942 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4943 const FunctionProtoType *Proto) { 4944 QualType Ty; 4945 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4946 Ty = V->getType().getNonReferenceType(); 4947 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4948 Ty = F->getType().getNonReferenceType(); 4949 else 4950 return false; 4951 4952 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4953 !Ty->isFunctionProtoType()) 4954 return false; 4955 4956 VariadicCallType CallType; 4957 if (!Proto || !Proto->isVariadic()) { 4958 CallType = VariadicDoesNotApply; 4959 } else if (Ty->isBlockPointerType()) { 4960 CallType = VariadicBlock; 4961 } else { // Ty->isFunctionPointerType() 4962 CallType = VariadicFunction; 4963 } 4964 4965 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4966 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4967 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4968 TheCall->getCallee()->getSourceRange(), CallType); 4969 4970 return false; 4971 } 4972 4973 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4974 /// such as function pointers returned from functions. 4975 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4976 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4977 TheCall->getCallee()); 4978 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4979 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4980 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4981 TheCall->getCallee()->getSourceRange(), CallType); 4982 4983 return false; 4984 } 4985 4986 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4987 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4988 return false; 4989 4990 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4991 switch (Op) { 4992 case AtomicExpr::AO__c11_atomic_init: 4993 case AtomicExpr::AO__opencl_atomic_init: 4994 llvm_unreachable("There is no ordering argument for an init"); 4995 4996 case AtomicExpr::AO__c11_atomic_load: 4997 case AtomicExpr::AO__opencl_atomic_load: 4998 case AtomicExpr::AO__atomic_load_n: 4999 case AtomicExpr::AO__atomic_load: 5000 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5001 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5002 5003 case AtomicExpr::AO__c11_atomic_store: 5004 case AtomicExpr::AO__opencl_atomic_store: 5005 case AtomicExpr::AO__atomic_store: 5006 case AtomicExpr::AO__atomic_store_n: 5007 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5008 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5009 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5010 5011 default: 5012 return true; 5013 } 5014 } 5015 5016 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5017 AtomicExpr::AtomicOp Op) { 5018 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5019 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5020 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5021 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5022 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5023 Op); 5024 } 5025 5026 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5027 SourceLocation RParenLoc, MultiExprArg Args, 5028 AtomicExpr::AtomicOp Op, 5029 AtomicArgumentOrder ArgOrder) { 5030 // All the non-OpenCL operations take one of the following forms. 5031 // The OpenCL operations take the __c11 forms with one extra argument for 5032 // synchronization scope. 5033 enum { 5034 // C __c11_atomic_init(A *, C) 5035 Init, 5036 5037 // C __c11_atomic_load(A *, int) 5038 Load, 5039 5040 // void __atomic_load(A *, CP, int) 5041 LoadCopy, 5042 5043 // void __atomic_store(A *, CP, int) 5044 Copy, 5045 5046 // C __c11_atomic_add(A *, M, int) 5047 Arithmetic, 5048 5049 // C __atomic_exchange_n(A *, CP, int) 5050 Xchg, 5051 5052 // void __atomic_exchange(A *, C *, CP, int) 5053 GNUXchg, 5054 5055 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5056 C11CmpXchg, 5057 5058 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5059 GNUCmpXchg 5060 } Form = Init; 5061 5062 const unsigned NumForm = GNUCmpXchg + 1; 5063 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5064 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5065 // where: 5066 // C is an appropriate type, 5067 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5068 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5069 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5070 // the int parameters are for orderings. 5071 5072 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5073 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5074 "need to update code for modified forms"); 5075 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5076 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5077 AtomicExpr::AO__atomic_load, 5078 "need to update code for modified C11 atomics"); 5079 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5080 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5081 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5082 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5083 IsOpenCL; 5084 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5085 Op == AtomicExpr::AO__atomic_store_n || 5086 Op == AtomicExpr::AO__atomic_exchange_n || 5087 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5088 bool IsAddSub = false; 5089 5090 switch (Op) { 5091 case AtomicExpr::AO__c11_atomic_init: 5092 case AtomicExpr::AO__opencl_atomic_init: 5093 Form = Init; 5094 break; 5095 5096 case AtomicExpr::AO__c11_atomic_load: 5097 case AtomicExpr::AO__opencl_atomic_load: 5098 case AtomicExpr::AO__atomic_load_n: 5099 Form = Load; 5100 break; 5101 5102 case AtomicExpr::AO__atomic_load: 5103 Form = LoadCopy; 5104 break; 5105 5106 case AtomicExpr::AO__c11_atomic_store: 5107 case AtomicExpr::AO__opencl_atomic_store: 5108 case AtomicExpr::AO__atomic_store: 5109 case AtomicExpr::AO__atomic_store_n: 5110 Form = Copy; 5111 break; 5112 5113 case AtomicExpr::AO__c11_atomic_fetch_add: 5114 case AtomicExpr::AO__c11_atomic_fetch_sub: 5115 case AtomicExpr::AO__opencl_atomic_fetch_add: 5116 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5117 case AtomicExpr::AO__atomic_fetch_add: 5118 case AtomicExpr::AO__atomic_fetch_sub: 5119 case AtomicExpr::AO__atomic_add_fetch: 5120 case AtomicExpr::AO__atomic_sub_fetch: 5121 IsAddSub = true; 5122 Form = Arithmetic; 5123 break; 5124 case AtomicExpr::AO__c11_atomic_fetch_and: 5125 case AtomicExpr::AO__c11_atomic_fetch_or: 5126 case AtomicExpr::AO__c11_atomic_fetch_xor: 5127 case AtomicExpr::AO__opencl_atomic_fetch_and: 5128 case AtomicExpr::AO__opencl_atomic_fetch_or: 5129 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5130 case AtomicExpr::AO__atomic_fetch_and: 5131 case AtomicExpr::AO__atomic_fetch_or: 5132 case AtomicExpr::AO__atomic_fetch_xor: 5133 case AtomicExpr::AO__atomic_fetch_nand: 5134 case AtomicExpr::AO__atomic_and_fetch: 5135 case AtomicExpr::AO__atomic_or_fetch: 5136 case AtomicExpr::AO__atomic_xor_fetch: 5137 case AtomicExpr::AO__atomic_nand_fetch: 5138 Form = Arithmetic; 5139 break; 5140 case AtomicExpr::AO__c11_atomic_fetch_min: 5141 case AtomicExpr::AO__c11_atomic_fetch_max: 5142 case AtomicExpr::AO__opencl_atomic_fetch_min: 5143 case AtomicExpr::AO__opencl_atomic_fetch_max: 5144 case AtomicExpr::AO__atomic_min_fetch: 5145 case AtomicExpr::AO__atomic_max_fetch: 5146 case AtomicExpr::AO__atomic_fetch_min: 5147 case AtomicExpr::AO__atomic_fetch_max: 5148 Form = Arithmetic; 5149 break; 5150 5151 case AtomicExpr::AO__c11_atomic_exchange: 5152 case AtomicExpr::AO__opencl_atomic_exchange: 5153 case AtomicExpr::AO__atomic_exchange_n: 5154 Form = Xchg; 5155 break; 5156 5157 case AtomicExpr::AO__atomic_exchange: 5158 Form = GNUXchg; 5159 break; 5160 5161 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5162 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5163 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5164 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5165 Form = C11CmpXchg; 5166 break; 5167 5168 case AtomicExpr::AO__atomic_compare_exchange: 5169 case AtomicExpr::AO__atomic_compare_exchange_n: 5170 Form = GNUCmpXchg; 5171 break; 5172 } 5173 5174 unsigned AdjustedNumArgs = NumArgs[Form]; 5175 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5176 ++AdjustedNumArgs; 5177 // Check we have the right number of arguments. 5178 if (Args.size() < AdjustedNumArgs) { 5179 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5180 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5181 << ExprRange; 5182 return ExprError(); 5183 } else if (Args.size() > AdjustedNumArgs) { 5184 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5185 diag::err_typecheck_call_too_many_args) 5186 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5187 << ExprRange; 5188 return ExprError(); 5189 } 5190 5191 // Inspect the first argument of the atomic operation. 5192 Expr *Ptr = Args[0]; 5193 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5194 if (ConvertedPtr.isInvalid()) 5195 return ExprError(); 5196 5197 Ptr = ConvertedPtr.get(); 5198 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5199 if (!pointerType) { 5200 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5201 << Ptr->getType() << Ptr->getSourceRange(); 5202 return ExprError(); 5203 } 5204 5205 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5206 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5207 QualType ValType = AtomTy; // 'C' 5208 if (IsC11) { 5209 if (!AtomTy->isAtomicType()) { 5210 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5211 << Ptr->getType() << Ptr->getSourceRange(); 5212 return ExprError(); 5213 } 5214 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5215 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5216 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5217 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5218 << Ptr->getSourceRange(); 5219 return ExprError(); 5220 } 5221 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5222 } else if (Form != Load && Form != LoadCopy) { 5223 if (ValType.isConstQualified()) { 5224 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5225 << Ptr->getType() << Ptr->getSourceRange(); 5226 return ExprError(); 5227 } 5228 } 5229 5230 // For an arithmetic operation, the implied arithmetic must be well-formed. 5231 if (Form == Arithmetic) { 5232 // gcc does not enforce these rules for GNU atomics, but we do so for 5233 // sanity. 5234 auto IsAllowedValueType = [&](QualType ValType) { 5235 if (ValType->isIntegerType()) 5236 return true; 5237 if (ValType->isPointerType()) 5238 return true; 5239 if (!ValType->isFloatingType()) 5240 return false; 5241 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5242 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5243 &Context.getTargetInfo().getLongDoubleFormat() == 5244 &llvm::APFloat::x87DoubleExtended()) 5245 return false; 5246 return true; 5247 }; 5248 if (IsAddSub && !IsAllowedValueType(ValType)) { 5249 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5250 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5251 return ExprError(); 5252 } 5253 if (!IsAddSub && !ValType->isIntegerType()) { 5254 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5255 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5256 return ExprError(); 5257 } 5258 if (IsC11 && ValType->isPointerType() && 5259 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5260 diag::err_incomplete_type)) { 5261 return ExprError(); 5262 } 5263 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5264 // For __atomic_*_n operations, the value type must be a scalar integral or 5265 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5266 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5267 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5268 return ExprError(); 5269 } 5270 5271 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5272 !AtomTy->isScalarType()) { 5273 // For GNU atomics, require a trivially-copyable type. This is not part of 5274 // the GNU atomics specification, but we enforce it for sanity. 5275 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5276 << Ptr->getType() << Ptr->getSourceRange(); 5277 return ExprError(); 5278 } 5279 5280 switch (ValType.getObjCLifetime()) { 5281 case Qualifiers::OCL_None: 5282 case Qualifiers::OCL_ExplicitNone: 5283 // okay 5284 break; 5285 5286 case Qualifiers::OCL_Weak: 5287 case Qualifiers::OCL_Strong: 5288 case Qualifiers::OCL_Autoreleasing: 5289 // FIXME: Can this happen? By this point, ValType should be known 5290 // to be trivially copyable. 5291 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5292 << ValType << Ptr->getSourceRange(); 5293 return ExprError(); 5294 } 5295 5296 // All atomic operations have an overload which takes a pointer to a volatile 5297 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5298 // into the result or the other operands. Similarly atomic_load takes a 5299 // pointer to a const 'A'. 5300 ValType.removeLocalVolatile(); 5301 ValType.removeLocalConst(); 5302 QualType ResultType = ValType; 5303 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5304 Form == Init) 5305 ResultType = Context.VoidTy; 5306 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5307 ResultType = Context.BoolTy; 5308 5309 // The type of a parameter passed 'by value'. In the GNU atomics, such 5310 // arguments are actually passed as pointers. 5311 QualType ByValType = ValType; // 'CP' 5312 bool IsPassedByAddress = false; 5313 if (!IsC11 && !IsN) { 5314 ByValType = Ptr->getType(); 5315 IsPassedByAddress = true; 5316 } 5317 5318 SmallVector<Expr *, 5> APIOrderedArgs; 5319 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5320 APIOrderedArgs.push_back(Args[0]); 5321 switch (Form) { 5322 case Init: 5323 case Load: 5324 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5325 break; 5326 case LoadCopy: 5327 case Copy: 5328 case Arithmetic: 5329 case Xchg: 5330 APIOrderedArgs.push_back(Args[2]); // Val1 5331 APIOrderedArgs.push_back(Args[1]); // Order 5332 break; 5333 case GNUXchg: 5334 APIOrderedArgs.push_back(Args[2]); // Val1 5335 APIOrderedArgs.push_back(Args[3]); // Val2 5336 APIOrderedArgs.push_back(Args[1]); // Order 5337 break; 5338 case C11CmpXchg: 5339 APIOrderedArgs.push_back(Args[2]); // Val1 5340 APIOrderedArgs.push_back(Args[4]); // Val2 5341 APIOrderedArgs.push_back(Args[1]); // Order 5342 APIOrderedArgs.push_back(Args[3]); // OrderFail 5343 break; 5344 case GNUCmpXchg: 5345 APIOrderedArgs.push_back(Args[2]); // Val1 5346 APIOrderedArgs.push_back(Args[4]); // Val2 5347 APIOrderedArgs.push_back(Args[5]); // Weak 5348 APIOrderedArgs.push_back(Args[1]); // Order 5349 APIOrderedArgs.push_back(Args[3]); // OrderFail 5350 break; 5351 } 5352 } else 5353 APIOrderedArgs.append(Args.begin(), Args.end()); 5354 5355 // The first argument's non-CV pointer type is used to deduce the type of 5356 // subsequent arguments, except for: 5357 // - weak flag (always converted to bool) 5358 // - memory order (always converted to int) 5359 // - scope (always converted to int) 5360 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5361 QualType Ty; 5362 if (i < NumVals[Form] + 1) { 5363 switch (i) { 5364 case 0: 5365 // The first argument is always a pointer. It has a fixed type. 5366 // It is always dereferenced, a nullptr is undefined. 5367 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5368 // Nothing else to do: we already know all we want about this pointer. 5369 continue; 5370 case 1: 5371 // The second argument is the non-atomic operand. For arithmetic, this 5372 // is always passed by value, and for a compare_exchange it is always 5373 // passed by address. For the rest, GNU uses by-address and C11 uses 5374 // by-value. 5375 assert(Form != Load); 5376 if (Form == Arithmetic && ValType->isPointerType()) 5377 Ty = Context.getPointerDiffType(); 5378 else if (Form == Init || Form == Arithmetic) 5379 Ty = ValType; 5380 else if (Form == Copy || Form == Xchg) { 5381 if (IsPassedByAddress) { 5382 // The value pointer is always dereferenced, a nullptr is undefined. 5383 CheckNonNullArgument(*this, APIOrderedArgs[i], 5384 ExprRange.getBegin()); 5385 } 5386 Ty = ByValType; 5387 } else { 5388 Expr *ValArg = APIOrderedArgs[i]; 5389 // The value pointer is always dereferenced, a nullptr is undefined. 5390 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5391 LangAS AS = LangAS::Default; 5392 // Keep address space of non-atomic pointer type. 5393 if (const PointerType *PtrTy = 5394 ValArg->getType()->getAs<PointerType>()) { 5395 AS = PtrTy->getPointeeType().getAddressSpace(); 5396 } 5397 Ty = Context.getPointerType( 5398 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5399 } 5400 break; 5401 case 2: 5402 // The third argument to compare_exchange / GNU exchange is the desired 5403 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5404 if (IsPassedByAddress) 5405 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5406 Ty = ByValType; 5407 break; 5408 case 3: 5409 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5410 Ty = Context.BoolTy; 5411 break; 5412 } 5413 } else { 5414 // The order(s) and scope are always converted to int. 5415 Ty = Context.IntTy; 5416 } 5417 5418 InitializedEntity Entity = 5419 InitializedEntity::InitializeParameter(Context, Ty, false); 5420 ExprResult Arg = APIOrderedArgs[i]; 5421 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5422 if (Arg.isInvalid()) 5423 return true; 5424 APIOrderedArgs[i] = Arg.get(); 5425 } 5426 5427 // Permute the arguments into a 'consistent' order. 5428 SmallVector<Expr*, 5> SubExprs; 5429 SubExprs.push_back(Ptr); 5430 switch (Form) { 5431 case Init: 5432 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5433 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5434 break; 5435 case Load: 5436 SubExprs.push_back(APIOrderedArgs[1]); // Order 5437 break; 5438 case LoadCopy: 5439 case Copy: 5440 case Arithmetic: 5441 case Xchg: 5442 SubExprs.push_back(APIOrderedArgs[2]); // Order 5443 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5444 break; 5445 case GNUXchg: 5446 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5447 SubExprs.push_back(APIOrderedArgs[3]); // Order 5448 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5449 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5450 break; 5451 case C11CmpXchg: 5452 SubExprs.push_back(APIOrderedArgs[3]); // Order 5453 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5454 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5455 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5456 break; 5457 case GNUCmpXchg: 5458 SubExprs.push_back(APIOrderedArgs[4]); // Order 5459 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5460 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5461 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5462 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5463 break; 5464 } 5465 5466 if (SubExprs.size() >= 2 && Form != Init) { 5467 if (Optional<llvm::APSInt> Result = 5468 SubExprs[1]->getIntegerConstantExpr(Context)) 5469 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5470 Diag(SubExprs[1]->getBeginLoc(), 5471 diag::warn_atomic_op_has_invalid_memory_order) 5472 << SubExprs[1]->getSourceRange(); 5473 } 5474 5475 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5476 auto *Scope = Args[Args.size() - 1]; 5477 if (Optional<llvm::APSInt> Result = 5478 Scope->getIntegerConstantExpr(Context)) { 5479 if (!ScopeModel->isValid(Result->getZExtValue())) 5480 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5481 << Scope->getSourceRange(); 5482 } 5483 SubExprs.push_back(Scope); 5484 } 5485 5486 AtomicExpr *AE = new (Context) 5487 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5488 5489 if ((Op == AtomicExpr::AO__c11_atomic_load || 5490 Op == AtomicExpr::AO__c11_atomic_store || 5491 Op == AtomicExpr::AO__opencl_atomic_load || 5492 Op == AtomicExpr::AO__opencl_atomic_store ) && 5493 Context.AtomicUsesUnsupportedLibcall(AE)) 5494 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5495 << ((Op == AtomicExpr::AO__c11_atomic_load || 5496 Op == AtomicExpr::AO__opencl_atomic_load) 5497 ? 0 5498 : 1); 5499 5500 if (ValType->isExtIntType()) { 5501 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5502 return ExprError(); 5503 } 5504 5505 return AE; 5506 } 5507 5508 /// checkBuiltinArgument - Given a call to a builtin function, perform 5509 /// normal type-checking on the given argument, updating the call in 5510 /// place. This is useful when a builtin function requires custom 5511 /// type-checking for some of its arguments but not necessarily all of 5512 /// them. 5513 /// 5514 /// Returns true on error. 5515 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5516 FunctionDecl *Fn = E->getDirectCallee(); 5517 assert(Fn && "builtin call without direct callee!"); 5518 5519 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5520 InitializedEntity Entity = 5521 InitializedEntity::InitializeParameter(S.Context, Param); 5522 5523 ExprResult Arg = E->getArg(0); 5524 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5525 if (Arg.isInvalid()) 5526 return true; 5527 5528 E->setArg(ArgIndex, Arg.get()); 5529 return false; 5530 } 5531 5532 /// We have a call to a function like __sync_fetch_and_add, which is an 5533 /// overloaded function based on the pointer type of its first argument. 5534 /// The main BuildCallExpr routines have already promoted the types of 5535 /// arguments because all of these calls are prototyped as void(...). 5536 /// 5537 /// This function goes through and does final semantic checking for these 5538 /// builtins, as well as generating any warnings. 5539 ExprResult 5540 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5541 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5542 Expr *Callee = TheCall->getCallee(); 5543 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5544 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5545 5546 // Ensure that we have at least one argument to do type inference from. 5547 if (TheCall->getNumArgs() < 1) { 5548 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5549 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5550 return ExprError(); 5551 } 5552 5553 // Inspect the first argument of the atomic builtin. This should always be 5554 // a pointer type, whose element is an integral scalar or pointer type. 5555 // Because it is a pointer type, we don't have to worry about any implicit 5556 // casts here. 5557 // FIXME: We don't allow floating point scalars as input. 5558 Expr *FirstArg = TheCall->getArg(0); 5559 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5560 if (FirstArgResult.isInvalid()) 5561 return ExprError(); 5562 FirstArg = FirstArgResult.get(); 5563 TheCall->setArg(0, FirstArg); 5564 5565 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5566 if (!pointerType) { 5567 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5568 << FirstArg->getType() << FirstArg->getSourceRange(); 5569 return ExprError(); 5570 } 5571 5572 QualType ValType = pointerType->getPointeeType(); 5573 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5574 !ValType->isBlockPointerType()) { 5575 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5576 << FirstArg->getType() << FirstArg->getSourceRange(); 5577 return ExprError(); 5578 } 5579 5580 if (ValType.isConstQualified()) { 5581 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5582 << FirstArg->getType() << FirstArg->getSourceRange(); 5583 return ExprError(); 5584 } 5585 5586 switch (ValType.getObjCLifetime()) { 5587 case Qualifiers::OCL_None: 5588 case Qualifiers::OCL_ExplicitNone: 5589 // okay 5590 break; 5591 5592 case Qualifiers::OCL_Weak: 5593 case Qualifiers::OCL_Strong: 5594 case Qualifiers::OCL_Autoreleasing: 5595 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5596 << ValType << FirstArg->getSourceRange(); 5597 return ExprError(); 5598 } 5599 5600 // Strip any qualifiers off ValType. 5601 ValType = ValType.getUnqualifiedType(); 5602 5603 // The majority of builtins return a value, but a few have special return 5604 // types, so allow them to override appropriately below. 5605 QualType ResultType = ValType; 5606 5607 // We need to figure out which concrete builtin this maps onto. For example, 5608 // __sync_fetch_and_add with a 2 byte object turns into 5609 // __sync_fetch_and_add_2. 5610 #define BUILTIN_ROW(x) \ 5611 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5612 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5613 5614 static const unsigned BuiltinIndices[][5] = { 5615 BUILTIN_ROW(__sync_fetch_and_add), 5616 BUILTIN_ROW(__sync_fetch_and_sub), 5617 BUILTIN_ROW(__sync_fetch_and_or), 5618 BUILTIN_ROW(__sync_fetch_and_and), 5619 BUILTIN_ROW(__sync_fetch_and_xor), 5620 BUILTIN_ROW(__sync_fetch_and_nand), 5621 5622 BUILTIN_ROW(__sync_add_and_fetch), 5623 BUILTIN_ROW(__sync_sub_and_fetch), 5624 BUILTIN_ROW(__sync_and_and_fetch), 5625 BUILTIN_ROW(__sync_or_and_fetch), 5626 BUILTIN_ROW(__sync_xor_and_fetch), 5627 BUILTIN_ROW(__sync_nand_and_fetch), 5628 5629 BUILTIN_ROW(__sync_val_compare_and_swap), 5630 BUILTIN_ROW(__sync_bool_compare_and_swap), 5631 BUILTIN_ROW(__sync_lock_test_and_set), 5632 BUILTIN_ROW(__sync_lock_release), 5633 BUILTIN_ROW(__sync_swap) 5634 }; 5635 #undef BUILTIN_ROW 5636 5637 // Determine the index of the size. 5638 unsigned SizeIndex; 5639 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5640 case 1: SizeIndex = 0; break; 5641 case 2: SizeIndex = 1; break; 5642 case 4: SizeIndex = 2; break; 5643 case 8: SizeIndex = 3; break; 5644 case 16: SizeIndex = 4; break; 5645 default: 5646 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5647 << FirstArg->getType() << FirstArg->getSourceRange(); 5648 return ExprError(); 5649 } 5650 5651 // Each of these builtins has one pointer argument, followed by some number of 5652 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5653 // that we ignore. Find out which row of BuiltinIndices to read from as well 5654 // as the number of fixed args. 5655 unsigned BuiltinID = FDecl->getBuiltinID(); 5656 unsigned BuiltinIndex, NumFixed = 1; 5657 bool WarnAboutSemanticsChange = false; 5658 switch (BuiltinID) { 5659 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5660 case Builtin::BI__sync_fetch_and_add: 5661 case Builtin::BI__sync_fetch_and_add_1: 5662 case Builtin::BI__sync_fetch_and_add_2: 5663 case Builtin::BI__sync_fetch_and_add_4: 5664 case Builtin::BI__sync_fetch_and_add_8: 5665 case Builtin::BI__sync_fetch_and_add_16: 5666 BuiltinIndex = 0; 5667 break; 5668 5669 case Builtin::BI__sync_fetch_and_sub: 5670 case Builtin::BI__sync_fetch_and_sub_1: 5671 case Builtin::BI__sync_fetch_and_sub_2: 5672 case Builtin::BI__sync_fetch_and_sub_4: 5673 case Builtin::BI__sync_fetch_and_sub_8: 5674 case Builtin::BI__sync_fetch_and_sub_16: 5675 BuiltinIndex = 1; 5676 break; 5677 5678 case Builtin::BI__sync_fetch_and_or: 5679 case Builtin::BI__sync_fetch_and_or_1: 5680 case Builtin::BI__sync_fetch_and_or_2: 5681 case Builtin::BI__sync_fetch_and_or_4: 5682 case Builtin::BI__sync_fetch_and_or_8: 5683 case Builtin::BI__sync_fetch_and_or_16: 5684 BuiltinIndex = 2; 5685 break; 5686 5687 case Builtin::BI__sync_fetch_and_and: 5688 case Builtin::BI__sync_fetch_and_and_1: 5689 case Builtin::BI__sync_fetch_and_and_2: 5690 case Builtin::BI__sync_fetch_and_and_4: 5691 case Builtin::BI__sync_fetch_and_and_8: 5692 case Builtin::BI__sync_fetch_and_and_16: 5693 BuiltinIndex = 3; 5694 break; 5695 5696 case Builtin::BI__sync_fetch_and_xor: 5697 case Builtin::BI__sync_fetch_and_xor_1: 5698 case Builtin::BI__sync_fetch_and_xor_2: 5699 case Builtin::BI__sync_fetch_and_xor_4: 5700 case Builtin::BI__sync_fetch_and_xor_8: 5701 case Builtin::BI__sync_fetch_and_xor_16: 5702 BuiltinIndex = 4; 5703 break; 5704 5705 case Builtin::BI__sync_fetch_and_nand: 5706 case Builtin::BI__sync_fetch_and_nand_1: 5707 case Builtin::BI__sync_fetch_and_nand_2: 5708 case Builtin::BI__sync_fetch_and_nand_4: 5709 case Builtin::BI__sync_fetch_and_nand_8: 5710 case Builtin::BI__sync_fetch_and_nand_16: 5711 BuiltinIndex = 5; 5712 WarnAboutSemanticsChange = true; 5713 break; 5714 5715 case Builtin::BI__sync_add_and_fetch: 5716 case Builtin::BI__sync_add_and_fetch_1: 5717 case Builtin::BI__sync_add_and_fetch_2: 5718 case Builtin::BI__sync_add_and_fetch_4: 5719 case Builtin::BI__sync_add_and_fetch_8: 5720 case Builtin::BI__sync_add_and_fetch_16: 5721 BuiltinIndex = 6; 5722 break; 5723 5724 case Builtin::BI__sync_sub_and_fetch: 5725 case Builtin::BI__sync_sub_and_fetch_1: 5726 case Builtin::BI__sync_sub_and_fetch_2: 5727 case Builtin::BI__sync_sub_and_fetch_4: 5728 case Builtin::BI__sync_sub_and_fetch_8: 5729 case Builtin::BI__sync_sub_and_fetch_16: 5730 BuiltinIndex = 7; 5731 break; 5732 5733 case Builtin::BI__sync_and_and_fetch: 5734 case Builtin::BI__sync_and_and_fetch_1: 5735 case Builtin::BI__sync_and_and_fetch_2: 5736 case Builtin::BI__sync_and_and_fetch_4: 5737 case Builtin::BI__sync_and_and_fetch_8: 5738 case Builtin::BI__sync_and_and_fetch_16: 5739 BuiltinIndex = 8; 5740 break; 5741 5742 case Builtin::BI__sync_or_and_fetch: 5743 case Builtin::BI__sync_or_and_fetch_1: 5744 case Builtin::BI__sync_or_and_fetch_2: 5745 case Builtin::BI__sync_or_and_fetch_4: 5746 case Builtin::BI__sync_or_and_fetch_8: 5747 case Builtin::BI__sync_or_and_fetch_16: 5748 BuiltinIndex = 9; 5749 break; 5750 5751 case Builtin::BI__sync_xor_and_fetch: 5752 case Builtin::BI__sync_xor_and_fetch_1: 5753 case Builtin::BI__sync_xor_and_fetch_2: 5754 case Builtin::BI__sync_xor_and_fetch_4: 5755 case Builtin::BI__sync_xor_and_fetch_8: 5756 case Builtin::BI__sync_xor_and_fetch_16: 5757 BuiltinIndex = 10; 5758 break; 5759 5760 case Builtin::BI__sync_nand_and_fetch: 5761 case Builtin::BI__sync_nand_and_fetch_1: 5762 case Builtin::BI__sync_nand_and_fetch_2: 5763 case Builtin::BI__sync_nand_and_fetch_4: 5764 case Builtin::BI__sync_nand_and_fetch_8: 5765 case Builtin::BI__sync_nand_and_fetch_16: 5766 BuiltinIndex = 11; 5767 WarnAboutSemanticsChange = true; 5768 break; 5769 5770 case Builtin::BI__sync_val_compare_and_swap: 5771 case Builtin::BI__sync_val_compare_and_swap_1: 5772 case Builtin::BI__sync_val_compare_and_swap_2: 5773 case Builtin::BI__sync_val_compare_and_swap_4: 5774 case Builtin::BI__sync_val_compare_and_swap_8: 5775 case Builtin::BI__sync_val_compare_and_swap_16: 5776 BuiltinIndex = 12; 5777 NumFixed = 2; 5778 break; 5779 5780 case Builtin::BI__sync_bool_compare_and_swap: 5781 case Builtin::BI__sync_bool_compare_and_swap_1: 5782 case Builtin::BI__sync_bool_compare_and_swap_2: 5783 case Builtin::BI__sync_bool_compare_and_swap_4: 5784 case Builtin::BI__sync_bool_compare_and_swap_8: 5785 case Builtin::BI__sync_bool_compare_and_swap_16: 5786 BuiltinIndex = 13; 5787 NumFixed = 2; 5788 ResultType = Context.BoolTy; 5789 break; 5790 5791 case Builtin::BI__sync_lock_test_and_set: 5792 case Builtin::BI__sync_lock_test_and_set_1: 5793 case Builtin::BI__sync_lock_test_and_set_2: 5794 case Builtin::BI__sync_lock_test_and_set_4: 5795 case Builtin::BI__sync_lock_test_and_set_8: 5796 case Builtin::BI__sync_lock_test_and_set_16: 5797 BuiltinIndex = 14; 5798 break; 5799 5800 case Builtin::BI__sync_lock_release: 5801 case Builtin::BI__sync_lock_release_1: 5802 case Builtin::BI__sync_lock_release_2: 5803 case Builtin::BI__sync_lock_release_4: 5804 case Builtin::BI__sync_lock_release_8: 5805 case Builtin::BI__sync_lock_release_16: 5806 BuiltinIndex = 15; 5807 NumFixed = 0; 5808 ResultType = Context.VoidTy; 5809 break; 5810 5811 case Builtin::BI__sync_swap: 5812 case Builtin::BI__sync_swap_1: 5813 case Builtin::BI__sync_swap_2: 5814 case Builtin::BI__sync_swap_4: 5815 case Builtin::BI__sync_swap_8: 5816 case Builtin::BI__sync_swap_16: 5817 BuiltinIndex = 16; 5818 break; 5819 } 5820 5821 // Now that we know how many fixed arguments we expect, first check that we 5822 // have at least that many. 5823 if (TheCall->getNumArgs() < 1+NumFixed) { 5824 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5825 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5826 << Callee->getSourceRange(); 5827 return ExprError(); 5828 } 5829 5830 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5831 << Callee->getSourceRange(); 5832 5833 if (WarnAboutSemanticsChange) { 5834 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5835 << Callee->getSourceRange(); 5836 } 5837 5838 // Get the decl for the concrete builtin from this, we can tell what the 5839 // concrete integer type we should convert to is. 5840 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5841 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5842 FunctionDecl *NewBuiltinDecl; 5843 if (NewBuiltinID == BuiltinID) 5844 NewBuiltinDecl = FDecl; 5845 else { 5846 // Perform builtin lookup to avoid redeclaring it. 5847 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5848 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5849 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5850 assert(Res.getFoundDecl()); 5851 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5852 if (!NewBuiltinDecl) 5853 return ExprError(); 5854 } 5855 5856 // The first argument --- the pointer --- has a fixed type; we 5857 // deduce the types of the rest of the arguments accordingly. Walk 5858 // the remaining arguments, converting them to the deduced value type. 5859 for (unsigned i = 0; i != NumFixed; ++i) { 5860 ExprResult Arg = TheCall->getArg(i+1); 5861 5862 // GCC does an implicit conversion to the pointer or integer ValType. This 5863 // can fail in some cases (1i -> int**), check for this error case now. 5864 // Initialize the argument. 5865 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5866 ValType, /*consume*/ false); 5867 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5868 if (Arg.isInvalid()) 5869 return ExprError(); 5870 5871 // Okay, we have something that *can* be converted to the right type. Check 5872 // to see if there is a potentially weird extension going on here. This can 5873 // happen when you do an atomic operation on something like an char* and 5874 // pass in 42. The 42 gets converted to char. This is even more strange 5875 // for things like 45.123 -> char, etc. 5876 // FIXME: Do this check. 5877 TheCall->setArg(i+1, Arg.get()); 5878 } 5879 5880 // Create a new DeclRefExpr to refer to the new decl. 5881 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5882 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5883 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5884 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5885 5886 // Set the callee in the CallExpr. 5887 // FIXME: This loses syntactic information. 5888 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5889 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5890 CK_BuiltinFnToFnPtr); 5891 TheCall->setCallee(PromotedCall.get()); 5892 5893 // Change the result type of the call to match the original value type. This 5894 // is arbitrary, but the codegen for these builtins ins design to handle it 5895 // gracefully. 5896 TheCall->setType(ResultType); 5897 5898 // Prohibit use of _ExtInt with atomic builtins. 5899 // The arguments would have already been converted to the first argument's 5900 // type, so only need to check the first argument. 5901 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5902 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5903 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5904 return ExprError(); 5905 } 5906 5907 return TheCallResult; 5908 } 5909 5910 /// SemaBuiltinNontemporalOverloaded - We have a call to 5911 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5912 /// overloaded function based on the pointer type of its last argument. 5913 /// 5914 /// This function goes through and does final semantic checking for these 5915 /// builtins. 5916 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5917 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5918 DeclRefExpr *DRE = 5919 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5920 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5921 unsigned BuiltinID = FDecl->getBuiltinID(); 5922 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5923 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5924 "Unexpected nontemporal load/store builtin!"); 5925 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5926 unsigned numArgs = isStore ? 2 : 1; 5927 5928 // Ensure that we have the proper number of arguments. 5929 if (checkArgCount(*this, TheCall, numArgs)) 5930 return ExprError(); 5931 5932 // Inspect the last argument of the nontemporal builtin. This should always 5933 // be a pointer type, from which we imply the type of the memory access. 5934 // Because it is a pointer type, we don't have to worry about any implicit 5935 // casts here. 5936 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5937 ExprResult PointerArgResult = 5938 DefaultFunctionArrayLvalueConversion(PointerArg); 5939 5940 if (PointerArgResult.isInvalid()) 5941 return ExprError(); 5942 PointerArg = PointerArgResult.get(); 5943 TheCall->setArg(numArgs - 1, PointerArg); 5944 5945 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5946 if (!pointerType) { 5947 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5948 << PointerArg->getType() << PointerArg->getSourceRange(); 5949 return ExprError(); 5950 } 5951 5952 QualType ValType = pointerType->getPointeeType(); 5953 5954 // Strip any qualifiers off ValType. 5955 ValType = ValType.getUnqualifiedType(); 5956 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5957 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5958 !ValType->isVectorType()) { 5959 Diag(DRE->getBeginLoc(), 5960 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5961 << PointerArg->getType() << PointerArg->getSourceRange(); 5962 return ExprError(); 5963 } 5964 5965 if (!isStore) { 5966 TheCall->setType(ValType); 5967 return TheCallResult; 5968 } 5969 5970 ExprResult ValArg = TheCall->getArg(0); 5971 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5972 Context, ValType, /*consume*/ false); 5973 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5974 if (ValArg.isInvalid()) 5975 return ExprError(); 5976 5977 TheCall->setArg(0, ValArg.get()); 5978 TheCall->setType(Context.VoidTy); 5979 return TheCallResult; 5980 } 5981 5982 /// CheckObjCString - Checks that the argument to the builtin 5983 /// CFString constructor is correct 5984 /// Note: It might also make sense to do the UTF-16 conversion here (would 5985 /// simplify the backend). 5986 bool Sema::CheckObjCString(Expr *Arg) { 5987 Arg = Arg->IgnoreParenCasts(); 5988 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5989 5990 if (!Literal || !Literal->isAscii()) { 5991 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5992 << Arg->getSourceRange(); 5993 return true; 5994 } 5995 5996 if (Literal->containsNonAsciiOrNull()) { 5997 StringRef String = Literal->getString(); 5998 unsigned NumBytes = String.size(); 5999 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6000 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6001 llvm::UTF16 *ToPtr = &ToBuf[0]; 6002 6003 llvm::ConversionResult Result = 6004 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6005 ToPtr + NumBytes, llvm::strictConversion); 6006 // Check for conversion failure. 6007 if (Result != llvm::conversionOK) 6008 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6009 << Arg->getSourceRange(); 6010 } 6011 return false; 6012 } 6013 6014 /// CheckObjCString - Checks that the format string argument to the os_log() 6015 /// and os_trace() functions is correct, and converts it to const char *. 6016 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6017 Arg = Arg->IgnoreParenCasts(); 6018 auto *Literal = dyn_cast<StringLiteral>(Arg); 6019 if (!Literal) { 6020 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6021 Literal = ObjcLiteral->getString(); 6022 } 6023 } 6024 6025 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6026 return ExprError( 6027 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6028 << Arg->getSourceRange()); 6029 } 6030 6031 ExprResult Result(Literal); 6032 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6033 InitializedEntity Entity = 6034 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6035 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6036 return Result; 6037 } 6038 6039 /// Check that the user is calling the appropriate va_start builtin for the 6040 /// target and calling convention. 6041 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6042 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6043 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6044 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6045 TT.getArch() == llvm::Triple::aarch64_32); 6046 bool IsWindows = TT.isOSWindows(); 6047 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6048 if (IsX64 || IsAArch64) { 6049 CallingConv CC = CC_C; 6050 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6051 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6052 if (IsMSVAStart) { 6053 // Don't allow this in System V ABI functions. 6054 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6055 return S.Diag(Fn->getBeginLoc(), 6056 diag::err_ms_va_start_used_in_sysv_function); 6057 } else { 6058 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6059 // On x64 Windows, don't allow this in System V ABI functions. 6060 // (Yes, that means there's no corresponding way to support variadic 6061 // System V ABI functions on Windows.) 6062 if ((IsWindows && CC == CC_X86_64SysV) || 6063 (!IsWindows && CC == CC_Win64)) 6064 return S.Diag(Fn->getBeginLoc(), 6065 diag::err_va_start_used_in_wrong_abi_function) 6066 << !IsWindows; 6067 } 6068 return false; 6069 } 6070 6071 if (IsMSVAStart) 6072 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6073 return false; 6074 } 6075 6076 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6077 ParmVarDecl **LastParam = nullptr) { 6078 // Determine whether the current function, block, or obj-c method is variadic 6079 // and get its parameter list. 6080 bool IsVariadic = false; 6081 ArrayRef<ParmVarDecl *> Params; 6082 DeclContext *Caller = S.CurContext; 6083 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6084 IsVariadic = Block->isVariadic(); 6085 Params = Block->parameters(); 6086 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6087 IsVariadic = FD->isVariadic(); 6088 Params = FD->parameters(); 6089 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6090 IsVariadic = MD->isVariadic(); 6091 // FIXME: This isn't correct for methods (results in bogus warning). 6092 Params = MD->parameters(); 6093 } else if (isa<CapturedDecl>(Caller)) { 6094 // We don't support va_start in a CapturedDecl. 6095 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6096 return true; 6097 } else { 6098 // This must be some other declcontext that parses exprs. 6099 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6100 return true; 6101 } 6102 6103 if (!IsVariadic) { 6104 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6105 return true; 6106 } 6107 6108 if (LastParam) 6109 *LastParam = Params.empty() ? nullptr : Params.back(); 6110 6111 return false; 6112 } 6113 6114 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6115 /// for validity. Emit an error and return true on failure; return false 6116 /// on success. 6117 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6118 Expr *Fn = TheCall->getCallee(); 6119 6120 if (checkVAStartABI(*this, BuiltinID, Fn)) 6121 return true; 6122 6123 if (checkArgCount(*this, TheCall, 2)) 6124 return true; 6125 6126 // Type-check the first argument normally. 6127 if (checkBuiltinArgument(*this, TheCall, 0)) 6128 return true; 6129 6130 // Check that the current function is variadic, and get its last parameter. 6131 ParmVarDecl *LastParam; 6132 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6133 return true; 6134 6135 // Verify that the second argument to the builtin is the last argument of the 6136 // current function or method. 6137 bool SecondArgIsLastNamedArgument = false; 6138 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6139 6140 // These are valid if SecondArgIsLastNamedArgument is false after the next 6141 // block. 6142 QualType Type; 6143 SourceLocation ParamLoc; 6144 bool IsCRegister = false; 6145 6146 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6147 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6148 SecondArgIsLastNamedArgument = PV == LastParam; 6149 6150 Type = PV->getType(); 6151 ParamLoc = PV->getLocation(); 6152 IsCRegister = 6153 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6154 } 6155 } 6156 6157 if (!SecondArgIsLastNamedArgument) 6158 Diag(TheCall->getArg(1)->getBeginLoc(), 6159 diag::warn_second_arg_of_va_start_not_last_named_param); 6160 else if (IsCRegister || Type->isReferenceType() || 6161 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6162 // Promotable integers are UB, but enumerations need a bit of 6163 // extra checking to see what their promotable type actually is. 6164 if (!Type->isPromotableIntegerType()) 6165 return false; 6166 if (!Type->isEnumeralType()) 6167 return true; 6168 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6169 return !(ED && 6170 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6171 }()) { 6172 unsigned Reason = 0; 6173 if (Type->isReferenceType()) Reason = 1; 6174 else if (IsCRegister) Reason = 2; 6175 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6176 Diag(ParamLoc, diag::note_parameter_type) << Type; 6177 } 6178 6179 TheCall->setType(Context.VoidTy); 6180 return false; 6181 } 6182 6183 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6184 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6185 // const char *named_addr); 6186 6187 Expr *Func = Call->getCallee(); 6188 6189 if (Call->getNumArgs() < 3) 6190 return Diag(Call->getEndLoc(), 6191 diag::err_typecheck_call_too_few_args_at_least) 6192 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6193 6194 // Type-check the first argument normally. 6195 if (checkBuiltinArgument(*this, Call, 0)) 6196 return true; 6197 6198 // Check that the current function is variadic. 6199 if (checkVAStartIsInVariadicFunction(*this, Func)) 6200 return true; 6201 6202 // __va_start on Windows does not validate the parameter qualifiers 6203 6204 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6205 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6206 6207 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6208 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6209 6210 const QualType &ConstCharPtrTy = 6211 Context.getPointerType(Context.CharTy.withConst()); 6212 if (!Arg1Ty->isPointerType() || 6213 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 6214 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6215 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6216 << 0 /* qualifier difference */ 6217 << 3 /* parameter mismatch */ 6218 << 2 << Arg1->getType() << ConstCharPtrTy; 6219 6220 const QualType SizeTy = Context.getSizeType(); 6221 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6222 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6223 << Arg2->getType() << SizeTy << 1 /* different class */ 6224 << 0 /* qualifier difference */ 6225 << 3 /* parameter mismatch */ 6226 << 3 << Arg2->getType() << SizeTy; 6227 6228 return false; 6229 } 6230 6231 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6232 /// friends. This is declared to take (...), so we have to check everything. 6233 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6234 if (checkArgCount(*this, TheCall, 2)) 6235 return true; 6236 6237 ExprResult OrigArg0 = TheCall->getArg(0); 6238 ExprResult OrigArg1 = TheCall->getArg(1); 6239 6240 // Do standard promotions between the two arguments, returning their common 6241 // type. 6242 QualType Res = UsualArithmeticConversions( 6243 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6244 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6245 return true; 6246 6247 // Make sure any conversions are pushed back into the call; this is 6248 // type safe since unordered compare builtins are declared as "_Bool 6249 // foo(...)". 6250 TheCall->setArg(0, OrigArg0.get()); 6251 TheCall->setArg(1, OrigArg1.get()); 6252 6253 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6254 return false; 6255 6256 // If the common type isn't a real floating type, then the arguments were 6257 // invalid for this operation. 6258 if (Res.isNull() || !Res->isRealFloatingType()) 6259 return Diag(OrigArg0.get()->getBeginLoc(), 6260 diag::err_typecheck_call_invalid_ordered_compare) 6261 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6262 << SourceRange(OrigArg0.get()->getBeginLoc(), 6263 OrigArg1.get()->getEndLoc()); 6264 6265 return false; 6266 } 6267 6268 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6269 /// __builtin_isnan and friends. This is declared to take (...), so we have 6270 /// to check everything. We expect the last argument to be a floating point 6271 /// value. 6272 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6273 if (checkArgCount(*this, TheCall, NumArgs)) 6274 return true; 6275 6276 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6277 // on all preceding parameters just being int. Try all of those. 6278 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6279 Expr *Arg = TheCall->getArg(i); 6280 6281 if (Arg->isTypeDependent()) 6282 return false; 6283 6284 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6285 6286 if (Res.isInvalid()) 6287 return true; 6288 TheCall->setArg(i, Res.get()); 6289 } 6290 6291 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6292 6293 if (OrigArg->isTypeDependent()) 6294 return false; 6295 6296 // Usual Unary Conversions will convert half to float, which we want for 6297 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6298 // type how it is, but do normal L->Rvalue conversions. 6299 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6300 OrigArg = UsualUnaryConversions(OrigArg).get(); 6301 else 6302 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6303 TheCall->setArg(NumArgs - 1, OrigArg); 6304 6305 // This operation requires a non-_Complex floating-point number. 6306 if (!OrigArg->getType()->isRealFloatingType()) 6307 return Diag(OrigArg->getBeginLoc(), 6308 diag::err_typecheck_call_invalid_unary_fp) 6309 << OrigArg->getType() << OrigArg->getSourceRange(); 6310 6311 return false; 6312 } 6313 6314 /// Perform semantic analysis for a call to __builtin_complex. 6315 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6316 if (checkArgCount(*this, TheCall, 2)) 6317 return true; 6318 6319 bool Dependent = false; 6320 for (unsigned I = 0; I != 2; ++I) { 6321 Expr *Arg = TheCall->getArg(I); 6322 QualType T = Arg->getType(); 6323 if (T->isDependentType()) { 6324 Dependent = true; 6325 continue; 6326 } 6327 6328 // Despite supporting _Complex int, GCC requires a real floating point type 6329 // for the operands of __builtin_complex. 6330 if (!T->isRealFloatingType()) { 6331 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6332 << Arg->getType() << Arg->getSourceRange(); 6333 } 6334 6335 ExprResult Converted = DefaultLvalueConversion(Arg); 6336 if (Converted.isInvalid()) 6337 return true; 6338 TheCall->setArg(I, Converted.get()); 6339 } 6340 6341 if (Dependent) { 6342 TheCall->setType(Context.DependentTy); 6343 return false; 6344 } 6345 6346 Expr *Real = TheCall->getArg(0); 6347 Expr *Imag = TheCall->getArg(1); 6348 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6349 return Diag(Real->getBeginLoc(), 6350 diag::err_typecheck_call_different_arg_types) 6351 << Real->getType() << Imag->getType() 6352 << Real->getSourceRange() << Imag->getSourceRange(); 6353 } 6354 6355 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6356 // don't allow this builtin to form those types either. 6357 // FIXME: Should we allow these types? 6358 if (Real->getType()->isFloat16Type()) 6359 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6360 << "_Float16"; 6361 if (Real->getType()->isHalfType()) 6362 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6363 << "half"; 6364 6365 TheCall->setType(Context.getComplexType(Real->getType())); 6366 return false; 6367 } 6368 6369 // Customized Sema Checking for VSX builtins that have the following signature: 6370 // vector [...] builtinName(vector [...], vector [...], const int); 6371 // Which takes the same type of vectors (any legal vector type) for the first 6372 // two arguments and takes compile time constant for the third argument. 6373 // Example builtins are : 6374 // vector double vec_xxpermdi(vector double, vector double, int); 6375 // vector short vec_xxsldwi(vector short, vector short, int); 6376 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6377 unsigned ExpectedNumArgs = 3; 6378 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6379 return true; 6380 6381 // Check the third argument is a compile time constant 6382 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6383 return Diag(TheCall->getBeginLoc(), 6384 diag::err_vsx_builtin_nonconstant_argument) 6385 << 3 /* argument index */ << TheCall->getDirectCallee() 6386 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6387 TheCall->getArg(2)->getEndLoc()); 6388 6389 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6390 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6391 6392 // Check the type of argument 1 and argument 2 are vectors. 6393 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6394 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6395 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6396 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6397 << TheCall->getDirectCallee() 6398 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6399 TheCall->getArg(1)->getEndLoc()); 6400 } 6401 6402 // Check the first two arguments are the same type. 6403 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6404 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6405 << TheCall->getDirectCallee() 6406 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6407 TheCall->getArg(1)->getEndLoc()); 6408 } 6409 6410 // When default clang type checking is turned off and the customized type 6411 // checking is used, the returning type of the function must be explicitly 6412 // set. Otherwise it is _Bool by default. 6413 TheCall->setType(Arg1Ty); 6414 6415 return false; 6416 } 6417 6418 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6419 // This is declared to take (...), so we have to check everything. 6420 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6421 if (TheCall->getNumArgs() < 2) 6422 return ExprError(Diag(TheCall->getEndLoc(), 6423 diag::err_typecheck_call_too_few_args_at_least) 6424 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6425 << TheCall->getSourceRange()); 6426 6427 // Determine which of the following types of shufflevector we're checking: 6428 // 1) unary, vector mask: (lhs, mask) 6429 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6430 QualType resType = TheCall->getArg(0)->getType(); 6431 unsigned numElements = 0; 6432 6433 if (!TheCall->getArg(0)->isTypeDependent() && 6434 !TheCall->getArg(1)->isTypeDependent()) { 6435 QualType LHSType = TheCall->getArg(0)->getType(); 6436 QualType RHSType = TheCall->getArg(1)->getType(); 6437 6438 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6439 return ExprError( 6440 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6441 << TheCall->getDirectCallee() 6442 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6443 TheCall->getArg(1)->getEndLoc())); 6444 6445 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6446 unsigned numResElements = TheCall->getNumArgs() - 2; 6447 6448 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6449 // with mask. If so, verify that RHS is an integer vector type with the 6450 // same number of elts as lhs. 6451 if (TheCall->getNumArgs() == 2) { 6452 if (!RHSType->hasIntegerRepresentation() || 6453 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6454 return ExprError(Diag(TheCall->getBeginLoc(), 6455 diag::err_vec_builtin_incompatible_vector) 6456 << TheCall->getDirectCallee() 6457 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6458 TheCall->getArg(1)->getEndLoc())); 6459 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6460 return ExprError(Diag(TheCall->getBeginLoc(), 6461 diag::err_vec_builtin_incompatible_vector) 6462 << TheCall->getDirectCallee() 6463 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6464 TheCall->getArg(1)->getEndLoc())); 6465 } else if (numElements != numResElements) { 6466 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6467 resType = Context.getVectorType(eltType, numResElements, 6468 VectorType::GenericVector); 6469 } 6470 } 6471 6472 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6473 if (TheCall->getArg(i)->isTypeDependent() || 6474 TheCall->getArg(i)->isValueDependent()) 6475 continue; 6476 6477 Optional<llvm::APSInt> Result; 6478 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6479 return ExprError(Diag(TheCall->getBeginLoc(), 6480 diag::err_shufflevector_nonconstant_argument) 6481 << TheCall->getArg(i)->getSourceRange()); 6482 6483 // Allow -1 which will be translated to undef in the IR. 6484 if (Result->isSigned() && Result->isAllOnesValue()) 6485 continue; 6486 6487 if (Result->getActiveBits() > 64 || 6488 Result->getZExtValue() >= numElements * 2) 6489 return ExprError(Diag(TheCall->getBeginLoc(), 6490 diag::err_shufflevector_argument_too_large) 6491 << TheCall->getArg(i)->getSourceRange()); 6492 } 6493 6494 SmallVector<Expr*, 32> exprs; 6495 6496 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6497 exprs.push_back(TheCall->getArg(i)); 6498 TheCall->setArg(i, nullptr); 6499 } 6500 6501 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6502 TheCall->getCallee()->getBeginLoc(), 6503 TheCall->getRParenLoc()); 6504 } 6505 6506 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6507 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6508 SourceLocation BuiltinLoc, 6509 SourceLocation RParenLoc) { 6510 ExprValueKind VK = VK_PRValue; 6511 ExprObjectKind OK = OK_Ordinary; 6512 QualType DstTy = TInfo->getType(); 6513 QualType SrcTy = E->getType(); 6514 6515 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6516 return ExprError(Diag(BuiltinLoc, 6517 diag::err_convertvector_non_vector) 6518 << E->getSourceRange()); 6519 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6520 return ExprError(Diag(BuiltinLoc, 6521 diag::err_convertvector_non_vector_type)); 6522 6523 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6524 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6525 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6526 if (SrcElts != DstElts) 6527 return ExprError(Diag(BuiltinLoc, 6528 diag::err_convertvector_incompatible_vector) 6529 << E->getSourceRange()); 6530 } 6531 6532 return new (Context) 6533 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6534 } 6535 6536 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6537 // This is declared to take (const void*, ...) and can take two 6538 // optional constant int args. 6539 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6540 unsigned NumArgs = TheCall->getNumArgs(); 6541 6542 if (NumArgs > 3) 6543 return Diag(TheCall->getEndLoc(), 6544 diag::err_typecheck_call_too_many_args_at_most) 6545 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6546 6547 // Argument 0 is checked for us and the remaining arguments must be 6548 // constant integers. 6549 for (unsigned i = 1; i != NumArgs; ++i) 6550 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6551 return true; 6552 6553 return false; 6554 } 6555 6556 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6557 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6558 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6559 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6560 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6561 if (checkArgCount(*this, TheCall, 1)) 6562 return true; 6563 Expr *Arg = TheCall->getArg(0); 6564 if (Arg->isInstantiationDependent()) 6565 return false; 6566 6567 QualType ArgTy = Arg->getType(); 6568 if (!ArgTy->hasFloatingRepresentation()) 6569 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6570 << ArgTy; 6571 if (Arg->isLValue()) { 6572 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6573 TheCall->setArg(0, FirstArg.get()); 6574 } 6575 TheCall->setType(TheCall->getArg(0)->getType()); 6576 return false; 6577 } 6578 6579 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6580 // __assume does not evaluate its arguments, and should warn if its argument 6581 // has side effects. 6582 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6583 Expr *Arg = TheCall->getArg(0); 6584 if (Arg->isInstantiationDependent()) return false; 6585 6586 if (Arg->HasSideEffects(Context)) 6587 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6588 << Arg->getSourceRange() 6589 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6590 6591 return false; 6592 } 6593 6594 /// Handle __builtin_alloca_with_align. This is declared 6595 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6596 /// than 8. 6597 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6598 // The alignment must be a constant integer. 6599 Expr *Arg = TheCall->getArg(1); 6600 6601 // We can't check the value of a dependent argument. 6602 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6603 if (const auto *UE = 6604 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6605 if (UE->getKind() == UETT_AlignOf || 6606 UE->getKind() == UETT_PreferredAlignOf) 6607 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6608 << Arg->getSourceRange(); 6609 6610 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6611 6612 if (!Result.isPowerOf2()) 6613 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6614 << Arg->getSourceRange(); 6615 6616 if (Result < Context.getCharWidth()) 6617 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6618 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6619 6620 if (Result > std::numeric_limits<int32_t>::max()) 6621 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6622 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6623 } 6624 6625 return false; 6626 } 6627 6628 /// Handle __builtin_assume_aligned. This is declared 6629 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6630 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6631 unsigned NumArgs = TheCall->getNumArgs(); 6632 6633 if (NumArgs > 3) 6634 return Diag(TheCall->getEndLoc(), 6635 diag::err_typecheck_call_too_many_args_at_most) 6636 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6637 6638 // The alignment must be a constant integer. 6639 Expr *Arg = TheCall->getArg(1); 6640 6641 // We can't check the value of a dependent argument. 6642 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6643 llvm::APSInt Result; 6644 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6645 return true; 6646 6647 if (!Result.isPowerOf2()) 6648 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6649 << Arg->getSourceRange(); 6650 6651 if (Result > Sema::MaximumAlignment) 6652 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6653 << Arg->getSourceRange() << Sema::MaximumAlignment; 6654 } 6655 6656 if (NumArgs > 2) { 6657 ExprResult Arg(TheCall->getArg(2)); 6658 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6659 Context.getSizeType(), false); 6660 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6661 if (Arg.isInvalid()) return true; 6662 TheCall->setArg(2, Arg.get()); 6663 } 6664 6665 return false; 6666 } 6667 6668 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6669 unsigned BuiltinID = 6670 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6671 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6672 6673 unsigned NumArgs = TheCall->getNumArgs(); 6674 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6675 if (NumArgs < NumRequiredArgs) { 6676 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6677 << 0 /* function call */ << NumRequiredArgs << NumArgs 6678 << TheCall->getSourceRange(); 6679 } 6680 if (NumArgs >= NumRequiredArgs + 0x100) { 6681 return Diag(TheCall->getEndLoc(), 6682 diag::err_typecheck_call_too_many_args_at_most) 6683 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6684 << TheCall->getSourceRange(); 6685 } 6686 unsigned i = 0; 6687 6688 // For formatting call, check buffer arg. 6689 if (!IsSizeCall) { 6690 ExprResult Arg(TheCall->getArg(i)); 6691 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6692 Context, Context.VoidPtrTy, false); 6693 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6694 if (Arg.isInvalid()) 6695 return true; 6696 TheCall->setArg(i, Arg.get()); 6697 i++; 6698 } 6699 6700 // Check string literal arg. 6701 unsigned FormatIdx = i; 6702 { 6703 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6704 if (Arg.isInvalid()) 6705 return true; 6706 TheCall->setArg(i, Arg.get()); 6707 i++; 6708 } 6709 6710 // Make sure variadic args are scalar. 6711 unsigned FirstDataArg = i; 6712 while (i < NumArgs) { 6713 ExprResult Arg = DefaultVariadicArgumentPromotion( 6714 TheCall->getArg(i), VariadicFunction, nullptr); 6715 if (Arg.isInvalid()) 6716 return true; 6717 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6718 if (ArgSize.getQuantity() >= 0x100) { 6719 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6720 << i << (int)ArgSize.getQuantity() << 0xff 6721 << TheCall->getSourceRange(); 6722 } 6723 TheCall->setArg(i, Arg.get()); 6724 i++; 6725 } 6726 6727 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6728 // call to avoid duplicate diagnostics. 6729 if (!IsSizeCall) { 6730 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6731 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6732 bool Success = CheckFormatArguments( 6733 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6734 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6735 CheckedVarArgs); 6736 if (!Success) 6737 return true; 6738 } 6739 6740 if (IsSizeCall) { 6741 TheCall->setType(Context.getSizeType()); 6742 } else { 6743 TheCall->setType(Context.VoidPtrTy); 6744 } 6745 return false; 6746 } 6747 6748 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6749 /// TheCall is a constant expression. 6750 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6751 llvm::APSInt &Result) { 6752 Expr *Arg = TheCall->getArg(ArgNum); 6753 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6754 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6755 6756 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6757 6758 Optional<llvm::APSInt> R; 6759 if (!(R = Arg->getIntegerConstantExpr(Context))) 6760 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6761 << FDecl->getDeclName() << Arg->getSourceRange(); 6762 Result = *R; 6763 return false; 6764 } 6765 6766 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6767 /// TheCall is a constant expression in the range [Low, High]. 6768 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6769 int Low, int High, bool RangeIsError) { 6770 if (isConstantEvaluated()) 6771 return false; 6772 llvm::APSInt Result; 6773 6774 // We can't check the value of a dependent argument. 6775 Expr *Arg = TheCall->getArg(ArgNum); 6776 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6777 return false; 6778 6779 // Check constant-ness first. 6780 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6781 return true; 6782 6783 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6784 if (RangeIsError) 6785 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6786 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 6787 else 6788 // Defer the warning until we know if the code will be emitted so that 6789 // dead code can ignore this. 6790 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6791 PDiag(diag::warn_argument_invalid_range) 6792 << toString(Result, 10) << Low << High 6793 << Arg->getSourceRange()); 6794 } 6795 6796 return false; 6797 } 6798 6799 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6800 /// TheCall is a constant expression is a multiple of Num.. 6801 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6802 unsigned Num) { 6803 llvm::APSInt Result; 6804 6805 // We can't check the value of a dependent argument. 6806 Expr *Arg = TheCall->getArg(ArgNum); 6807 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6808 return false; 6809 6810 // Check constant-ness first. 6811 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6812 return true; 6813 6814 if (Result.getSExtValue() % Num != 0) 6815 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6816 << Num << Arg->getSourceRange(); 6817 6818 return false; 6819 } 6820 6821 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6822 /// constant expression representing a power of 2. 6823 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6824 llvm::APSInt Result; 6825 6826 // We can't check the value of a dependent argument. 6827 Expr *Arg = TheCall->getArg(ArgNum); 6828 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6829 return false; 6830 6831 // Check constant-ness first. 6832 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6833 return true; 6834 6835 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6836 // and only if x is a power of 2. 6837 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6838 return false; 6839 6840 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6841 << Arg->getSourceRange(); 6842 } 6843 6844 static bool IsShiftedByte(llvm::APSInt Value) { 6845 if (Value.isNegative()) 6846 return false; 6847 6848 // Check if it's a shifted byte, by shifting it down 6849 while (true) { 6850 // If the value fits in the bottom byte, the check passes. 6851 if (Value < 0x100) 6852 return true; 6853 6854 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6855 // fails. 6856 if ((Value & 0xFF) != 0) 6857 return false; 6858 6859 // If the bottom 8 bits are all 0, but something above that is nonzero, 6860 // then shifting the value right by 8 bits won't affect whether it's a 6861 // shifted byte or not. So do that, and go round again. 6862 Value >>= 8; 6863 } 6864 } 6865 6866 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6867 /// a constant expression representing an arbitrary byte value shifted left by 6868 /// a multiple of 8 bits. 6869 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6870 unsigned ArgBits) { 6871 llvm::APSInt Result; 6872 6873 // We can't check the value of a dependent argument. 6874 Expr *Arg = TheCall->getArg(ArgNum); 6875 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6876 return false; 6877 6878 // Check constant-ness first. 6879 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6880 return true; 6881 6882 // Truncate to the given size. 6883 Result = Result.getLoBits(ArgBits); 6884 Result.setIsUnsigned(true); 6885 6886 if (IsShiftedByte(Result)) 6887 return false; 6888 6889 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6890 << Arg->getSourceRange(); 6891 } 6892 6893 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6894 /// TheCall is a constant expression representing either a shifted byte value, 6895 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6896 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6897 /// Arm MVE intrinsics. 6898 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6899 int ArgNum, 6900 unsigned ArgBits) { 6901 llvm::APSInt Result; 6902 6903 // We can't check the value of a dependent argument. 6904 Expr *Arg = TheCall->getArg(ArgNum); 6905 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6906 return false; 6907 6908 // Check constant-ness first. 6909 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6910 return true; 6911 6912 // Truncate to the given size. 6913 Result = Result.getLoBits(ArgBits); 6914 Result.setIsUnsigned(true); 6915 6916 // Check to see if it's in either of the required forms. 6917 if (IsShiftedByte(Result) || 6918 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6919 return false; 6920 6921 return Diag(TheCall->getBeginLoc(), 6922 diag::err_argument_not_shifted_byte_or_xxff) 6923 << Arg->getSourceRange(); 6924 } 6925 6926 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6927 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6928 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6929 if (checkArgCount(*this, TheCall, 2)) 6930 return true; 6931 Expr *Arg0 = TheCall->getArg(0); 6932 Expr *Arg1 = TheCall->getArg(1); 6933 6934 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6935 if (FirstArg.isInvalid()) 6936 return true; 6937 QualType FirstArgType = FirstArg.get()->getType(); 6938 if (!FirstArgType->isAnyPointerType()) 6939 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6940 << "first" << FirstArgType << Arg0->getSourceRange(); 6941 TheCall->setArg(0, FirstArg.get()); 6942 6943 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6944 if (SecArg.isInvalid()) 6945 return true; 6946 QualType SecArgType = SecArg.get()->getType(); 6947 if (!SecArgType->isIntegerType()) 6948 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6949 << "second" << SecArgType << Arg1->getSourceRange(); 6950 6951 // Derive the return type from the pointer argument. 6952 TheCall->setType(FirstArgType); 6953 return false; 6954 } 6955 6956 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6957 if (checkArgCount(*this, TheCall, 2)) 6958 return true; 6959 6960 Expr *Arg0 = TheCall->getArg(0); 6961 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6962 if (FirstArg.isInvalid()) 6963 return true; 6964 QualType FirstArgType = FirstArg.get()->getType(); 6965 if (!FirstArgType->isAnyPointerType()) 6966 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6967 << "first" << FirstArgType << Arg0->getSourceRange(); 6968 TheCall->setArg(0, FirstArg.get()); 6969 6970 // Derive the return type from the pointer argument. 6971 TheCall->setType(FirstArgType); 6972 6973 // Second arg must be an constant in range [0,15] 6974 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6975 } 6976 6977 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6978 if (checkArgCount(*this, TheCall, 2)) 6979 return true; 6980 Expr *Arg0 = TheCall->getArg(0); 6981 Expr *Arg1 = TheCall->getArg(1); 6982 6983 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6984 if (FirstArg.isInvalid()) 6985 return true; 6986 QualType FirstArgType = FirstArg.get()->getType(); 6987 if (!FirstArgType->isAnyPointerType()) 6988 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6989 << "first" << FirstArgType << Arg0->getSourceRange(); 6990 6991 QualType SecArgType = Arg1->getType(); 6992 if (!SecArgType->isIntegerType()) 6993 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6994 << "second" << SecArgType << Arg1->getSourceRange(); 6995 TheCall->setType(Context.IntTy); 6996 return false; 6997 } 6998 6999 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7000 BuiltinID == AArch64::BI__builtin_arm_stg) { 7001 if (checkArgCount(*this, TheCall, 1)) 7002 return true; 7003 Expr *Arg0 = TheCall->getArg(0); 7004 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7005 if (FirstArg.isInvalid()) 7006 return true; 7007 7008 QualType FirstArgType = FirstArg.get()->getType(); 7009 if (!FirstArgType->isAnyPointerType()) 7010 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7011 << "first" << FirstArgType << Arg0->getSourceRange(); 7012 TheCall->setArg(0, FirstArg.get()); 7013 7014 // Derive the return type from the pointer argument. 7015 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7016 TheCall->setType(FirstArgType); 7017 return false; 7018 } 7019 7020 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7021 Expr *ArgA = TheCall->getArg(0); 7022 Expr *ArgB = TheCall->getArg(1); 7023 7024 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7025 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7026 7027 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7028 return true; 7029 7030 QualType ArgTypeA = ArgExprA.get()->getType(); 7031 QualType ArgTypeB = ArgExprB.get()->getType(); 7032 7033 auto isNull = [&] (Expr *E) -> bool { 7034 return E->isNullPointerConstant( 7035 Context, Expr::NPC_ValueDependentIsNotNull); }; 7036 7037 // argument should be either a pointer or null 7038 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7039 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7040 << "first" << ArgTypeA << ArgA->getSourceRange(); 7041 7042 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7043 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7044 << "second" << ArgTypeB << ArgB->getSourceRange(); 7045 7046 // Ensure Pointee types are compatible 7047 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7048 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7049 QualType pointeeA = ArgTypeA->getPointeeType(); 7050 QualType pointeeB = ArgTypeB->getPointeeType(); 7051 if (!Context.typesAreCompatible( 7052 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7053 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7054 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7055 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7056 << ArgB->getSourceRange(); 7057 } 7058 } 7059 7060 // at least one argument should be pointer type 7061 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7062 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7063 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7064 7065 if (isNull(ArgA)) // adopt type of the other pointer 7066 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7067 7068 if (isNull(ArgB)) 7069 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7070 7071 TheCall->setArg(0, ArgExprA.get()); 7072 TheCall->setArg(1, ArgExprB.get()); 7073 TheCall->setType(Context.LongLongTy); 7074 return false; 7075 } 7076 assert(false && "Unhandled ARM MTE intrinsic"); 7077 return true; 7078 } 7079 7080 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7081 /// TheCall is an ARM/AArch64 special register string literal. 7082 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7083 int ArgNum, unsigned ExpectedFieldNum, 7084 bool AllowName) { 7085 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7086 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7087 BuiltinID == ARM::BI__builtin_arm_rsr || 7088 BuiltinID == ARM::BI__builtin_arm_rsrp || 7089 BuiltinID == ARM::BI__builtin_arm_wsr || 7090 BuiltinID == ARM::BI__builtin_arm_wsrp; 7091 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7092 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7093 BuiltinID == AArch64::BI__builtin_arm_rsr || 7094 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7095 BuiltinID == AArch64::BI__builtin_arm_wsr || 7096 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7097 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7098 7099 // We can't check the value of a dependent argument. 7100 Expr *Arg = TheCall->getArg(ArgNum); 7101 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7102 return false; 7103 7104 // Check if the argument is a string literal. 7105 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7106 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7107 << Arg->getSourceRange(); 7108 7109 // Check the type of special register given. 7110 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7111 SmallVector<StringRef, 6> Fields; 7112 Reg.split(Fields, ":"); 7113 7114 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7115 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7116 << Arg->getSourceRange(); 7117 7118 // If the string is the name of a register then we cannot check that it is 7119 // valid here but if the string is of one the forms described in ACLE then we 7120 // can check that the supplied fields are integers and within the valid 7121 // ranges. 7122 if (Fields.size() > 1) { 7123 bool FiveFields = Fields.size() == 5; 7124 7125 bool ValidString = true; 7126 if (IsARMBuiltin) { 7127 ValidString &= Fields[0].startswith_insensitive("cp") || 7128 Fields[0].startswith_insensitive("p"); 7129 if (ValidString) 7130 Fields[0] = Fields[0].drop_front( 7131 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7132 7133 ValidString &= Fields[2].startswith_insensitive("c"); 7134 if (ValidString) 7135 Fields[2] = Fields[2].drop_front(1); 7136 7137 if (FiveFields) { 7138 ValidString &= Fields[3].startswith_insensitive("c"); 7139 if (ValidString) 7140 Fields[3] = Fields[3].drop_front(1); 7141 } 7142 } 7143 7144 SmallVector<int, 5> Ranges; 7145 if (FiveFields) 7146 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7147 else 7148 Ranges.append({15, 7, 15}); 7149 7150 for (unsigned i=0; i<Fields.size(); ++i) { 7151 int IntField; 7152 ValidString &= !Fields[i].getAsInteger(10, IntField); 7153 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7154 } 7155 7156 if (!ValidString) 7157 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7158 << Arg->getSourceRange(); 7159 } else if (IsAArch64Builtin && Fields.size() == 1) { 7160 // If the register name is one of those that appear in the condition below 7161 // and the special register builtin being used is one of the write builtins, 7162 // then we require that the argument provided for writing to the register 7163 // is an integer constant expression. This is because it will be lowered to 7164 // an MSR (immediate) instruction, so we need to know the immediate at 7165 // compile time. 7166 if (TheCall->getNumArgs() != 2) 7167 return false; 7168 7169 std::string RegLower = Reg.lower(); 7170 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7171 RegLower != "pan" && RegLower != "uao") 7172 return false; 7173 7174 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7175 } 7176 7177 return false; 7178 } 7179 7180 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7181 /// Emit an error and return true on failure; return false on success. 7182 /// TypeStr is a string containing the type descriptor of the value returned by 7183 /// the builtin and the descriptors of the expected type of the arguments. 7184 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 7185 7186 assert((TypeStr[0] != '\0') && 7187 "Invalid types in PPC MMA builtin declaration"); 7188 7189 unsigned Mask = 0; 7190 unsigned ArgNum = 0; 7191 7192 // The first type in TypeStr is the type of the value returned by the 7193 // builtin. So we first read that type and change the type of TheCall. 7194 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7195 TheCall->setType(type); 7196 7197 while (*TypeStr != '\0') { 7198 Mask = 0; 7199 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7200 if (ArgNum >= TheCall->getNumArgs()) { 7201 ArgNum++; 7202 break; 7203 } 7204 7205 Expr *Arg = TheCall->getArg(ArgNum); 7206 QualType ArgType = Arg->getType(); 7207 7208 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7209 (!ExpectedType->isVoidPointerType() && 7210 ArgType.getCanonicalType() != ExpectedType)) 7211 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7212 << ArgType << ExpectedType << 1 << 0 << 0; 7213 7214 // If the value of the Mask is not 0, we have a constraint in the size of 7215 // the integer argument so here we ensure the argument is a constant that 7216 // is in the valid range. 7217 if (Mask != 0 && 7218 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7219 return true; 7220 7221 ArgNum++; 7222 } 7223 7224 // In case we exited early from the previous loop, there are other types to 7225 // read from TypeStr. So we need to read them all to ensure we have the right 7226 // number of arguments in TheCall and if it is not the case, to display a 7227 // better error message. 7228 while (*TypeStr != '\0') { 7229 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7230 ArgNum++; 7231 } 7232 if (checkArgCount(*this, TheCall, ArgNum)) 7233 return true; 7234 7235 return false; 7236 } 7237 7238 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7239 /// This checks that the target supports __builtin_longjmp and 7240 /// that val is a constant 1. 7241 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7242 if (!Context.getTargetInfo().hasSjLjLowering()) 7243 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7244 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7245 7246 Expr *Arg = TheCall->getArg(1); 7247 llvm::APSInt Result; 7248 7249 // TODO: This is less than ideal. Overload this to take a value. 7250 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7251 return true; 7252 7253 if (Result != 1) 7254 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7255 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7256 7257 return false; 7258 } 7259 7260 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7261 /// This checks that the target supports __builtin_setjmp. 7262 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7263 if (!Context.getTargetInfo().hasSjLjLowering()) 7264 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7265 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7266 return false; 7267 } 7268 7269 namespace { 7270 7271 class UncoveredArgHandler { 7272 enum { Unknown = -1, AllCovered = -2 }; 7273 7274 signed FirstUncoveredArg = Unknown; 7275 SmallVector<const Expr *, 4> DiagnosticExprs; 7276 7277 public: 7278 UncoveredArgHandler() = default; 7279 7280 bool hasUncoveredArg() const { 7281 return (FirstUncoveredArg >= 0); 7282 } 7283 7284 unsigned getUncoveredArg() const { 7285 assert(hasUncoveredArg() && "no uncovered argument"); 7286 return FirstUncoveredArg; 7287 } 7288 7289 void setAllCovered() { 7290 // A string has been found with all arguments covered, so clear out 7291 // the diagnostics. 7292 DiagnosticExprs.clear(); 7293 FirstUncoveredArg = AllCovered; 7294 } 7295 7296 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7297 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7298 7299 // Don't update if a previous string covers all arguments. 7300 if (FirstUncoveredArg == AllCovered) 7301 return; 7302 7303 // UncoveredArgHandler tracks the highest uncovered argument index 7304 // and with it all the strings that match this index. 7305 if (NewFirstUncoveredArg == FirstUncoveredArg) 7306 DiagnosticExprs.push_back(StrExpr); 7307 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7308 DiagnosticExprs.clear(); 7309 DiagnosticExprs.push_back(StrExpr); 7310 FirstUncoveredArg = NewFirstUncoveredArg; 7311 } 7312 } 7313 7314 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7315 }; 7316 7317 enum StringLiteralCheckType { 7318 SLCT_NotALiteral, 7319 SLCT_UncheckedLiteral, 7320 SLCT_CheckedLiteral 7321 }; 7322 7323 } // namespace 7324 7325 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7326 BinaryOperatorKind BinOpKind, 7327 bool AddendIsRight) { 7328 unsigned BitWidth = Offset.getBitWidth(); 7329 unsigned AddendBitWidth = Addend.getBitWidth(); 7330 // There might be negative interim results. 7331 if (Addend.isUnsigned()) { 7332 Addend = Addend.zext(++AddendBitWidth); 7333 Addend.setIsSigned(true); 7334 } 7335 // Adjust the bit width of the APSInts. 7336 if (AddendBitWidth > BitWidth) { 7337 Offset = Offset.sext(AddendBitWidth); 7338 BitWidth = AddendBitWidth; 7339 } else if (BitWidth > AddendBitWidth) { 7340 Addend = Addend.sext(BitWidth); 7341 } 7342 7343 bool Ov = false; 7344 llvm::APSInt ResOffset = Offset; 7345 if (BinOpKind == BO_Add) 7346 ResOffset = Offset.sadd_ov(Addend, Ov); 7347 else { 7348 assert(AddendIsRight && BinOpKind == BO_Sub && 7349 "operator must be add or sub with addend on the right"); 7350 ResOffset = Offset.ssub_ov(Addend, Ov); 7351 } 7352 7353 // We add an offset to a pointer here so we should support an offset as big as 7354 // possible. 7355 if (Ov) { 7356 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7357 "index (intermediate) result too big"); 7358 Offset = Offset.sext(2 * BitWidth); 7359 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7360 return; 7361 } 7362 7363 Offset = ResOffset; 7364 } 7365 7366 namespace { 7367 7368 // This is a wrapper class around StringLiteral to support offsetted string 7369 // literals as format strings. It takes the offset into account when returning 7370 // the string and its length or the source locations to display notes correctly. 7371 class FormatStringLiteral { 7372 const StringLiteral *FExpr; 7373 int64_t Offset; 7374 7375 public: 7376 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7377 : FExpr(fexpr), Offset(Offset) {} 7378 7379 StringRef getString() const { 7380 return FExpr->getString().drop_front(Offset); 7381 } 7382 7383 unsigned getByteLength() const { 7384 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7385 } 7386 7387 unsigned getLength() const { return FExpr->getLength() - Offset; } 7388 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7389 7390 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7391 7392 QualType getType() const { return FExpr->getType(); } 7393 7394 bool isAscii() const { return FExpr->isAscii(); } 7395 bool isWide() const { return FExpr->isWide(); } 7396 bool isUTF8() const { return FExpr->isUTF8(); } 7397 bool isUTF16() const { return FExpr->isUTF16(); } 7398 bool isUTF32() const { return FExpr->isUTF32(); } 7399 bool isPascal() const { return FExpr->isPascal(); } 7400 7401 SourceLocation getLocationOfByte( 7402 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7403 const TargetInfo &Target, unsigned *StartToken = nullptr, 7404 unsigned *StartTokenByteOffset = nullptr) const { 7405 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7406 StartToken, StartTokenByteOffset); 7407 } 7408 7409 SourceLocation getBeginLoc() const LLVM_READONLY { 7410 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7411 } 7412 7413 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7414 }; 7415 7416 } // namespace 7417 7418 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7419 const Expr *OrigFormatExpr, 7420 ArrayRef<const Expr *> Args, 7421 bool HasVAListArg, unsigned format_idx, 7422 unsigned firstDataArg, 7423 Sema::FormatStringType Type, 7424 bool inFunctionCall, 7425 Sema::VariadicCallType CallType, 7426 llvm::SmallBitVector &CheckedVarArgs, 7427 UncoveredArgHandler &UncoveredArg, 7428 bool IgnoreStringsWithoutSpecifiers); 7429 7430 // Determine if an expression is a string literal or constant string. 7431 // If this function returns false on the arguments to a function expecting a 7432 // format string, we will usually need to emit a warning. 7433 // True string literals are then checked by CheckFormatString. 7434 static StringLiteralCheckType 7435 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7436 bool HasVAListArg, unsigned format_idx, 7437 unsigned firstDataArg, Sema::FormatStringType Type, 7438 Sema::VariadicCallType CallType, bool InFunctionCall, 7439 llvm::SmallBitVector &CheckedVarArgs, 7440 UncoveredArgHandler &UncoveredArg, 7441 llvm::APSInt Offset, 7442 bool IgnoreStringsWithoutSpecifiers = false) { 7443 if (S.isConstantEvaluated()) 7444 return SLCT_NotALiteral; 7445 tryAgain: 7446 assert(Offset.isSigned() && "invalid offset"); 7447 7448 if (E->isTypeDependent() || E->isValueDependent()) 7449 return SLCT_NotALiteral; 7450 7451 E = E->IgnoreParenCasts(); 7452 7453 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7454 // Technically -Wformat-nonliteral does not warn about this case. 7455 // The behavior of printf and friends in this case is implementation 7456 // dependent. Ideally if the format string cannot be null then 7457 // it should have a 'nonnull' attribute in the function prototype. 7458 return SLCT_UncheckedLiteral; 7459 7460 switch (E->getStmtClass()) { 7461 case Stmt::BinaryConditionalOperatorClass: 7462 case Stmt::ConditionalOperatorClass: { 7463 // The expression is a literal if both sub-expressions were, and it was 7464 // completely checked only if both sub-expressions were checked. 7465 const AbstractConditionalOperator *C = 7466 cast<AbstractConditionalOperator>(E); 7467 7468 // Determine whether it is necessary to check both sub-expressions, for 7469 // example, because the condition expression is a constant that can be 7470 // evaluated at compile time. 7471 bool CheckLeft = true, CheckRight = true; 7472 7473 bool Cond; 7474 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7475 S.isConstantEvaluated())) { 7476 if (Cond) 7477 CheckRight = false; 7478 else 7479 CheckLeft = false; 7480 } 7481 7482 // We need to maintain the offsets for the right and the left hand side 7483 // separately to check if every possible indexed expression is a valid 7484 // string literal. They might have different offsets for different string 7485 // literals in the end. 7486 StringLiteralCheckType Left; 7487 if (!CheckLeft) 7488 Left = SLCT_UncheckedLiteral; 7489 else { 7490 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7491 HasVAListArg, format_idx, firstDataArg, 7492 Type, CallType, InFunctionCall, 7493 CheckedVarArgs, UncoveredArg, Offset, 7494 IgnoreStringsWithoutSpecifiers); 7495 if (Left == SLCT_NotALiteral || !CheckRight) { 7496 return Left; 7497 } 7498 } 7499 7500 StringLiteralCheckType Right = checkFormatStringExpr( 7501 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7502 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7503 IgnoreStringsWithoutSpecifiers); 7504 7505 return (CheckLeft && Left < Right) ? Left : Right; 7506 } 7507 7508 case Stmt::ImplicitCastExprClass: 7509 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7510 goto tryAgain; 7511 7512 case Stmt::OpaqueValueExprClass: 7513 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7514 E = src; 7515 goto tryAgain; 7516 } 7517 return SLCT_NotALiteral; 7518 7519 case Stmt::PredefinedExprClass: 7520 // While __func__, etc., are technically not string literals, they 7521 // cannot contain format specifiers and thus are not a security 7522 // liability. 7523 return SLCT_UncheckedLiteral; 7524 7525 case Stmt::DeclRefExprClass: { 7526 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7527 7528 // As an exception, do not flag errors for variables binding to 7529 // const string literals. 7530 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7531 bool isConstant = false; 7532 QualType T = DR->getType(); 7533 7534 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7535 isConstant = AT->getElementType().isConstant(S.Context); 7536 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7537 isConstant = T.isConstant(S.Context) && 7538 PT->getPointeeType().isConstant(S.Context); 7539 } else if (T->isObjCObjectPointerType()) { 7540 // In ObjC, there is usually no "const ObjectPointer" type, 7541 // so don't check if the pointee type is constant. 7542 isConstant = T.isConstant(S.Context); 7543 } 7544 7545 if (isConstant) { 7546 if (const Expr *Init = VD->getAnyInitializer()) { 7547 // Look through initializers like const char c[] = { "foo" } 7548 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7549 if (InitList->isStringLiteralInit()) 7550 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7551 } 7552 return checkFormatStringExpr(S, Init, Args, 7553 HasVAListArg, format_idx, 7554 firstDataArg, Type, CallType, 7555 /*InFunctionCall*/ false, CheckedVarArgs, 7556 UncoveredArg, Offset); 7557 } 7558 } 7559 7560 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7561 // special check to see if the format string is a function parameter 7562 // of the function calling the printf function. If the function 7563 // has an attribute indicating it is a printf-like function, then we 7564 // should suppress warnings concerning non-literals being used in a call 7565 // to a vprintf function. For example: 7566 // 7567 // void 7568 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7569 // va_list ap; 7570 // va_start(ap, fmt); 7571 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7572 // ... 7573 // } 7574 if (HasVAListArg) { 7575 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7576 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7577 int PVIndex = PV->getFunctionScopeIndex() + 1; 7578 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7579 // adjust for implicit parameter 7580 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7581 if (MD->isInstance()) 7582 ++PVIndex; 7583 // We also check if the formats are compatible. 7584 // We can't pass a 'scanf' string to a 'printf' function. 7585 if (PVIndex == PVFormat->getFormatIdx() && 7586 Type == S.GetFormatStringType(PVFormat)) 7587 return SLCT_UncheckedLiteral; 7588 } 7589 } 7590 } 7591 } 7592 } 7593 7594 return SLCT_NotALiteral; 7595 } 7596 7597 case Stmt::CallExprClass: 7598 case Stmt::CXXMemberCallExprClass: { 7599 const CallExpr *CE = cast<CallExpr>(E); 7600 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7601 bool IsFirst = true; 7602 StringLiteralCheckType CommonResult; 7603 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7604 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7605 StringLiteralCheckType Result = checkFormatStringExpr( 7606 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7607 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7608 IgnoreStringsWithoutSpecifiers); 7609 if (IsFirst) { 7610 CommonResult = Result; 7611 IsFirst = false; 7612 } 7613 } 7614 if (!IsFirst) 7615 return CommonResult; 7616 7617 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7618 unsigned BuiltinID = FD->getBuiltinID(); 7619 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7620 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7621 const Expr *Arg = CE->getArg(0); 7622 return checkFormatStringExpr(S, Arg, Args, 7623 HasVAListArg, format_idx, 7624 firstDataArg, Type, CallType, 7625 InFunctionCall, CheckedVarArgs, 7626 UncoveredArg, Offset, 7627 IgnoreStringsWithoutSpecifiers); 7628 } 7629 } 7630 } 7631 7632 return SLCT_NotALiteral; 7633 } 7634 case Stmt::ObjCMessageExprClass: { 7635 const auto *ME = cast<ObjCMessageExpr>(E); 7636 if (const auto *MD = ME->getMethodDecl()) { 7637 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7638 // As a special case heuristic, if we're using the method -[NSBundle 7639 // localizedStringForKey:value:table:], ignore any key strings that lack 7640 // format specifiers. The idea is that if the key doesn't have any 7641 // format specifiers then its probably just a key to map to the 7642 // localized strings. If it does have format specifiers though, then its 7643 // likely that the text of the key is the format string in the 7644 // programmer's language, and should be checked. 7645 const ObjCInterfaceDecl *IFace; 7646 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7647 IFace->getIdentifier()->isStr("NSBundle") && 7648 MD->getSelector().isKeywordSelector( 7649 {"localizedStringForKey", "value", "table"})) { 7650 IgnoreStringsWithoutSpecifiers = true; 7651 } 7652 7653 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7654 return checkFormatStringExpr( 7655 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7656 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7657 IgnoreStringsWithoutSpecifiers); 7658 } 7659 } 7660 7661 return SLCT_NotALiteral; 7662 } 7663 case Stmt::ObjCStringLiteralClass: 7664 case Stmt::StringLiteralClass: { 7665 const StringLiteral *StrE = nullptr; 7666 7667 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7668 StrE = ObjCFExpr->getString(); 7669 else 7670 StrE = cast<StringLiteral>(E); 7671 7672 if (StrE) { 7673 if (Offset.isNegative() || Offset > StrE->getLength()) { 7674 // TODO: It would be better to have an explicit warning for out of 7675 // bounds literals. 7676 return SLCT_NotALiteral; 7677 } 7678 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7679 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7680 firstDataArg, Type, InFunctionCall, CallType, 7681 CheckedVarArgs, UncoveredArg, 7682 IgnoreStringsWithoutSpecifiers); 7683 return SLCT_CheckedLiteral; 7684 } 7685 7686 return SLCT_NotALiteral; 7687 } 7688 case Stmt::BinaryOperatorClass: { 7689 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7690 7691 // A string literal + an int offset is still a string literal. 7692 if (BinOp->isAdditiveOp()) { 7693 Expr::EvalResult LResult, RResult; 7694 7695 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7696 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7697 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7698 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7699 7700 if (LIsInt != RIsInt) { 7701 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7702 7703 if (LIsInt) { 7704 if (BinOpKind == BO_Add) { 7705 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7706 E = BinOp->getRHS(); 7707 goto tryAgain; 7708 } 7709 } else { 7710 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7711 E = BinOp->getLHS(); 7712 goto tryAgain; 7713 } 7714 } 7715 } 7716 7717 return SLCT_NotALiteral; 7718 } 7719 case Stmt::UnaryOperatorClass: { 7720 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7721 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7722 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7723 Expr::EvalResult IndexResult; 7724 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7725 Expr::SE_NoSideEffects, 7726 S.isConstantEvaluated())) { 7727 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7728 /*RHS is int*/ true); 7729 E = ASE->getBase(); 7730 goto tryAgain; 7731 } 7732 } 7733 7734 return SLCT_NotALiteral; 7735 } 7736 7737 default: 7738 return SLCT_NotALiteral; 7739 } 7740 } 7741 7742 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7743 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7744 .Case("scanf", FST_Scanf) 7745 .Cases("printf", "printf0", FST_Printf) 7746 .Cases("NSString", "CFString", FST_NSString) 7747 .Case("strftime", FST_Strftime) 7748 .Case("strfmon", FST_Strfmon) 7749 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7750 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7751 .Case("os_trace", FST_OSLog) 7752 .Case("os_log", FST_OSLog) 7753 .Default(FST_Unknown); 7754 } 7755 7756 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7757 /// functions) for correct use of format strings. 7758 /// Returns true if a format string has been fully checked. 7759 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7760 ArrayRef<const Expr *> Args, 7761 bool IsCXXMember, 7762 VariadicCallType CallType, 7763 SourceLocation Loc, SourceRange Range, 7764 llvm::SmallBitVector &CheckedVarArgs) { 7765 FormatStringInfo FSI; 7766 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7767 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7768 FSI.FirstDataArg, GetFormatStringType(Format), 7769 CallType, Loc, Range, CheckedVarArgs); 7770 return false; 7771 } 7772 7773 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7774 bool HasVAListArg, unsigned format_idx, 7775 unsigned firstDataArg, FormatStringType Type, 7776 VariadicCallType CallType, 7777 SourceLocation Loc, SourceRange Range, 7778 llvm::SmallBitVector &CheckedVarArgs) { 7779 // CHECK: printf/scanf-like function is called with no format string. 7780 if (format_idx >= Args.size()) { 7781 Diag(Loc, diag::warn_missing_format_string) << Range; 7782 return false; 7783 } 7784 7785 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7786 7787 // CHECK: format string is not a string literal. 7788 // 7789 // Dynamically generated format strings are difficult to 7790 // automatically vet at compile time. Requiring that format strings 7791 // are string literals: (1) permits the checking of format strings by 7792 // the compiler and thereby (2) can practically remove the source of 7793 // many format string exploits. 7794 7795 // Format string can be either ObjC string (e.g. @"%d") or 7796 // C string (e.g. "%d") 7797 // ObjC string uses the same format specifiers as C string, so we can use 7798 // the same format string checking logic for both ObjC and C strings. 7799 UncoveredArgHandler UncoveredArg; 7800 StringLiteralCheckType CT = 7801 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7802 format_idx, firstDataArg, Type, CallType, 7803 /*IsFunctionCall*/ true, CheckedVarArgs, 7804 UncoveredArg, 7805 /*no string offset*/ llvm::APSInt(64, false) = 0); 7806 7807 // Generate a diagnostic where an uncovered argument is detected. 7808 if (UncoveredArg.hasUncoveredArg()) { 7809 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7810 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7811 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7812 } 7813 7814 if (CT != SLCT_NotALiteral) 7815 // Literal format string found, check done! 7816 return CT == SLCT_CheckedLiteral; 7817 7818 // Strftime is particular as it always uses a single 'time' argument, 7819 // so it is safe to pass a non-literal string. 7820 if (Type == FST_Strftime) 7821 return false; 7822 7823 // Do not emit diag when the string param is a macro expansion and the 7824 // format is either NSString or CFString. This is a hack to prevent 7825 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7826 // which are usually used in place of NS and CF string literals. 7827 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7828 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7829 return false; 7830 7831 // If there are no arguments specified, warn with -Wformat-security, otherwise 7832 // warn only with -Wformat-nonliteral. 7833 if (Args.size() == firstDataArg) { 7834 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7835 << OrigFormatExpr->getSourceRange(); 7836 switch (Type) { 7837 default: 7838 break; 7839 case FST_Kprintf: 7840 case FST_FreeBSDKPrintf: 7841 case FST_Printf: 7842 Diag(FormatLoc, diag::note_format_security_fixit) 7843 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7844 break; 7845 case FST_NSString: 7846 Diag(FormatLoc, diag::note_format_security_fixit) 7847 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7848 break; 7849 } 7850 } else { 7851 Diag(FormatLoc, diag::warn_format_nonliteral) 7852 << OrigFormatExpr->getSourceRange(); 7853 } 7854 return false; 7855 } 7856 7857 namespace { 7858 7859 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7860 protected: 7861 Sema &S; 7862 const FormatStringLiteral *FExpr; 7863 const Expr *OrigFormatExpr; 7864 const Sema::FormatStringType FSType; 7865 const unsigned FirstDataArg; 7866 const unsigned NumDataArgs; 7867 const char *Beg; // Start of format string. 7868 const bool HasVAListArg; 7869 ArrayRef<const Expr *> Args; 7870 unsigned FormatIdx; 7871 llvm::SmallBitVector CoveredArgs; 7872 bool usesPositionalArgs = false; 7873 bool atFirstArg = true; 7874 bool inFunctionCall; 7875 Sema::VariadicCallType CallType; 7876 llvm::SmallBitVector &CheckedVarArgs; 7877 UncoveredArgHandler &UncoveredArg; 7878 7879 public: 7880 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7881 const Expr *origFormatExpr, 7882 const Sema::FormatStringType type, unsigned firstDataArg, 7883 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7884 ArrayRef<const Expr *> Args, unsigned formatIdx, 7885 bool inFunctionCall, Sema::VariadicCallType callType, 7886 llvm::SmallBitVector &CheckedVarArgs, 7887 UncoveredArgHandler &UncoveredArg) 7888 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7889 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7890 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7891 inFunctionCall(inFunctionCall), CallType(callType), 7892 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7893 CoveredArgs.resize(numDataArgs); 7894 CoveredArgs.reset(); 7895 } 7896 7897 void DoneProcessing(); 7898 7899 void HandleIncompleteSpecifier(const char *startSpecifier, 7900 unsigned specifierLen) override; 7901 7902 void HandleInvalidLengthModifier( 7903 const analyze_format_string::FormatSpecifier &FS, 7904 const analyze_format_string::ConversionSpecifier &CS, 7905 const char *startSpecifier, unsigned specifierLen, 7906 unsigned DiagID); 7907 7908 void HandleNonStandardLengthModifier( 7909 const analyze_format_string::FormatSpecifier &FS, 7910 const char *startSpecifier, unsigned specifierLen); 7911 7912 void HandleNonStandardConversionSpecifier( 7913 const analyze_format_string::ConversionSpecifier &CS, 7914 const char *startSpecifier, unsigned specifierLen); 7915 7916 void HandlePosition(const char *startPos, unsigned posLen) override; 7917 7918 void HandleInvalidPosition(const char *startSpecifier, 7919 unsigned specifierLen, 7920 analyze_format_string::PositionContext p) override; 7921 7922 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7923 7924 void HandleNullChar(const char *nullCharacter) override; 7925 7926 template <typename Range> 7927 static void 7928 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7929 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7930 bool IsStringLocation, Range StringRange, 7931 ArrayRef<FixItHint> Fixit = None); 7932 7933 protected: 7934 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7935 const char *startSpec, 7936 unsigned specifierLen, 7937 const char *csStart, unsigned csLen); 7938 7939 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7940 const char *startSpec, 7941 unsigned specifierLen); 7942 7943 SourceRange getFormatStringRange(); 7944 CharSourceRange getSpecifierRange(const char *startSpecifier, 7945 unsigned specifierLen); 7946 SourceLocation getLocationOfByte(const char *x); 7947 7948 const Expr *getDataArg(unsigned i) const; 7949 7950 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7951 const analyze_format_string::ConversionSpecifier &CS, 7952 const char *startSpecifier, unsigned specifierLen, 7953 unsigned argIndex); 7954 7955 template <typename Range> 7956 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7957 bool IsStringLocation, Range StringRange, 7958 ArrayRef<FixItHint> Fixit = None); 7959 }; 7960 7961 } // namespace 7962 7963 SourceRange CheckFormatHandler::getFormatStringRange() { 7964 return OrigFormatExpr->getSourceRange(); 7965 } 7966 7967 CharSourceRange CheckFormatHandler:: 7968 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7969 SourceLocation Start = getLocationOfByte(startSpecifier); 7970 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7971 7972 // Advance the end SourceLocation by one due to half-open ranges. 7973 End = End.getLocWithOffset(1); 7974 7975 return CharSourceRange::getCharRange(Start, End); 7976 } 7977 7978 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7979 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7980 S.getLangOpts(), S.Context.getTargetInfo()); 7981 } 7982 7983 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7984 unsigned specifierLen){ 7985 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7986 getLocationOfByte(startSpecifier), 7987 /*IsStringLocation*/true, 7988 getSpecifierRange(startSpecifier, specifierLen)); 7989 } 7990 7991 void CheckFormatHandler::HandleInvalidLengthModifier( 7992 const analyze_format_string::FormatSpecifier &FS, 7993 const analyze_format_string::ConversionSpecifier &CS, 7994 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7995 using namespace analyze_format_string; 7996 7997 const LengthModifier &LM = FS.getLengthModifier(); 7998 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7999 8000 // See if we know how to fix this length modifier. 8001 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8002 if (FixedLM) { 8003 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8004 getLocationOfByte(LM.getStart()), 8005 /*IsStringLocation*/true, 8006 getSpecifierRange(startSpecifier, specifierLen)); 8007 8008 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8009 << FixedLM->toString() 8010 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8011 8012 } else { 8013 FixItHint Hint; 8014 if (DiagID == diag::warn_format_nonsensical_length) 8015 Hint = FixItHint::CreateRemoval(LMRange); 8016 8017 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8018 getLocationOfByte(LM.getStart()), 8019 /*IsStringLocation*/true, 8020 getSpecifierRange(startSpecifier, specifierLen), 8021 Hint); 8022 } 8023 } 8024 8025 void CheckFormatHandler::HandleNonStandardLengthModifier( 8026 const analyze_format_string::FormatSpecifier &FS, 8027 const char *startSpecifier, unsigned specifierLen) { 8028 using namespace analyze_format_string; 8029 8030 const LengthModifier &LM = FS.getLengthModifier(); 8031 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8032 8033 // See if we know how to fix this length modifier. 8034 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8035 if (FixedLM) { 8036 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8037 << LM.toString() << 0, 8038 getLocationOfByte(LM.getStart()), 8039 /*IsStringLocation*/true, 8040 getSpecifierRange(startSpecifier, specifierLen)); 8041 8042 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8043 << FixedLM->toString() 8044 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8045 8046 } else { 8047 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8048 << LM.toString() << 0, 8049 getLocationOfByte(LM.getStart()), 8050 /*IsStringLocation*/true, 8051 getSpecifierRange(startSpecifier, specifierLen)); 8052 } 8053 } 8054 8055 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8056 const analyze_format_string::ConversionSpecifier &CS, 8057 const char *startSpecifier, unsigned specifierLen) { 8058 using namespace analyze_format_string; 8059 8060 // See if we know how to fix this conversion specifier. 8061 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8062 if (FixedCS) { 8063 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8064 << CS.toString() << /*conversion specifier*/1, 8065 getLocationOfByte(CS.getStart()), 8066 /*IsStringLocation*/true, 8067 getSpecifierRange(startSpecifier, specifierLen)); 8068 8069 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8070 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8071 << FixedCS->toString() 8072 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8073 } else { 8074 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8075 << CS.toString() << /*conversion specifier*/1, 8076 getLocationOfByte(CS.getStart()), 8077 /*IsStringLocation*/true, 8078 getSpecifierRange(startSpecifier, specifierLen)); 8079 } 8080 } 8081 8082 void CheckFormatHandler::HandlePosition(const char *startPos, 8083 unsigned posLen) { 8084 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8085 getLocationOfByte(startPos), 8086 /*IsStringLocation*/true, 8087 getSpecifierRange(startPos, posLen)); 8088 } 8089 8090 void 8091 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8092 analyze_format_string::PositionContext p) { 8093 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8094 << (unsigned) p, 8095 getLocationOfByte(startPos), /*IsStringLocation*/true, 8096 getSpecifierRange(startPos, posLen)); 8097 } 8098 8099 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8100 unsigned posLen) { 8101 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8102 getLocationOfByte(startPos), 8103 /*IsStringLocation*/true, 8104 getSpecifierRange(startPos, posLen)); 8105 } 8106 8107 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8108 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8109 // The presence of a null character is likely an error. 8110 EmitFormatDiagnostic( 8111 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8112 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8113 getFormatStringRange()); 8114 } 8115 } 8116 8117 // Note that this may return NULL if there was an error parsing or building 8118 // one of the argument expressions. 8119 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8120 return Args[FirstDataArg + i]; 8121 } 8122 8123 void CheckFormatHandler::DoneProcessing() { 8124 // Does the number of data arguments exceed the number of 8125 // format conversions in the format string? 8126 if (!HasVAListArg) { 8127 // Find any arguments that weren't covered. 8128 CoveredArgs.flip(); 8129 signed notCoveredArg = CoveredArgs.find_first(); 8130 if (notCoveredArg >= 0) { 8131 assert((unsigned)notCoveredArg < NumDataArgs); 8132 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8133 } else { 8134 UncoveredArg.setAllCovered(); 8135 } 8136 } 8137 } 8138 8139 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8140 const Expr *ArgExpr) { 8141 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8142 "Invalid state"); 8143 8144 if (!ArgExpr) 8145 return; 8146 8147 SourceLocation Loc = ArgExpr->getBeginLoc(); 8148 8149 if (S.getSourceManager().isInSystemMacro(Loc)) 8150 return; 8151 8152 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8153 for (auto E : DiagnosticExprs) 8154 PDiag << E->getSourceRange(); 8155 8156 CheckFormatHandler::EmitFormatDiagnostic( 8157 S, IsFunctionCall, DiagnosticExprs[0], 8158 PDiag, Loc, /*IsStringLocation*/false, 8159 DiagnosticExprs[0]->getSourceRange()); 8160 } 8161 8162 bool 8163 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8164 SourceLocation Loc, 8165 const char *startSpec, 8166 unsigned specifierLen, 8167 const char *csStart, 8168 unsigned csLen) { 8169 bool keepGoing = true; 8170 if (argIndex < NumDataArgs) { 8171 // Consider the argument coverered, even though the specifier doesn't 8172 // make sense. 8173 CoveredArgs.set(argIndex); 8174 } 8175 else { 8176 // If argIndex exceeds the number of data arguments we 8177 // don't issue a warning because that is just a cascade of warnings (and 8178 // they may have intended '%%' anyway). We don't want to continue processing 8179 // the format string after this point, however, as we will like just get 8180 // gibberish when trying to match arguments. 8181 keepGoing = false; 8182 } 8183 8184 StringRef Specifier(csStart, csLen); 8185 8186 // If the specifier in non-printable, it could be the first byte of a UTF-8 8187 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8188 // hex value. 8189 std::string CodePointStr; 8190 if (!llvm::sys::locale::isPrint(*csStart)) { 8191 llvm::UTF32 CodePoint; 8192 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8193 const llvm::UTF8 *E = 8194 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8195 llvm::ConversionResult Result = 8196 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8197 8198 if (Result != llvm::conversionOK) { 8199 unsigned char FirstChar = *csStart; 8200 CodePoint = (llvm::UTF32)FirstChar; 8201 } 8202 8203 llvm::raw_string_ostream OS(CodePointStr); 8204 if (CodePoint < 256) 8205 OS << "\\x" << llvm::format("%02x", CodePoint); 8206 else if (CodePoint <= 0xFFFF) 8207 OS << "\\u" << llvm::format("%04x", CodePoint); 8208 else 8209 OS << "\\U" << llvm::format("%08x", CodePoint); 8210 OS.flush(); 8211 Specifier = CodePointStr; 8212 } 8213 8214 EmitFormatDiagnostic( 8215 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8216 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8217 8218 return keepGoing; 8219 } 8220 8221 void 8222 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8223 const char *startSpec, 8224 unsigned specifierLen) { 8225 EmitFormatDiagnostic( 8226 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8227 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8228 } 8229 8230 bool 8231 CheckFormatHandler::CheckNumArgs( 8232 const analyze_format_string::FormatSpecifier &FS, 8233 const analyze_format_string::ConversionSpecifier &CS, 8234 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8235 8236 if (argIndex >= NumDataArgs) { 8237 PartialDiagnostic PDiag = FS.usesPositionalArg() 8238 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8239 << (argIndex+1) << NumDataArgs) 8240 : S.PDiag(diag::warn_printf_insufficient_data_args); 8241 EmitFormatDiagnostic( 8242 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8243 getSpecifierRange(startSpecifier, specifierLen)); 8244 8245 // Since more arguments than conversion tokens are given, by extension 8246 // all arguments are covered, so mark this as so. 8247 UncoveredArg.setAllCovered(); 8248 return false; 8249 } 8250 return true; 8251 } 8252 8253 template<typename Range> 8254 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8255 SourceLocation Loc, 8256 bool IsStringLocation, 8257 Range StringRange, 8258 ArrayRef<FixItHint> FixIt) { 8259 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8260 Loc, IsStringLocation, StringRange, FixIt); 8261 } 8262 8263 /// If the format string is not within the function call, emit a note 8264 /// so that the function call and string are in diagnostic messages. 8265 /// 8266 /// \param InFunctionCall if true, the format string is within the function 8267 /// call and only one diagnostic message will be produced. Otherwise, an 8268 /// extra note will be emitted pointing to location of the format string. 8269 /// 8270 /// \param ArgumentExpr the expression that is passed as the format string 8271 /// argument in the function call. Used for getting locations when two 8272 /// diagnostics are emitted. 8273 /// 8274 /// \param PDiag the callee should already have provided any strings for the 8275 /// diagnostic message. This function only adds locations and fixits 8276 /// to diagnostics. 8277 /// 8278 /// \param Loc primary location for diagnostic. If two diagnostics are 8279 /// required, one will be at Loc and a new SourceLocation will be created for 8280 /// the other one. 8281 /// 8282 /// \param IsStringLocation if true, Loc points to the format string should be 8283 /// used for the note. Otherwise, Loc points to the argument list and will 8284 /// be used with PDiag. 8285 /// 8286 /// \param StringRange some or all of the string to highlight. This is 8287 /// templated so it can accept either a CharSourceRange or a SourceRange. 8288 /// 8289 /// \param FixIt optional fix it hint for the format string. 8290 template <typename Range> 8291 void CheckFormatHandler::EmitFormatDiagnostic( 8292 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8293 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8294 Range StringRange, ArrayRef<FixItHint> FixIt) { 8295 if (InFunctionCall) { 8296 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8297 D << StringRange; 8298 D << FixIt; 8299 } else { 8300 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8301 << ArgumentExpr->getSourceRange(); 8302 8303 const Sema::SemaDiagnosticBuilder &Note = 8304 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8305 diag::note_format_string_defined); 8306 8307 Note << StringRange; 8308 Note << FixIt; 8309 } 8310 } 8311 8312 //===--- CHECK: Printf format string checking ------------------------------===// 8313 8314 namespace { 8315 8316 class CheckPrintfHandler : public CheckFormatHandler { 8317 public: 8318 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8319 const Expr *origFormatExpr, 8320 const Sema::FormatStringType type, unsigned firstDataArg, 8321 unsigned numDataArgs, bool isObjC, const char *beg, 8322 bool hasVAListArg, ArrayRef<const Expr *> Args, 8323 unsigned formatIdx, bool inFunctionCall, 8324 Sema::VariadicCallType CallType, 8325 llvm::SmallBitVector &CheckedVarArgs, 8326 UncoveredArgHandler &UncoveredArg) 8327 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8328 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8329 inFunctionCall, CallType, CheckedVarArgs, 8330 UncoveredArg) {} 8331 8332 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8333 8334 /// Returns true if '%@' specifiers are allowed in the format string. 8335 bool allowsObjCArg() const { 8336 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8337 FSType == Sema::FST_OSTrace; 8338 } 8339 8340 bool HandleInvalidPrintfConversionSpecifier( 8341 const analyze_printf::PrintfSpecifier &FS, 8342 const char *startSpecifier, 8343 unsigned specifierLen) override; 8344 8345 void handleInvalidMaskType(StringRef MaskType) override; 8346 8347 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8348 const char *startSpecifier, 8349 unsigned specifierLen) override; 8350 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8351 const char *StartSpecifier, 8352 unsigned SpecifierLen, 8353 const Expr *E); 8354 8355 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8356 const char *startSpecifier, unsigned specifierLen); 8357 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8358 const analyze_printf::OptionalAmount &Amt, 8359 unsigned type, 8360 const char *startSpecifier, unsigned specifierLen); 8361 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8362 const analyze_printf::OptionalFlag &flag, 8363 const char *startSpecifier, unsigned specifierLen); 8364 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8365 const analyze_printf::OptionalFlag &ignoredFlag, 8366 const analyze_printf::OptionalFlag &flag, 8367 const char *startSpecifier, unsigned specifierLen); 8368 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8369 const Expr *E); 8370 8371 void HandleEmptyObjCModifierFlag(const char *startFlag, 8372 unsigned flagLen) override; 8373 8374 void HandleInvalidObjCModifierFlag(const char *startFlag, 8375 unsigned flagLen) override; 8376 8377 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8378 const char *flagsEnd, 8379 const char *conversionPosition) 8380 override; 8381 }; 8382 8383 } // namespace 8384 8385 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8386 const analyze_printf::PrintfSpecifier &FS, 8387 const char *startSpecifier, 8388 unsigned specifierLen) { 8389 const analyze_printf::PrintfConversionSpecifier &CS = 8390 FS.getConversionSpecifier(); 8391 8392 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8393 getLocationOfByte(CS.getStart()), 8394 startSpecifier, specifierLen, 8395 CS.getStart(), CS.getLength()); 8396 } 8397 8398 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8399 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8400 } 8401 8402 bool CheckPrintfHandler::HandleAmount( 8403 const analyze_format_string::OptionalAmount &Amt, 8404 unsigned k, const char *startSpecifier, 8405 unsigned specifierLen) { 8406 if (Amt.hasDataArgument()) { 8407 if (!HasVAListArg) { 8408 unsigned argIndex = Amt.getArgIndex(); 8409 if (argIndex >= NumDataArgs) { 8410 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8411 << k, 8412 getLocationOfByte(Amt.getStart()), 8413 /*IsStringLocation*/true, 8414 getSpecifierRange(startSpecifier, specifierLen)); 8415 // Don't do any more checking. We will just emit 8416 // spurious errors. 8417 return false; 8418 } 8419 8420 // Type check the data argument. It should be an 'int'. 8421 // Although not in conformance with C99, we also allow the argument to be 8422 // an 'unsigned int' as that is a reasonably safe case. GCC also 8423 // doesn't emit a warning for that case. 8424 CoveredArgs.set(argIndex); 8425 const Expr *Arg = getDataArg(argIndex); 8426 if (!Arg) 8427 return false; 8428 8429 QualType T = Arg->getType(); 8430 8431 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8432 assert(AT.isValid()); 8433 8434 if (!AT.matchesType(S.Context, T)) { 8435 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8436 << k << AT.getRepresentativeTypeName(S.Context) 8437 << T << Arg->getSourceRange(), 8438 getLocationOfByte(Amt.getStart()), 8439 /*IsStringLocation*/true, 8440 getSpecifierRange(startSpecifier, specifierLen)); 8441 // Don't do any more checking. We will just emit 8442 // spurious errors. 8443 return false; 8444 } 8445 } 8446 } 8447 return true; 8448 } 8449 8450 void CheckPrintfHandler::HandleInvalidAmount( 8451 const analyze_printf::PrintfSpecifier &FS, 8452 const analyze_printf::OptionalAmount &Amt, 8453 unsigned type, 8454 const char *startSpecifier, 8455 unsigned specifierLen) { 8456 const analyze_printf::PrintfConversionSpecifier &CS = 8457 FS.getConversionSpecifier(); 8458 8459 FixItHint fixit = 8460 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8461 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8462 Amt.getConstantLength())) 8463 : FixItHint(); 8464 8465 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8466 << type << CS.toString(), 8467 getLocationOfByte(Amt.getStart()), 8468 /*IsStringLocation*/true, 8469 getSpecifierRange(startSpecifier, specifierLen), 8470 fixit); 8471 } 8472 8473 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8474 const analyze_printf::OptionalFlag &flag, 8475 const char *startSpecifier, 8476 unsigned specifierLen) { 8477 // Warn about pointless flag with a fixit removal. 8478 const analyze_printf::PrintfConversionSpecifier &CS = 8479 FS.getConversionSpecifier(); 8480 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8481 << flag.toString() << CS.toString(), 8482 getLocationOfByte(flag.getPosition()), 8483 /*IsStringLocation*/true, 8484 getSpecifierRange(startSpecifier, specifierLen), 8485 FixItHint::CreateRemoval( 8486 getSpecifierRange(flag.getPosition(), 1))); 8487 } 8488 8489 void CheckPrintfHandler::HandleIgnoredFlag( 8490 const analyze_printf::PrintfSpecifier &FS, 8491 const analyze_printf::OptionalFlag &ignoredFlag, 8492 const analyze_printf::OptionalFlag &flag, 8493 const char *startSpecifier, 8494 unsigned specifierLen) { 8495 // Warn about ignored flag with a fixit removal. 8496 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8497 << ignoredFlag.toString() << flag.toString(), 8498 getLocationOfByte(ignoredFlag.getPosition()), 8499 /*IsStringLocation*/true, 8500 getSpecifierRange(startSpecifier, specifierLen), 8501 FixItHint::CreateRemoval( 8502 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8503 } 8504 8505 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8506 unsigned flagLen) { 8507 // Warn about an empty flag. 8508 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8509 getLocationOfByte(startFlag), 8510 /*IsStringLocation*/true, 8511 getSpecifierRange(startFlag, flagLen)); 8512 } 8513 8514 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8515 unsigned flagLen) { 8516 // Warn about an invalid flag. 8517 auto Range = getSpecifierRange(startFlag, flagLen); 8518 StringRef flag(startFlag, flagLen); 8519 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8520 getLocationOfByte(startFlag), 8521 /*IsStringLocation*/true, 8522 Range, FixItHint::CreateRemoval(Range)); 8523 } 8524 8525 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8526 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8527 // Warn about using '[...]' without a '@' conversion. 8528 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8529 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8530 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8531 getLocationOfByte(conversionPosition), 8532 /*IsStringLocation*/true, 8533 Range, FixItHint::CreateRemoval(Range)); 8534 } 8535 8536 // Determines if the specified is a C++ class or struct containing 8537 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8538 // "c_str()"). 8539 template<typename MemberKind> 8540 static llvm::SmallPtrSet<MemberKind*, 1> 8541 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8542 const RecordType *RT = Ty->getAs<RecordType>(); 8543 llvm::SmallPtrSet<MemberKind*, 1> Results; 8544 8545 if (!RT) 8546 return Results; 8547 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8548 if (!RD || !RD->getDefinition()) 8549 return Results; 8550 8551 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8552 Sema::LookupMemberName); 8553 R.suppressDiagnostics(); 8554 8555 // We just need to include all members of the right kind turned up by the 8556 // filter, at this point. 8557 if (S.LookupQualifiedName(R, RT->getDecl())) 8558 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8559 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8560 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8561 Results.insert(FK); 8562 } 8563 return Results; 8564 } 8565 8566 /// Check if we could call '.c_str()' on an object. 8567 /// 8568 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8569 /// allow the call, or if it would be ambiguous). 8570 bool Sema::hasCStrMethod(const Expr *E) { 8571 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8572 8573 MethodSet Results = 8574 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8575 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8576 MI != ME; ++MI) 8577 if ((*MI)->getMinRequiredArguments() == 0) 8578 return true; 8579 return false; 8580 } 8581 8582 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8583 // better diagnostic if so. AT is assumed to be valid. 8584 // Returns true when a c_str() conversion method is found. 8585 bool CheckPrintfHandler::checkForCStrMembers( 8586 const analyze_printf::ArgType &AT, const Expr *E) { 8587 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8588 8589 MethodSet Results = 8590 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8591 8592 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8593 MI != ME; ++MI) { 8594 const CXXMethodDecl *Method = *MI; 8595 if (Method->getMinRequiredArguments() == 0 && 8596 AT.matchesType(S.Context, Method->getReturnType())) { 8597 // FIXME: Suggest parens if the expression needs them. 8598 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8599 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8600 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8601 return true; 8602 } 8603 } 8604 8605 return false; 8606 } 8607 8608 bool 8609 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8610 &FS, 8611 const char *startSpecifier, 8612 unsigned specifierLen) { 8613 using namespace analyze_format_string; 8614 using namespace analyze_printf; 8615 8616 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8617 8618 if (FS.consumesDataArgument()) { 8619 if (atFirstArg) { 8620 atFirstArg = false; 8621 usesPositionalArgs = FS.usesPositionalArg(); 8622 } 8623 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8624 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8625 startSpecifier, specifierLen); 8626 return false; 8627 } 8628 } 8629 8630 // First check if the field width, precision, and conversion specifier 8631 // have matching data arguments. 8632 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8633 startSpecifier, specifierLen)) { 8634 return false; 8635 } 8636 8637 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8638 startSpecifier, specifierLen)) { 8639 return false; 8640 } 8641 8642 if (!CS.consumesDataArgument()) { 8643 // FIXME: Technically specifying a precision or field width here 8644 // makes no sense. Worth issuing a warning at some point. 8645 return true; 8646 } 8647 8648 // Consume the argument. 8649 unsigned argIndex = FS.getArgIndex(); 8650 if (argIndex < NumDataArgs) { 8651 // The check to see if the argIndex is valid will come later. 8652 // We set the bit here because we may exit early from this 8653 // function if we encounter some other error. 8654 CoveredArgs.set(argIndex); 8655 } 8656 8657 // FreeBSD kernel extensions. 8658 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8659 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8660 // We need at least two arguments. 8661 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8662 return false; 8663 8664 // Claim the second argument. 8665 CoveredArgs.set(argIndex + 1); 8666 8667 // Type check the first argument (int for %b, pointer for %D) 8668 const Expr *Ex = getDataArg(argIndex); 8669 const analyze_printf::ArgType &AT = 8670 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8671 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8672 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8673 EmitFormatDiagnostic( 8674 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8675 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8676 << false << Ex->getSourceRange(), 8677 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8678 getSpecifierRange(startSpecifier, specifierLen)); 8679 8680 // Type check the second argument (char * for both %b and %D) 8681 Ex = getDataArg(argIndex + 1); 8682 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8683 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8684 EmitFormatDiagnostic( 8685 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8686 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8687 << false << Ex->getSourceRange(), 8688 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8689 getSpecifierRange(startSpecifier, specifierLen)); 8690 8691 return true; 8692 } 8693 8694 // Check for using an Objective-C specific conversion specifier 8695 // in a non-ObjC literal. 8696 if (!allowsObjCArg() && CS.isObjCArg()) { 8697 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8698 specifierLen); 8699 } 8700 8701 // %P can only be used with os_log. 8702 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8703 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8704 specifierLen); 8705 } 8706 8707 // %n is not allowed with os_log. 8708 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8709 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8710 getLocationOfByte(CS.getStart()), 8711 /*IsStringLocation*/ false, 8712 getSpecifierRange(startSpecifier, specifierLen)); 8713 8714 return true; 8715 } 8716 8717 // Only scalars are allowed for os_trace. 8718 if (FSType == Sema::FST_OSTrace && 8719 (CS.getKind() == ConversionSpecifier::PArg || 8720 CS.getKind() == ConversionSpecifier::sArg || 8721 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8722 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8723 specifierLen); 8724 } 8725 8726 // Check for use of public/private annotation outside of os_log(). 8727 if (FSType != Sema::FST_OSLog) { 8728 if (FS.isPublic().isSet()) { 8729 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8730 << "public", 8731 getLocationOfByte(FS.isPublic().getPosition()), 8732 /*IsStringLocation*/ false, 8733 getSpecifierRange(startSpecifier, specifierLen)); 8734 } 8735 if (FS.isPrivate().isSet()) { 8736 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8737 << "private", 8738 getLocationOfByte(FS.isPrivate().getPosition()), 8739 /*IsStringLocation*/ false, 8740 getSpecifierRange(startSpecifier, specifierLen)); 8741 } 8742 } 8743 8744 // Check for invalid use of field width 8745 if (!FS.hasValidFieldWidth()) { 8746 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8747 startSpecifier, specifierLen); 8748 } 8749 8750 // Check for invalid use of precision 8751 if (!FS.hasValidPrecision()) { 8752 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8753 startSpecifier, specifierLen); 8754 } 8755 8756 // Precision is mandatory for %P specifier. 8757 if (CS.getKind() == ConversionSpecifier::PArg && 8758 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8759 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8760 getLocationOfByte(startSpecifier), 8761 /*IsStringLocation*/ false, 8762 getSpecifierRange(startSpecifier, specifierLen)); 8763 } 8764 8765 // Check each flag does not conflict with any other component. 8766 if (!FS.hasValidThousandsGroupingPrefix()) 8767 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8768 if (!FS.hasValidLeadingZeros()) 8769 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8770 if (!FS.hasValidPlusPrefix()) 8771 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8772 if (!FS.hasValidSpacePrefix()) 8773 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8774 if (!FS.hasValidAlternativeForm()) 8775 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8776 if (!FS.hasValidLeftJustified()) 8777 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8778 8779 // Check that flags are not ignored by another flag 8780 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8781 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8782 startSpecifier, specifierLen); 8783 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8784 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8785 startSpecifier, specifierLen); 8786 8787 // Check the length modifier is valid with the given conversion specifier. 8788 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8789 S.getLangOpts())) 8790 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8791 diag::warn_format_nonsensical_length); 8792 else if (!FS.hasStandardLengthModifier()) 8793 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8794 else if (!FS.hasStandardLengthConversionCombination()) 8795 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8796 diag::warn_format_non_standard_conversion_spec); 8797 8798 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8799 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8800 8801 // The remaining checks depend on the data arguments. 8802 if (HasVAListArg) 8803 return true; 8804 8805 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8806 return false; 8807 8808 const Expr *Arg = getDataArg(argIndex); 8809 if (!Arg) 8810 return true; 8811 8812 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8813 } 8814 8815 static bool requiresParensToAddCast(const Expr *E) { 8816 // FIXME: We should have a general way to reason about operator 8817 // precedence and whether parens are actually needed here. 8818 // Take care of a few common cases where they aren't. 8819 const Expr *Inside = E->IgnoreImpCasts(); 8820 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8821 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8822 8823 switch (Inside->getStmtClass()) { 8824 case Stmt::ArraySubscriptExprClass: 8825 case Stmt::CallExprClass: 8826 case Stmt::CharacterLiteralClass: 8827 case Stmt::CXXBoolLiteralExprClass: 8828 case Stmt::DeclRefExprClass: 8829 case Stmt::FloatingLiteralClass: 8830 case Stmt::IntegerLiteralClass: 8831 case Stmt::MemberExprClass: 8832 case Stmt::ObjCArrayLiteralClass: 8833 case Stmt::ObjCBoolLiteralExprClass: 8834 case Stmt::ObjCBoxedExprClass: 8835 case Stmt::ObjCDictionaryLiteralClass: 8836 case Stmt::ObjCEncodeExprClass: 8837 case Stmt::ObjCIvarRefExprClass: 8838 case Stmt::ObjCMessageExprClass: 8839 case Stmt::ObjCPropertyRefExprClass: 8840 case Stmt::ObjCStringLiteralClass: 8841 case Stmt::ObjCSubscriptRefExprClass: 8842 case Stmt::ParenExprClass: 8843 case Stmt::StringLiteralClass: 8844 case Stmt::UnaryOperatorClass: 8845 return false; 8846 default: 8847 return true; 8848 } 8849 } 8850 8851 static std::pair<QualType, StringRef> 8852 shouldNotPrintDirectly(const ASTContext &Context, 8853 QualType IntendedTy, 8854 const Expr *E) { 8855 // Use a 'while' to peel off layers of typedefs. 8856 QualType TyTy = IntendedTy; 8857 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8858 StringRef Name = UserTy->getDecl()->getName(); 8859 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8860 .Case("CFIndex", Context.getNSIntegerType()) 8861 .Case("NSInteger", Context.getNSIntegerType()) 8862 .Case("NSUInteger", Context.getNSUIntegerType()) 8863 .Case("SInt32", Context.IntTy) 8864 .Case("UInt32", Context.UnsignedIntTy) 8865 .Default(QualType()); 8866 8867 if (!CastTy.isNull()) 8868 return std::make_pair(CastTy, Name); 8869 8870 TyTy = UserTy->desugar(); 8871 } 8872 8873 // Strip parens if necessary. 8874 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8875 return shouldNotPrintDirectly(Context, 8876 PE->getSubExpr()->getType(), 8877 PE->getSubExpr()); 8878 8879 // If this is a conditional expression, then its result type is constructed 8880 // via usual arithmetic conversions and thus there might be no necessary 8881 // typedef sugar there. Recurse to operands to check for NSInteger & 8882 // Co. usage condition. 8883 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8884 QualType TrueTy, FalseTy; 8885 StringRef TrueName, FalseName; 8886 8887 std::tie(TrueTy, TrueName) = 8888 shouldNotPrintDirectly(Context, 8889 CO->getTrueExpr()->getType(), 8890 CO->getTrueExpr()); 8891 std::tie(FalseTy, FalseName) = 8892 shouldNotPrintDirectly(Context, 8893 CO->getFalseExpr()->getType(), 8894 CO->getFalseExpr()); 8895 8896 if (TrueTy == FalseTy) 8897 return std::make_pair(TrueTy, TrueName); 8898 else if (TrueTy.isNull()) 8899 return std::make_pair(FalseTy, FalseName); 8900 else if (FalseTy.isNull()) 8901 return std::make_pair(TrueTy, TrueName); 8902 } 8903 8904 return std::make_pair(QualType(), StringRef()); 8905 } 8906 8907 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8908 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8909 /// type do not count. 8910 static bool 8911 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8912 QualType From = ICE->getSubExpr()->getType(); 8913 QualType To = ICE->getType(); 8914 // It's an integer promotion if the destination type is the promoted 8915 // source type. 8916 if (ICE->getCastKind() == CK_IntegralCast && 8917 From->isPromotableIntegerType() && 8918 S.Context.getPromotedIntegerType(From) == To) 8919 return true; 8920 // Look through vector types, since we do default argument promotion for 8921 // those in OpenCL. 8922 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8923 From = VecTy->getElementType(); 8924 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8925 To = VecTy->getElementType(); 8926 // It's a floating promotion if the source type is a lower rank. 8927 return ICE->getCastKind() == CK_FloatingCast && 8928 S.Context.getFloatingTypeOrder(From, To) < 0; 8929 } 8930 8931 bool 8932 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8933 const char *StartSpecifier, 8934 unsigned SpecifierLen, 8935 const Expr *E) { 8936 using namespace analyze_format_string; 8937 using namespace analyze_printf; 8938 8939 // Now type check the data expression that matches the 8940 // format specifier. 8941 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8942 if (!AT.isValid()) 8943 return true; 8944 8945 QualType ExprTy = E->getType(); 8946 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8947 ExprTy = TET->getUnderlyingExpr()->getType(); 8948 } 8949 8950 // Diagnose attempts to print a boolean value as a character. Unlike other 8951 // -Wformat diagnostics, this is fine from a type perspective, but it still 8952 // doesn't make sense. 8953 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8954 E->isKnownToHaveBooleanValue()) { 8955 const CharSourceRange &CSR = 8956 getSpecifierRange(StartSpecifier, SpecifierLen); 8957 SmallString<4> FSString; 8958 llvm::raw_svector_ostream os(FSString); 8959 FS.toString(os); 8960 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8961 << FSString, 8962 E->getExprLoc(), false, CSR); 8963 return true; 8964 } 8965 8966 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8967 if (Match == analyze_printf::ArgType::Match) 8968 return true; 8969 8970 // Look through argument promotions for our error message's reported type. 8971 // This includes the integral and floating promotions, but excludes array 8972 // and function pointer decay (seeing that an argument intended to be a 8973 // string has type 'char [6]' is probably more confusing than 'char *') and 8974 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8975 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8976 if (isArithmeticArgumentPromotion(S, ICE)) { 8977 E = ICE->getSubExpr(); 8978 ExprTy = E->getType(); 8979 8980 // Check if we didn't match because of an implicit cast from a 'char' 8981 // or 'short' to an 'int'. This is done because printf is a varargs 8982 // function. 8983 if (ICE->getType() == S.Context.IntTy || 8984 ICE->getType() == S.Context.UnsignedIntTy) { 8985 // All further checking is done on the subexpression 8986 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8987 AT.matchesType(S.Context, ExprTy); 8988 if (ImplicitMatch == analyze_printf::ArgType::Match) 8989 return true; 8990 if (ImplicitMatch == ArgType::NoMatchPedantic || 8991 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8992 Match = ImplicitMatch; 8993 } 8994 } 8995 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8996 // Special case for 'a', which has type 'int' in C. 8997 // Note, however, that we do /not/ want to treat multibyte constants like 8998 // 'MooV' as characters! This form is deprecated but still exists. In 8999 // addition, don't treat expressions as of type 'char' if one byte length 9000 // modifier is provided. 9001 if (ExprTy == S.Context.IntTy && 9002 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9003 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9004 ExprTy = S.Context.CharTy; 9005 } 9006 9007 // Look through enums to their underlying type. 9008 bool IsEnum = false; 9009 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9010 ExprTy = EnumTy->getDecl()->getIntegerType(); 9011 IsEnum = true; 9012 } 9013 9014 // %C in an Objective-C context prints a unichar, not a wchar_t. 9015 // If the argument is an integer of some kind, believe the %C and suggest 9016 // a cast instead of changing the conversion specifier. 9017 QualType IntendedTy = ExprTy; 9018 if (isObjCContext() && 9019 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9020 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9021 !ExprTy->isCharType()) { 9022 // 'unichar' is defined as a typedef of unsigned short, but we should 9023 // prefer using the typedef if it is visible. 9024 IntendedTy = S.Context.UnsignedShortTy; 9025 9026 // While we are here, check if the value is an IntegerLiteral that happens 9027 // to be within the valid range. 9028 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9029 const llvm::APInt &V = IL->getValue(); 9030 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9031 return true; 9032 } 9033 9034 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9035 Sema::LookupOrdinaryName); 9036 if (S.LookupName(Result, S.getCurScope())) { 9037 NamedDecl *ND = Result.getFoundDecl(); 9038 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9039 if (TD->getUnderlyingType() == IntendedTy) 9040 IntendedTy = S.Context.getTypedefType(TD); 9041 } 9042 } 9043 } 9044 9045 // Special-case some of Darwin's platform-independence types by suggesting 9046 // casts to primitive types that are known to be large enough. 9047 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9048 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9049 QualType CastTy; 9050 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9051 if (!CastTy.isNull()) { 9052 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9053 // (long in ASTContext). Only complain to pedants. 9054 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9055 (AT.isSizeT() || AT.isPtrdiffT()) && 9056 AT.matchesType(S.Context, CastTy)) 9057 Match = ArgType::NoMatchPedantic; 9058 IntendedTy = CastTy; 9059 ShouldNotPrintDirectly = true; 9060 } 9061 } 9062 9063 // We may be able to offer a FixItHint if it is a supported type. 9064 PrintfSpecifier fixedFS = FS; 9065 bool Success = 9066 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9067 9068 if (Success) { 9069 // Get the fix string from the fixed format specifier 9070 SmallString<16> buf; 9071 llvm::raw_svector_ostream os(buf); 9072 fixedFS.toString(os); 9073 9074 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9075 9076 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9077 unsigned Diag; 9078 switch (Match) { 9079 case ArgType::Match: llvm_unreachable("expected non-matching"); 9080 case ArgType::NoMatchPedantic: 9081 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9082 break; 9083 case ArgType::NoMatchTypeConfusion: 9084 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9085 break; 9086 case ArgType::NoMatch: 9087 Diag = diag::warn_format_conversion_argument_type_mismatch; 9088 break; 9089 } 9090 9091 // In this case, the specifier is wrong and should be changed to match 9092 // the argument. 9093 EmitFormatDiagnostic(S.PDiag(Diag) 9094 << AT.getRepresentativeTypeName(S.Context) 9095 << IntendedTy << IsEnum << E->getSourceRange(), 9096 E->getBeginLoc(), 9097 /*IsStringLocation*/ false, SpecRange, 9098 FixItHint::CreateReplacement(SpecRange, os.str())); 9099 } else { 9100 // The canonical type for formatting this value is different from the 9101 // actual type of the expression. (This occurs, for example, with Darwin's 9102 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9103 // should be printed as 'long' for 64-bit compatibility.) 9104 // Rather than emitting a normal format/argument mismatch, we want to 9105 // add a cast to the recommended type (and correct the format string 9106 // if necessary). 9107 SmallString<16> CastBuf; 9108 llvm::raw_svector_ostream CastFix(CastBuf); 9109 CastFix << "("; 9110 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9111 CastFix << ")"; 9112 9113 SmallVector<FixItHint,4> Hints; 9114 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9115 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9116 9117 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9118 // If there's already a cast present, just replace it. 9119 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9120 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9121 9122 } else if (!requiresParensToAddCast(E)) { 9123 // If the expression has high enough precedence, 9124 // just write the C-style cast. 9125 Hints.push_back( 9126 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9127 } else { 9128 // Otherwise, add parens around the expression as well as the cast. 9129 CastFix << "("; 9130 Hints.push_back( 9131 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9132 9133 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9134 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9135 } 9136 9137 if (ShouldNotPrintDirectly) { 9138 // The expression has a type that should not be printed directly. 9139 // We extract the name from the typedef because we don't want to show 9140 // the underlying type in the diagnostic. 9141 StringRef Name; 9142 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9143 Name = TypedefTy->getDecl()->getName(); 9144 else 9145 Name = CastTyName; 9146 unsigned Diag = Match == ArgType::NoMatchPedantic 9147 ? diag::warn_format_argument_needs_cast_pedantic 9148 : diag::warn_format_argument_needs_cast; 9149 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9150 << E->getSourceRange(), 9151 E->getBeginLoc(), /*IsStringLocation=*/false, 9152 SpecRange, Hints); 9153 } else { 9154 // In this case, the expression could be printed using a different 9155 // specifier, but we've decided that the specifier is probably correct 9156 // and we should cast instead. Just use the normal warning message. 9157 EmitFormatDiagnostic( 9158 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9159 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9160 << E->getSourceRange(), 9161 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9162 } 9163 } 9164 } else { 9165 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9166 SpecifierLen); 9167 // Since the warning for passing non-POD types to variadic functions 9168 // was deferred until now, we emit a warning for non-POD 9169 // arguments here. 9170 switch (S.isValidVarArgType(ExprTy)) { 9171 case Sema::VAK_Valid: 9172 case Sema::VAK_ValidInCXX11: { 9173 unsigned Diag; 9174 switch (Match) { 9175 case ArgType::Match: llvm_unreachable("expected non-matching"); 9176 case ArgType::NoMatchPedantic: 9177 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9178 break; 9179 case ArgType::NoMatchTypeConfusion: 9180 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9181 break; 9182 case ArgType::NoMatch: 9183 Diag = diag::warn_format_conversion_argument_type_mismatch; 9184 break; 9185 } 9186 9187 EmitFormatDiagnostic( 9188 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9189 << IsEnum << CSR << E->getSourceRange(), 9190 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9191 break; 9192 } 9193 case Sema::VAK_Undefined: 9194 case Sema::VAK_MSVCUndefined: 9195 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9196 << S.getLangOpts().CPlusPlus11 << ExprTy 9197 << CallType 9198 << AT.getRepresentativeTypeName(S.Context) << CSR 9199 << E->getSourceRange(), 9200 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9201 checkForCStrMembers(AT, E); 9202 break; 9203 9204 case Sema::VAK_Invalid: 9205 if (ExprTy->isObjCObjectType()) 9206 EmitFormatDiagnostic( 9207 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9208 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9209 << AT.getRepresentativeTypeName(S.Context) << CSR 9210 << E->getSourceRange(), 9211 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9212 else 9213 // FIXME: If this is an initializer list, suggest removing the braces 9214 // or inserting a cast to the target type. 9215 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9216 << isa<InitListExpr>(E) << ExprTy << CallType 9217 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9218 break; 9219 } 9220 9221 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9222 "format string specifier index out of range"); 9223 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9224 } 9225 9226 return true; 9227 } 9228 9229 //===--- CHECK: Scanf format string checking ------------------------------===// 9230 9231 namespace { 9232 9233 class CheckScanfHandler : public CheckFormatHandler { 9234 public: 9235 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9236 const Expr *origFormatExpr, Sema::FormatStringType type, 9237 unsigned firstDataArg, unsigned numDataArgs, 9238 const char *beg, bool hasVAListArg, 9239 ArrayRef<const Expr *> Args, unsigned formatIdx, 9240 bool inFunctionCall, Sema::VariadicCallType CallType, 9241 llvm::SmallBitVector &CheckedVarArgs, 9242 UncoveredArgHandler &UncoveredArg) 9243 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9244 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9245 inFunctionCall, CallType, CheckedVarArgs, 9246 UncoveredArg) {} 9247 9248 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9249 const char *startSpecifier, 9250 unsigned specifierLen) override; 9251 9252 bool HandleInvalidScanfConversionSpecifier( 9253 const analyze_scanf::ScanfSpecifier &FS, 9254 const char *startSpecifier, 9255 unsigned specifierLen) override; 9256 9257 void HandleIncompleteScanList(const char *start, const char *end) override; 9258 }; 9259 9260 } // namespace 9261 9262 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9263 const char *end) { 9264 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9265 getLocationOfByte(end), /*IsStringLocation*/true, 9266 getSpecifierRange(start, end - start)); 9267 } 9268 9269 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9270 const analyze_scanf::ScanfSpecifier &FS, 9271 const char *startSpecifier, 9272 unsigned specifierLen) { 9273 const analyze_scanf::ScanfConversionSpecifier &CS = 9274 FS.getConversionSpecifier(); 9275 9276 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9277 getLocationOfByte(CS.getStart()), 9278 startSpecifier, specifierLen, 9279 CS.getStart(), CS.getLength()); 9280 } 9281 9282 bool CheckScanfHandler::HandleScanfSpecifier( 9283 const analyze_scanf::ScanfSpecifier &FS, 9284 const char *startSpecifier, 9285 unsigned specifierLen) { 9286 using namespace analyze_scanf; 9287 using namespace analyze_format_string; 9288 9289 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9290 9291 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9292 // be used to decide if we are using positional arguments consistently. 9293 if (FS.consumesDataArgument()) { 9294 if (atFirstArg) { 9295 atFirstArg = false; 9296 usesPositionalArgs = FS.usesPositionalArg(); 9297 } 9298 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9299 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9300 startSpecifier, specifierLen); 9301 return false; 9302 } 9303 } 9304 9305 // Check if the field with is non-zero. 9306 const OptionalAmount &Amt = FS.getFieldWidth(); 9307 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9308 if (Amt.getConstantAmount() == 0) { 9309 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9310 Amt.getConstantLength()); 9311 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9312 getLocationOfByte(Amt.getStart()), 9313 /*IsStringLocation*/true, R, 9314 FixItHint::CreateRemoval(R)); 9315 } 9316 } 9317 9318 if (!FS.consumesDataArgument()) { 9319 // FIXME: Technically specifying a precision or field width here 9320 // makes no sense. Worth issuing a warning at some point. 9321 return true; 9322 } 9323 9324 // Consume the argument. 9325 unsigned argIndex = FS.getArgIndex(); 9326 if (argIndex < NumDataArgs) { 9327 // The check to see if the argIndex is valid will come later. 9328 // We set the bit here because we may exit early from this 9329 // function if we encounter some other error. 9330 CoveredArgs.set(argIndex); 9331 } 9332 9333 // Check the length modifier is valid with the given conversion specifier. 9334 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9335 S.getLangOpts())) 9336 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9337 diag::warn_format_nonsensical_length); 9338 else if (!FS.hasStandardLengthModifier()) 9339 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9340 else if (!FS.hasStandardLengthConversionCombination()) 9341 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9342 diag::warn_format_non_standard_conversion_spec); 9343 9344 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9345 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9346 9347 // The remaining checks depend on the data arguments. 9348 if (HasVAListArg) 9349 return true; 9350 9351 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9352 return false; 9353 9354 // Check that the argument type matches the format specifier. 9355 const Expr *Ex = getDataArg(argIndex); 9356 if (!Ex) 9357 return true; 9358 9359 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9360 9361 if (!AT.isValid()) { 9362 return true; 9363 } 9364 9365 analyze_format_string::ArgType::MatchKind Match = 9366 AT.matchesType(S.Context, Ex->getType()); 9367 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9368 if (Match == analyze_format_string::ArgType::Match) 9369 return true; 9370 9371 ScanfSpecifier fixedFS = FS; 9372 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9373 S.getLangOpts(), S.Context); 9374 9375 unsigned Diag = 9376 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9377 : diag::warn_format_conversion_argument_type_mismatch; 9378 9379 if (Success) { 9380 // Get the fix string from the fixed format specifier. 9381 SmallString<128> buf; 9382 llvm::raw_svector_ostream os(buf); 9383 fixedFS.toString(os); 9384 9385 EmitFormatDiagnostic( 9386 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9387 << Ex->getType() << false << Ex->getSourceRange(), 9388 Ex->getBeginLoc(), 9389 /*IsStringLocation*/ false, 9390 getSpecifierRange(startSpecifier, specifierLen), 9391 FixItHint::CreateReplacement( 9392 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9393 } else { 9394 EmitFormatDiagnostic(S.PDiag(Diag) 9395 << AT.getRepresentativeTypeName(S.Context) 9396 << Ex->getType() << false << Ex->getSourceRange(), 9397 Ex->getBeginLoc(), 9398 /*IsStringLocation*/ false, 9399 getSpecifierRange(startSpecifier, specifierLen)); 9400 } 9401 9402 return true; 9403 } 9404 9405 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9406 const Expr *OrigFormatExpr, 9407 ArrayRef<const Expr *> Args, 9408 bool HasVAListArg, unsigned format_idx, 9409 unsigned firstDataArg, 9410 Sema::FormatStringType Type, 9411 bool inFunctionCall, 9412 Sema::VariadicCallType CallType, 9413 llvm::SmallBitVector &CheckedVarArgs, 9414 UncoveredArgHandler &UncoveredArg, 9415 bool IgnoreStringsWithoutSpecifiers) { 9416 // CHECK: is the format string a wide literal? 9417 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9418 CheckFormatHandler::EmitFormatDiagnostic( 9419 S, inFunctionCall, Args[format_idx], 9420 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9421 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9422 return; 9423 } 9424 9425 // Str - The format string. NOTE: this is NOT null-terminated! 9426 StringRef StrRef = FExpr->getString(); 9427 const char *Str = StrRef.data(); 9428 // Account for cases where the string literal is truncated in a declaration. 9429 const ConstantArrayType *T = 9430 S.Context.getAsConstantArrayType(FExpr->getType()); 9431 assert(T && "String literal not of constant array type!"); 9432 size_t TypeSize = T->getSize().getZExtValue(); 9433 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9434 const unsigned numDataArgs = Args.size() - firstDataArg; 9435 9436 if (IgnoreStringsWithoutSpecifiers && 9437 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9438 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9439 return; 9440 9441 // Emit a warning if the string literal is truncated and does not contain an 9442 // embedded null character. 9443 if (TypeSize <= StrRef.size() && 9444 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9445 CheckFormatHandler::EmitFormatDiagnostic( 9446 S, inFunctionCall, Args[format_idx], 9447 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9448 FExpr->getBeginLoc(), 9449 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9450 return; 9451 } 9452 9453 // CHECK: empty format string? 9454 if (StrLen == 0 && numDataArgs > 0) { 9455 CheckFormatHandler::EmitFormatDiagnostic( 9456 S, inFunctionCall, Args[format_idx], 9457 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9458 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9459 return; 9460 } 9461 9462 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9463 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9464 Type == Sema::FST_OSTrace) { 9465 CheckPrintfHandler H( 9466 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9467 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9468 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9469 CheckedVarArgs, UncoveredArg); 9470 9471 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9472 S.getLangOpts(), 9473 S.Context.getTargetInfo(), 9474 Type == Sema::FST_FreeBSDKPrintf)) 9475 H.DoneProcessing(); 9476 } else if (Type == Sema::FST_Scanf) { 9477 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9478 numDataArgs, Str, HasVAListArg, Args, format_idx, 9479 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9480 9481 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9482 S.getLangOpts(), 9483 S.Context.getTargetInfo())) 9484 H.DoneProcessing(); 9485 } // TODO: handle other formats 9486 } 9487 9488 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9489 // Str - The format string. NOTE: this is NOT null-terminated! 9490 StringRef StrRef = FExpr->getString(); 9491 const char *Str = StrRef.data(); 9492 // Account for cases where the string literal is truncated in a declaration. 9493 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9494 assert(T && "String literal not of constant array type!"); 9495 size_t TypeSize = T->getSize().getZExtValue(); 9496 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9497 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9498 getLangOpts(), 9499 Context.getTargetInfo()); 9500 } 9501 9502 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9503 9504 // Returns the related absolute value function that is larger, of 0 if one 9505 // does not exist. 9506 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9507 switch (AbsFunction) { 9508 default: 9509 return 0; 9510 9511 case Builtin::BI__builtin_abs: 9512 return Builtin::BI__builtin_labs; 9513 case Builtin::BI__builtin_labs: 9514 return Builtin::BI__builtin_llabs; 9515 case Builtin::BI__builtin_llabs: 9516 return 0; 9517 9518 case Builtin::BI__builtin_fabsf: 9519 return Builtin::BI__builtin_fabs; 9520 case Builtin::BI__builtin_fabs: 9521 return Builtin::BI__builtin_fabsl; 9522 case Builtin::BI__builtin_fabsl: 9523 return 0; 9524 9525 case Builtin::BI__builtin_cabsf: 9526 return Builtin::BI__builtin_cabs; 9527 case Builtin::BI__builtin_cabs: 9528 return Builtin::BI__builtin_cabsl; 9529 case Builtin::BI__builtin_cabsl: 9530 return 0; 9531 9532 case Builtin::BIabs: 9533 return Builtin::BIlabs; 9534 case Builtin::BIlabs: 9535 return Builtin::BIllabs; 9536 case Builtin::BIllabs: 9537 return 0; 9538 9539 case Builtin::BIfabsf: 9540 return Builtin::BIfabs; 9541 case Builtin::BIfabs: 9542 return Builtin::BIfabsl; 9543 case Builtin::BIfabsl: 9544 return 0; 9545 9546 case Builtin::BIcabsf: 9547 return Builtin::BIcabs; 9548 case Builtin::BIcabs: 9549 return Builtin::BIcabsl; 9550 case Builtin::BIcabsl: 9551 return 0; 9552 } 9553 } 9554 9555 // Returns the argument type of the absolute value function. 9556 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9557 unsigned AbsType) { 9558 if (AbsType == 0) 9559 return QualType(); 9560 9561 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9562 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9563 if (Error != ASTContext::GE_None) 9564 return QualType(); 9565 9566 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9567 if (!FT) 9568 return QualType(); 9569 9570 if (FT->getNumParams() != 1) 9571 return QualType(); 9572 9573 return FT->getParamType(0); 9574 } 9575 9576 // Returns the best absolute value function, or zero, based on type and 9577 // current absolute value function. 9578 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9579 unsigned AbsFunctionKind) { 9580 unsigned BestKind = 0; 9581 uint64_t ArgSize = Context.getTypeSize(ArgType); 9582 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9583 Kind = getLargerAbsoluteValueFunction(Kind)) { 9584 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9585 if (Context.getTypeSize(ParamType) >= ArgSize) { 9586 if (BestKind == 0) 9587 BestKind = Kind; 9588 else if (Context.hasSameType(ParamType, ArgType)) { 9589 BestKind = Kind; 9590 break; 9591 } 9592 } 9593 } 9594 return BestKind; 9595 } 9596 9597 enum AbsoluteValueKind { 9598 AVK_Integer, 9599 AVK_Floating, 9600 AVK_Complex 9601 }; 9602 9603 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9604 if (T->isIntegralOrEnumerationType()) 9605 return AVK_Integer; 9606 if (T->isRealFloatingType()) 9607 return AVK_Floating; 9608 if (T->isAnyComplexType()) 9609 return AVK_Complex; 9610 9611 llvm_unreachable("Type not integer, floating, or complex"); 9612 } 9613 9614 // Changes the absolute value function to a different type. Preserves whether 9615 // the function is a builtin. 9616 static unsigned changeAbsFunction(unsigned AbsKind, 9617 AbsoluteValueKind ValueKind) { 9618 switch (ValueKind) { 9619 case AVK_Integer: 9620 switch (AbsKind) { 9621 default: 9622 return 0; 9623 case Builtin::BI__builtin_fabsf: 9624 case Builtin::BI__builtin_fabs: 9625 case Builtin::BI__builtin_fabsl: 9626 case Builtin::BI__builtin_cabsf: 9627 case Builtin::BI__builtin_cabs: 9628 case Builtin::BI__builtin_cabsl: 9629 return Builtin::BI__builtin_abs; 9630 case Builtin::BIfabsf: 9631 case Builtin::BIfabs: 9632 case Builtin::BIfabsl: 9633 case Builtin::BIcabsf: 9634 case Builtin::BIcabs: 9635 case Builtin::BIcabsl: 9636 return Builtin::BIabs; 9637 } 9638 case AVK_Floating: 9639 switch (AbsKind) { 9640 default: 9641 return 0; 9642 case Builtin::BI__builtin_abs: 9643 case Builtin::BI__builtin_labs: 9644 case Builtin::BI__builtin_llabs: 9645 case Builtin::BI__builtin_cabsf: 9646 case Builtin::BI__builtin_cabs: 9647 case Builtin::BI__builtin_cabsl: 9648 return Builtin::BI__builtin_fabsf; 9649 case Builtin::BIabs: 9650 case Builtin::BIlabs: 9651 case Builtin::BIllabs: 9652 case Builtin::BIcabsf: 9653 case Builtin::BIcabs: 9654 case Builtin::BIcabsl: 9655 return Builtin::BIfabsf; 9656 } 9657 case AVK_Complex: 9658 switch (AbsKind) { 9659 default: 9660 return 0; 9661 case Builtin::BI__builtin_abs: 9662 case Builtin::BI__builtin_labs: 9663 case Builtin::BI__builtin_llabs: 9664 case Builtin::BI__builtin_fabsf: 9665 case Builtin::BI__builtin_fabs: 9666 case Builtin::BI__builtin_fabsl: 9667 return Builtin::BI__builtin_cabsf; 9668 case Builtin::BIabs: 9669 case Builtin::BIlabs: 9670 case Builtin::BIllabs: 9671 case Builtin::BIfabsf: 9672 case Builtin::BIfabs: 9673 case Builtin::BIfabsl: 9674 return Builtin::BIcabsf; 9675 } 9676 } 9677 llvm_unreachable("Unable to convert function"); 9678 } 9679 9680 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9681 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9682 if (!FnInfo) 9683 return 0; 9684 9685 switch (FDecl->getBuiltinID()) { 9686 default: 9687 return 0; 9688 case Builtin::BI__builtin_abs: 9689 case Builtin::BI__builtin_fabs: 9690 case Builtin::BI__builtin_fabsf: 9691 case Builtin::BI__builtin_fabsl: 9692 case Builtin::BI__builtin_labs: 9693 case Builtin::BI__builtin_llabs: 9694 case Builtin::BI__builtin_cabs: 9695 case Builtin::BI__builtin_cabsf: 9696 case Builtin::BI__builtin_cabsl: 9697 case Builtin::BIabs: 9698 case Builtin::BIlabs: 9699 case Builtin::BIllabs: 9700 case Builtin::BIfabs: 9701 case Builtin::BIfabsf: 9702 case Builtin::BIfabsl: 9703 case Builtin::BIcabs: 9704 case Builtin::BIcabsf: 9705 case Builtin::BIcabsl: 9706 return FDecl->getBuiltinID(); 9707 } 9708 llvm_unreachable("Unknown Builtin type"); 9709 } 9710 9711 // If the replacement is valid, emit a note with replacement function. 9712 // Additionally, suggest including the proper header if not already included. 9713 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9714 unsigned AbsKind, QualType ArgType) { 9715 bool EmitHeaderHint = true; 9716 const char *HeaderName = nullptr; 9717 const char *FunctionName = nullptr; 9718 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9719 FunctionName = "std::abs"; 9720 if (ArgType->isIntegralOrEnumerationType()) { 9721 HeaderName = "cstdlib"; 9722 } else if (ArgType->isRealFloatingType()) { 9723 HeaderName = "cmath"; 9724 } else { 9725 llvm_unreachable("Invalid Type"); 9726 } 9727 9728 // Lookup all std::abs 9729 if (NamespaceDecl *Std = S.getStdNamespace()) { 9730 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9731 R.suppressDiagnostics(); 9732 S.LookupQualifiedName(R, Std); 9733 9734 for (const auto *I : R) { 9735 const FunctionDecl *FDecl = nullptr; 9736 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9737 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9738 } else { 9739 FDecl = dyn_cast<FunctionDecl>(I); 9740 } 9741 if (!FDecl) 9742 continue; 9743 9744 // Found std::abs(), check that they are the right ones. 9745 if (FDecl->getNumParams() != 1) 9746 continue; 9747 9748 // Check that the parameter type can handle the argument. 9749 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9750 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9751 S.Context.getTypeSize(ArgType) <= 9752 S.Context.getTypeSize(ParamType)) { 9753 // Found a function, don't need the header hint. 9754 EmitHeaderHint = false; 9755 break; 9756 } 9757 } 9758 } 9759 } else { 9760 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9761 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9762 9763 if (HeaderName) { 9764 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9765 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9766 R.suppressDiagnostics(); 9767 S.LookupName(R, S.getCurScope()); 9768 9769 if (R.isSingleResult()) { 9770 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9771 if (FD && FD->getBuiltinID() == AbsKind) { 9772 EmitHeaderHint = false; 9773 } else { 9774 return; 9775 } 9776 } else if (!R.empty()) { 9777 return; 9778 } 9779 } 9780 } 9781 9782 S.Diag(Loc, diag::note_replace_abs_function) 9783 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9784 9785 if (!HeaderName) 9786 return; 9787 9788 if (!EmitHeaderHint) 9789 return; 9790 9791 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9792 << FunctionName; 9793 } 9794 9795 template <std::size_t StrLen> 9796 static bool IsStdFunction(const FunctionDecl *FDecl, 9797 const char (&Str)[StrLen]) { 9798 if (!FDecl) 9799 return false; 9800 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9801 return false; 9802 if (!FDecl->isInStdNamespace()) 9803 return false; 9804 9805 return true; 9806 } 9807 9808 // Warn when using the wrong abs() function. 9809 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9810 const FunctionDecl *FDecl) { 9811 if (Call->getNumArgs() != 1) 9812 return; 9813 9814 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9815 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9816 if (AbsKind == 0 && !IsStdAbs) 9817 return; 9818 9819 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9820 QualType ParamType = Call->getArg(0)->getType(); 9821 9822 // Unsigned types cannot be negative. Suggest removing the absolute value 9823 // function call. 9824 if (ArgType->isUnsignedIntegerType()) { 9825 const char *FunctionName = 9826 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9827 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9828 Diag(Call->getExprLoc(), diag::note_remove_abs) 9829 << FunctionName 9830 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9831 return; 9832 } 9833 9834 // Taking the absolute value of a pointer is very suspicious, they probably 9835 // wanted to index into an array, dereference a pointer, call a function, etc. 9836 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9837 unsigned DiagType = 0; 9838 if (ArgType->isFunctionType()) 9839 DiagType = 1; 9840 else if (ArgType->isArrayType()) 9841 DiagType = 2; 9842 9843 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9844 return; 9845 } 9846 9847 // std::abs has overloads which prevent most of the absolute value problems 9848 // from occurring. 9849 if (IsStdAbs) 9850 return; 9851 9852 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9853 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9854 9855 // The argument and parameter are the same kind. Check if they are the right 9856 // size. 9857 if (ArgValueKind == ParamValueKind) { 9858 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9859 return; 9860 9861 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9862 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9863 << FDecl << ArgType << ParamType; 9864 9865 if (NewAbsKind == 0) 9866 return; 9867 9868 emitReplacement(*this, Call->getExprLoc(), 9869 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9870 return; 9871 } 9872 9873 // ArgValueKind != ParamValueKind 9874 // The wrong type of absolute value function was used. Attempt to find the 9875 // proper one. 9876 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9877 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9878 if (NewAbsKind == 0) 9879 return; 9880 9881 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9882 << FDecl << ParamValueKind << ArgValueKind; 9883 9884 emitReplacement(*this, Call->getExprLoc(), 9885 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9886 } 9887 9888 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9889 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9890 const FunctionDecl *FDecl) { 9891 if (!Call || !FDecl) return; 9892 9893 // Ignore template specializations and macros. 9894 if (inTemplateInstantiation()) return; 9895 if (Call->getExprLoc().isMacroID()) return; 9896 9897 // Only care about the one template argument, two function parameter std::max 9898 if (Call->getNumArgs() != 2) return; 9899 if (!IsStdFunction(FDecl, "max")) return; 9900 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9901 if (!ArgList) return; 9902 if (ArgList->size() != 1) return; 9903 9904 // Check that template type argument is unsigned integer. 9905 const auto& TA = ArgList->get(0); 9906 if (TA.getKind() != TemplateArgument::Type) return; 9907 QualType ArgType = TA.getAsType(); 9908 if (!ArgType->isUnsignedIntegerType()) return; 9909 9910 // See if either argument is a literal zero. 9911 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9912 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9913 if (!MTE) return false; 9914 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9915 if (!Num) return false; 9916 if (Num->getValue() != 0) return false; 9917 return true; 9918 }; 9919 9920 const Expr *FirstArg = Call->getArg(0); 9921 const Expr *SecondArg = Call->getArg(1); 9922 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9923 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9924 9925 // Only warn when exactly one argument is zero. 9926 if (IsFirstArgZero == IsSecondArgZero) return; 9927 9928 SourceRange FirstRange = FirstArg->getSourceRange(); 9929 SourceRange SecondRange = SecondArg->getSourceRange(); 9930 9931 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9932 9933 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9934 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9935 9936 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9937 SourceRange RemovalRange; 9938 if (IsFirstArgZero) { 9939 RemovalRange = SourceRange(FirstRange.getBegin(), 9940 SecondRange.getBegin().getLocWithOffset(-1)); 9941 } else { 9942 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9943 SecondRange.getEnd()); 9944 } 9945 9946 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9947 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9948 << FixItHint::CreateRemoval(RemovalRange); 9949 } 9950 9951 //===--- CHECK: Standard memory functions ---------------------------------===// 9952 9953 /// Takes the expression passed to the size_t parameter of functions 9954 /// such as memcmp, strncat, etc and warns if it's a comparison. 9955 /// 9956 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9957 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9958 IdentifierInfo *FnName, 9959 SourceLocation FnLoc, 9960 SourceLocation RParenLoc) { 9961 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9962 if (!Size) 9963 return false; 9964 9965 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9966 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9967 return false; 9968 9969 SourceRange SizeRange = Size->getSourceRange(); 9970 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9971 << SizeRange << FnName; 9972 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9973 << FnName 9974 << FixItHint::CreateInsertion( 9975 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9976 << FixItHint::CreateRemoval(RParenLoc); 9977 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9978 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9979 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9980 ")"); 9981 9982 return true; 9983 } 9984 9985 /// Determine whether the given type is or contains a dynamic class type 9986 /// (e.g., whether it has a vtable). 9987 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9988 bool &IsContained) { 9989 // Look through array types while ignoring qualifiers. 9990 const Type *Ty = T->getBaseElementTypeUnsafe(); 9991 IsContained = false; 9992 9993 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9994 RD = RD ? RD->getDefinition() : nullptr; 9995 if (!RD || RD->isInvalidDecl()) 9996 return nullptr; 9997 9998 if (RD->isDynamicClass()) 9999 return RD; 10000 10001 // Check all the fields. If any bases were dynamic, the class is dynamic. 10002 // It's impossible for a class to transitively contain itself by value, so 10003 // infinite recursion is impossible. 10004 for (auto *FD : RD->fields()) { 10005 bool SubContained; 10006 if (const CXXRecordDecl *ContainedRD = 10007 getContainedDynamicClass(FD->getType(), SubContained)) { 10008 IsContained = true; 10009 return ContainedRD; 10010 } 10011 } 10012 10013 return nullptr; 10014 } 10015 10016 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10017 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10018 if (Unary->getKind() == UETT_SizeOf) 10019 return Unary; 10020 return nullptr; 10021 } 10022 10023 /// If E is a sizeof expression, returns its argument expression, 10024 /// otherwise returns NULL. 10025 static const Expr *getSizeOfExprArg(const Expr *E) { 10026 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10027 if (!SizeOf->isArgumentType()) 10028 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10029 return nullptr; 10030 } 10031 10032 /// If E is a sizeof expression, returns its argument type. 10033 static QualType getSizeOfArgType(const Expr *E) { 10034 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10035 return SizeOf->getTypeOfArgument(); 10036 return QualType(); 10037 } 10038 10039 namespace { 10040 10041 struct SearchNonTrivialToInitializeField 10042 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10043 using Super = 10044 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10045 10046 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10047 10048 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10049 SourceLocation SL) { 10050 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10051 asDerived().visitArray(PDIK, AT, SL); 10052 return; 10053 } 10054 10055 Super::visitWithKind(PDIK, FT, SL); 10056 } 10057 10058 void visitARCStrong(QualType FT, SourceLocation SL) { 10059 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10060 } 10061 void visitARCWeak(QualType FT, SourceLocation SL) { 10062 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10063 } 10064 void visitStruct(QualType FT, SourceLocation SL) { 10065 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10066 visit(FD->getType(), FD->getLocation()); 10067 } 10068 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10069 const ArrayType *AT, SourceLocation SL) { 10070 visit(getContext().getBaseElementType(AT), SL); 10071 } 10072 void visitTrivial(QualType FT, SourceLocation SL) {} 10073 10074 static void diag(QualType RT, const Expr *E, Sema &S) { 10075 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10076 } 10077 10078 ASTContext &getContext() { return S.getASTContext(); } 10079 10080 const Expr *E; 10081 Sema &S; 10082 }; 10083 10084 struct SearchNonTrivialToCopyField 10085 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10086 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10087 10088 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10089 10090 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10091 SourceLocation SL) { 10092 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10093 asDerived().visitArray(PCK, AT, SL); 10094 return; 10095 } 10096 10097 Super::visitWithKind(PCK, FT, SL); 10098 } 10099 10100 void visitARCStrong(QualType FT, SourceLocation SL) { 10101 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10102 } 10103 void visitARCWeak(QualType FT, SourceLocation SL) { 10104 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10105 } 10106 void visitStruct(QualType FT, SourceLocation SL) { 10107 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10108 visit(FD->getType(), FD->getLocation()); 10109 } 10110 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10111 SourceLocation SL) { 10112 visit(getContext().getBaseElementType(AT), SL); 10113 } 10114 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10115 SourceLocation SL) {} 10116 void visitTrivial(QualType FT, SourceLocation SL) {} 10117 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10118 10119 static void diag(QualType RT, const Expr *E, Sema &S) { 10120 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10121 } 10122 10123 ASTContext &getContext() { return S.getASTContext(); } 10124 10125 const Expr *E; 10126 Sema &S; 10127 }; 10128 10129 } 10130 10131 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10132 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10133 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10134 10135 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10136 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10137 return false; 10138 10139 return doesExprLikelyComputeSize(BO->getLHS()) || 10140 doesExprLikelyComputeSize(BO->getRHS()); 10141 } 10142 10143 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10144 } 10145 10146 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10147 /// 10148 /// \code 10149 /// #define MACRO 0 10150 /// foo(MACRO); 10151 /// foo(0); 10152 /// \endcode 10153 /// 10154 /// This should return true for the first call to foo, but not for the second 10155 /// (regardless of whether foo is a macro or function). 10156 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10157 SourceLocation CallLoc, 10158 SourceLocation ArgLoc) { 10159 if (!CallLoc.isMacroID()) 10160 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10161 10162 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10163 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10164 } 10165 10166 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10167 /// last two arguments transposed. 10168 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10169 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10170 return; 10171 10172 const Expr *SizeArg = 10173 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10174 10175 auto isLiteralZero = [](const Expr *E) { 10176 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10177 }; 10178 10179 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10180 SourceLocation CallLoc = Call->getRParenLoc(); 10181 SourceManager &SM = S.getSourceManager(); 10182 if (isLiteralZero(SizeArg) && 10183 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10184 10185 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10186 10187 // Some platforms #define bzero to __builtin_memset. See if this is the 10188 // case, and if so, emit a better diagnostic. 10189 if (BId == Builtin::BIbzero || 10190 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10191 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10192 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10193 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10194 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10195 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10196 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10197 } 10198 return; 10199 } 10200 10201 // If the second argument to a memset is a sizeof expression and the third 10202 // isn't, this is also likely an error. This should catch 10203 // 'memset(buf, sizeof(buf), 0xff)'. 10204 if (BId == Builtin::BImemset && 10205 doesExprLikelyComputeSize(Call->getArg(1)) && 10206 !doesExprLikelyComputeSize(Call->getArg(2))) { 10207 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10208 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10209 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10210 return; 10211 } 10212 } 10213 10214 /// Check for dangerous or invalid arguments to memset(). 10215 /// 10216 /// This issues warnings on known problematic, dangerous or unspecified 10217 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10218 /// function calls. 10219 /// 10220 /// \param Call The call expression to diagnose. 10221 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10222 unsigned BId, 10223 IdentifierInfo *FnName) { 10224 assert(BId != 0); 10225 10226 // It is possible to have a non-standard definition of memset. Validate 10227 // we have enough arguments, and if not, abort further checking. 10228 unsigned ExpectedNumArgs = 10229 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10230 if (Call->getNumArgs() < ExpectedNumArgs) 10231 return; 10232 10233 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10234 BId == Builtin::BIstrndup ? 1 : 2); 10235 unsigned LenArg = 10236 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10237 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10238 10239 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10240 Call->getBeginLoc(), Call->getRParenLoc())) 10241 return; 10242 10243 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10244 CheckMemaccessSize(*this, BId, Call); 10245 10246 // We have special checking when the length is a sizeof expression. 10247 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10248 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10249 llvm::FoldingSetNodeID SizeOfArgID; 10250 10251 // Although widely used, 'bzero' is not a standard function. Be more strict 10252 // with the argument types before allowing diagnostics and only allow the 10253 // form bzero(ptr, sizeof(...)). 10254 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10255 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10256 return; 10257 10258 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10259 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10260 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10261 10262 QualType DestTy = Dest->getType(); 10263 QualType PointeeTy; 10264 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10265 PointeeTy = DestPtrTy->getPointeeType(); 10266 10267 // Never warn about void type pointers. This can be used to suppress 10268 // false positives. 10269 if (PointeeTy->isVoidType()) 10270 continue; 10271 10272 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10273 // actually comparing the expressions for equality. Because computing the 10274 // expression IDs can be expensive, we only do this if the diagnostic is 10275 // enabled. 10276 if (SizeOfArg && 10277 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10278 SizeOfArg->getExprLoc())) { 10279 // We only compute IDs for expressions if the warning is enabled, and 10280 // cache the sizeof arg's ID. 10281 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10282 SizeOfArg->Profile(SizeOfArgID, Context, true); 10283 llvm::FoldingSetNodeID DestID; 10284 Dest->Profile(DestID, Context, true); 10285 if (DestID == SizeOfArgID) { 10286 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10287 // over sizeof(src) as well. 10288 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10289 StringRef ReadableName = FnName->getName(); 10290 10291 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10292 if (UnaryOp->getOpcode() == UO_AddrOf) 10293 ActionIdx = 1; // If its an address-of operator, just remove it. 10294 if (!PointeeTy->isIncompleteType() && 10295 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10296 ActionIdx = 2; // If the pointee's size is sizeof(char), 10297 // suggest an explicit length. 10298 10299 // If the function is defined as a builtin macro, do not show macro 10300 // expansion. 10301 SourceLocation SL = SizeOfArg->getExprLoc(); 10302 SourceRange DSR = Dest->getSourceRange(); 10303 SourceRange SSR = SizeOfArg->getSourceRange(); 10304 SourceManager &SM = getSourceManager(); 10305 10306 if (SM.isMacroArgExpansion(SL)) { 10307 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10308 SL = SM.getSpellingLoc(SL); 10309 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10310 SM.getSpellingLoc(DSR.getEnd())); 10311 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10312 SM.getSpellingLoc(SSR.getEnd())); 10313 } 10314 10315 DiagRuntimeBehavior(SL, SizeOfArg, 10316 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10317 << ReadableName 10318 << PointeeTy 10319 << DestTy 10320 << DSR 10321 << SSR); 10322 DiagRuntimeBehavior(SL, SizeOfArg, 10323 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10324 << ActionIdx 10325 << SSR); 10326 10327 break; 10328 } 10329 } 10330 10331 // Also check for cases where the sizeof argument is the exact same 10332 // type as the memory argument, and where it points to a user-defined 10333 // record type. 10334 if (SizeOfArgTy != QualType()) { 10335 if (PointeeTy->isRecordType() && 10336 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10337 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10338 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10339 << FnName << SizeOfArgTy << ArgIdx 10340 << PointeeTy << Dest->getSourceRange() 10341 << LenExpr->getSourceRange()); 10342 break; 10343 } 10344 } 10345 } else if (DestTy->isArrayType()) { 10346 PointeeTy = DestTy; 10347 } 10348 10349 if (PointeeTy == QualType()) 10350 continue; 10351 10352 // Always complain about dynamic classes. 10353 bool IsContained; 10354 if (const CXXRecordDecl *ContainedRD = 10355 getContainedDynamicClass(PointeeTy, IsContained)) { 10356 10357 unsigned OperationType = 0; 10358 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10359 // "overwritten" if we're warning about the destination for any call 10360 // but memcmp; otherwise a verb appropriate to the call. 10361 if (ArgIdx != 0 || IsCmp) { 10362 if (BId == Builtin::BImemcpy) 10363 OperationType = 1; 10364 else if(BId == Builtin::BImemmove) 10365 OperationType = 2; 10366 else if (IsCmp) 10367 OperationType = 3; 10368 } 10369 10370 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10371 PDiag(diag::warn_dyn_class_memaccess) 10372 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10373 << IsContained << ContainedRD << OperationType 10374 << Call->getCallee()->getSourceRange()); 10375 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10376 BId != Builtin::BImemset) 10377 DiagRuntimeBehavior( 10378 Dest->getExprLoc(), Dest, 10379 PDiag(diag::warn_arc_object_memaccess) 10380 << ArgIdx << FnName << PointeeTy 10381 << Call->getCallee()->getSourceRange()); 10382 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10383 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10384 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10385 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10386 PDiag(diag::warn_cstruct_memaccess) 10387 << ArgIdx << FnName << PointeeTy << 0); 10388 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10389 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10390 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10391 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10392 PDiag(diag::warn_cstruct_memaccess) 10393 << ArgIdx << FnName << PointeeTy << 1); 10394 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10395 } else { 10396 continue; 10397 } 10398 } else 10399 continue; 10400 10401 DiagRuntimeBehavior( 10402 Dest->getExprLoc(), Dest, 10403 PDiag(diag::note_bad_memaccess_silence) 10404 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10405 break; 10406 } 10407 } 10408 10409 // A little helper routine: ignore addition and subtraction of integer literals. 10410 // This intentionally does not ignore all integer constant expressions because 10411 // we don't want to remove sizeof(). 10412 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10413 Ex = Ex->IgnoreParenCasts(); 10414 10415 while (true) { 10416 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10417 if (!BO || !BO->isAdditiveOp()) 10418 break; 10419 10420 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10421 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10422 10423 if (isa<IntegerLiteral>(RHS)) 10424 Ex = LHS; 10425 else if (isa<IntegerLiteral>(LHS)) 10426 Ex = RHS; 10427 else 10428 break; 10429 } 10430 10431 return Ex; 10432 } 10433 10434 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10435 ASTContext &Context) { 10436 // Only handle constant-sized or VLAs, but not flexible members. 10437 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10438 // Only issue the FIXIT for arrays of size > 1. 10439 if (CAT->getSize().getSExtValue() <= 1) 10440 return false; 10441 } else if (!Ty->isVariableArrayType()) { 10442 return false; 10443 } 10444 return true; 10445 } 10446 10447 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10448 // be the size of the source, instead of the destination. 10449 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10450 IdentifierInfo *FnName) { 10451 10452 // Don't crash if the user has the wrong number of arguments 10453 unsigned NumArgs = Call->getNumArgs(); 10454 if ((NumArgs != 3) && (NumArgs != 4)) 10455 return; 10456 10457 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10458 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10459 const Expr *CompareWithSrc = nullptr; 10460 10461 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10462 Call->getBeginLoc(), Call->getRParenLoc())) 10463 return; 10464 10465 // Look for 'strlcpy(dst, x, sizeof(x))' 10466 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10467 CompareWithSrc = Ex; 10468 else { 10469 // Look for 'strlcpy(dst, x, strlen(x))' 10470 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10471 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10472 SizeCall->getNumArgs() == 1) 10473 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10474 } 10475 } 10476 10477 if (!CompareWithSrc) 10478 return; 10479 10480 // Determine if the argument to sizeof/strlen is equal to the source 10481 // argument. In principle there's all kinds of things you could do 10482 // here, for instance creating an == expression and evaluating it with 10483 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10484 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10485 if (!SrcArgDRE) 10486 return; 10487 10488 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10489 if (!CompareWithSrcDRE || 10490 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10491 return; 10492 10493 const Expr *OriginalSizeArg = Call->getArg(2); 10494 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10495 << OriginalSizeArg->getSourceRange() << FnName; 10496 10497 // Output a FIXIT hint if the destination is an array (rather than a 10498 // pointer to an array). This could be enhanced to handle some 10499 // pointers if we know the actual size, like if DstArg is 'array+2' 10500 // we could say 'sizeof(array)-2'. 10501 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10502 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10503 return; 10504 10505 SmallString<128> sizeString; 10506 llvm::raw_svector_ostream OS(sizeString); 10507 OS << "sizeof("; 10508 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10509 OS << ")"; 10510 10511 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10512 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10513 OS.str()); 10514 } 10515 10516 /// Check if two expressions refer to the same declaration. 10517 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10518 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10519 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10520 return D1->getDecl() == D2->getDecl(); 10521 return false; 10522 } 10523 10524 static const Expr *getStrlenExprArg(const Expr *E) { 10525 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10526 const FunctionDecl *FD = CE->getDirectCallee(); 10527 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10528 return nullptr; 10529 return CE->getArg(0)->IgnoreParenCasts(); 10530 } 10531 return nullptr; 10532 } 10533 10534 // Warn on anti-patterns as the 'size' argument to strncat. 10535 // The correct size argument should look like following: 10536 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10537 void Sema::CheckStrncatArguments(const CallExpr *CE, 10538 IdentifierInfo *FnName) { 10539 // Don't crash if the user has the wrong number of arguments. 10540 if (CE->getNumArgs() < 3) 10541 return; 10542 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10543 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10544 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10545 10546 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10547 CE->getRParenLoc())) 10548 return; 10549 10550 // Identify common expressions, which are wrongly used as the size argument 10551 // to strncat and may lead to buffer overflows. 10552 unsigned PatternType = 0; 10553 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10554 // - sizeof(dst) 10555 if (referToTheSameDecl(SizeOfArg, DstArg)) 10556 PatternType = 1; 10557 // - sizeof(src) 10558 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10559 PatternType = 2; 10560 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10561 if (BE->getOpcode() == BO_Sub) { 10562 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10563 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10564 // - sizeof(dst) - strlen(dst) 10565 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10566 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10567 PatternType = 1; 10568 // - sizeof(src) - (anything) 10569 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10570 PatternType = 2; 10571 } 10572 } 10573 10574 if (PatternType == 0) 10575 return; 10576 10577 // Generate the diagnostic. 10578 SourceLocation SL = LenArg->getBeginLoc(); 10579 SourceRange SR = LenArg->getSourceRange(); 10580 SourceManager &SM = getSourceManager(); 10581 10582 // If the function is defined as a builtin macro, do not show macro expansion. 10583 if (SM.isMacroArgExpansion(SL)) { 10584 SL = SM.getSpellingLoc(SL); 10585 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10586 SM.getSpellingLoc(SR.getEnd())); 10587 } 10588 10589 // Check if the destination is an array (rather than a pointer to an array). 10590 QualType DstTy = DstArg->getType(); 10591 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10592 Context); 10593 if (!isKnownSizeArray) { 10594 if (PatternType == 1) 10595 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10596 else 10597 Diag(SL, diag::warn_strncat_src_size) << SR; 10598 return; 10599 } 10600 10601 if (PatternType == 1) 10602 Diag(SL, diag::warn_strncat_large_size) << SR; 10603 else 10604 Diag(SL, diag::warn_strncat_src_size) << SR; 10605 10606 SmallString<128> sizeString; 10607 llvm::raw_svector_ostream OS(sizeString); 10608 OS << "sizeof("; 10609 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10610 OS << ") - "; 10611 OS << "strlen("; 10612 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10613 OS << ") - 1"; 10614 10615 Diag(SL, diag::note_strncat_wrong_size) 10616 << FixItHint::CreateReplacement(SR, OS.str()); 10617 } 10618 10619 namespace { 10620 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10621 const UnaryOperator *UnaryExpr, const Decl *D) { 10622 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10623 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10624 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10625 return; 10626 } 10627 } 10628 10629 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10630 const UnaryOperator *UnaryExpr) { 10631 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10632 const Decl *D = Lvalue->getDecl(); 10633 if (isa<VarDecl, FunctionDecl>(D)) 10634 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10635 } 10636 10637 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10638 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10639 Lvalue->getMemberDecl()); 10640 } 10641 10642 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10643 const UnaryOperator *UnaryExpr) { 10644 const auto *Lambda = dyn_cast<LambdaExpr>( 10645 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10646 if (!Lambda) 10647 return; 10648 10649 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10650 << CalleeName << 2 /*object: lambda expression*/; 10651 } 10652 10653 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10654 const DeclRefExpr *Lvalue) { 10655 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10656 if (Var == nullptr) 10657 return; 10658 10659 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10660 << CalleeName << 0 /*object: */ << Var; 10661 } 10662 10663 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10664 const CastExpr *Cast) { 10665 SmallString<128> SizeString; 10666 llvm::raw_svector_ostream OS(SizeString); 10667 10668 clang::CastKind Kind = Cast->getCastKind(); 10669 if (Kind == clang::CK_BitCast && 10670 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10671 return; 10672 if (Kind == clang::CK_IntegralToPointer && 10673 !isa<IntegerLiteral>( 10674 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10675 return; 10676 10677 switch (Cast->getCastKind()) { 10678 case clang::CK_BitCast: 10679 case clang::CK_IntegralToPointer: 10680 case clang::CK_FunctionToPointerDecay: 10681 OS << '\''; 10682 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10683 OS << '\''; 10684 break; 10685 default: 10686 return; 10687 } 10688 10689 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10690 << CalleeName << 0 /*object: */ << OS.str(); 10691 } 10692 } // namespace 10693 10694 /// Alerts the user that they are attempting to free a non-malloc'd object. 10695 void Sema::CheckFreeArguments(const CallExpr *E) { 10696 const std::string CalleeName = 10697 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10698 10699 { // Prefer something that doesn't involve a cast to make things simpler. 10700 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10701 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10702 switch (UnaryExpr->getOpcode()) { 10703 case UnaryOperator::Opcode::UO_AddrOf: 10704 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10705 case UnaryOperator::Opcode::UO_Plus: 10706 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10707 default: 10708 break; 10709 } 10710 10711 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10712 if (Lvalue->getType()->isArrayType()) 10713 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10714 10715 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10716 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10717 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10718 return; 10719 } 10720 10721 if (isa<BlockExpr>(Arg)) { 10722 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10723 << CalleeName << 1 /*object: block*/; 10724 return; 10725 } 10726 } 10727 // Maybe the cast was important, check after the other cases. 10728 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10729 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10730 } 10731 10732 void 10733 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10734 SourceLocation ReturnLoc, 10735 bool isObjCMethod, 10736 const AttrVec *Attrs, 10737 const FunctionDecl *FD) { 10738 // Check if the return value is null but should not be. 10739 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10740 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10741 CheckNonNullExpr(*this, RetValExp)) 10742 Diag(ReturnLoc, diag::warn_null_ret) 10743 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10744 10745 // C++11 [basic.stc.dynamic.allocation]p4: 10746 // If an allocation function declared with a non-throwing 10747 // exception-specification fails to allocate storage, it shall return 10748 // a null pointer. Any other allocation function that fails to allocate 10749 // storage shall indicate failure only by throwing an exception [...] 10750 if (FD) { 10751 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10752 if (Op == OO_New || Op == OO_Array_New) { 10753 const FunctionProtoType *Proto 10754 = FD->getType()->castAs<FunctionProtoType>(); 10755 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10756 CheckNonNullExpr(*this, RetValExp)) 10757 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10758 << FD << getLangOpts().CPlusPlus11; 10759 } 10760 } 10761 10762 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10763 // here prevent the user from using a PPC MMA type as trailing return type. 10764 if (Context.getTargetInfo().getTriple().isPPC64()) 10765 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10766 } 10767 10768 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10769 10770 /// Check for comparisons of floating point operands using != and ==. 10771 /// Issue a warning if these are no self-comparisons, as they are not likely 10772 /// to do what the programmer intended. 10773 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10774 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10775 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10776 10777 // Special case: check for x == x (which is OK). 10778 // Do not emit warnings for such cases. 10779 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10780 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10781 if (DRL->getDecl() == DRR->getDecl()) 10782 return; 10783 10784 // Special case: check for comparisons against literals that can be exactly 10785 // represented by APFloat. In such cases, do not emit a warning. This 10786 // is a heuristic: often comparison against such literals are used to 10787 // detect if a value in a variable has not changed. This clearly can 10788 // lead to false negatives. 10789 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10790 if (FLL->isExact()) 10791 return; 10792 } else 10793 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10794 if (FLR->isExact()) 10795 return; 10796 10797 // Check for comparisons with builtin types. 10798 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10799 if (CL->getBuiltinCallee()) 10800 return; 10801 10802 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10803 if (CR->getBuiltinCallee()) 10804 return; 10805 10806 // Emit the diagnostic. 10807 Diag(Loc, diag::warn_floatingpoint_eq) 10808 << LHS->getSourceRange() << RHS->getSourceRange(); 10809 } 10810 10811 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10812 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10813 10814 namespace { 10815 10816 /// Structure recording the 'active' range of an integer-valued 10817 /// expression. 10818 struct IntRange { 10819 /// The number of bits active in the int. Note that this includes exactly one 10820 /// sign bit if !NonNegative. 10821 unsigned Width; 10822 10823 /// True if the int is known not to have negative values. If so, all leading 10824 /// bits before Width are known zero, otherwise they are known to be the 10825 /// same as the MSB within Width. 10826 bool NonNegative; 10827 10828 IntRange(unsigned Width, bool NonNegative) 10829 : Width(Width), NonNegative(NonNegative) {} 10830 10831 /// Number of bits excluding the sign bit. 10832 unsigned valueBits() const { 10833 return NonNegative ? Width : Width - 1; 10834 } 10835 10836 /// Returns the range of the bool type. 10837 static IntRange forBoolType() { 10838 return IntRange(1, true); 10839 } 10840 10841 /// Returns the range of an opaque value of the given integral type. 10842 static IntRange forValueOfType(ASTContext &C, QualType T) { 10843 return forValueOfCanonicalType(C, 10844 T->getCanonicalTypeInternal().getTypePtr()); 10845 } 10846 10847 /// Returns the range of an opaque value of a canonical integral type. 10848 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10849 assert(T->isCanonicalUnqualified()); 10850 10851 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10852 T = VT->getElementType().getTypePtr(); 10853 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10854 T = CT->getElementType().getTypePtr(); 10855 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10856 T = AT->getValueType().getTypePtr(); 10857 10858 if (!C.getLangOpts().CPlusPlus) { 10859 // For enum types in C code, use the underlying datatype. 10860 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10861 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10862 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10863 // For enum types in C++, use the known bit width of the enumerators. 10864 EnumDecl *Enum = ET->getDecl(); 10865 // In C++11, enums can have a fixed underlying type. Use this type to 10866 // compute the range. 10867 if (Enum->isFixed()) { 10868 return IntRange(C.getIntWidth(QualType(T, 0)), 10869 !ET->isSignedIntegerOrEnumerationType()); 10870 } 10871 10872 unsigned NumPositive = Enum->getNumPositiveBits(); 10873 unsigned NumNegative = Enum->getNumNegativeBits(); 10874 10875 if (NumNegative == 0) 10876 return IntRange(NumPositive, true/*NonNegative*/); 10877 else 10878 return IntRange(std::max(NumPositive + 1, NumNegative), 10879 false/*NonNegative*/); 10880 } 10881 10882 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10883 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10884 10885 const BuiltinType *BT = cast<BuiltinType>(T); 10886 assert(BT->isInteger()); 10887 10888 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10889 } 10890 10891 /// Returns the "target" range of a canonical integral type, i.e. 10892 /// the range of values expressible in the type. 10893 /// 10894 /// This matches forValueOfCanonicalType except that enums have the 10895 /// full range of their type, not the range of their enumerators. 10896 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10897 assert(T->isCanonicalUnqualified()); 10898 10899 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10900 T = VT->getElementType().getTypePtr(); 10901 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10902 T = CT->getElementType().getTypePtr(); 10903 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10904 T = AT->getValueType().getTypePtr(); 10905 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10906 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10907 10908 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10909 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10910 10911 const BuiltinType *BT = cast<BuiltinType>(T); 10912 assert(BT->isInteger()); 10913 10914 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10915 } 10916 10917 /// Returns the supremum of two ranges: i.e. their conservative merge. 10918 static IntRange join(IntRange L, IntRange R) { 10919 bool Unsigned = L.NonNegative && R.NonNegative; 10920 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10921 L.NonNegative && R.NonNegative); 10922 } 10923 10924 /// Return the range of a bitwise-AND of the two ranges. 10925 static IntRange bit_and(IntRange L, IntRange R) { 10926 unsigned Bits = std::max(L.Width, R.Width); 10927 bool NonNegative = false; 10928 if (L.NonNegative) { 10929 Bits = std::min(Bits, L.Width); 10930 NonNegative = true; 10931 } 10932 if (R.NonNegative) { 10933 Bits = std::min(Bits, R.Width); 10934 NonNegative = true; 10935 } 10936 return IntRange(Bits, NonNegative); 10937 } 10938 10939 /// Return the range of a sum of the two ranges. 10940 static IntRange sum(IntRange L, IntRange R) { 10941 bool Unsigned = L.NonNegative && R.NonNegative; 10942 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10943 Unsigned); 10944 } 10945 10946 /// Return the range of a difference of the two ranges. 10947 static IntRange difference(IntRange L, IntRange R) { 10948 // We need a 1-bit-wider range if: 10949 // 1) LHS can be negative: least value can be reduced. 10950 // 2) RHS can be negative: greatest value can be increased. 10951 bool CanWiden = !L.NonNegative || !R.NonNegative; 10952 bool Unsigned = L.NonNegative && R.Width == 0; 10953 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10954 !Unsigned, 10955 Unsigned); 10956 } 10957 10958 /// Return the range of a product of the two ranges. 10959 static IntRange product(IntRange L, IntRange R) { 10960 // If both LHS and RHS can be negative, we can form 10961 // -2^L * -2^R = 2^(L + R) 10962 // which requires L + R + 1 value bits to represent. 10963 bool CanWiden = !L.NonNegative && !R.NonNegative; 10964 bool Unsigned = L.NonNegative && R.NonNegative; 10965 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10966 Unsigned); 10967 } 10968 10969 /// Return the range of a remainder operation between the two ranges. 10970 static IntRange rem(IntRange L, IntRange R) { 10971 // The result of a remainder can't be larger than the result of 10972 // either side. The sign of the result is the sign of the LHS. 10973 bool Unsigned = L.NonNegative; 10974 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10975 Unsigned); 10976 } 10977 }; 10978 10979 } // namespace 10980 10981 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10982 unsigned MaxWidth) { 10983 if (value.isSigned() && value.isNegative()) 10984 return IntRange(value.getMinSignedBits(), false); 10985 10986 if (value.getBitWidth() > MaxWidth) 10987 value = value.trunc(MaxWidth); 10988 10989 // isNonNegative() just checks the sign bit without considering 10990 // signedness. 10991 return IntRange(value.getActiveBits(), true); 10992 } 10993 10994 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10995 unsigned MaxWidth) { 10996 if (result.isInt()) 10997 return GetValueRange(C, result.getInt(), MaxWidth); 10998 10999 if (result.isVector()) { 11000 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11001 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11002 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11003 R = IntRange::join(R, El); 11004 } 11005 return R; 11006 } 11007 11008 if (result.isComplexInt()) { 11009 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11010 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11011 return IntRange::join(R, I); 11012 } 11013 11014 // This can happen with lossless casts to intptr_t of "based" lvalues. 11015 // Assume it might use arbitrary bits. 11016 // FIXME: The only reason we need to pass the type in here is to get 11017 // the sign right on this one case. It would be nice if APValue 11018 // preserved this. 11019 assert(result.isLValue() || result.isAddrLabelDiff()); 11020 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11021 } 11022 11023 static QualType GetExprType(const Expr *E) { 11024 QualType Ty = E->getType(); 11025 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11026 Ty = AtomicRHS->getValueType(); 11027 return Ty; 11028 } 11029 11030 /// Pseudo-evaluate the given integer expression, estimating the 11031 /// range of values it might take. 11032 /// 11033 /// \param MaxWidth The width to which the value will be truncated. 11034 /// \param Approximate If \c true, return a likely range for the result: in 11035 /// particular, assume that aritmetic on narrower types doesn't leave 11036 /// those types. If \c false, return a range including all possible 11037 /// result values. 11038 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11039 bool InConstantContext, bool Approximate) { 11040 E = E->IgnoreParens(); 11041 11042 // Try a full evaluation first. 11043 Expr::EvalResult result; 11044 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11045 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11046 11047 // I think we only want to look through implicit casts here; if the 11048 // user has an explicit widening cast, we should treat the value as 11049 // being of the new, wider type. 11050 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11051 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11052 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11053 Approximate); 11054 11055 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11056 11057 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11058 CE->getCastKind() == CK_BooleanToSignedIntegral; 11059 11060 // Assume that non-integer casts can span the full range of the type. 11061 if (!isIntegerCast) 11062 return OutputTypeRange; 11063 11064 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11065 std::min(MaxWidth, OutputTypeRange.Width), 11066 InConstantContext, Approximate); 11067 11068 // Bail out if the subexpr's range is as wide as the cast type. 11069 if (SubRange.Width >= OutputTypeRange.Width) 11070 return OutputTypeRange; 11071 11072 // Otherwise, we take the smaller width, and we're non-negative if 11073 // either the output type or the subexpr is. 11074 return IntRange(SubRange.Width, 11075 SubRange.NonNegative || OutputTypeRange.NonNegative); 11076 } 11077 11078 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11079 // If we can fold the condition, just take that operand. 11080 bool CondResult; 11081 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11082 return GetExprRange(C, 11083 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11084 MaxWidth, InConstantContext, Approximate); 11085 11086 // Otherwise, conservatively merge. 11087 // GetExprRange requires an integer expression, but a throw expression 11088 // results in a void type. 11089 Expr *E = CO->getTrueExpr(); 11090 IntRange L = E->getType()->isVoidType() 11091 ? IntRange{0, true} 11092 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11093 E = CO->getFalseExpr(); 11094 IntRange R = E->getType()->isVoidType() 11095 ? IntRange{0, true} 11096 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11097 return IntRange::join(L, R); 11098 } 11099 11100 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11101 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11102 11103 switch (BO->getOpcode()) { 11104 case BO_Cmp: 11105 llvm_unreachable("builtin <=> should have class type"); 11106 11107 // Boolean-valued operations are single-bit and positive. 11108 case BO_LAnd: 11109 case BO_LOr: 11110 case BO_LT: 11111 case BO_GT: 11112 case BO_LE: 11113 case BO_GE: 11114 case BO_EQ: 11115 case BO_NE: 11116 return IntRange::forBoolType(); 11117 11118 // The type of the assignments is the type of the LHS, so the RHS 11119 // is not necessarily the same type. 11120 case BO_MulAssign: 11121 case BO_DivAssign: 11122 case BO_RemAssign: 11123 case BO_AddAssign: 11124 case BO_SubAssign: 11125 case BO_XorAssign: 11126 case BO_OrAssign: 11127 // TODO: bitfields? 11128 return IntRange::forValueOfType(C, GetExprType(E)); 11129 11130 // Simple assignments just pass through the RHS, which will have 11131 // been coerced to the LHS type. 11132 case BO_Assign: 11133 // TODO: bitfields? 11134 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11135 Approximate); 11136 11137 // Operations with opaque sources are black-listed. 11138 case BO_PtrMemD: 11139 case BO_PtrMemI: 11140 return IntRange::forValueOfType(C, GetExprType(E)); 11141 11142 // Bitwise-and uses the *infinum* of the two source ranges. 11143 case BO_And: 11144 case BO_AndAssign: 11145 Combine = IntRange::bit_and; 11146 break; 11147 11148 // Left shift gets black-listed based on a judgement call. 11149 case BO_Shl: 11150 // ...except that we want to treat '1 << (blah)' as logically 11151 // positive. It's an important idiom. 11152 if (IntegerLiteral *I 11153 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11154 if (I->getValue() == 1) { 11155 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11156 return IntRange(R.Width, /*NonNegative*/ true); 11157 } 11158 } 11159 LLVM_FALLTHROUGH; 11160 11161 case BO_ShlAssign: 11162 return IntRange::forValueOfType(C, GetExprType(E)); 11163 11164 // Right shift by a constant can narrow its left argument. 11165 case BO_Shr: 11166 case BO_ShrAssign: { 11167 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11168 Approximate); 11169 11170 // If the shift amount is a positive constant, drop the width by 11171 // that much. 11172 if (Optional<llvm::APSInt> shift = 11173 BO->getRHS()->getIntegerConstantExpr(C)) { 11174 if (shift->isNonNegative()) { 11175 unsigned zext = shift->getZExtValue(); 11176 if (zext >= L.Width) 11177 L.Width = (L.NonNegative ? 0 : 1); 11178 else 11179 L.Width -= zext; 11180 } 11181 } 11182 11183 return L; 11184 } 11185 11186 // Comma acts as its right operand. 11187 case BO_Comma: 11188 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11189 Approximate); 11190 11191 case BO_Add: 11192 if (!Approximate) 11193 Combine = IntRange::sum; 11194 break; 11195 11196 case BO_Sub: 11197 if (BO->getLHS()->getType()->isPointerType()) 11198 return IntRange::forValueOfType(C, GetExprType(E)); 11199 if (!Approximate) 11200 Combine = IntRange::difference; 11201 break; 11202 11203 case BO_Mul: 11204 if (!Approximate) 11205 Combine = IntRange::product; 11206 break; 11207 11208 // The width of a division result is mostly determined by the size 11209 // of the LHS. 11210 case BO_Div: { 11211 // Don't 'pre-truncate' the operands. 11212 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11213 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11214 Approximate); 11215 11216 // If the divisor is constant, use that. 11217 if (Optional<llvm::APSInt> divisor = 11218 BO->getRHS()->getIntegerConstantExpr(C)) { 11219 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11220 if (log2 >= L.Width) 11221 L.Width = (L.NonNegative ? 0 : 1); 11222 else 11223 L.Width = std::min(L.Width - log2, MaxWidth); 11224 return L; 11225 } 11226 11227 // Otherwise, just use the LHS's width. 11228 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11229 // could be -1. 11230 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11231 Approximate); 11232 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11233 } 11234 11235 case BO_Rem: 11236 Combine = IntRange::rem; 11237 break; 11238 11239 // The default behavior is okay for these. 11240 case BO_Xor: 11241 case BO_Or: 11242 break; 11243 } 11244 11245 // Combine the two ranges, but limit the result to the type in which we 11246 // performed the computation. 11247 QualType T = GetExprType(E); 11248 unsigned opWidth = C.getIntWidth(T); 11249 IntRange L = 11250 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11251 IntRange R = 11252 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11253 IntRange C = Combine(L, R); 11254 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11255 C.Width = std::min(C.Width, MaxWidth); 11256 return C; 11257 } 11258 11259 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11260 switch (UO->getOpcode()) { 11261 // Boolean-valued operations are white-listed. 11262 case UO_LNot: 11263 return IntRange::forBoolType(); 11264 11265 // Operations with opaque sources are black-listed. 11266 case UO_Deref: 11267 case UO_AddrOf: // should be impossible 11268 return IntRange::forValueOfType(C, GetExprType(E)); 11269 11270 default: 11271 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11272 Approximate); 11273 } 11274 } 11275 11276 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11277 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11278 Approximate); 11279 11280 if (const auto *BitField = E->getSourceBitField()) 11281 return IntRange(BitField->getBitWidthValue(C), 11282 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11283 11284 return IntRange::forValueOfType(C, GetExprType(E)); 11285 } 11286 11287 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11288 bool InConstantContext, bool Approximate) { 11289 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11290 Approximate); 11291 } 11292 11293 /// Checks whether the given value, which currently has the given 11294 /// source semantics, has the same value when coerced through the 11295 /// target semantics. 11296 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11297 const llvm::fltSemantics &Src, 11298 const llvm::fltSemantics &Tgt) { 11299 llvm::APFloat truncated = value; 11300 11301 bool ignored; 11302 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11303 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11304 11305 return truncated.bitwiseIsEqual(value); 11306 } 11307 11308 /// Checks whether the given value, which currently has the given 11309 /// source semantics, has the same value when coerced through the 11310 /// target semantics. 11311 /// 11312 /// The value might be a vector of floats (or a complex number). 11313 static bool IsSameFloatAfterCast(const APValue &value, 11314 const llvm::fltSemantics &Src, 11315 const llvm::fltSemantics &Tgt) { 11316 if (value.isFloat()) 11317 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11318 11319 if (value.isVector()) { 11320 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11321 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11322 return false; 11323 return true; 11324 } 11325 11326 assert(value.isComplexFloat()); 11327 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11328 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11329 } 11330 11331 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11332 bool IsListInit = false); 11333 11334 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11335 // Suppress cases where we are comparing against an enum constant. 11336 if (const DeclRefExpr *DR = 11337 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11338 if (isa<EnumConstantDecl>(DR->getDecl())) 11339 return true; 11340 11341 // Suppress cases where the value is expanded from a macro, unless that macro 11342 // is how a language represents a boolean literal. This is the case in both C 11343 // and Objective-C. 11344 SourceLocation BeginLoc = E->getBeginLoc(); 11345 if (BeginLoc.isMacroID()) { 11346 StringRef MacroName = Lexer::getImmediateMacroName( 11347 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11348 return MacroName != "YES" && MacroName != "NO" && 11349 MacroName != "true" && MacroName != "false"; 11350 } 11351 11352 return false; 11353 } 11354 11355 static bool isKnownToHaveUnsignedValue(Expr *E) { 11356 return E->getType()->isIntegerType() && 11357 (!E->getType()->isSignedIntegerType() || 11358 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11359 } 11360 11361 namespace { 11362 /// The promoted range of values of a type. In general this has the 11363 /// following structure: 11364 /// 11365 /// |-----------| . . . |-----------| 11366 /// ^ ^ ^ ^ 11367 /// Min HoleMin HoleMax Max 11368 /// 11369 /// ... where there is only a hole if a signed type is promoted to unsigned 11370 /// (in which case Min and Max are the smallest and largest representable 11371 /// values). 11372 struct PromotedRange { 11373 // Min, or HoleMax if there is a hole. 11374 llvm::APSInt PromotedMin; 11375 // Max, or HoleMin if there is a hole. 11376 llvm::APSInt PromotedMax; 11377 11378 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11379 if (R.Width == 0) 11380 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11381 else if (R.Width >= BitWidth && !Unsigned) { 11382 // Promotion made the type *narrower*. This happens when promoting 11383 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11384 // Treat all values of 'signed int' as being in range for now. 11385 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11386 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11387 } else { 11388 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11389 .extOrTrunc(BitWidth); 11390 PromotedMin.setIsUnsigned(Unsigned); 11391 11392 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11393 .extOrTrunc(BitWidth); 11394 PromotedMax.setIsUnsigned(Unsigned); 11395 } 11396 } 11397 11398 // Determine whether this range is contiguous (has no hole). 11399 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11400 11401 // Where a constant value is within the range. 11402 enum ComparisonResult { 11403 LT = 0x1, 11404 LE = 0x2, 11405 GT = 0x4, 11406 GE = 0x8, 11407 EQ = 0x10, 11408 NE = 0x20, 11409 InRangeFlag = 0x40, 11410 11411 Less = LE | LT | NE, 11412 Min = LE | InRangeFlag, 11413 InRange = InRangeFlag, 11414 Max = GE | InRangeFlag, 11415 Greater = GE | GT | NE, 11416 11417 OnlyValue = LE | GE | EQ | InRangeFlag, 11418 InHole = NE 11419 }; 11420 11421 ComparisonResult compare(const llvm::APSInt &Value) const { 11422 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11423 Value.isUnsigned() == PromotedMin.isUnsigned()); 11424 if (!isContiguous()) { 11425 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11426 if (Value.isMinValue()) return Min; 11427 if (Value.isMaxValue()) return Max; 11428 if (Value >= PromotedMin) return InRange; 11429 if (Value <= PromotedMax) return InRange; 11430 return InHole; 11431 } 11432 11433 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11434 case -1: return Less; 11435 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11436 case 1: 11437 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11438 case -1: return InRange; 11439 case 0: return Max; 11440 case 1: return Greater; 11441 } 11442 } 11443 11444 llvm_unreachable("impossible compare result"); 11445 } 11446 11447 static llvm::Optional<StringRef> 11448 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11449 if (Op == BO_Cmp) { 11450 ComparisonResult LTFlag = LT, GTFlag = GT; 11451 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11452 11453 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11454 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11455 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11456 return llvm::None; 11457 } 11458 11459 ComparisonResult TrueFlag, FalseFlag; 11460 if (Op == BO_EQ) { 11461 TrueFlag = EQ; 11462 FalseFlag = NE; 11463 } else if (Op == BO_NE) { 11464 TrueFlag = NE; 11465 FalseFlag = EQ; 11466 } else { 11467 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11468 TrueFlag = LT; 11469 FalseFlag = GE; 11470 } else { 11471 TrueFlag = GT; 11472 FalseFlag = LE; 11473 } 11474 if (Op == BO_GE || Op == BO_LE) 11475 std::swap(TrueFlag, FalseFlag); 11476 } 11477 if (R & TrueFlag) 11478 return StringRef("true"); 11479 if (R & FalseFlag) 11480 return StringRef("false"); 11481 return llvm::None; 11482 } 11483 }; 11484 } 11485 11486 static bool HasEnumType(Expr *E) { 11487 // Strip off implicit integral promotions. 11488 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11489 if (ICE->getCastKind() != CK_IntegralCast && 11490 ICE->getCastKind() != CK_NoOp) 11491 break; 11492 E = ICE->getSubExpr(); 11493 } 11494 11495 return E->getType()->isEnumeralType(); 11496 } 11497 11498 static int classifyConstantValue(Expr *Constant) { 11499 // The values of this enumeration are used in the diagnostics 11500 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11501 enum ConstantValueKind { 11502 Miscellaneous = 0, 11503 LiteralTrue, 11504 LiteralFalse 11505 }; 11506 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11507 return BL->getValue() ? ConstantValueKind::LiteralTrue 11508 : ConstantValueKind::LiteralFalse; 11509 return ConstantValueKind::Miscellaneous; 11510 } 11511 11512 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11513 Expr *Constant, Expr *Other, 11514 const llvm::APSInt &Value, 11515 bool RhsConstant) { 11516 if (S.inTemplateInstantiation()) 11517 return false; 11518 11519 Expr *OriginalOther = Other; 11520 11521 Constant = Constant->IgnoreParenImpCasts(); 11522 Other = Other->IgnoreParenImpCasts(); 11523 11524 // Suppress warnings on tautological comparisons between values of the same 11525 // enumeration type. There are only two ways we could warn on this: 11526 // - If the constant is outside the range of representable values of 11527 // the enumeration. In such a case, we should warn about the cast 11528 // to enumeration type, not about the comparison. 11529 // - If the constant is the maximum / minimum in-range value. For an 11530 // enumeratin type, such comparisons can be meaningful and useful. 11531 if (Constant->getType()->isEnumeralType() && 11532 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11533 return false; 11534 11535 IntRange OtherValueRange = GetExprRange( 11536 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11537 11538 QualType OtherT = Other->getType(); 11539 if (const auto *AT = OtherT->getAs<AtomicType>()) 11540 OtherT = AT->getValueType(); 11541 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11542 11543 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11544 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11545 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11546 S.NSAPIObj->isObjCBOOLType(OtherT) && 11547 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11548 11549 // Whether we're treating Other as being a bool because of the form of 11550 // expression despite it having another type (typically 'int' in C). 11551 bool OtherIsBooleanDespiteType = 11552 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11553 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11554 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11555 11556 // Check if all values in the range of possible values of this expression 11557 // lead to the same comparison outcome. 11558 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11559 Value.isUnsigned()); 11560 auto Cmp = OtherPromotedValueRange.compare(Value); 11561 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11562 if (!Result) 11563 return false; 11564 11565 // Also consider the range determined by the type alone. This allows us to 11566 // classify the warning under the proper diagnostic group. 11567 bool TautologicalTypeCompare = false; 11568 { 11569 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11570 Value.isUnsigned()); 11571 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11572 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11573 RhsConstant)) { 11574 TautologicalTypeCompare = true; 11575 Cmp = TypeCmp; 11576 Result = TypeResult; 11577 } 11578 } 11579 11580 // Don't warn if the non-constant operand actually always evaluates to the 11581 // same value. 11582 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11583 return false; 11584 11585 // Suppress the diagnostic for an in-range comparison if the constant comes 11586 // from a macro or enumerator. We don't want to diagnose 11587 // 11588 // some_long_value <= INT_MAX 11589 // 11590 // when sizeof(int) == sizeof(long). 11591 bool InRange = Cmp & PromotedRange::InRangeFlag; 11592 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11593 return false; 11594 11595 // A comparison of an unsigned bit-field against 0 is really a type problem, 11596 // even though at the type level the bit-field might promote to 'signed int'. 11597 if (Other->refersToBitField() && InRange && Value == 0 && 11598 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11599 TautologicalTypeCompare = true; 11600 11601 // If this is a comparison to an enum constant, include that 11602 // constant in the diagnostic. 11603 const EnumConstantDecl *ED = nullptr; 11604 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11605 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11606 11607 // Should be enough for uint128 (39 decimal digits) 11608 SmallString<64> PrettySourceValue; 11609 llvm::raw_svector_ostream OS(PrettySourceValue); 11610 if (ED) { 11611 OS << '\'' << *ED << "' (" << Value << ")"; 11612 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11613 Constant->IgnoreParenImpCasts())) { 11614 OS << (BL->getValue() ? "YES" : "NO"); 11615 } else { 11616 OS << Value; 11617 } 11618 11619 if (!TautologicalTypeCompare) { 11620 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11621 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11622 << E->getOpcodeStr() << OS.str() << *Result 11623 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11624 return true; 11625 } 11626 11627 if (IsObjCSignedCharBool) { 11628 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11629 S.PDiag(diag::warn_tautological_compare_objc_bool) 11630 << OS.str() << *Result); 11631 return true; 11632 } 11633 11634 // FIXME: We use a somewhat different formatting for the in-range cases and 11635 // cases involving boolean values for historical reasons. We should pick a 11636 // consistent way of presenting these diagnostics. 11637 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11638 11639 S.DiagRuntimeBehavior( 11640 E->getOperatorLoc(), E, 11641 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11642 : diag::warn_tautological_bool_compare) 11643 << OS.str() << classifyConstantValue(Constant) << OtherT 11644 << OtherIsBooleanDespiteType << *Result 11645 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11646 } else { 11647 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11648 unsigned Diag = 11649 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11650 ? (HasEnumType(OriginalOther) 11651 ? diag::warn_unsigned_enum_always_true_comparison 11652 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11653 : diag::warn_unsigned_always_true_comparison) 11654 : diag::warn_tautological_constant_compare; 11655 11656 S.Diag(E->getOperatorLoc(), Diag) 11657 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11658 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11659 } 11660 11661 return true; 11662 } 11663 11664 /// Analyze the operands of the given comparison. Implements the 11665 /// fallback case from AnalyzeComparison. 11666 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11667 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11668 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11669 } 11670 11671 /// Implements -Wsign-compare. 11672 /// 11673 /// \param E the binary operator to check for warnings 11674 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11675 // The type the comparison is being performed in. 11676 QualType T = E->getLHS()->getType(); 11677 11678 // Only analyze comparison operators where both sides have been converted to 11679 // the same type. 11680 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11681 return AnalyzeImpConvsInComparison(S, E); 11682 11683 // Don't analyze value-dependent comparisons directly. 11684 if (E->isValueDependent()) 11685 return AnalyzeImpConvsInComparison(S, E); 11686 11687 Expr *LHS = E->getLHS(); 11688 Expr *RHS = E->getRHS(); 11689 11690 if (T->isIntegralType(S.Context)) { 11691 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11692 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11693 11694 // We don't care about expressions whose result is a constant. 11695 if (RHSValue && LHSValue) 11696 return AnalyzeImpConvsInComparison(S, E); 11697 11698 // We only care about expressions where just one side is literal 11699 if ((bool)RHSValue ^ (bool)LHSValue) { 11700 // Is the constant on the RHS or LHS? 11701 const bool RhsConstant = (bool)RHSValue; 11702 Expr *Const = RhsConstant ? RHS : LHS; 11703 Expr *Other = RhsConstant ? LHS : RHS; 11704 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11705 11706 // Check whether an integer constant comparison results in a value 11707 // of 'true' or 'false'. 11708 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11709 return AnalyzeImpConvsInComparison(S, E); 11710 } 11711 } 11712 11713 if (!T->hasUnsignedIntegerRepresentation()) { 11714 // We don't do anything special if this isn't an unsigned integral 11715 // comparison: we're only interested in integral comparisons, and 11716 // signed comparisons only happen in cases we don't care to warn about. 11717 return AnalyzeImpConvsInComparison(S, E); 11718 } 11719 11720 LHS = LHS->IgnoreParenImpCasts(); 11721 RHS = RHS->IgnoreParenImpCasts(); 11722 11723 if (!S.getLangOpts().CPlusPlus) { 11724 // Avoid warning about comparison of integers with different signs when 11725 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11726 // the type of `E`. 11727 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11728 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11729 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11730 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11731 } 11732 11733 // Check to see if one of the (unmodified) operands is of different 11734 // signedness. 11735 Expr *signedOperand, *unsignedOperand; 11736 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11737 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11738 "unsigned comparison between two signed integer expressions?"); 11739 signedOperand = LHS; 11740 unsignedOperand = RHS; 11741 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11742 signedOperand = RHS; 11743 unsignedOperand = LHS; 11744 } else { 11745 return AnalyzeImpConvsInComparison(S, E); 11746 } 11747 11748 // Otherwise, calculate the effective range of the signed operand. 11749 IntRange signedRange = GetExprRange( 11750 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11751 11752 // Go ahead and analyze implicit conversions in the operands. Note 11753 // that we skip the implicit conversions on both sides. 11754 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11755 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11756 11757 // If the signed range is non-negative, -Wsign-compare won't fire. 11758 if (signedRange.NonNegative) 11759 return; 11760 11761 // For (in)equality comparisons, if the unsigned operand is a 11762 // constant which cannot collide with a overflowed signed operand, 11763 // then reinterpreting the signed operand as unsigned will not 11764 // change the result of the comparison. 11765 if (E->isEqualityOp()) { 11766 unsigned comparisonWidth = S.Context.getIntWidth(T); 11767 IntRange unsignedRange = 11768 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11769 /*Approximate*/ true); 11770 11771 // We should never be unable to prove that the unsigned operand is 11772 // non-negative. 11773 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11774 11775 if (unsignedRange.Width < comparisonWidth) 11776 return; 11777 } 11778 11779 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11780 S.PDiag(diag::warn_mixed_sign_comparison) 11781 << LHS->getType() << RHS->getType() 11782 << LHS->getSourceRange() << RHS->getSourceRange()); 11783 } 11784 11785 /// Analyzes an attempt to assign the given value to a bitfield. 11786 /// 11787 /// Returns true if there was something fishy about the attempt. 11788 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11789 SourceLocation InitLoc) { 11790 assert(Bitfield->isBitField()); 11791 if (Bitfield->isInvalidDecl()) 11792 return false; 11793 11794 // White-list bool bitfields. 11795 QualType BitfieldType = Bitfield->getType(); 11796 if (BitfieldType->isBooleanType()) 11797 return false; 11798 11799 if (BitfieldType->isEnumeralType()) { 11800 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11801 // If the underlying enum type was not explicitly specified as an unsigned 11802 // type and the enum contain only positive values, MSVC++ will cause an 11803 // inconsistency by storing this as a signed type. 11804 if (S.getLangOpts().CPlusPlus11 && 11805 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11806 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11807 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11808 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11809 << BitfieldEnumDecl; 11810 } 11811 } 11812 11813 if (Bitfield->getType()->isBooleanType()) 11814 return false; 11815 11816 // Ignore value- or type-dependent expressions. 11817 if (Bitfield->getBitWidth()->isValueDependent() || 11818 Bitfield->getBitWidth()->isTypeDependent() || 11819 Init->isValueDependent() || 11820 Init->isTypeDependent()) 11821 return false; 11822 11823 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11824 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11825 11826 Expr::EvalResult Result; 11827 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11828 Expr::SE_AllowSideEffects)) { 11829 // The RHS is not constant. If the RHS has an enum type, make sure the 11830 // bitfield is wide enough to hold all the values of the enum without 11831 // truncation. 11832 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11833 EnumDecl *ED = EnumTy->getDecl(); 11834 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11835 11836 // Enum types are implicitly signed on Windows, so check if there are any 11837 // negative enumerators to see if the enum was intended to be signed or 11838 // not. 11839 bool SignedEnum = ED->getNumNegativeBits() > 0; 11840 11841 // Check for surprising sign changes when assigning enum values to a 11842 // bitfield of different signedness. If the bitfield is signed and we 11843 // have exactly the right number of bits to store this unsigned enum, 11844 // suggest changing the enum to an unsigned type. This typically happens 11845 // on Windows where unfixed enums always use an underlying type of 'int'. 11846 unsigned DiagID = 0; 11847 if (SignedEnum && !SignedBitfield) { 11848 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11849 } else if (SignedBitfield && !SignedEnum && 11850 ED->getNumPositiveBits() == FieldWidth) { 11851 DiagID = diag::warn_signed_bitfield_enum_conversion; 11852 } 11853 11854 if (DiagID) { 11855 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11856 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11857 SourceRange TypeRange = 11858 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11859 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11860 << SignedEnum << TypeRange; 11861 } 11862 11863 // Compute the required bitwidth. If the enum has negative values, we need 11864 // one more bit than the normal number of positive bits to represent the 11865 // sign bit. 11866 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11867 ED->getNumNegativeBits()) 11868 : ED->getNumPositiveBits(); 11869 11870 // Check the bitwidth. 11871 if (BitsNeeded > FieldWidth) { 11872 Expr *WidthExpr = Bitfield->getBitWidth(); 11873 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11874 << Bitfield << ED; 11875 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11876 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11877 } 11878 } 11879 11880 return false; 11881 } 11882 11883 llvm::APSInt Value = Result.Val.getInt(); 11884 11885 unsigned OriginalWidth = Value.getBitWidth(); 11886 11887 if (!Value.isSigned() || Value.isNegative()) 11888 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11889 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11890 OriginalWidth = Value.getMinSignedBits(); 11891 11892 if (OriginalWidth <= FieldWidth) 11893 return false; 11894 11895 // Compute the value which the bitfield will contain. 11896 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11897 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11898 11899 // Check whether the stored value is equal to the original value. 11900 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11901 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11902 return false; 11903 11904 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11905 // therefore don't strictly fit into a signed bitfield of width 1. 11906 if (FieldWidth == 1 && Value == 1) 11907 return false; 11908 11909 std::string PrettyValue = toString(Value, 10); 11910 std::string PrettyTrunc = toString(TruncatedValue, 10); 11911 11912 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11913 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11914 << Init->getSourceRange(); 11915 11916 return true; 11917 } 11918 11919 /// Analyze the given simple or compound assignment for warning-worthy 11920 /// operations. 11921 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11922 // Just recurse on the LHS. 11923 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11924 11925 // We want to recurse on the RHS as normal unless we're assigning to 11926 // a bitfield. 11927 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11928 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11929 E->getOperatorLoc())) { 11930 // Recurse, ignoring any implicit conversions on the RHS. 11931 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11932 E->getOperatorLoc()); 11933 } 11934 } 11935 11936 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11937 11938 // Diagnose implicitly sequentially-consistent atomic assignment. 11939 if (E->getLHS()->getType()->isAtomicType()) 11940 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11941 } 11942 11943 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11944 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11945 SourceLocation CContext, unsigned diag, 11946 bool pruneControlFlow = false) { 11947 if (pruneControlFlow) { 11948 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11949 S.PDiag(diag) 11950 << SourceType << T << E->getSourceRange() 11951 << SourceRange(CContext)); 11952 return; 11953 } 11954 S.Diag(E->getExprLoc(), diag) 11955 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11956 } 11957 11958 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11959 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11960 SourceLocation CContext, 11961 unsigned diag, bool pruneControlFlow = false) { 11962 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11963 } 11964 11965 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11966 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11967 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11968 } 11969 11970 static void adornObjCBoolConversionDiagWithTernaryFixit( 11971 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11972 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11973 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11974 Ignored = OVE->getSourceExpr(); 11975 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11976 isa<BinaryOperator>(Ignored) || 11977 isa<CXXOperatorCallExpr>(Ignored); 11978 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11979 if (NeedsParens) 11980 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11981 << FixItHint::CreateInsertion(EndLoc, ")"); 11982 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11983 } 11984 11985 /// Diagnose an implicit cast from a floating point value to an integer value. 11986 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11987 SourceLocation CContext) { 11988 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11989 const bool PruneWarnings = S.inTemplateInstantiation(); 11990 11991 Expr *InnerE = E->IgnoreParenImpCasts(); 11992 // We also want to warn on, e.g., "int i = -1.234" 11993 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11994 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11995 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11996 11997 const bool IsLiteral = 11998 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11999 12000 llvm::APFloat Value(0.0); 12001 bool IsConstant = 12002 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12003 if (!IsConstant) { 12004 if (isObjCSignedCharBool(S, T)) { 12005 return adornObjCBoolConversionDiagWithTernaryFixit( 12006 S, E, 12007 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12008 << E->getType()); 12009 } 12010 12011 return DiagnoseImpCast(S, E, T, CContext, 12012 diag::warn_impcast_float_integer, PruneWarnings); 12013 } 12014 12015 bool isExact = false; 12016 12017 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12018 T->hasUnsignedIntegerRepresentation()); 12019 llvm::APFloat::opStatus Result = Value.convertToInteger( 12020 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12021 12022 // FIXME: Force the precision of the source value down so we don't print 12023 // digits which are usually useless (we don't really care here if we 12024 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12025 // would automatically print the shortest representation, but it's a bit 12026 // tricky to implement. 12027 SmallString<16> PrettySourceValue; 12028 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12029 precision = (precision * 59 + 195) / 196; 12030 Value.toString(PrettySourceValue, precision); 12031 12032 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12033 return adornObjCBoolConversionDiagWithTernaryFixit( 12034 S, E, 12035 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12036 << PrettySourceValue); 12037 } 12038 12039 if (Result == llvm::APFloat::opOK && isExact) { 12040 if (IsLiteral) return; 12041 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12042 PruneWarnings); 12043 } 12044 12045 // Conversion of a floating-point value to a non-bool integer where the 12046 // integral part cannot be represented by the integer type is undefined. 12047 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12048 return DiagnoseImpCast( 12049 S, E, T, CContext, 12050 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12051 : diag::warn_impcast_float_to_integer_out_of_range, 12052 PruneWarnings); 12053 12054 unsigned DiagID = 0; 12055 if (IsLiteral) { 12056 // Warn on floating point literal to integer. 12057 DiagID = diag::warn_impcast_literal_float_to_integer; 12058 } else if (IntegerValue == 0) { 12059 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12060 return DiagnoseImpCast(S, E, T, CContext, 12061 diag::warn_impcast_float_integer, PruneWarnings); 12062 } 12063 // Warn on non-zero to zero conversion. 12064 DiagID = diag::warn_impcast_float_to_integer_zero; 12065 } else { 12066 if (IntegerValue.isUnsigned()) { 12067 if (!IntegerValue.isMaxValue()) { 12068 return DiagnoseImpCast(S, E, T, CContext, 12069 diag::warn_impcast_float_integer, PruneWarnings); 12070 } 12071 } else { // IntegerValue.isSigned() 12072 if (!IntegerValue.isMaxSignedValue() && 12073 !IntegerValue.isMinSignedValue()) { 12074 return DiagnoseImpCast(S, E, T, CContext, 12075 diag::warn_impcast_float_integer, PruneWarnings); 12076 } 12077 } 12078 // Warn on evaluatable floating point expression to integer conversion. 12079 DiagID = diag::warn_impcast_float_to_integer; 12080 } 12081 12082 SmallString<16> PrettyTargetValue; 12083 if (IsBool) 12084 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12085 else 12086 IntegerValue.toString(PrettyTargetValue); 12087 12088 if (PruneWarnings) { 12089 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12090 S.PDiag(DiagID) 12091 << E->getType() << T.getUnqualifiedType() 12092 << PrettySourceValue << PrettyTargetValue 12093 << E->getSourceRange() << SourceRange(CContext)); 12094 } else { 12095 S.Diag(E->getExprLoc(), DiagID) 12096 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12097 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12098 } 12099 } 12100 12101 /// Analyze the given compound assignment for the possible losing of 12102 /// floating-point precision. 12103 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12104 assert(isa<CompoundAssignOperator>(E) && 12105 "Must be compound assignment operation"); 12106 // Recurse on the LHS and RHS in here 12107 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12108 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12109 12110 if (E->getLHS()->getType()->isAtomicType()) 12111 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12112 12113 // Now check the outermost expression 12114 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12115 const auto *RBT = cast<CompoundAssignOperator>(E) 12116 ->getComputationResultType() 12117 ->getAs<BuiltinType>(); 12118 12119 // The below checks assume source is floating point. 12120 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12121 12122 // If source is floating point but target is an integer. 12123 if (ResultBT->isInteger()) 12124 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12125 E->getExprLoc(), diag::warn_impcast_float_integer); 12126 12127 if (!ResultBT->isFloatingPoint()) 12128 return; 12129 12130 // If both source and target are floating points, warn about losing precision. 12131 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12132 QualType(ResultBT, 0), QualType(RBT, 0)); 12133 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12134 // warn about dropping FP rank. 12135 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12136 diag::warn_impcast_float_result_precision); 12137 } 12138 12139 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12140 IntRange Range) { 12141 if (!Range.Width) return "0"; 12142 12143 llvm::APSInt ValueInRange = Value; 12144 ValueInRange.setIsSigned(!Range.NonNegative); 12145 ValueInRange = ValueInRange.trunc(Range.Width); 12146 return toString(ValueInRange, 10); 12147 } 12148 12149 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12150 if (!isa<ImplicitCastExpr>(Ex)) 12151 return false; 12152 12153 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12154 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12155 const Type *Source = 12156 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12157 if (Target->isDependentType()) 12158 return false; 12159 12160 const BuiltinType *FloatCandidateBT = 12161 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12162 const Type *BoolCandidateType = ToBool ? Target : Source; 12163 12164 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12165 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12166 } 12167 12168 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12169 SourceLocation CC) { 12170 unsigned NumArgs = TheCall->getNumArgs(); 12171 for (unsigned i = 0; i < NumArgs; ++i) { 12172 Expr *CurrA = TheCall->getArg(i); 12173 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12174 continue; 12175 12176 bool IsSwapped = ((i > 0) && 12177 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12178 IsSwapped |= ((i < (NumArgs - 1)) && 12179 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12180 if (IsSwapped) { 12181 // Warn on this floating-point to bool conversion. 12182 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12183 CurrA->getType(), CC, 12184 diag::warn_impcast_floating_point_to_bool); 12185 } 12186 } 12187 } 12188 12189 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12190 SourceLocation CC) { 12191 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12192 E->getExprLoc())) 12193 return; 12194 12195 // Don't warn on functions which have return type nullptr_t. 12196 if (isa<CallExpr>(E)) 12197 return; 12198 12199 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12200 const Expr::NullPointerConstantKind NullKind = 12201 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12202 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12203 return; 12204 12205 // Return if target type is a safe conversion. 12206 if (T->isAnyPointerType() || T->isBlockPointerType() || 12207 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12208 return; 12209 12210 SourceLocation Loc = E->getSourceRange().getBegin(); 12211 12212 // Venture through the macro stacks to get to the source of macro arguments. 12213 // The new location is a better location than the complete location that was 12214 // passed in. 12215 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12216 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12217 12218 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12219 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12220 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12221 Loc, S.SourceMgr, S.getLangOpts()); 12222 if (MacroName == "NULL") 12223 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12224 } 12225 12226 // Only warn if the null and context location are in the same macro expansion. 12227 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12228 return; 12229 12230 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12231 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12232 << FixItHint::CreateReplacement(Loc, 12233 S.getFixItZeroLiteralForType(T, Loc)); 12234 } 12235 12236 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12237 ObjCArrayLiteral *ArrayLiteral); 12238 12239 static void 12240 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12241 ObjCDictionaryLiteral *DictionaryLiteral); 12242 12243 /// Check a single element within a collection literal against the 12244 /// target element type. 12245 static void checkObjCCollectionLiteralElement(Sema &S, 12246 QualType TargetElementType, 12247 Expr *Element, 12248 unsigned ElementKind) { 12249 // Skip a bitcast to 'id' or qualified 'id'. 12250 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12251 if (ICE->getCastKind() == CK_BitCast && 12252 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12253 Element = ICE->getSubExpr(); 12254 } 12255 12256 QualType ElementType = Element->getType(); 12257 ExprResult ElementResult(Element); 12258 if (ElementType->getAs<ObjCObjectPointerType>() && 12259 S.CheckSingleAssignmentConstraints(TargetElementType, 12260 ElementResult, 12261 false, false) 12262 != Sema::Compatible) { 12263 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12264 << ElementType << ElementKind << TargetElementType 12265 << Element->getSourceRange(); 12266 } 12267 12268 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12269 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12270 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12271 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12272 } 12273 12274 /// Check an Objective-C array literal being converted to the given 12275 /// target type. 12276 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12277 ObjCArrayLiteral *ArrayLiteral) { 12278 if (!S.NSArrayDecl) 12279 return; 12280 12281 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12282 if (!TargetObjCPtr) 12283 return; 12284 12285 if (TargetObjCPtr->isUnspecialized() || 12286 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12287 != S.NSArrayDecl->getCanonicalDecl()) 12288 return; 12289 12290 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12291 if (TypeArgs.size() != 1) 12292 return; 12293 12294 QualType TargetElementType = TypeArgs[0]; 12295 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12296 checkObjCCollectionLiteralElement(S, TargetElementType, 12297 ArrayLiteral->getElement(I), 12298 0); 12299 } 12300 } 12301 12302 /// Check an Objective-C dictionary literal being converted to the given 12303 /// target type. 12304 static void 12305 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12306 ObjCDictionaryLiteral *DictionaryLiteral) { 12307 if (!S.NSDictionaryDecl) 12308 return; 12309 12310 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12311 if (!TargetObjCPtr) 12312 return; 12313 12314 if (TargetObjCPtr->isUnspecialized() || 12315 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12316 != S.NSDictionaryDecl->getCanonicalDecl()) 12317 return; 12318 12319 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12320 if (TypeArgs.size() != 2) 12321 return; 12322 12323 QualType TargetKeyType = TypeArgs[0]; 12324 QualType TargetObjectType = TypeArgs[1]; 12325 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12326 auto Element = DictionaryLiteral->getKeyValueElement(I); 12327 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12328 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12329 } 12330 } 12331 12332 // Helper function to filter out cases for constant width constant conversion. 12333 // Don't warn on char array initialization or for non-decimal values. 12334 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12335 SourceLocation CC) { 12336 // If initializing from a constant, and the constant starts with '0', 12337 // then it is a binary, octal, or hexadecimal. Allow these constants 12338 // to fill all the bits, even if there is a sign change. 12339 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12340 const char FirstLiteralCharacter = 12341 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12342 if (FirstLiteralCharacter == '0') 12343 return false; 12344 } 12345 12346 // If the CC location points to a '{', and the type is char, then assume 12347 // assume it is an array initialization. 12348 if (CC.isValid() && T->isCharType()) { 12349 const char FirstContextCharacter = 12350 S.getSourceManager().getCharacterData(CC)[0]; 12351 if (FirstContextCharacter == '{') 12352 return false; 12353 } 12354 12355 return true; 12356 } 12357 12358 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12359 const auto *IL = dyn_cast<IntegerLiteral>(E); 12360 if (!IL) { 12361 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12362 if (UO->getOpcode() == UO_Minus) 12363 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12364 } 12365 } 12366 12367 return IL; 12368 } 12369 12370 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12371 E = E->IgnoreParenImpCasts(); 12372 SourceLocation ExprLoc = E->getExprLoc(); 12373 12374 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12375 BinaryOperator::Opcode Opc = BO->getOpcode(); 12376 Expr::EvalResult Result; 12377 // Do not diagnose unsigned shifts. 12378 if (Opc == BO_Shl) { 12379 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12380 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12381 if (LHS && LHS->getValue() == 0) 12382 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12383 else if (!E->isValueDependent() && LHS && RHS && 12384 RHS->getValue().isNonNegative() && 12385 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12386 S.Diag(ExprLoc, diag::warn_left_shift_always) 12387 << (Result.Val.getInt() != 0); 12388 else if (E->getType()->isSignedIntegerType()) 12389 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12390 } 12391 } 12392 12393 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12394 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12395 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12396 if (!LHS || !RHS) 12397 return; 12398 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12399 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12400 // Do not diagnose common idioms. 12401 return; 12402 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12403 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12404 } 12405 } 12406 12407 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12408 SourceLocation CC, 12409 bool *ICContext = nullptr, 12410 bool IsListInit = false) { 12411 if (E->isTypeDependent() || E->isValueDependent()) return; 12412 12413 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12414 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12415 if (Source == Target) return; 12416 if (Target->isDependentType()) return; 12417 12418 // If the conversion context location is invalid don't complain. We also 12419 // don't want to emit a warning if the issue occurs from the expansion of 12420 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12421 // delay this check as long as possible. Once we detect we are in that 12422 // scenario, we just return. 12423 if (CC.isInvalid()) 12424 return; 12425 12426 if (Source->isAtomicType()) 12427 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12428 12429 // Diagnose implicit casts to bool. 12430 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12431 if (isa<StringLiteral>(E)) 12432 // Warn on string literal to bool. Checks for string literals in logical 12433 // and expressions, for instance, assert(0 && "error here"), are 12434 // prevented by a check in AnalyzeImplicitConversions(). 12435 return DiagnoseImpCast(S, E, T, CC, 12436 diag::warn_impcast_string_literal_to_bool); 12437 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12438 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12439 // This covers the literal expressions that evaluate to Objective-C 12440 // objects. 12441 return DiagnoseImpCast(S, E, T, CC, 12442 diag::warn_impcast_objective_c_literal_to_bool); 12443 } 12444 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12445 // Warn on pointer to bool conversion that is always true. 12446 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12447 SourceRange(CC)); 12448 } 12449 } 12450 12451 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12452 // is a typedef for signed char (macOS), then that constant value has to be 1 12453 // or 0. 12454 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12455 Expr::EvalResult Result; 12456 if (E->EvaluateAsInt(Result, S.getASTContext(), 12457 Expr::SE_AllowSideEffects)) { 12458 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12459 adornObjCBoolConversionDiagWithTernaryFixit( 12460 S, E, 12461 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12462 << toString(Result.Val.getInt(), 10)); 12463 } 12464 return; 12465 } 12466 } 12467 12468 // Check implicit casts from Objective-C collection literals to specialized 12469 // collection types, e.g., NSArray<NSString *> *. 12470 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12471 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12472 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12473 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12474 12475 // Strip vector types. 12476 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12477 if (Target->isVLSTBuiltinType()) { 12478 auto SourceVectorKind = SourceVT->getVectorKind(); 12479 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12480 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12481 (SourceVectorKind == VectorType::GenericVector && 12482 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12483 return; 12484 } 12485 12486 if (!isa<VectorType>(Target)) { 12487 if (S.SourceMgr.isInSystemMacro(CC)) 12488 return; 12489 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12490 } 12491 12492 // If the vector cast is cast between two vectors of the same size, it is 12493 // a bitcast, not a conversion. 12494 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12495 return; 12496 12497 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12498 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12499 } 12500 if (auto VecTy = dyn_cast<VectorType>(Target)) 12501 Target = VecTy->getElementType().getTypePtr(); 12502 12503 // Strip complex types. 12504 if (isa<ComplexType>(Source)) { 12505 if (!isa<ComplexType>(Target)) { 12506 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12507 return; 12508 12509 return DiagnoseImpCast(S, E, T, CC, 12510 S.getLangOpts().CPlusPlus 12511 ? diag::err_impcast_complex_scalar 12512 : diag::warn_impcast_complex_scalar); 12513 } 12514 12515 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12516 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12517 } 12518 12519 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12520 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12521 12522 // If the source is floating point... 12523 if (SourceBT && SourceBT->isFloatingPoint()) { 12524 // ...and the target is floating point... 12525 if (TargetBT && TargetBT->isFloatingPoint()) { 12526 // ...then warn if we're dropping FP rank. 12527 12528 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12529 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12530 if (Order > 0) { 12531 // Don't warn about float constants that are precisely 12532 // representable in the target type. 12533 Expr::EvalResult result; 12534 if (E->EvaluateAsRValue(result, S.Context)) { 12535 // Value might be a float, a float vector, or a float complex. 12536 if (IsSameFloatAfterCast(result.Val, 12537 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12538 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12539 return; 12540 } 12541 12542 if (S.SourceMgr.isInSystemMacro(CC)) 12543 return; 12544 12545 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12546 } 12547 // ... or possibly if we're increasing rank, too 12548 else if (Order < 0) { 12549 if (S.SourceMgr.isInSystemMacro(CC)) 12550 return; 12551 12552 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12553 } 12554 return; 12555 } 12556 12557 // If the target is integral, always warn. 12558 if (TargetBT && TargetBT->isInteger()) { 12559 if (S.SourceMgr.isInSystemMacro(CC)) 12560 return; 12561 12562 DiagnoseFloatingImpCast(S, E, T, CC); 12563 } 12564 12565 // Detect the case where a call result is converted from floating-point to 12566 // to bool, and the final argument to the call is converted from bool, to 12567 // discover this typo: 12568 // 12569 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12570 // 12571 // FIXME: This is an incredibly special case; is there some more general 12572 // way to detect this class of misplaced-parentheses bug? 12573 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12574 // Check last argument of function call to see if it is an 12575 // implicit cast from a type matching the type the result 12576 // is being cast to. 12577 CallExpr *CEx = cast<CallExpr>(E); 12578 if (unsigned NumArgs = CEx->getNumArgs()) { 12579 Expr *LastA = CEx->getArg(NumArgs - 1); 12580 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12581 if (isa<ImplicitCastExpr>(LastA) && 12582 InnerE->getType()->isBooleanType()) { 12583 // Warn on this floating-point to bool conversion 12584 DiagnoseImpCast(S, E, T, CC, 12585 diag::warn_impcast_floating_point_to_bool); 12586 } 12587 } 12588 } 12589 return; 12590 } 12591 12592 // Valid casts involving fixed point types should be accounted for here. 12593 if (Source->isFixedPointType()) { 12594 if (Target->isUnsaturatedFixedPointType()) { 12595 Expr::EvalResult Result; 12596 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12597 S.isConstantEvaluated())) { 12598 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12599 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12600 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12601 if (Value > MaxVal || Value < MinVal) { 12602 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12603 S.PDiag(diag::warn_impcast_fixed_point_range) 12604 << Value.toString() << T 12605 << E->getSourceRange() 12606 << clang::SourceRange(CC)); 12607 return; 12608 } 12609 } 12610 } else if (Target->isIntegerType()) { 12611 Expr::EvalResult Result; 12612 if (!S.isConstantEvaluated() && 12613 E->EvaluateAsFixedPoint(Result, S.Context, 12614 Expr::SE_AllowSideEffects)) { 12615 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12616 12617 bool Overflowed; 12618 llvm::APSInt IntResult = FXResult.convertToInt( 12619 S.Context.getIntWidth(T), 12620 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12621 12622 if (Overflowed) { 12623 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12624 S.PDiag(diag::warn_impcast_fixed_point_range) 12625 << FXResult.toString() << T 12626 << E->getSourceRange() 12627 << clang::SourceRange(CC)); 12628 return; 12629 } 12630 } 12631 } 12632 } else if (Target->isUnsaturatedFixedPointType()) { 12633 if (Source->isIntegerType()) { 12634 Expr::EvalResult Result; 12635 if (!S.isConstantEvaluated() && 12636 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12637 llvm::APSInt Value = Result.Val.getInt(); 12638 12639 bool Overflowed; 12640 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12641 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12642 12643 if (Overflowed) { 12644 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12645 S.PDiag(diag::warn_impcast_fixed_point_range) 12646 << toString(Value, /*Radix=*/10) << T 12647 << E->getSourceRange() 12648 << clang::SourceRange(CC)); 12649 return; 12650 } 12651 } 12652 } 12653 } 12654 12655 // If we are casting an integer type to a floating point type without 12656 // initialization-list syntax, we might lose accuracy if the floating 12657 // point type has a narrower significand than the integer type. 12658 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12659 TargetBT->isFloatingType() && !IsListInit) { 12660 // Determine the number of precision bits in the source integer type. 12661 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12662 /*Approximate*/ true); 12663 unsigned int SourcePrecision = SourceRange.Width; 12664 12665 // Determine the number of precision bits in the 12666 // target floating point type. 12667 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12668 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12669 12670 if (SourcePrecision > 0 && TargetPrecision > 0 && 12671 SourcePrecision > TargetPrecision) { 12672 12673 if (Optional<llvm::APSInt> SourceInt = 12674 E->getIntegerConstantExpr(S.Context)) { 12675 // If the source integer is a constant, convert it to the target 12676 // floating point type. Issue a warning if the value changes 12677 // during the whole conversion. 12678 llvm::APFloat TargetFloatValue( 12679 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12680 llvm::APFloat::opStatus ConversionStatus = 12681 TargetFloatValue.convertFromAPInt( 12682 *SourceInt, SourceBT->isSignedInteger(), 12683 llvm::APFloat::rmNearestTiesToEven); 12684 12685 if (ConversionStatus != llvm::APFloat::opOK) { 12686 SmallString<32> PrettySourceValue; 12687 SourceInt->toString(PrettySourceValue, 10); 12688 SmallString<32> PrettyTargetValue; 12689 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12690 12691 S.DiagRuntimeBehavior( 12692 E->getExprLoc(), E, 12693 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12694 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12695 << E->getSourceRange() << clang::SourceRange(CC)); 12696 } 12697 } else { 12698 // Otherwise, the implicit conversion may lose precision. 12699 DiagnoseImpCast(S, E, T, CC, 12700 diag::warn_impcast_integer_float_precision); 12701 } 12702 } 12703 } 12704 12705 DiagnoseNullConversion(S, E, T, CC); 12706 12707 S.DiscardMisalignedMemberAddress(Target, E); 12708 12709 if (Target->isBooleanType()) 12710 DiagnoseIntInBoolContext(S, E); 12711 12712 if (!Source->isIntegerType() || !Target->isIntegerType()) 12713 return; 12714 12715 // TODO: remove this early return once the false positives for constant->bool 12716 // in templates, macros, etc, are reduced or removed. 12717 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12718 return; 12719 12720 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12721 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12722 return adornObjCBoolConversionDiagWithTernaryFixit( 12723 S, E, 12724 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12725 << E->getType()); 12726 } 12727 12728 IntRange SourceTypeRange = 12729 IntRange::forTargetOfCanonicalType(S.Context, Source); 12730 IntRange LikelySourceRange = 12731 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12732 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12733 12734 if (LikelySourceRange.Width > TargetRange.Width) { 12735 // If the source is a constant, use a default-on diagnostic. 12736 // TODO: this should happen for bitfield stores, too. 12737 Expr::EvalResult Result; 12738 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12739 S.isConstantEvaluated())) { 12740 llvm::APSInt Value(32); 12741 Value = Result.Val.getInt(); 12742 12743 if (S.SourceMgr.isInSystemMacro(CC)) 12744 return; 12745 12746 std::string PrettySourceValue = toString(Value, 10); 12747 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12748 12749 S.DiagRuntimeBehavior( 12750 E->getExprLoc(), E, 12751 S.PDiag(diag::warn_impcast_integer_precision_constant) 12752 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12753 << E->getSourceRange() << SourceRange(CC)); 12754 return; 12755 } 12756 12757 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12758 if (S.SourceMgr.isInSystemMacro(CC)) 12759 return; 12760 12761 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12762 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12763 /* pruneControlFlow */ true); 12764 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12765 } 12766 12767 if (TargetRange.Width > SourceTypeRange.Width) { 12768 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12769 if (UO->getOpcode() == UO_Minus) 12770 if (Source->isUnsignedIntegerType()) { 12771 if (Target->isUnsignedIntegerType()) 12772 return DiagnoseImpCast(S, E, T, CC, 12773 diag::warn_impcast_high_order_zero_bits); 12774 if (Target->isSignedIntegerType()) 12775 return DiagnoseImpCast(S, E, T, CC, 12776 diag::warn_impcast_nonnegative_result); 12777 } 12778 } 12779 12780 if (TargetRange.Width == LikelySourceRange.Width && 12781 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12782 Source->isSignedIntegerType()) { 12783 // Warn when doing a signed to signed conversion, warn if the positive 12784 // source value is exactly the width of the target type, which will 12785 // cause a negative value to be stored. 12786 12787 Expr::EvalResult Result; 12788 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12789 !S.SourceMgr.isInSystemMacro(CC)) { 12790 llvm::APSInt Value = Result.Val.getInt(); 12791 if (isSameWidthConstantConversion(S, E, T, CC)) { 12792 std::string PrettySourceValue = toString(Value, 10); 12793 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12794 12795 S.DiagRuntimeBehavior( 12796 E->getExprLoc(), E, 12797 S.PDiag(diag::warn_impcast_integer_precision_constant) 12798 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12799 << E->getSourceRange() << SourceRange(CC)); 12800 return; 12801 } 12802 } 12803 12804 // Fall through for non-constants to give a sign conversion warning. 12805 } 12806 12807 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12808 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12809 LikelySourceRange.Width == TargetRange.Width)) { 12810 if (S.SourceMgr.isInSystemMacro(CC)) 12811 return; 12812 12813 unsigned DiagID = diag::warn_impcast_integer_sign; 12814 12815 // Traditionally, gcc has warned about this under -Wsign-compare. 12816 // We also want to warn about it in -Wconversion. 12817 // So if -Wconversion is off, use a completely identical diagnostic 12818 // in the sign-compare group. 12819 // The conditional-checking code will 12820 if (ICContext) { 12821 DiagID = diag::warn_impcast_integer_sign_conditional; 12822 *ICContext = true; 12823 } 12824 12825 return DiagnoseImpCast(S, E, T, CC, DiagID); 12826 } 12827 12828 // Diagnose conversions between different enumeration types. 12829 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12830 // type, to give us better diagnostics. 12831 QualType SourceType = E->getType(); 12832 if (!S.getLangOpts().CPlusPlus) { 12833 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12834 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12835 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12836 SourceType = S.Context.getTypeDeclType(Enum); 12837 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12838 } 12839 } 12840 12841 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12842 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12843 if (SourceEnum->getDecl()->hasNameForLinkage() && 12844 TargetEnum->getDecl()->hasNameForLinkage() && 12845 SourceEnum != TargetEnum) { 12846 if (S.SourceMgr.isInSystemMacro(CC)) 12847 return; 12848 12849 return DiagnoseImpCast(S, E, SourceType, T, CC, 12850 diag::warn_impcast_different_enum_types); 12851 } 12852 } 12853 12854 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12855 SourceLocation CC, QualType T); 12856 12857 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12858 SourceLocation CC, bool &ICContext) { 12859 E = E->IgnoreParenImpCasts(); 12860 12861 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12862 return CheckConditionalOperator(S, CO, CC, T); 12863 12864 AnalyzeImplicitConversions(S, E, CC); 12865 if (E->getType() != T) 12866 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12867 } 12868 12869 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12870 SourceLocation CC, QualType T) { 12871 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12872 12873 Expr *TrueExpr = E->getTrueExpr(); 12874 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12875 TrueExpr = BCO->getCommon(); 12876 12877 bool Suspicious = false; 12878 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12879 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12880 12881 if (T->isBooleanType()) 12882 DiagnoseIntInBoolContext(S, E); 12883 12884 // If -Wconversion would have warned about either of the candidates 12885 // for a signedness conversion to the context type... 12886 if (!Suspicious) return; 12887 12888 // ...but it's currently ignored... 12889 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12890 return; 12891 12892 // ...then check whether it would have warned about either of the 12893 // candidates for a signedness conversion to the condition type. 12894 if (E->getType() == T) return; 12895 12896 Suspicious = false; 12897 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12898 E->getType(), CC, &Suspicious); 12899 if (!Suspicious) 12900 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12901 E->getType(), CC, &Suspicious); 12902 } 12903 12904 /// Check conversion of given expression to boolean. 12905 /// Input argument E is a logical expression. 12906 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12907 if (S.getLangOpts().Bool) 12908 return; 12909 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12910 return; 12911 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12912 } 12913 12914 namespace { 12915 struct AnalyzeImplicitConversionsWorkItem { 12916 Expr *E; 12917 SourceLocation CC; 12918 bool IsListInit; 12919 }; 12920 } 12921 12922 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12923 /// that should be visited are added to WorkList. 12924 static void AnalyzeImplicitConversions( 12925 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12926 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12927 Expr *OrigE = Item.E; 12928 SourceLocation CC = Item.CC; 12929 12930 QualType T = OrigE->getType(); 12931 Expr *E = OrigE->IgnoreParenImpCasts(); 12932 12933 // Propagate whether we are in a C++ list initialization expression. 12934 // If so, we do not issue warnings for implicit int-float conversion 12935 // precision loss, because C++11 narrowing already handles it. 12936 bool IsListInit = Item.IsListInit || 12937 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12938 12939 if (E->isTypeDependent() || E->isValueDependent()) 12940 return; 12941 12942 Expr *SourceExpr = E; 12943 // Examine, but don't traverse into the source expression of an 12944 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12945 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12946 // evaluate it in the context of checking the specific conversion to T though. 12947 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12948 if (auto *Src = OVE->getSourceExpr()) 12949 SourceExpr = Src; 12950 12951 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12952 if (UO->getOpcode() == UO_Not && 12953 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12954 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12955 << OrigE->getSourceRange() << T->isBooleanType() 12956 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12957 12958 // For conditional operators, we analyze the arguments as if they 12959 // were being fed directly into the output. 12960 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12961 CheckConditionalOperator(S, CO, CC, T); 12962 return; 12963 } 12964 12965 // Check implicit argument conversions for function calls. 12966 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12967 CheckImplicitArgumentConversions(S, Call, CC); 12968 12969 // Go ahead and check any implicit conversions we might have skipped. 12970 // The non-canonical typecheck is just an optimization; 12971 // CheckImplicitConversion will filter out dead implicit conversions. 12972 if (SourceExpr->getType() != T) 12973 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12974 12975 // Now continue drilling into this expression. 12976 12977 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12978 // The bound subexpressions in a PseudoObjectExpr are not reachable 12979 // as transitive children. 12980 // FIXME: Use a more uniform representation for this. 12981 for (auto *SE : POE->semantics()) 12982 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12983 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12984 } 12985 12986 // Skip past explicit casts. 12987 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12988 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12989 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12990 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12991 WorkList.push_back({E, CC, IsListInit}); 12992 return; 12993 } 12994 12995 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12996 // Do a somewhat different check with comparison operators. 12997 if (BO->isComparisonOp()) 12998 return AnalyzeComparison(S, BO); 12999 13000 // And with simple assignments. 13001 if (BO->getOpcode() == BO_Assign) 13002 return AnalyzeAssignment(S, BO); 13003 // And with compound assignments. 13004 if (BO->isAssignmentOp()) 13005 return AnalyzeCompoundAssignment(S, BO); 13006 } 13007 13008 // These break the otherwise-useful invariant below. Fortunately, 13009 // we don't really need to recurse into them, because any internal 13010 // expressions should have been analyzed already when they were 13011 // built into statements. 13012 if (isa<StmtExpr>(E)) return; 13013 13014 // Don't descend into unevaluated contexts. 13015 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13016 13017 // Now just recurse over the expression's children. 13018 CC = E->getExprLoc(); 13019 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13020 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13021 for (Stmt *SubStmt : E->children()) { 13022 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13023 if (!ChildExpr) 13024 continue; 13025 13026 if (IsLogicalAndOperator && 13027 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13028 // Ignore checking string literals that are in logical and operators. 13029 // This is a common pattern for asserts. 13030 continue; 13031 WorkList.push_back({ChildExpr, CC, IsListInit}); 13032 } 13033 13034 if (BO && BO->isLogicalOp()) { 13035 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13036 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13037 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13038 13039 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13040 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13041 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13042 } 13043 13044 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13045 if (U->getOpcode() == UO_LNot) { 13046 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13047 } else if (U->getOpcode() != UO_AddrOf) { 13048 if (U->getSubExpr()->getType()->isAtomicType()) 13049 S.Diag(U->getSubExpr()->getBeginLoc(), 13050 diag::warn_atomic_implicit_seq_cst); 13051 } 13052 } 13053 } 13054 13055 /// AnalyzeImplicitConversions - Find and report any interesting 13056 /// implicit conversions in the given expression. There are a couple 13057 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13058 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13059 bool IsListInit/*= false*/) { 13060 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13061 WorkList.push_back({OrigE, CC, IsListInit}); 13062 while (!WorkList.empty()) 13063 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13064 } 13065 13066 /// Diagnose integer type and any valid implicit conversion to it. 13067 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13068 // Taking into account implicit conversions, 13069 // allow any integer. 13070 if (!E->getType()->isIntegerType()) { 13071 S.Diag(E->getBeginLoc(), 13072 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13073 return true; 13074 } 13075 // Potentially emit standard warnings for implicit conversions if enabled 13076 // using -Wconversion. 13077 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13078 return false; 13079 } 13080 13081 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13082 // Returns true when emitting a warning about taking the address of a reference. 13083 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13084 const PartialDiagnostic &PD) { 13085 E = E->IgnoreParenImpCasts(); 13086 13087 const FunctionDecl *FD = nullptr; 13088 13089 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13090 if (!DRE->getDecl()->getType()->isReferenceType()) 13091 return false; 13092 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13093 if (!M->getMemberDecl()->getType()->isReferenceType()) 13094 return false; 13095 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13096 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13097 return false; 13098 FD = Call->getDirectCallee(); 13099 } else { 13100 return false; 13101 } 13102 13103 SemaRef.Diag(E->getExprLoc(), PD); 13104 13105 // If possible, point to location of function. 13106 if (FD) { 13107 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13108 } 13109 13110 return true; 13111 } 13112 13113 // Returns true if the SourceLocation is expanded from any macro body. 13114 // Returns false if the SourceLocation is invalid, is from not in a macro 13115 // expansion, or is from expanded from a top-level macro argument. 13116 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13117 if (Loc.isInvalid()) 13118 return false; 13119 13120 while (Loc.isMacroID()) { 13121 if (SM.isMacroBodyExpansion(Loc)) 13122 return true; 13123 Loc = SM.getImmediateMacroCallerLoc(Loc); 13124 } 13125 13126 return false; 13127 } 13128 13129 /// Diagnose pointers that are always non-null. 13130 /// \param E the expression containing the pointer 13131 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13132 /// compared to a null pointer 13133 /// \param IsEqual True when the comparison is equal to a null pointer 13134 /// \param Range Extra SourceRange to highlight in the diagnostic 13135 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13136 Expr::NullPointerConstantKind NullKind, 13137 bool IsEqual, SourceRange Range) { 13138 if (!E) 13139 return; 13140 13141 // Don't warn inside macros. 13142 if (E->getExprLoc().isMacroID()) { 13143 const SourceManager &SM = getSourceManager(); 13144 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13145 IsInAnyMacroBody(SM, Range.getBegin())) 13146 return; 13147 } 13148 E = E->IgnoreImpCasts(); 13149 13150 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13151 13152 if (isa<CXXThisExpr>(E)) { 13153 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13154 : diag::warn_this_bool_conversion; 13155 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13156 return; 13157 } 13158 13159 bool IsAddressOf = false; 13160 13161 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13162 if (UO->getOpcode() != UO_AddrOf) 13163 return; 13164 IsAddressOf = true; 13165 E = UO->getSubExpr(); 13166 } 13167 13168 if (IsAddressOf) { 13169 unsigned DiagID = IsCompare 13170 ? diag::warn_address_of_reference_null_compare 13171 : diag::warn_address_of_reference_bool_conversion; 13172 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13173 << IsEqual; 13174 if (CheckForReference(*this, E, PD)) { 13175 return; 13176 } 13177 } 13178 13179 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13180 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13181 std::string Str; 13182 llvm::raw_string_ostream S(Str); 13183 E->printPretty(S, nullptr, getPrintingPolicy()); 13184 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13185 : diag::warn_cast_nonnull_to_bool; 13186 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13187 << E->getSourceRange() << Range << IsEqual; 13188 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13189 }; 13190 13191 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13192 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13193 if (auto *Callee = Call->getDirectCallee()) { 13194 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13195 ComplainAboutNonnullParamOrCall(A); 13196 return; 13197 } 13198 } 13199 } 13200 13201 // Expect to find a single Decl. Skip anything more complicated. 13202 ValueDecl *D = nullptr; 13203 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13204 D = R->getDecl(); 13205 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13206 D = M->getMemberDecl(); 13207 } 13208 13209 // Weak Decls can be null. 13210 if (!D || D->isWeak()) 13211 return; 13212 13213 // Check for parameter decl with nonnull attribute 13214 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13215 if (getCurFunction() && 13216 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13217 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13218 ComplainAboutNonnullParamOrCall(A); 13219 return; 13220 } 13221 13222 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13223 // Skip function template not specialized yet. 13224 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13225 return; 13226 auto ParamIter = llvm::find(FD->parameters(), PV); 13227 assert(ParamIter != FD->param_end()); 13228 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13229 13230 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13231 if (!NonNull->args_size()) { 13232 ComplainAboutNonnullParamOrCall(NonNull); 13233 return; 13234 } 13235 13236 for (const ParamIdx &ArgNo : NonNull->args()) { 13237 if (ArgNo.getASTIndex() == ParamNo) { 13238 ComplainAboutNonnullParamOrCall(NonNull); 13239 return; 13240 } 13241 } 13242 } 13243 } 13244 } 13245 } 13246 13247 QualType T = D->getType(); 13248 const bool IsArray = T->isArrayType(); 13249 const bool IsFunction = T->isFunctionType(); 13250 13251 // Address of function is used to silence the function warning. 13252 if (IsAddressOf && IsFunction) { 13253 return; 13254 } 13255 13256 // Found nothing. 13257 if (!IsAddressOf && !IsFunction && !IsArray) 13258 return; 13259 13260 // Pretty print the expression for the diagnostic. 13261 std::string Str; 13262 llvm::raw_string_ostream S(Str); 13263 E->printPretty(S, nullptr, getPrintingPolicy()); 13264 13265 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13266 : diag::warn_impcast_pointer_to_bool; 13267 enum { 13268 AddressOf, 13269 FunctionPointer, 13270 ArrayPointer 13271 } DiagType; 13272 if (IsAddressOf) 13273 DiagType = AddressOf; 13274 else if (IsFunction) 13275 DiagType = FunctionPointer; 13276 else if (IsArray) 13277 DiagType = ArrayPointer; 13278 else 13279 llvm_unreachable("Could not determine diagnostic."); 13280 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13281 << Range << IsEqual; 13282 13283 if (!IsFunction) 13284 return; 13285 13286 // Suggest '&' to silence the function warning. 13287 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13288 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13289 13290 // Check to see if '()' fixit should be emitted. 13291 QualType ReturnType; 13292 UnresolvedSet<4> NonTemplateOverloads; 13293 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13294 if (ReturnType.isNull()) 13295 return; 13296 13297 if (IsCompare) { 13298 // There are two cases here. If there is null constant, the only suggest 13299 // for a pointer return type. If the null is 0, then suggest if the return 13300 // type is a pointer or an integer type. 13301 if (!ReturnType->isPointerType()) { 13302 if (NullKind == Expr::NPCK_ZeroExpression || 13303 NullKind == Expr::NPCK_ZeroLiteral) { 13304 if (!ReturnType->isIntegerType()) 13305 return; 13306 } else { 13307 return; 13308 } 13309 } 13310 } else { // !IsCompare 13311 // For function to bool, only suggest if the function pointer has bool 13312 // return type. 13313 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13314 return; 13315 } 13316 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13317 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13318 } 13319 13320 /// Diagnoses "dangerous" implicit conversions within the given 13321 /// expression (which is a full expression). Implements -Wconversion 13322 /// and -Wsign-compare. 13323 /// 13324 /// \param CC the "context" location of the implicit conversion, i.e. 13325 /// the most location of the syntactic entity requiring the implicit 13326 /// conversion 13327 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13328 // Don't diagnose in unevaluated contexts. 13329 if (isUnevaluatedContext()) 13330 return; 13331 13332 // Don't diagnose for value- or type-dependent expressions. 13333 if (E->isTypeDependent() || E->isValueDependent()) 13334 return; 13335 13336 // Check for array bounds violations in cases where the check isn't triggered 13337 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13338 // ArraySubscriptExpr is on the RHS of a variable initialization. 13339 CheckArrayAccess(E); 13340 13341 // This is not the right CC for (e.g.) a variable initialization. 13342 AnalyzeImplicitConversions(*this, E, CC); 13343 } 13344 13345 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13346 /// Input argument E is a logical expression. 13347 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13348 ::CheckBoolLikeConversion(*this, E, CC); 13349 } 13350 13351 /// Diagnose when expression is an integer constant expression and its evaluation 13352 /// results in integer overflow 13353 void Sema::CheckForIntOverflow (Expr *E) { 13354 // Use a work list to deal with nested struct initializers. 13355 SmallVector<Expr *, 2> Exprs(1, E); 13356 13357 do { 13358 Expr *OriginalE = Exprs.pop_back_val(); 13359 Expr *E = OriginalE->IgnoreParenCasts(); 13360 13361 if (isa<BinaryOperator>(E)) { 13362 E->EvaluateForOverflow(Context); 13363 continue; 13364 } 13365 13366 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13367 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13368 else if (isa<ObjCBoxedExpr>(OriginalE)) 13369 E->EvaluateForOverflow(Context); 13370 else if (auto Call = dyn_cast<CallExpr>(E)) 13371 Exprs.append(Call->arg_begin(), Call->arg_end()); 13372 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13373 Exprs.append(Message->arg_begin(), Message->arg_end()); 13374 } while (!Exprs.empty()); 13375 } 13376 13377 namespace { 13378 13379 /// Visitor for expressions which looks for unsequenced operations on the 13380 /// same object. 13381 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13382 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13383 13384 /// A tree of sequenced regions within an expression. Two regions are 13385 /// unsequenced if one is an ancestor or a descendent of the other. When we 13386 /// finish processing an expression with sequencing, such as a comma 13387 /// expression, we fold its tree nodes into its parent, since they are 13388 /// unsequenced with respect to nodes we will visit later. 13389 class SequenceTree { 13390 struct Value { 13391 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13392 unsigned Parent : 31; 13393 unsigned Merged : 1; 13394 }; 13395 SmallVector<Value, 8> Values; 13396 13397 public: 13398 /// A region within an expression which may be sequenced with respect 13399 /// to some other region. 13400 class Seq { 13401 friend class SequenceTree; 13402 13403 unsigned Index; 13404 13405 explicit Seq(unsigned N) : Index(N) {} 13406 13407 public: 13408 Seq() : Index(0) {} 13409 }; 13410 13411 SequenceTree() { Values.push_back(Value(0)); } 13412 Seq root() const { return Seq(0); } 13413 13414 /// Create a new sequence of operations, which is an unsequenced 13415 /// subset of \p Parent. This sequence of operations is sequenced with 13416 /// respect to other children of \p Parent. 13417 Seq allocate(Seq Parent) { 13418 Values.push_back(Value(Parent.Index)); 13419 return Seq(Values.size() - 1); 13420 } 13421 13422 /// Merge a sequence of operations into its parent. 13423 void merge(Seq S) { 13424 Values[S.Index].Merged = true; 13425 } 13426 13427 /// Determine whether two operations are unsequenced. This operation 13428 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13429 /// should have been merged into its parent as appropriate. 13430 bool isUnsequenced(Seq Cur, Seq Old) { 13431 unsigned C = representative(Cur.Index); 13432 unsigned Target = representative(Old.Index); 13433 while (C >= Target) { 13434 if (C == Target) 13435 return true; 13436 C = Values[C].Parent; 13437 } 13438 return false; 13439 } 13440 13441 private: 13442 /// Pick a representative for a sequence. 13443 unsigned representative(unsigned K) { 13444 if (Values[K].Merged) 13445 // Perform path compression as we go. 13446 return Values[K].Parent = representative(Values[K].Parent); 13447 return K; 13448 } 13449 }; 13450 13451 /// An object for which we can track unsequenced uses. 13452 using Object = const NamedDecl *; 13453 13454 /// Different flavors of object usage which we track. We only track the 13455 /// least-sequenced usage of each kind. 13456 enum UsageKind { 13457 /// A read of an object. Multiple unsequenced reads are OK. 13458 UK_Use, 13459 13460 /// A modification of an object which is sequenced before the value 13461 /// computation of the expression, such as ++n in C++. 13462 UK_ModAsValue, 13463 13464 /// A modification of an object which is not sequenced before the value 13465 /// computation of the expression, such as n++. 13466 UK_ModAsSideEffect, 13467 13468 UK_Count = UK_ModAsSideEffect + 1 13469 }; 13470 13471 /// Bundle together a sequencing region and the expression corresponding 13472 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13473 struct Usage { 13474 const Expr *UsageExpr; 13475 SequenceTree::Seq Seq; 13476 13477 Usage() : UsageExpr(nullptr), Seq() {} 13478 }; 13479 13480 struct UsageInfo { 13481 Usage Uses[UK_Count]; 13482 13483 /// Have we issued a diagnostic for this object already? 13484 bool Diagnosed; 13485 13486 UsageInfo() : Uses(), Diagnosed(false) {} 13487 }; 13488 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13489 13490 Sema &SemaRef; 13491 13492 /// Sequenced regions within the expression. 13493 SequenceTree Tree; 13494 13495 /// Declaration modifications and references which we have seen. 13496 UsageInfoMap UsageMap; 13497 13498 /// The region we are currently within. 13499 SequenceTree::Seq Region; 13500 13501 /// Filled in with declarations which were modified as a side-effect 13502 /// (that is, post-increment operations). 13503 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13504 13505 /// Expressions to check later. We defer checking these to reduce 13506 /// stack usage. 13507 SmallVectorImpl<const Expr *> &WorkList; 13508 13509 /// RAII object wrapping the visitation of a sequenced subexpression of an 13510 /// expression. At the end of this process, the side-effects of the evaluation 13511 /// become sequenced with respect to the value computation of the result, so 13512 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13513 /// UK_ModAsValue. 13514 struct SequencedSubexpression { 13515 SequencedSubexpression(SequenceChecker &Self) 13516 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13517 Self.ModAsSideEffect = &ModAsSideEffect; 13518 } 13519 13520 ~SequencedSubexpression() { 13521 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13522 // Add a new usage with usage kind UK_ModAsValue, and then restore 13523 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13524 // the previous one was empty). 13525 UsageInfo &UI = Self.UsageMap[M.first]; 13526 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13527 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13528 SideEffectUsage = M.second; 13529 } 13530 Self.ModAsSideEffect = OldModAsSideEffect; 13531 } 13532 13533 SequenceChecker &Self; 13534 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13535 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13536 }; 13537 13538 /// RAII object wrapping the visitation of a subexpression which we might 13539 /// choose to evaluate as a constant. If any subexpression is evaluated and 13540 /// found to be non-constant, this allows us to suppress the evaluation of 13541 /// the outer expression. 13542 class EvaluationTracker { 13543 public: 13544 EvaluationTracker(SequenceChecker &Self) 13545 : Self(Self), Prev(Self.EvalTracker) { 13546 Self.EvalTracker = this; 13547 } 13548 13549 ~EvaluationTracker() { 13550 Self.EvalTracker = Prev; 13551 if (Prev) 13552 Prev->EvalOK &= EvalOK; 13553 } 13554 13555 bool evaluate(const Expr *E, bool &Result) { 13556 if (!EvalOK || E->isValueDependent()) 13557 return false; 13558 EvalOK = E->EvaluateAsBooleanCondition( 13559 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13560 return EvalOK; 13561 } 13562 13563 private: 13564 SequenceChecker &Self; 13565 EvaluationTracker *Prev; 13566 bool EvalOK = true; 13567 } *EvalTracker = nullptr; 13568 13569 /// Find the object which is produced by the specified expression, 13570 /// if any. 13571 Object getObject(const Expr *E, bool Mod) const { 13572 E = E->IgnoreParenCasts(); 13573 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13574 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13575 return getObject(UO->getSubExpr(), Mod); 13576 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13577 if (BO->getOpcode() == BO_Comma) 13578 return getObject(BO->getRHS(), Mod); 13579 if (Mod && BO->isAssignmentOp()) 13580 return getObject(BO->getLHS(), Mod); 13581 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13582 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13583 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13584 return ME->getMemberDecl(); 13585 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13586 // FIXME: If this is a reference, map through to its value. 13587 return DRE->getDecl(); 13588 return nullptr; 13589 } 13590 13591 /// Note that an object \p O was modified or used by an expression 13592 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13593 /// the object \p O as obtained via the \p UsageMap. 13594 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13595 // Get the old usage for the given object and usage kind. 13596 Usage &U = UI.Uses[UK]; 13597 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13598 // If we have a modification as side effect and are in a sequenced 13599 // subexpression, save the old Usage so that we can restore it later 13600 // in SequencedSubexpression::~SequencedSubexpression. 13601 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13602 ModAsSideEffect->push_back(std::make_pair(O, U)); 13603 // Then record the new usage with the current sequencing region. 13604 U.UsageExpr = UsageExpr; 13605 U.Seq = Region; 13606 } 13607 } 13608 13609 /// Check whether a modification or use of an object \p O in an expression 13610 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13611 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13612 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13613 /// usage and false we are checking for a mod-use unsequenced usage. 13614 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13615 UsageKind OtherKind, bool IsModMod) { 13616 if (UI.Diagnosed) 13617 return; 13618 13619 const Usage &U = UI.Uses[OtherKind]; 13620 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13621 return; 13622 13623 const Expr *Mod = U.UsageExpr; 13624 const Expr *ModOrUse = UsageExpr; 13625 if (OtherKind == UK_Use) 13626 std::swap(Mod, ModOrUse); 13627 13628 SemaRef.DiagRuntimeBehavior( 13629 Mod->getExprLoc(), {Mod, ModOrUse}, 13630 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13631 : diag::warn_unsequenced_mod_use) 13632 << O << SourceRange(ModOrUse->getExprLoc())); 13633 UI.Diagnosed = true; 13634 } 13635 13636 // A note on note{Pre, Post}{Use, Mod}: 13637 // 13638 // (It helps to follow the algorithm with an expression such as 13639 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13640 // operations before C++17 and both are well-defined in C++17). 13641 // 13642 // When visiting a node which uses/modify an object we first call notePreUse 13643 // or notePreMod before visiting its sub-expression(s). At this point the 13644 // children of the current node have not yet been visited and so the eventual 13645 // uses/modifications resulting from the children of the current node have not 13646 // been recorded yet. 13647 // 13648 // We then visit the children of the current node. After that notePostUse or 13649 // notePostMod is called. These will 1) detect an unsequenced modification 13650 // as side effect (as in "k++ + k") and 2) add a new usage with the 13651 // appropriate usage kind. 13652 // 13653 // We also have to be careful that some operation sequences modification as 13654 // side effect as well (for example: || or ,). To account for this we wrap 13655 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13656 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13657 // which record usages which are modifications as side effect, and then 13658 // downgrade them (or more accurately restore the previous usage which was a 13659 // modification as side effect) when exiting the scope of the sequenced 13660 // subexpression. 13661 13662 void notePreUse(Object O, const Expr *UseExpr) { 13663 UsageInfo &UI = UsageMap[O]; 13664 // Uses conflict with other modifications. 13665 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13666 } 13667 13668 void notePostUse(Object O, const Expr *UseExpr) { 13669 UsageInfo &UI = UsageMap[O]; 13670 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13671 /*IsModMod=*/false); 13672 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13673 } 13674 13675 void notePreMod(Object O, const Expr *ModExpr) { 13676 UsageInfo &UI = UsageMap[O]; 13677 // Modifications conflict with other modifications and with uses. 13678 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13679 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13680 } 13681 13682 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13683 UsageInfo &UI = UsageMap[O]; 13684 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13685 /*IsModMod=*/true); 13686 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13687 } 13688 13689 public: 13690 SequenceChecker(Sema &S, const Expr *E, 13691 SmallVectorImpl<const Expr *> &WorkList) 13692 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13693 Visit(E); 13694 // Silence a -Wunused-private-field since WorkList is now unused. 13695 // TODO: Evaluate if it can be used, and if not remove it. 13696 (void)this->WorkList; 13697 } 13698 13699 void VisitStmt(const Stmt *S) { 13700 // Skip all statements which aren't expressions for now. 13701 } 13702 13703 void VisitExpr(const Expr *E) { 13704 // By default, just recurse to evaluated subexpressions. 13705 Base::VisitStmt(E); 13706 } 13707 13708 void VisitCastExpr(const CastExpr *E) { 13709 Object O = Object(); 13710 if (E->getCastKind() == CK_LValueToRValue) 13711 O = getObject(E->getSubExpr(), false); 13712 13713 if (O) 13714 notePreUse(O, E); 13715 VisitExpr(E); 13716 if (O) 13717 notePostUse(O, E); 13718 } 13719 13720 void VisitSequencedExpressions(const Expr *SequencedBefore, 13721 const Expr *SequencedAfter) { 13722 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13723 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13724 SequenceTree::Seq OldRegion = Region; 13725 13726 { 13727 SequencedSubexpression SeqBefore(*this); 13728 Region = BeforeRegion; 13729 Visit(SequencedBefore); 13730 } 13731 13732 Region = AfterRegion; 13733 Visit(SequencedAfter); 13734 13735 Region = OldRegion; 13736 13737 Tree.merge(BeforeRegion); 13738 Tree.merge(AfterRegion); 13739 } 13740 13741 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13742 // C++17 [expr.sub]p1: 13743 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13744 // expression E1 is sequenced before the expression E2. 13745 if (SemaRef.getLangOpts().CPlusPlus17) 13746 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13747 else { 13748 Visit(ASE->getLHS()); 13749 Visit(ASE->getRHS()); 13750 } 13751 } 13752 13753 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13754 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13755 void VisitBinPtrMem(const BinaryOperator *BO) { 13756 // C++17 [expr.mptr.oper]p4: 13757 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13758 // the expression E1 is sequenced before the expression E2. 13759 if (SemaRef.getLangOpts().CPlusPlus17) 13760 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13761 else { 13762 Visit(BO->getLHS()); 13763 Visit(BO->getRHS()); 13764 } 13765 } 13766 13767 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13768 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13769 void VisitBinShlShr(const BinaryOperator *BO) { 13770 // C++17 [expr.shift]p4: 13771 // The expression E1 is sequenced before the expression E2. 13772 if (SemaRef.getLangOpts().CPlusPlus17) 13773 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13774 else { 13775 Visit(BO->getLHS()); 13776 Visit(BO->getRHS()); 13777 } 13778 } 13779 13780 void VisitBinComma(const BinaryOperator *BO) { 13781 // C++11 [expr.comma]p1: 13782 // Every value computation and side effect associated with the left 13783 // expression is sequenced before every value computation and side 13784 // effect associated with the right expression. 13785 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13786 } 13787 13788 void VisitBinAssign(const BinaryOperator *BO) { 13789 SequenceTree::Seq RHSRegion; 13790 SequenceTree::Seq LHSRegion; 13791 if (SemaRef.getLangOpts().CPlusPlus17) { 13792 RHSRegion = Tree.allocate(Region); 13793 LHSRegion = Tree.allocate(Region); 13794 } else { 13795 RHSRegion = Region; 13796 LHSRegion = Region; 13797 } 13798 SequenceTree::Seq OldRegion = Region; 13799 13800 // C++11 [expr.ass]p1: 13801 // [...] the assignment is sequenced after the value computation 13802 // of the right and left operands, [...] 13803 // 13804 // so check it before inspecting the operands and update the 13805 // map afterwards. 13806 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13807 if (O) 13808 notePreMod(O, BO); 13809 13810 if (SemaRef.getLangOpts().CPlusPlus17) { 13811 // C++17 [expr.ass]p1: 13812 // [...] The right operand is sequenced before the left operand. [...] 13813 { 13814 SequencedSubexpression SeqBefore(*this); 13815 Region = RHSRegion; 13816 Visit(BO->getRHS()); 13817 } 13818 13819 Region = LHSRegion; 13820 Visit(BO->getLHS()); 13821 13822 if (O && isa<CompoundAssignOperator>(BO)) 13823 notePostUse(O, BO); 13824 13825 } else { 13826 // C++11 does not specify any sequencing between the LHS and RHS. 13827 Region = LHSRegion; 13828 Visit(BO->getLHS()); 13829 13830 if (O && isa<CompoundAssignOperator>(BO)) 13831 notePostUse(O, BO); 13832 13833 Region = RHSRegion; 13834 Visit(BO->getRHS()); 13835 } 13836 13837 // C++11 [expr.ass]p1: 13838 // the assignment is sequenced [...] before the value computation of the 13839 // assignment expression. 13840 // C11 6.5.16/3 has no such rule. 13841 Region = OldRegion; 13842 if (O) 13843 notePostMod(O, BO, 13844 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13845 : UK_ModAsSideEffect); 13846 if (SemaRef.getLangOpts().CPlusPlus17) { 13847 Tree.merge(RHSRegion); 13848 Tree.merge(LHSRegion); 13849 } 13850 } 13851 13852 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13853 VisitBinAssign(CAO); 13854 } 13855 13856 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13857 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13858 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13859 Object O = getObject(UO->getSubExpr(), true); 13860 if (!O) 13861 return VisitExpr(UO); 13862 13863 notePreMod(O, UO); 13864 Visit(UO->getSubExpr()); 13865 // C++11 [expr.pre.incr]p1: 13866 // the expression ++x is equivalent to x+=1 13867 notePostMod(O, UO, 13868 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13869 : UK_ModAsSideEffect); 13870 } 13871 13872 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13873 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13874 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13875 Object O = getObject(UO->getSubExpr(), true); 13876 if (!O) 13877 return VisitExpr(UO); 13878 13879 notePreMod(O, UO); 13880 Visit(UO->getSubExpr()); 13881 notePostMod(O, UO, UK_ModAsSideEffect); 13882 } 13883 13884 void VisitBinLOr(const BinaryOperator *BO) { 13885 // C++11 [expr.log.or]p2: 13886 // If the second expression is evaluated, every value computation and 13887 // side effect associated with the first expression is sequenced before 13888 // every value computation and side effect associated with the 13889 // second expression. 13890 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13891 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13892 SequenceTree::Seq OldRegion = Region; 13893 13894 EvaluationTracker Eval(*this); 13895 { 13896 SequencedSubexpression Sequenced(*this); 13897 Region = LHSRegion; 13898 Visit(BO->getLHS()); 13899 } 13900 13901 // C++11 [expr.log.or]p1: 13902 // [...] the second operand is not evaluated if the first operand 13903 // evaluates to true. 13904 bool EvalResult = false; 13905 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13906 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13907 if (ShouldVisitRHS) { 13908 Region = RHSRegion; 13909 Visit(BO->getRHS()); 13910 } 13911 13912 Region = OldRegion; 13913 Tree.merge(LHSRegion); 13914 Tree.merge(RHSRegion); 13915 } 13916 13917 void VisitBinLAnd(const BinaryOperator *BO) { 13918 // C++11 [expr.log.and]p2: 13919 // If the second expression is evaluated, every value computation and 13920 // side effect associated with the first expression is sequenced before 13921 // every value computation and side effect associated with the 13922 // second expression. 13923 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13924 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13925 SequenceTree::Seq OldRegion = Region; 13926 13927 EvaluationTracker Eval(*this); 13928 { 13929 SequencedSubexpression Sequenced(*this); 13930 Region = LHSRegion; 13931 Visit(BO->getLHS()); 13932 } 13933 13934 // C++11 [expr.log.and]p1: 13935 // [...] the second operand is not evaluated if the first operand is false. 13936 bool EvalResult = false; 13937 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13938 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13939 if (ShouldVisitRHS) { 13940 Region = RHSRegion; 13941 Visit(BO->getRHS()); 13942 } 13943 13944 Region = OldRegion; 13945 Tree.merge(LHSRegion); 13946 Tree.merge(RHSRegion); 13947 } 13948 13949 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13950 // C++11 [expr.cond]p1: 13951 // [...] Every value computation and side effect associated with the first 13952 // expression is sequenced before every value computation and side effect 13953 // associated with the second or third expression. 13954 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13955 13956 // No sequencing is specified between the true and false expression. 13957 // However since exactly one of both is going to be evaluated we can 13958 // consider them to be sequenced. This is needed to avoid warning on 13959 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13960 // both the true and false expressions because we can't evaluate x. 13961 // This will still allow us to detect an expression like (pre C++17) 13962 // "(x ? y += 1 : y += 2) = y". 13963 // 13964 // We don't wrap the visitation of the true and false expression with 13965 // SequencedSubexpression because we don't want to downgrade modifications 13966 // as side effect in the true and false expressions after the visition 13967 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13968 // not warn between the two "y++", but we should warn between the "y++" 13969 // and the "y". 13970 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13971 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13972 SequenceTree::Seq OldRegion = Region; 13973 13974 EvaluationTracker Eval(*this); 13975 { 13976 SequencedSubexpression Sequenced(*this); 13977 Region = ConditionRegion; 13978 Visit(CO->getCond()); 13979 } 13980 13981 // C++11 [expr.cond]p1: 13982 // [...] The first expression is contextually converted to bool (Clause 4). 13983 // It is evaluated and if it is true, the result of the conditional 13984 // expression is the value of the second expression, otherwise that of the 13985 // third expression. Only one of the second and third expressions is 13986 // evaluated. [...] 13987 bool EvalResult = false; 13988 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13989 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13990 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13991 if (ShouldVisitTrueExpr) { 13992 Region = TrueRegion; 13993 Visit(CO->getTrueExpr()); 13994 } 13995 if (ShouldVisitFalseExpr) { 13996 Region = FalseRegion; 13997 Visit(CO->getFalseExpr()); 13998 } 13999 14000 Region = OldRegion; 14001 Tree.merge(ConditionRegion); 14002 Tree.merge(TrueRegion); 14003 Tree.merge(FalseRegion); 14004 } 14005 14006 void VisitCallExpr(const CallExpr *CE) { 14007 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14008 14009 if (CE->isUnevaluatedBuiltinCall(Context)) 14010 return; 14011 14012 // C++11 [intro.execution]p15: 14013 // When calling a function [...], every value computation and side effect 14014 // associated with any argument expression, or with the postfix expression 14015 // designating the called function, is sequenced before execution of every 14016 // expression or statement in the body of the function [and thus before 14017 // the value computation of its result]. 14018 SequencedSubexpression Sequenced(*this); 14019 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14020 // C++17 [expr.call]p5 14021 // The postfix-expression is sequenced before each expression in the 14022 // expression-list and any default argument. [...] 14023 SequenceTree::Seq CalleeRegion; 14024 SequenceTree::Seq OtherRegion; 14025 if (SemaRef.getLangOpts().CPlusPlus17) { 14026 CalleeRegion = Tree.allocate(Region); 14027 OtherRegion = Tree.allocate(Region); 14028 } else { 14029 CalleeRegion = Region; 14030 OtherRegion = Region; 14031 } 14032 SequenceTree::Seq OldRegion = Region; 14033 14034 // Visit the callee expression first. 14035 Region = CalleeRegion; 14036 if (SemaRef.getLangOpts().CPlusPlus17) { 14037 SequencedSubexpression Sequenced(*this); 14038 Visit(CE->getCallee()); 14039 } else { 14040 Visit(CE->getCallee()); 14041 } 14042 14043 // Then visit the argument expressions. 14044 Region = OtherRegion; 14045 for (const Expr *Argument : CE->arguments()) 14046 Visit(Argument); 14047 14048 Region = OldRegion; 14049 if (SemaRef.getLangOpts().CPlusPlus17) { 14050 Tree.merge(CalleeRegion); 14051 Tree.merge(OtherRegion); 14052 } 14053 }); 14054 } 14055 14056 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14057 // C++17 [over.match.oper]p2: 14058 // [...] the operator notation is first transformed to the equivalent 14059 // function-call notation as summarized in Table 12 (where @ denotes one 14060 // of the operators covered in the specified subclause). However, the 14061 // operands are sequenced in the order prescribed for the built-in 14062 // operator (Clause 8). 14063 // 14064 // From the above only overloaded binary operators and overloaded call 14065 // operators have sequencing rules in C++17 that we need to handle 14066 // separately. 14067 if (!SemaRef.getLangOpts().CPlusPlus17 || 14068 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14069 return VisitCallExpr(CXXOCE); 14070 14071 enum { 14072 NoSequencing, 14073 LHSBeforeRHS, 14074 RHSBeforeLHS, 14075 LHSBeforeRest 14076 } SequencingKind; 14077 switch (CXXOCE->getOperator()) { 14078 case OO_Equal: 14079 case OO_PlusEqual: 14080 case OO_MinusEqual: 14081 case OO_StarEqual: 14082 case OO_SlashEqual: 14083 case OO_PercentEqual: 14084 case OO_CaretEqual: 14085 case OO_AmpEqual: 14086 case OO_PipeEqual: 14087 case OO_LessLessEqual: 14088 case OO_GreaterGreaterEqual: 14089 SequencingKind = RHSBeforeLHS; 14090 break; 14091 14092 case OO_LessLess: 14093 case OO_GreaterGreater: 14094 case OO_AmpAmp: 14095 case OO_PipePipe: 14096 case OO_Comma: 14097 case OO_ArrowStar: 14098 case OO_Subscript: 14099 SequencingKind = LHSBeforeRHS; 14100 break; 14101 14102 case OO_Call: 14103 SequencingKind = LHSBeforeRest; 14104 break; 14105 14106 default: 14107 SequencingKind = NoSequencing; 14108 break; 14109 } 14110 14111 if (SequencingKind == NoSequencing) 14112 return VisitCallExpr(CXXOCE); 14113 14114 // This is a call, so all subexpressions are sequenced before the result. 14115 SequencedSubexpression Sequenced(*this); 14116 14117 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14118 assert(SemaRef.getLangOpts().CPlusPlus17 && 14119 "Should only get there with C++17 and above!"); 14120 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14121 "Should only get there with an overloaded binary operator" 14122 " or an overloaded call operator!"); 14123 14124 if (SequencingKind == LHSBeforeRest) { 14125 assert(CXXOCE->getOperator() == OO_Call && 14126 "We should only have an overloaded call operator here!"); 14127 14128 // This is very similar to VisitCallExpr, except that we only have the 14129 // C++17 case. The postfix-expression is the first argument of the 14130 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14131 // are in the following arguments. 14132 // 14133 // Note that we intentionally do not visit the callee expression since 14134 // it is just a decayed reference to a function. 14135 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14136 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14137 SequenceTree::Seq OldRegion = Region; 14138 14139 assert(CXXOCE->getNumArgs() >= 1 && 14140 "An overloaded call operator must have at least one argument" 14141 " for the postfix-expression!"); 14142 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14143 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14144 CXXOCE->getNumArgs() - 1); 14145 14146 // Visit the postfix-expression first. 14147 { 14148 Region = PostfixExprRegion; 14149 SequencedSubexpression Sequenced(*this); 14150 Visit(PostfixExpr); 14151 } 14152 14153 // Then visit the argument expressions. 14154 Region = ArgsRegion; 14155 for (const Expr *Arg : Args) 14156 Visit(Arg); 14157 14158 Region = OldRegion; 14159 Tree.merge(PostfixExprRegion); 14160 Tree.merge(ArgsRegion); 14161 } else { 14162 assert(CXXOCE->getNumArgs() == 2 && 14163 "Should only have two arguments here!"); 14164 assert((SequencingKind == LHSBeforeRHS || 14165 SequencingKind == RHSBeforeLHS) && 14166 "Unexpected sequencing kind!"); 14167 14168 // We do not visit the callee expression since it is just a decayed 14169 // reference to a function. 14170 const Expr *E1 = CXXOCE->getArg(0); 14171 const Expr *E2 = CXXOCE->getArg(1); 14172 if (SequencingKind == RHSBeforeLHS) 14173 std::swap(E1, E2); 14174 14175 return VisitSequencedExpressions(E1, E2); 14176 } 14177 }); 14178 } 14179 14180 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14181 // This is a call, so all subexpressions are sequenced before the result. 14182 SequencedSubexpression Sequenced(*this); 14183 14184 if (!CCE->isListInitialization()) 14185 return VisitExpr(CCE); 14186 14187 // In C++11, list initializations are sequenced. 14188 SmallVector<SequenceTree::Seq, 32> Elts; 14189 SequenceTree::Seq Parent = Region; 14190 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14191 E = CCE->arg_end(); 14192 I != E; ++I) { 14193 Region = Tree.allocate(Parent); 14194 Elts.push_back(Region); 14195 Visit(*I); 14196 } 14197 14198 // Forget that the initializers are sequenced. 14199 Region = Parent; 14200 for (unsigned I = 0; I < Elts.size(); ++I) 14201 Tree.merge(Elts[I]); 14202 } 14203 14204 void VisitInitListExpr(const InitListExpr *ILE) { 14205 if (!SemaRef.getLangOpts().CPlusPlus11) 14206 return VisitExpr(ILE); 14207 14208 // In C++11, list initializations are sequenced. 14209 SmallVector<SequenceTree::Seq, 32> Elts; 14210 SequenceTree::Seq Parent = Region; 14211 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14212 const Expr *E = ILE->getInit(I); 14213 if (!E) 14214 continue; 14215 Region = Tree.allocate(Parent); 14216 Elts.push_back(Region); 14217 Visit(E); 14218 } 14219 14220 // Forget that the initializers are sequenced. 14221 Region = Parent; 14222 for (unsigned I = 0; I < Elts.size(); ++I) 14223 Tree.merge(Elts[I]); 14224 } 14225 }; 14226 14227 } // namespace 14228 14229 void Sema::CheckUnsequencedOperations(const Expr *E) { 14230 SmallVector<const Expr *, 8> WorkList; 14231 WorkList.push_back(E); 14232 while (!WorkList.empty()) { 14233 const Expr *Item = WorkList.pop_back_val(); 14234 SequenceChecker(*this, Item, WorkList); 14235 } 14236 } 14237 14238 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14239 bool IsConstexpr) { 14240 llvm::SaveAndRestore<bool> ConstantContext( 14241 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14242 CheckImplicitConversions(E, CheckLoc); 14243 if (!E->isInstantiationDependent()) 14244 CheckUnsequencedOperations(E); 14245 if (!IsConstexpr && !E->isValueDependent()) 14246 CheckForIntOverflow(E); 14247 DiagnoseMisalignedMembers(); 14248 } 14249 14250 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14251 FieldDecl *BitField, 14252 Expr *Init) { 14253 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14254 } 14255 14256 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14257 SourceLocation Loc) { 14258 if (!PType->isVariablyModifiedType()) 14259 return; 14260 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14261 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14262 return; 14263 } 14264 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14265 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14266 return; 14267 } 14268 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14269 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14270 return; 14271 } 14272 14273 const ArrayType *AT = S.Context.getAsArrayType(PType); 14274 if (!AT) 14275 return; 14276 14277 if (AT->getSizeModifier() != ArrayType::Star) { 14278 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14279 return; 14280 } 14281 14282 S.Diag(Loc, diag::err_array_star_in_function_definition); 14283 } 14284 14285 /// CheckParmsForFunctionDef - Check that the parameters of the given 14286 /// function are appropriate for the definition of a function. This 14287 /// takes care of any checks that cannot be performed on the 14288 /// declaration itself, e.g., that the types of each of the function 14289 /// parameters are complete. 14290 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14291 bool CheckParameterNames) { 14292 bool HasInvalidParm = false; 14293 for (ParmVarDecl *Param : Parameters) { 14294 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14295 // function declarator that is part of a function definition of 14296 // that function shall not have incomplete type. 14297 // 14298 // This is also C++ [dcl.fct]p6. 14299 if (!Param->isInvalidDecl() && 14300 RequireCompleteType(Param->getLocation(), Param->getType(), 14301 diag::err_typecheck_decl_incomplete_type)) { 14302 Param->setInvalidDecl(); 14303 HasInvalidParm = true; 14304 } 14305 14306 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14307 // declaration of each parameter shall include an identifier. 14308 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14309 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14310 // Diagnose this as an extension in C17 and earlier. 14311 if (!getLangOpts().C2x) 14312 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14313 } 14314 14315 // C99 6.7.5.3p12: 14316 // If the function declarator is not part of a definition of that 14317 // function, parameters may have incomplete type and may use the [*] 14318 // notation in their sequences of declarator specifiers to specify 14319 // variable length array types. 14320 QualType PType = Param->getOriginalType(); 14321 // FIXME: This diagnostic should point the '[*]' if source-location 14322 // information is added for it. 14323 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14324 14325 // If the parameter is a c++ class type and it has to be destructed in the 14326 // callee function, declare the destructor so that it can be called by the 14327 // callee function. Do not perform any direct access check on the dtor here. 14328 if (!Param->isInvalidDecl()) { 14329 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14330 if (!ClassDecl->isInvalidDecl() && 14331 !ClassDecl->hasIrrelevantDestructor() && 14332 !ClassDecl->isDependentContext() && 14333 ClassDecl->isParamDestroyedInCallee()) { 14334 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14335 MarkFunctionReferenced(Param->getLocation(), Destructor); 14336 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14337 } 14338 } 14339 } 14340 14341 // Parameters with the pass_object_size attribute only need to be marked 14342 // constant at function definitions. Because we lack information about 14343 // whether we're on a declaration or definition when we're instantiating the 14344 // attribute, we need to check for constness here. 14345 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14346 if (!Param->getType().isConstQualified()) 14347 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14348 << Attr->getSpelling() << 1; 14349 14350 // Check for parameter names shadowing fields from the class. 14351 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14352 // The owning context for the parameter should be the function, but we 14353 // want to see if this function's declaration context is a record. 14354 DeclContext *DC = Param->getDeclContext(); 14355 if (DC && DC->isFunctionOrMethod()) { 14356 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14357 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14358 RD, /*DeclIsField*/ false); 14359 } 14360 } 14361 } 14362 14363 return HasInvalidParm; 14364 } 14365 14366 Optional<std::pair<CharUnits, CharUnits>> 14367 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14368 14369 /// Compute the alignment and offset of the base class object given the 14370 /// derived-to-base cast expression and the alignment and offset of the derived 14371 /// class object. 14372 static std::pair<CharUnits, CharUnits> 14373 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14374 CharUnits BaseAlignment, CharUnits Offset, 14375 ASTContext &Ctx) { 14376 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14377 ++PathI) { 14378 const CXXBaseSpecifier *Base = *PathI; 14379 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14380 if (Base->isVirtual()) { 14381 // The complete object may have a lower alignment than the non-virtual 14382 // alignment of the base, in which case the base may be misaligned. Choose 14383 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14384 // conservative lower bound of the complete object alignment. 14385 CharUnits NonVirtualAlignment = 14386 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14387 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14388 Offset = CharUnits::Zero(); 14389 } else { 14390 const ASTRecordLayout &RL = 14391 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14392 Offset += RL.getBaseClassOffset(BaseDecl); 14393 } 14394 DerivedType = Base->getType(); 14395 } 14396 14397 return std::make_pair(BaseAlignment, Offset); 14398 } 14399 14400 /// Compute the alignment and offset of a binary additive operator. 14401 static Optional<std::pair<CharUnits, CharUnits>> 14402 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14403 bool IsSub, ASTContext &Ctx) { 14404 QualType PointeeType = PtrE->getType()->getPointeeType(); 14405 14406 if (!PointeeType->isConstantSizeType()) 14407 return llvm::None; 14408 14409 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14410 14411 if (!P) 14412 return llvm::None; 14413 14414 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14415 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14416 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14417 if (IsSub) 14418 Offset = -Offset; 14419 return std::make_pair(P->first, P->second + Offset); 14420 } 14421 14422 // If the integer expression isn't a constant expression, compute the lower 14423 // bound of the alignment using the alignment and offset of the pointer 14424 // expression and the element size. 14425 return std::make_pair( 14426 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14427 CharUnits::Zero()); 14428 } 14429 14430 /// This helper function takes an lvalue expression and returns the alignment of 14431 /// a VarDecl and a constant offset from the VarDecl. 14432 Optional<std::pair<CharUnits, CharUnits>> 14433 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14434 E = E->IgnoreParens(); 14435 switch (E->getStmtClass()) { 14436 default: 14437 break; 14438 case Stmt::CStyleCastExprClass: 14439 case Stmt::CXXStaticCastExprClass: 14440 case Stmt::ImplicitCastExprClass: { 14441 auto *CE = cast<CastExpr>(E); 14442 const Expr *From = CE->getSubExpr(); 14443 switch (CE->getCastKind()) { 14444 default: 14445 break; 14446 case CK_NoOp: 14447 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14448 case CK_UncheckedDerivedToBase: 14449 case CK_DerivedToBase: { 14450 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14451 if (!P) 14452 break; 14453 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14454 P->second, Ctx); 14455 } 14456 } 14457 break; 14458 } 14459 case Stmt::ArraySubscriptExprClass: { 14460 auto *ASE = cast<ArraySubscriptExpr>(E); 14461 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14462 false, Ctx); 14463 } 14464 case Stmt::DeclRefExprClass: { 14465 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14466 // FIXME: If VD is captured by copy or is an escaping __block variable, 14467 // use the alignment of VD's type. 14468 if (!VD->getType()->isReferenceType()) 14469 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14470 if (VD->hasInit()) 14471 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14472 } 14473 break; 14474 } 14475 case Stmt::MemberExprClass: { 14476 auto *ME = cast<MemberExpr>(E); 14477 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14478 if (!FD || FD->getType()->isReferenceType()) 14479 break; 14480 Optional<std::pair<CharUnits, CharUnits>> P; 14481 if (ME->isArrow()) 14482 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14483 else 14484 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14485 if (!P) 14486 break; 14487 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14488 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14489 return std::make_pair(P->first, 14490 P->second + CharUnits::fromQuantity(Offset)); 14491 } 14492 case Stmt::UnaryOperatorClass: { 14493 auto *UO = cast<UnaryOperator>(E); 14494 switch (UO->getOpcode()) { 14495 default: 14496 break; 14497 case UO_Deref: 14498 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14499 } 14500 break; 14501 } 14502 case Stmt::BinaryOperatorClass: { 14503 auto *BO = cast<BinaryOperator>(E); 14504 auto Opcode = BO->getOpcode(); 14505 switch (Opcode) { 14506 default: 14507 break; 14508 case BO_Comma: 14509 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14510 } 14511 break; 14512 } 14513 } 14514 return llvm::None; 14515 } 14516 14517 /// This helper function takes a pointer expression and returns the alignment of 14518 /// a VarDecl and a constant offset from the VarDecl. 14519 Optional<std::pair<CharUnits, CharUnits>> 14520 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14521 E = E->IgnoreParens(); 14522 switch (E->getStmtClass()) { 14523 default: 14524 break; 14525 case Stmt::CStyleCastExprClass: 14526 case Stmt::CXXStaticCastExprClass: 14527 case Stmt::ImplicitCastExprClass: { 14528 auto *CE = cast<CastExpr>(E); 14529 const Expr *From = CE->getSubExpr(); 14530 switch (CE->getCastKind()) { 14531 default: 14532 break; 14533 case CK_NoOp: 14534 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14535 case CK_ArrayToPointerDecay: 14536 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14537 case CK_UncheckedDerivedToBase: 14538 case CK_DerivedToBase: { 14539 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14540 if (!P) 14541 break; 14542 return getDerivedToBaseAlignmentAndOffset( 14543 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14544 } 14545 } 14546 break; 14547 } 14548 case Stmt::CXXThisExprClass: { 14549 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14550 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14551 return std::make_pair(Alignment, CharUnits::Zero()); 14552 } 14553 case Stmt::UnaryOperatorClass: { 14554 auto *UO = cast<UnaryOperator>(E); 14555 if (UO->getOpcode() == UO_AddrOf) 14556 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14557 break; 14558 } 14559 case Stmt::BinaryOperatorClass: { 14560 auto *BO = cast<BinaryOperator>(E); 14561 auto Opcode = BO->getOpcode(); 14562 switch (Opcode) { 14563 default: 14564 break; 14565 case BO_Add: 14566 case BO_Sub: { 14567 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14568 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14569 std::swap(LHS, RHS); 14570 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14571 Ctx); 14572 } 14573 case BO_Comma: 14574 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14575 } 14576 break; 14577 } 14578 } 14579 return llvm::None; 14580 } 14581 14582 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14583 // See if we can compute the alignment of a VarDecl and an offset from it. 14584 Optional<std::pair<CharUnits, CharUnits>> P = 14585 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14586 14587 if (P) 14588 return P->first.alignmentAtOffset(P->second); 14589 14590 // If that failed, return the type's alignment. 14591 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14592 } 14593 14594 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14595 /// pointer cast increases the alignment requirements. 14596 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14597 // This is actually a lot of work to potentially be doing on every 14598 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14599 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14600 return; 14601 14602 // Ignore dependent types. 14603 if (T->isDependentType() || Op->getType()->isDependentType()) 14604 return; 14605 14606 // Require that the destination be a pointer type. 14607 const PointerType *DestPtr = T->getAs<PointerType>(); 14608 if (!DestPtr) return; 14609 14610 // If the destination has alignment 1, we're done. 14611 QualType DestPointee = DestPtr->getPointeeType(); 14612 if (DestPointee->isIncompleteType()) return; 14613 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14614 if (DestAlign.isOne()) return; 14615 14616 // Require that the source be a pointer type. 14617 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14618 if (!SrcPtr) return; 14619 QualType SrcPointee = SrcPtr->getPointeeType(); 14620 14621 // Explicitly allow casts from cv void*. We already implicitly 14622 // allowed casts to cv void*, since they have alignment 1. 14623 // Also allow casts involving incomplete types, which implicitly 14624 // includes 'void'. 14625 if (SrcPointee->isIncompleteType()) return; 14626 14627 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14628 14629 if (SrcAlign >= DestAlign) return; 14630 14631 Diag(TRange.getBegin(), diag::warn_cast_align) 14632 << Op->getType() << T 14633 << static_cast<unsigned>(SrcAlign.getQuantity()) 14634 << static_cast<unsigned>(DestAlign.getQuantity()) 14635 << TRange << Op->getSourceRange(); 14636 } 14637 14638 /// Check whether this array fits the idiom of a size-one tail padded 14639 /// array member of a struct. 14640 /// 14641 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14642 /// commonly used to emulate flexible arrays in C89 code. 14643 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14644 const NamedDecl *ND) { 14645 if (Size != 1 || !ND) return false; 14646 14647 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14648 if (!FD) return false; 14649 14650 // Don't consider sizes resulting from macro expansions or template argument 14651 // substitution to form C89 tail-padded arrays. 14652 14653 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14654 while (TInfo) { 14655 TypeLoc TL = TInfo->getTypeLoc(); 14656 // Look through typedefs. 14657 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14658 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14659 TInfo = TDL->getTypeSourceInfo(); 14660 continue; 14661 } 14662 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14663 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14664 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14665 return false; 14666 } 14667 break; 14668 } 14669 14670 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14671 if (!RD) return false; 14672 if (RD->isUnion()) return false; 14673 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14674 if (!CRD->isStandardLayout()) return false; 14675 } 14676 14677 // See if this is the last field decl in the record. 14678 const Decl *D = FD; 14679 while ((D = D->getNextDeclInContext())) 14680 if (isa<FieldDecl>(D)) 14681 return false; 14682 return true; 14683 } 14684 14685 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14686 const ArraySubscriptExpr *ASE, 14687 bool AllowOnePastEnd, bool IndexNegated) { 14688 // Already diagnosed by the constant evaluator. 14689 if (isConstantEvaluated()) 14690 return; 14691 14692 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14693 if (IndexExpr->isValueDependent()) 14694 return; 14695 14696 const Type *EffectiveType = 14697 BaseExpr->getType()->getPointeeOrArrayElementType(); 14698 BaseExpr = BaseExpr->IgnoreParenCasts(); 14699 const ConstantArrayType *ArrayTy = 14700 Context.getAsConstantArrayType(BaseExpr->getType()); 14701 14702 const Type *BaseType = 14703 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 14704 bool IsUnboundedArray = (BaseType == nullptr); 14705 if (EffectiveType->isDependentType() || 14706 (!IsUnboundedArray && BaseType->isDependentType())) 14707 return; 14708 14709 Expr::EvalResult Result; 14710 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14711 return; 14712 14713 llvm::APSInt index = Result.Val.getInt(); 14714 if (IndexNegated) { 14715 index.setIsUnsigned(false); 14716 index = -index; 14717 } 14718 14719 const NamedDecl *ND = nullptr; 14720 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14721 ND = DRE->getDecl(); 14722 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14723 ND = ME->getMemberDecl(); 14724 14725 if (IsUnboundedArray) { 14726 if (index.isUnsigned() || !index.isNegative()) { 14727 const auto &ASTC = getASTContext(); 14728 unsigned AddrBits = 14729 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 14730 EffectiveType->getCanonicalTypeInternal())); 14731 if (index.getBitWidth() < AddrBits) 14732 index = index.zext(AddrBits); 14733 Optional<CharUnits> ElemCharUnits = 14734 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 14735 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 14736 // pointer) bounds-checking isn't meaningful. 14737 if (!ElemCharUnits) 14738 return; 14739 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 14740 // If index has more active bits than address space, we already know 14741 // we have a bounds violation to warn about. Otherwise, compute 14742 // address of (index + 1)th element, and warn about bounds violation 14743 // only if that address exceeds address space. 14744 if (index.getActiveBits() <= AddrBits) { 14745 bool Overflow; 14746 llvm::APInt Product(index); 14747 Product += 1; 14748 Product = Product.umul_ov(ElemBytes, Overflow); 14749 if (!Overflow && Product.getActiveBits() <= AddrBits) 14750 return; 14751 } 14752 14753 // Need to compute max possible elements in address space, since that 14754 // is included in diag message. 14755 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 14756 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 14757 MaxElems += 1; 14758 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 14759 MaxElems = MaxElems.udiv(ElemBytes); 14760 14761 unsigned DiagID = 14762 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 14763 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 14764 14765 // Diag message shows element size in bits and in "bytes" (platform- 14766 // dependent CharUnits) 14767 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14768 PDiag(DiagID) 14769 << toString(index, 10, true) << AddrBits 14770 << (unsigned)ASTC.toBits(*ElemCharUnits) 14771 << toString(ElemBytes, 10, false) 14772 << toString(MaxElems, 10, false) 14773 << (unsigned)MaxElems.getLimitedValue(~0U) 14774 << IndexExpr->getSourceRange()); 14775 14776 if (!ND) { 14777 // Try harder to find a NamedDecl to point at in the note. 14778 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14779 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14780 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14781 ND = DRE->getDecl(); 14782 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14783 ND = ME->getMemberDecl(); 14784 } 14785 14786 if (ND) 14787 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14788 PDiag(diag::note_array_declared_here) << ND); 14789 } 14790 return; 14791 } 14792 14793 if (index.isUnsigned() || !index.isNegative()) { 14794 // It is possible that the type of the base expression after 14795 // IgnoreParenCasts is incomplete, even though the type of the base 14796 // expression before IgnoreParenCasts is complete (see PR39746 for an 14797 // example). In this case we have no information about whether the array 14798 // access exceeds the array bounds. However we can still diagnose an array 14799 // access which precedes the array bounds. 14800 if (BaseType->isIncompleteType()) 14801 return; 14802 14803 llvm::APInt size = ArrayTy->getSize(); 14804 if (!size.isStrictlyPositive()) 14805 return; 14806 14807 if (BaseType != EffectiveType) { 14808 // Make sure we're comparing apples to apples when comparing index to size 14809 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14810 uint64_t array_typesize = Context.getTypeSize(BaseType); 14811 // Handle ptrarith_typesize being zero, such as when casting to void* 14812 if (!ptrarith_typesize) ptrarith_typesize = 1; 14813 if (ptrarith_typesize != array_typesize) { 14814 // There's a cast to a different size type involved 14815 uint64_t ratio = array_typesize / ptrarith_typesize; 14816 // TODO: Be smarter about handling cases where array_typesize is not a 14817 // multiple of ptrarith_typesize 14818 if (ptrarith_typesize * ratio == array_typesize) 14819 size *= llvm::APInt(size.getBitWidth(), ratio); 14820 } 14821 } 14822 14823 if (size.getBitWidth() > index.getBitWidth()) 14824 index = index.zext(size.getBitWidth()); 14825 else if (size.getBitWidth() < index.getBitWidth()) 14826 size = size.zext(index.getBitWidth()); 14827 14828 // For array subscripting the index must be less than size, but for pointer 14829 // arithmetic also allow the index (offset) to be equal to size since 14830 // computing the next address after the end of the array is legal and 14831 // commonly done e.g. in C++ iterators and range-based for loops. 14832 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14833 return; 14834 14835 // Also don't warn for arrays of size 1 which are members of some 14836 // structure. These are often used to approximate flexible arrays in C89 14837 // code. 14838 if (IsTailPaddedMemberArray(*this, size, ND)) 14839 return; 14840 14841 // Suppress the warning if the subscript expression (as identified by the 14842 // ']' location) and the index expression are both from macro expansions 14843 // within a system header. 14844 if (ASE) { 14845 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14846 ASE->getRBracketLoc()); 14847 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14848 SourceLocation IndexLoc = 14849 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14850 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14851 return; 14852 } 14853 } 14854 14855 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 14856 : diag::warn_ptr_arith_exceeds_bounds; 14857 14858 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14859 PDiag(DiagID) << toString(index, 10, true) 14860 << toString(size, 10, true) 14861 << (unsigned)size.getLimitedValue(~0U) 14862 << IndexExpr->getSourceRange()); 14863 } else { 14864 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14865 if (!ASE) { 14866 DiagID = diag::warn_ptr_arith_precedes_bounds; 14867 if (index.isNegative()) index = -index; 14868 } 14869 14870 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14871 PDiag(DiagID) << toString(index, 10, true) 14872 << IndexExpr->getSourceRange()); 14873 } 14874 14875 if (!ND) { 14876 // Try harder to find a NamedDecl to point at in the note. 14877 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14878 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14879 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14880 ND = DRE->getDecl(); 14881 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14882 ND = ME->getMemberDecl(); 14883 } 14884 14885 if (ND) 14886 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14887 PDiag(diag::note_array_declared_here) << ND); 14888 } 14889 14890 void Sema::CheckArrayAccess(const Expr *expr) { 14891 int AllowOnePastEnd = 0; 14892 while (expr) { 14893 expr = expr->IgnoreParenImpCasts(); 14894 switch (expr->getStmtClass()) { 14895 case Stmt::ArraySubscriptExprClass: { 14896 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14897 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14898 AllowOnePastEnd > 0); 14899 expr = ASE->getBase(); 14900 break; 14901 } 14902 case Stmt::MemberExprClass: { 14903 expr = cast<MemberExpr>(expr)->getBase(); 14904 break; 14905 } 14906 case Stmt::OMPArraySectionExprClass: { 14907 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14908 if (ASE->getLowerBound()) 14909 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14910 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14911 return; 14912 } 14913 case Stmt::UnaryOperatorClass: { 14914 // Only unwrap the * and & unary operators 14915 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14916 expr = UO->getSubExpr(); 14917 switch (UO->getOpcode()) { 14918 case UO_AddrOf: 14919 AllowOnePastEnd++; 14920 break; 14921 case UO_Deref: 14922 AllowOnePastEnd--; 14923 break; 14924 default: 14925 return; 14926 } 14927 break; 14928 } 14929 case Stmt::ConditionalOperatorClass: { 14930 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14931 if (const Expr *lhs = cond->getLHS()) 14932 CheckArrayAccess(lhs); 14933 if (const Expr *rhs = cond->getRHS()) 14934 CheckArrayAccess(rhs); 14935 return; 14936 } 14937 case Stmt::CXXOperatorCallExprClass: { 14938 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14939 for (const auto *Arg : OCE->arguments()) 14940 CheckArrayAccess(Arg); 14941 return; 14942 } 14943 default: 14944 return; 14945 } 14946 } 14947 } 14948 14949 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14950 14951 namespace { 14952 14953 struct RetainCycleOwner { 14954 VarDecl *Variable = nullptr; 14955 SourceRange Range; 14956 SourceLocation Loc; 14957 bool Indirect = false; 14958 14959 RetainCycleOwner() = default; 14960 14961 void setLocsFrom(Expr *e) { 14962 Loc = e->getExprLoc(); 14963 Range = e->getSourceRange(); 14964 } 14965 }; 14966 14967 } // namespace 14968 14969 /// Consider whether capturing the given variable can possibly lead to 14970 /// a retain cycle. 14971 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14972 // In ARC, it's captured strongly iff the variable has __strong 14973 // lifetime. In MRR, it's captured strongly if the variable is 14974 // __block and has an appropriate type. 14975 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14976 return false; 14977 14978 owner.Variable = var; 14979 if (ref) 14980 owner.setLocsFrom(ref); 14981 return true; 14982 } 14983 14984 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14985 while (true) { 14986 e = e->IgnoreParens(); 14987 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14988 switch (cast->getCastKind()) { 14989 case CK_BitCast: 14990 case CK_LValueBitCast: 14991 case CK_LValueToRValue: 14992 case CK_ARCReclaimReturnedObject: 14993 e = cast->getSubExpr(); 14994 continue; 14995 14996 default: 14997 return false; 14998 } 14999 } 15000 15001 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15002 ObjCIvarDecl *ivar = ref->getDecl(); 15003 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15004 return false; 15005 15006 // Try to find a retain cycle in the base. 15007 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15008 return false; 15009 15010 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15011 owner.Indirect = true; 15012 return true; 15013 } 15014 15015 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15016 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15017 if (!var) return false; 15018 return considerVariable(var, ref, owner); 15019 } 15020 15021 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15022 if (member->isArrow()) return false; 15023 15024 // Don't count this as an indirect ownership. 15025 e = member->getBase(); 15026 continue; 15027 } 15028 15029 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15030 // Only pay attention to pseudo-objects on property references. 15031 ObjCPropertyRefExpr *pre 15032 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15033 ->IgnoreParens()); 15034 if (!pre) return false; 15035 if (pre->isImplicitProperty()) return false; 15036 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15037 if (!property->isRetaining() && 15038 !(property->getPropertyIvarDecl() && 15039 property->getPropertyIvarDecl()->getType() 15040 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15041 return false; 15042 15043 owner.Indirect = true; 15044 if (pre->isSuperReceiver()) { 15045 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15046 if (!owner.Variable) 15047 return false; 15048 owner.Loc = pre->getLocation(); 15049 owner.Range = pre->getSourceRange(); 15050 return true; 15051 } 15052 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15053 ->getSourceExpr()); 15054 continue; 15055 } 15056 15057 // Array ivars? 15058 15059 return false; 15060 } 15061 } 15062 15063 namespace { 15064 15065 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15066 ASTContext &Context; 15067 VarDecl *Variable; 15068 Expr *Capturer = nullptr; 15069 bool VarWillBeReased = false; 15070 15071 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15072 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15073 Context(Context), Variable(variable) {} 15074 15075 void VisitDeclRefExpr(DeclRefExpr *ref) { 15076 if (ref->getDecl() == Variable && !Capturer) 15077 Capturer = ref; 15078 } 15079 15080 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15081 if (Capturer) return; 15082 Visit(ref->getBase()); 15083 if (Capturer && ref->isFreeIvar()) 15084 Capturer = ref; 15085 } 15086 15087 void VisitBlockExpr(BlockExpr *block) { 15088 // Look inside nested blocks 15089 if (block->getBlockDecl()->capturesVariable(Variable)) 15090 Visit(block->getBlockDecl()->getBody()); 15091 } 15092 15093 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15094 if (Capturer) return; 15095 if (OVE->getSourceExpr()) 15096 Visit(OVE->getSourceExpr()); 15097 } 15098 15099 void VisitBinaryOperator(BinaryOperator *BinOp) { 15100 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15101 return; 15102 Expr *LHS = BinOp->getLHS(); 15103 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15104 if (DRE->getDecl() != Variable) 15105 return; 15106 if (Expr *RHS = BinOp->getRHS()) { 15107 RHS = RHS->IgnoreParenCasts(); 15108 Optional<llvm::APSInt> Value; 15109 VarWillBeReased = 15110 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15111 *Value == 0); 15112 } 15113 } 15114 } 15115 }; 15116 15117 } // namespace 15118 15119 /// Check whether the given argument is a block which captures a 15120 /// variable. 15121 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15122 assert(owner.Variable && owner.Loc.isValid()); 15123 15124 e = e->IgnoreParenCasts(); 15125 15126 // Look through [^{...} copy] and Block_copy(^{...}). 15127 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15128 Selector Cmd = ME->getSelector(); 15129 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15130 e = ME->getInstanceReceiver(); 15131 if (!e) 15132 return nullptr; 15133 e = e->IgnoreParenCasts(); 15134 } 15135 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15136 if (CE->getNumArgs() == 1) { 15137 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15138 if (Fn) { 15139 const IdentifierInfo *FnI = Fn->getIdentifier(); 15140 if (FnI && FnI->isStr("_Block_copy")) { 15141 e = CE->getArg(0)->IgnoreParenCasts(); 15142 } 15143 } 15144 } 15145 } 15146 15147 BlockExpr *block = dyn_cast<BlockExpr>(e); 15148 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15149 return nullptr; 15150 15151 FindCaptureVisitor visitor(S.Context, owner.Variable); 15152 visitor.Visit(block->getBlockDecl()->getBody()); 15153 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15154 } 15155 15156 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15157 RetainCycleOwner &owner) { 15158 assert(capturer); 15159 assert(owner.Variable && owner.Loc.isValid()); 15160 15161 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15162 << owner.Variable << capturer->getSourceRange(); 15163 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15164 << owner.Indirect << owner.Range; 15165 } 15166 15167 /// Check for a keyword selector that starts with the word 'add' or 15168 /// 'set'. 15169 static bool isSetterLikeSelector(Selector sel) { 15170 if (sel.isUnarySelector()) return false; 15171 15172 StringRef str = sel.getNameForSlot(0); 15173 while (!str.empty() && str.front() == '_') str = str.substr(1); 15174 if (str.startswith("set")) 15175 str = str.substr(3); 15176 else if (str.startswith("add")) { 15177 // Specially allow 'addOperationWithBlock:'. 15178 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15179 return false; 15180 str = str.substr(3); 15181 } 15182 else 15183 return false; 15184 15185 if (str.empty()) return true; 15186 return !isLowercase(str.front()); 15187 } 15188 15189 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15190 ObjCMessageExpr *Message) { 15191 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15192 Message->getReceiverInterface(), 15193 NSAPI::ClassId_NSMutableArray); 15194 if (!IsMutableArray) { 15195 return None; 15196 } 15197 15198 Selector Sel = Message->getSelector(); 15199 15200 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15201 S.NSAPIObj->getNSArrayMethodKind(Sel); 15202 if (!MKOpt) { 15203 return None; 15204 } 15205 15206 NSAPI::NSArrayMethodKind MK = *MKOpt; 15207 15208 switch (MK) { 15209 case NSAPI::NSMutableArr_addObject: 15210 case NSAPI::NSMutableArr_insertObjectAtIndex: 15211 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15212 return 0; 15213 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15214 return 1; 15215 15216 default: 15217 return None; 15218 } 15219 15220 return None; 15221 } 15222 15223 static 15224 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15225 ObjCMessageExpr *Message) { 15226 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15227 Message->getReceiverInterface(), 15228 NSAPI::ClassId_NSMutableDictionary); 15229 if (!IsMutableDictionary) { 15230 return None; 15231 } 15232 15233 Selector Sel = Message->getSelector(); 15234 15235 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15236 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15237 if (!MKOpt) { 15238 return None; 15239 } 15240 15241 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15242 15243 switch (MK) { 15244 case NSAPI::NSMutableDict_setObjectForKey: 15245 case NSAPI::NSMutableDict_setValueForKey: 15246 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15247 return 0; 15248 15249 default: 15250 return None; 15251 } 15252 15253 return None; 15254 } 15255 15256 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15257 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15258 Message->getReceiverInterface(), 15259 NSAPI::ClassId_NSMutableSet); 15260 15261 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15262 Message->getReceiverInterface(), 15263 NSAPI::ClassId_NSMutableOrderedSet); 15264 if (!IsMutableSet && !IsMutableOrderedSet) { 15265 return None; 15266 } 15267 15268 Selector Sel = Message->getSelector(); 15269 15270 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15271 if (!MKOpt) { 15272 return None; 15273 } 15274 15275 NSAPI::NSSetMethodKind MK = *MKOpt; 15276 15277 switch (MK) { 15278 case NSAPI::NSMutableSet_addObject: 15279 case NSAPI::NSOrderedSet_setObjectAtIndex: 15280 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15281 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15282 return 0; 15283 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15284 return 1; 15285 } 15286 15287 return None; 15288 } 15289 15290 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15291 if (!Message->isInstanceMessage()) { 15292 return; 15293 } 15294 15295 Optional<int> ArgOpt; 15296 15297 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15298 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15299 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15300 return; 15301 } 15302 15303 int ArgIndex = *ArgOpt; 15304 15305 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15306 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15307 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15308 } 15309 15310 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15311 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15312 if (ArgRE->isObjCSelfExpr()) { 15313 Diag(Message->getSourceRange().getBegin(), 15314 diag::warn_objc_circular_container) 15315 << ArgRE->getDecl() << StringRef("'super'"); 15316 } 15317 } 15318 } else { 15319 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15320 15321 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15322 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15323 } 15324 15325 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15326 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15327 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15328 ValueDecl *Decl = ReceiverRE->getDecl(); 15329 Diag(Message->getSourceRange().getBegin(), 15330 diag::warn_objc_circular_container) 15331 << Decl << Decl; 15332 if (!ArgRE->isObjCSelfExpr()) { 15333 Diag(Decl->getLocation(), 15334 diag::note_objc_circular_container_declared_here) 15335 << Decl; 15336 } 15337 } 15338 } 15339 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15340 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15341 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15342 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15343 Diag(Message->getSourceRange().getBegin(), 15344 diag::warn_objc_circular_container) 15345 << Decl << Decl; 15346 Diag(Decl->getLocation(), 15347 diag::note_objc_circular_container_declared_here) 15348 << Decl; 15349 } 15350 } 15351 } 15352 } 15353 } 15354 15355 /// Check a message send to see if it's likely to cause a retain cycle. 15356 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15357 // Only check instance methods whose selector looks like a setter. 15358 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15359 return; 15360 15361 // Try to find a variable that the receiver is strongly owned by. 15362 RetainCycleOwner owner; 15363 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15364 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15365 return; 15366 } else { 15367 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15368 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15369 owner.Loc = msg->getSuperLoc(); 15370 owner.Range = msg->getSuperLoc(); 15371 } 15372 15373 // Check whether the receiver is captured by any of the arguments. 15374 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15375 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15376 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15377 // noescape blocks should not be retained by the method. 15378 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15379 continue; 15380 return diagnoseRetainCycle(*this, capturer, owner); 15381 } 15382 } 15383 } 15384 15385 /// Check a property assign to see if it's likely to cause a retain cycle. 15386 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15387 RetainCycleOwner owner; 15388 if (!findRetainCycleOwner(*this, receiver, owner)) 15389 return; 15390 15391 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15392 diagnoseRetainCycle(*this, capturer, owner); 15393 } 15394 15395 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15396 RetainCycleOwner Owner; 15397 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15398 return; 15399 15400 // Because we don't have an expression for the variable, we have to set the 15401 // location explicitly here. 15402 Owner.Loc = Var->getLocation(); 15403 Owner.Range = Var->getSourceRange(); 15404 15405 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15406 diagnoseRetainCycle(*this, Capturer, Owner); 15407 } 15408 15409 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15410 Expr *RHS, bool isProperty) { 15411 // Check if RHS is an Objective-C object literal, which also can get 15412 // immediately zapped in a weak reference. Note that we explicitly 15413 // allow ObjCStringLiterals, since those are designed to never really die. 15414 RHS = RHS->IgnoreParenImpCasts(); 15415 15416 // This enum needs to match with the 'select' in 15417 // warn_objc_arc_literal_assign (off-by-1). 15418 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15419 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15420 return false; 15421 15422 S.Diag(Loc, diag::warn_arc_literal_assign) 15423 << (unsigned) Kind 15424 << (isProperty ? 0 : 1) 15425 << RHS->getSourceRange(); 15426 15427 return true; 15428 } 15429 15430 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15431 Qualifiers::ObjCLifetime LT, 15432 Expr *RHS, bool isProperty) { 15433 // Strip off any implicit cast added to get to the one ARC-specific. 15434 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15435 if (cast->getCastKind() == CK_ARCConsumeObject) { 15436 S.Diag(Loc, diag::warn_arc_retained_assign) 15437 << (LT == Qualifiers::OCL_ExplicitNone) 15438 << (isProperty ? 0 : 1) 15439 << RHS->getSourceRange(); 15440 return true; 15441 } 15442 RHS = cast->getSubExpr(); 15443 } 15444 15445 if (LT == Qualifiers::OCL_Weak && 15446 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15447 return true; 15448 15449 return false; 15450 } 15451 15452 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15453 QualType LHS, Expr *RHS) { 15454 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15455 15456 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15457 return false; 15458 15459 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15460 return true; 15461 15462 return false; 15463 } 15464 15465 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15466 Expr *LHS, Expr *RHS) { 15467 QualType LHSType; 15468 // PropertyRef on LHS type need be directly obtained from 15469 // its declaration as it has a PseudoType. 15470 ObjCPropertyRefExpr *PRE 15471 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15472 if (PRE && !PRE->isImplicitProperty()) { 15473 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15474 if (PD) 15475 LHSType = PD->getType(); 15476 } 15477 15478 if (LHSType.isNull()) 15479 LHSType = LHS->getType(); 15480 15481 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15482 15483 if (LT == Qualifiers::OCL_Weak) { 15484 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15485 getCurFunction()->markSafeWeakUse(LHS); 15486 } 15487 15488 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15489 return; 15490 15491 // FIXME. Check for other life times. 15492 if (LT != Qualifiers::OCL_None) 15493 return; 15494 15495 if (PRE) { 15496 if (PRE->isImplicitProperty()) 15497 return; 15498 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15499 if (!PD) 15500 return; 15501 15502 unsigned Attributes = PD->getPropertyAttributes(); 15503 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15504 // when 'assign' attribute was not explicitly specified 15505 // by user, ignore it and rely on property type itself 15506 // for lifetime info. 15507 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15508 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15509 LHSType->isObjCRetainableType()) 15510 return; 15511 15512 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15513 if (cast->getCastKind() == CK_ARCConsumeObject) { 15514 Diag(Loc, diag::warn_arc_retained_property_assign) 15515 << RHS->getSourceRange(); 15516 return; 15517 } 15518 RHS = cast->getSubExpr(); 15519 } 15520 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15521 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15522 return; 15523 } 15524 } 15525 } 15526 15527 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15528 15529 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15530 SourceLocation StmtLoc, 15531 const NullStmt *Body) { 15532 // Do not warn if the body is a macro that expands to nothing, e.g: 15533 // 15534 // #define CALL(x) 15535 // if (condition) 15536 // CALL(0); 15537 if (Body->hasLeadingEmptyMacro()) 15538 return false; 15539 15540 // Get line numbers of statement and body. 15541 bool StmtLineInvalid; 15542 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15543 &StmtLineInvalid); 15544 if (StmtLineInvalid) 15545 return false; 15546 15547 bool BodyLineInvalid; 15548 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15549 &BodyLineInvalid); 15550 if (BodyLineInvalid) 15551 return false; 15552 15553 // Warn if null statement and body are on the same line. 15554 if (StmtLine != BodyLine) 15555 return false; 15556 15557 return true; 15558 } 15559 15560 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15561 const Stmt *Body, 15562 unsigned DiagID) { 15563 // Since this is a syntactic check, don't emit diagnostic for template 15564 // instantiations, this just adds noise. 15565 if (CurrentInstantiationScope) 15566 return; 15567 15568 // The body should be a null statement. 15569 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15570 if (!NBody) 15571 return; 15572 15573 // Do the usual checks. 15574 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15575 return; 15576 15577 Diag(NBody->getSemiLoc(), DiagID); 15578 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15579 } 15580 15581 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15582 const Stmt *PossibleBody) { 15583 assert(!CurrentInstantiationScope); // Ensured by caller 15584 15585 SourceLocation StmtLoc; 15586 const Stmt *Body; 15587 unsigned DiagID; 15588 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15589 StmtLoc = FS->getRParenLoc(); 15590 Body = FS->getBody(); 15591 DiagID = diag::warn_empty_for_body; 15592 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15593 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15594 Body = WS->getBody(); 15595 DiagID = diag::warn_empty_while_body; 15596 } else 15597 return; // Neither `for' nor `while'. 15598 15599 // The body should be a null statement. 15600 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15601 if (!NBody) 15602 return; 15603 15604 // Skip expensive checks if diagnostic is disabled. 15605 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15606 return; 15607 15608 // Do the usual checks. 15609 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15610 return; 15611 15612 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15613 // noise level low, emit diagnostics only if for/while is followed by a 15614 // CompoundStmt, e.g.: 15615 // for (int i = 0; i < n; i++); 15616 // { 15617 // a(i); 15618 // } 15619 // or if for/while is followed by a statement with more indentation 15620 // than for/while itself: 15621 // for (int i = 0; i < n; i++); 15622 // a(i); 15623 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15624 if (!ProbableTypo) { 15625 bool BodyColInvalid; 15626 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15627 PossibleBody->getBeginLoc(), &BodyColInvalid); 15628 if (BodyColInvalid) 15629 return; 15630 15631 bool StmtColInvalid; 15632 unsigned StmtCol = 15633 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15634 if (StmtColInvalid) 15635 return; 15636 15637 if (BodyCol > StmtCol) 15638 ProbableTypo = true; 15639 } 15640 15641 if (ProbableTypo) { 15642 Diag(NBody->getSemiLoc(), DiagID); 15643 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15644 } 15645 } 15646 15647 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15648 15649 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15650 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15651 SourceLocation OpLoc) { 15652 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15653 return; 15654 15655 if (inTemplateInstantiation()) 15656 return; 15657 15658 // Strip parens and casts away. 15659 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15660 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15661 15662 // Check for a call expression 15663 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15664 if (!CE || CE->getNumArgs() != 1) 15665 return; 15666 15667 // Check for a call to std::move 15668 if (!CE->isCallToStdMove()) 15669 return; 15670 15671 // Get argument from std::move 15672 RHSExpr = CE->getArg(0); 15673 15674 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15675 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15676 15677 // Two DeclRefExpr's, check that the decls are the same. 15678 if (LHSDeclRef && RHSDeclRef) { 15679 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15680 return; 15681 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15682 RHSDeclRef->getDecl()->getCanonicalDecl()) 15683 return; 15684 15685 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15686 << LHSExpr->getSourceRange() 15687 << RHSExpr->getSourceRange(); 15688 return; 15689 } 15690 15691 // Member variables require a different approach to check for self moves. 15692 // MemberExpr's are the same if every nested MemberExpr refers to the same 15693 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15694 // the base Expr's are CXXThisExpr's. 15695 const Expr *LHSBase = LHSExpr; 15696 const Expr *RHSBase = RHSExpr; 15697 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15698 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15699 if (!LHSME || !RHSME) 15700 return; 15701 15702 while (LHSME && RHSME) { 15703 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15704 RHSME->getMemberDecl()->getCanonicalDecl()) 15705 return; 15706 15707 LHSBase = LHSME->getBase(); 15708 RHSBase = RHSME->getBase(); 15709 LHSME = dyn_cast<MemberExpr>(LHSBase); 15710 RHSME = dyn_cast<MemberExpr>(RHSBase); 15711 } 15712 15713 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15714 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15715 if (LHSDeclRef && RHSDeclRef) { 15716 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15717 return; 15718 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15719 RHSDeclRef->getDecl()->getCanonicalDecl()) 15720 return; 15721 15722 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15723 << LHSExpr->getSourceRange() 15724 << RHSExpr->getSourceRange(); 15725 return; 15726 } 15727 15728 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15729 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15730 << LHSExpr->getSourceRange() 15731 << RHSExpr->getSourceRange(); 15732 } 15733 15734 //===--- Layout compatibility ----------------------------------------------// 15735 15736 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15737 15738 /// Check if two enumeration types are layout-compatible. 15739 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15740 // C++11 [dcl.enum] p8: 15741 // Two enumeration types are layout-compatible if they have the same 15742 // underlying type. 15743 return ED1->isComplete() && ED2->isComplete() && 15744 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15745 } 15746 15747 /// Check if two fields are layout-compatible. 15748 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15749 FieldDecl *Field2) { 15750 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15751 return false; 15752 15753 if (Field1->isBitField() != Field2->isBitField()) 15754 return false; 15755 15756 if (Field1->isBitField()) { 15757 // Make sure that the bit-fields are the same length. 15758 unsigned Bits1 = Field1->getBitWidthValue(C); 15759 unsigned Bits2 = Field2->getBitWidthValue(C); 15760 15761 if (Bits1 != Bits2) 15762 return false; 15763 } 15764 15765 return true; 15766 } 15767 15768 /// Check if two standard-layout structs are layout-compatible. 15769 /// (C++11 [class.mem] p17) 15770 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15771 RecordDecl *RD2) { 15772 // If both records are C++ classes, check that base classes match. 15773 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15774 // If one of records is a CXXRecordDecl we are in C++ mode, 15775 // thus the other one is a CXXRecordDecl, too. 15776 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15777 // Check number of base classes. 15778 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15779 return false; 15780 15781 // Check the base classes. 15782 for (CXXRecordDecl::base_class_const_iterator 15783 Base1 = D1CXX->bases_begin(), 15784 BaseEnd1 = D1CXX->bases_end(), 15785 Base2 = D2CXX->bases_begin(); 15786 Base1 != BaseEnd1; 15787 ++Base1, ++Base2) { 15788 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15789 return false; 15790 } 15791 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15792 // If only RD2 is a C++ class, it should have zero base classes. 15793 if (D2CXX->getNumBases() > 0) 15794 return false; 15795 } 15796 15797 // Check the fields. 15798 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15799 Field2End = RD2->field_end(), 15800 Field1 = RD1->field_begin(), 15801 Field1End = RD1->field_end(); 15802 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15803 if (!isLayoutCompatible(C, *Field1, *Field2)) 15804 return false; 15805 } 15806 if (Field1 != Field1End || Field2 != Field2End) 15807 return false; 15808 15809 return true; 15810 } 15811 15812 /// Check if two standard-layout unions are layout-compatible. 15813 /// (C++11 [class.mem] p18) 15814 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15815 RecordDecl *RD2) { 15816 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15817 for (auto *Field2 : RD2->fields()) 15818 UnmatchedFields.insert(Field2); 15819 15820 for (auto *Field1 : RD1->fields()) { 15821 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15822 I = UnmatchedFields.begin(), 15823 E = UnmatchedFields.end(); 15824 15825 for ( ; I != E; ++I) { 15826 if (isLayoutCompatible(C, Field1, *I)) { 15827 bool Result = UnmatchedFields.erase(*I); 15828 (void) Result; 15829 assert(Result); 15830 break; 15831 } 15832 } 15833 if (I == E) 15834 return false; 15835 } 15836 15837 return UnmatchedFields.empty(); 15838 } 15839 15840 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15841 RecordDecl *RD2) { 15842 if (RD1->isUnion() != RD2->isUnion()) 15843 return false; 15844 15845 if (RD1->isUnion()) 15846 return isLayoutCompatibleUnion(C, RD1, RD2); 15847 else 15848 return isLayoutCompatibleStruct(C, RD1, RD2); 15849 } 15850 15851 /// Check if two types are layout-compatible in C++11 sense. 15852 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15853 if (T1.isNull() || T2.isNull()) 15854 return false; 15855 15856 // C++11 [basic.types] p11: 15857 // If two types T1 and T2 are the same type, then T1 and T2 are 15858 // layout-compatible types. 15859 if (C.hasSameType(T1, T2)) 15860 return true; 15861 15862 T1 = T1.getCanonicalType().getUnqualifiedType(); 15863 T2 = T2.getCanonicalType().getUnqualifiedType(); 15864 15865 const Type::TypeClass TC1 = T1->getTypeClass(); 15866 const Type::TypeClass TC2 = T2->getTypeClass(); 15867 15868 if (TC1 != TC2) 15869 return false; 15870 15871 if (TC1 == Type::Enum) { 15872 return isLayoutCompatible(C, 15873 cast<EnumType>(T1)->getDecl(), 15874 cast<EnumType>(T2)->getDecl()); 15875 } else if (TC1 == Type::Record) { 15876 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15877 return false; 15878 15879 return isLayoutCompatible(C, 15880 cast<RecordType>(T1)->getDecl(), 15881 cast<RecordType>(T2)->getDecl()); 15882 } 15883 15884 return false; 15885 } 15886 15887 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15888 15889 /// Given a type tag expression find the type tag itself. 15890 /// 15891 /// \param TypeExpr Type tag expression, as it appears in user's code. 15892 /// 15893 /// \param VD Declaration of an identifier that appears in a type tag. 15894 /// 15895 /// \param MagicValue Type tag magic value. 15896 /// 15897 /// \param isConstantEvaluated wether the evalaution should be performed in 15898 15899 /// constant context. 15900 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15901 const ValueDecl **VD, uint64_t *MagicValue, 15902 bool isConstantEvaluated) { 15903 while(true) { 15904 if (!TypeExpr) 15905 return false; 15906 15907 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15908 15909 switch (TypeExpr->getStmtClass()) { 15910 case Stmt::UnaryOperatorClass: { 15911 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15912 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15913 TypeExpr = UO->getSubExpr(); 15914 continue; 15915 } 15916 return false; 15917 } 15918 15919 case Stmt::DeclRefExprClass: { 15920 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15921 *VD = DRE->getDecl(); 15922 return true; 15923 } 15924 15925 case Stmt::IntegerLiteralClass: { 15926 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15927 llvm::APInt MagicValueAPInt = IL->getValue(); 15928 if (MagicValueAPInt.getActiveBits() <= 64) { 15929 *MagicValue = MagicValueAPInt.getZExtValue(); 15930 return true; 15931 } else 15932 return false; 15933 } 15934 15935 case Stmt::BinaryConditionalOperatorClass: 15936 case Stmt::ConditionalOperatorClass: { 15937 const AbstractConditionalOperator *ACO = 15938 cast<AbstractConditionalOperator>(TypeExpr); 15939 bool Result; 15940 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15941 isConstantEvaluated)) { 15942 if (Result) 15943 TypeExpr = ACO->getTrueExpr(); 15944 else 15945 TypeExpr = ACO->getFalseExpr(); 15946 continue; 15947 } 15948 return false; 15949 } 15950 15951 case Stmt::BinaryOperatorClass: { 15952 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15953 if (BO->getOpcode() == BO_Comma) { 15954 TypeExpr = BO->getRHS(); 15955 continue; 15956 } 15957 return false; 15958 } 15959 15960 default: 15961 return false; 15962 } 15963 } 15964 } 15965 15966 /// Retrieve the C type corresponding to type tag TypeExpr. 15967 /// 15968 /// \param TypeExpr Expression that specifies a type tag. 15969 /// 15970 /// \param MagicValues Registered magic values. 15971 /// 15972 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15973 /// kind. 15974 /// 15975 /// \param TypeInfo Information about the corresponding C type. 15976 /// 15977 /// \param isConstantEvaluated wether the evalaution should be performed in 15978 /// constant context. 15979 /// 15980 /// \returns true if the corresponding C type was found. 15981 static bool GetMatchingCType( 15982 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15983 const ASTContext &Ctx, 15984 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15985 *MagicValues, 15986 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15987 bool isConstantEvaluated) { 15988 FoundWrongKind = false; 15989 15990 // Variable declaration that has type_tag_for_datatype attribute. 15991 const ValueDecl *VD = nullptr; 15992 15993 uint64_t MagicValue; 15994 15995 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15996 return false; 15997 15998 if (VD) { 15999 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16000 if (I->getArgumentKind() != ArgumentKind) { 16001 FoundWrongKind = true; 16002 return false; 16003 } 16004 TypeInfo.Type = I->getMatchingCType(); 16005 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16006 TypeInfo.MustBeNull = I->getMustBeNull(); 16007 return true; 16008 } 16009 return false; 16010 } 16011 16012 if (!MagicValues) 16013 return false; 16014 16015 llvm::DenseMap<Sema::TypeTagMagicValue, 16016 Sema::TypeTagData>::const_iterator I = 16017 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16018 if (I == MagicValues->end()) 16019 return false; 16020 16021 TypeInfo = I->second; 16022 return true; 16023 } 16024 16025 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16026 uint64_t MagicValue, QualType Type, 16027 bool LayoutCompatible, 16028 bool MustBeNull) { 16029 if (!TypeTagForDatatypeMagicValues) 16030 TypeTagForDatatypeMagicValues.reset( 16031 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16032 16033 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16034 (*TypeTagForDatatypeMagicValues)[Magic] = 16035 TypeTagData(Type, LayoutCompatible, MustBeNull); 16036 } 16037 16038 static bool IsSameCharType(QualType T1, QualType T2) { 16039 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16040 if (!BT1) 16041 return false; 16042 16043 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16044 if (!BT2) 16045 return false; 16046 16047 BuiltinType::Kind T1Kind = BT1->getKind(); 16048 BuiltinType::Kind T2Kind = BT2->getKind(); 16049 16050 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16051 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16052 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16053 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16054 } 16055 16056 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16057 const ArrayRef<const Expr *> ExprArgs, 16058 SourceLocation CallSiteLoc) { 16059 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16060 bool IsPointerAttr = Attr->getIsPointer(); 16061 16062 // Retrieve the argument representing the 'type_tag'. 16063 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16064 if (TypeTagIdxAST >= ExprArgs.size()) { 16065 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16066 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16067 return; 16068 } 16069 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16070 bool FoundWrongKind; 16071 TypeTagData TypeInfo; 16072 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16073 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16074 TypeInfo, isConstantEvaluated())) { 16075 if (FoundWrongKind) 16076 Diag(TypeTagExpr->getExprLoc(), 16077 diag::warn_type_tag_for_datatype_wrong_kind) 16078 << TypeTagExpr->getSourceRange(); 16079 return; 16080 } 16081 16082 // Retrieve the argument representing the 'arg_idx'. 16083 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16084 if (ArgumentIdxAST >= ExprArgs.size()) { 16085 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16086 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16087 return; 16088 } 16089 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16090 if (IsPointerAttr) { 16091 // Skip implicit cast of pointer to `void *' (as a function argument). 16092 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16093 if (ICE->getType()->isVoidPointerType() && 16094 ICE->getCastKind() == CK_BitCast) 16095 ArgumentExpr = ICE->getSubExpr(); 16096 } 16097 QualType ArgumentType = ArgumentExpr->getType(); 16098 16099 // Passing a `void*' pointer shouldn't trigger a warning. 16100 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16101 return; 16102 16103 if (TypeInfo.MustBeNull) { 16104 // Type tag with matching void type requires a null pointer. 16105 if (!ArgumentExpr->isNullPointerConstant(Context, 16106 Expr::NPC_ValueDependentIsNotNull)) { 16107 Diag(ArgumentExpr->getExprLoc(), 16108 diag::warn_type_safety_null_pointer_required) 16109 << ArgumentKind->getName() 16110 << ArgumentExpr->getSourceRange() 16111 << TypeTagExpr->getSourceRange(); 16112 } 16113 return; 16114 } 16115 16116 QualType RequiredType = TypeInfo.Type; 16117 if (IsPointerAttr) 16118 RequiredType = Context.getPointerType(RequiredType); 16119 16120 bool mismatch = false; 16121 if (!TypeInfo.LayoutCompatible) { 16122 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16123 16124 // C++11 [basic.fundamental] p1: 16125 // Plain char, signed char, and unsigned char are three distinct types. 16126 // 16127 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16128 // char' depending on the current char signedness mode. 16129 if (mismatch) 16130 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16131 RequiredType->getPointeeType())) || 16132 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16133 mismatch = false; 16134 } else 16135 if (IsPointerAttr) 16136 mismatch = !isLayoutCompatible(Context, 16137 ArgumentType->getPointeeType(), 16138 RequiredType->getPointeeType()); 16139 else 16140 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16141 16142 if (mismatch) 16143 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16144 << ArgumentType << ArgumentKind 16145 << TypeInfo.LayoutCompatible << RequiredType 16146 << ArgumentExpr->getSourceRange() 16147 << TypeTagExpr->getSourceRange(); 16148 } 16149 16150 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16151 CharUnits Alignment) { 16152 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16153 } 16154 16155 void Sema::DiagnoseMisalignedMembers() { 16156 for (MisalignedMember &m : MisalignedMembers) { 16157 const NamedDecl *ND = m.RD; 16158 if (ND->getName().empty()) { 16159 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16160 ND = TD; 16161 } 16162 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16163 << m.MD << ND << m.E->getSourceRange(); 16164 } 16165 MisalignedMembers.clear(); 16166 } 16167 16168 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16169 E = E->IgnoreParens(); 16170 if (!T->isPointerType() && !T->isIntegerType()) 16171 return; 16172 if (isa<UnaryOperator>(E) && 16173 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16174 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16175 if (isa<MemberExpr>(Op)) { 16176 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16177 if (MA != MisalignedMembers.end() && 16178 (T->isIntegerType() || 16179 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16180 Context.getTypeAlignInChars( 16181 T->getPointeeType()) <= MA->Alignment)))) 16182 MisalignedMembers.erase(MA); 16183 } 16184 } 16185 } 16186 16187 void Sema::RefersToMemberWithReducedAlignment( 16188 Expr *E, 16189 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16190 Action) { 16191 const auto *ME = dyn_cast<MemberExpr>(E); 16192 if (!ME) 16193 return; 16194 16195 // No need to check expressions with an __unaligned-qualified type. 16196 if (E->getType().getQualifiers().hasUnaligned()) 16197 return; 16198 16199 // For a chain of MemberExpr like "a.b.c.d" this list 16200 // will keep FieldDecl's like [d, c, b]. 16201 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16202 const MemberExpr *TopME = nullptr; 16203 bool AnyIsPacked = false; 16204 do { 16205 QualType BaseType = ME->getBase()->getType(); 16206 if (BaseType->isDependentType()) 16207 return; 16208 if (ME->isArrow()) 16209 BaseType = BaseType->getPointeeType(); 16210 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16211 if (RD->isInvalidDecl()) 16212 return; 16213 16214 ValueDecl *MD = ME->getMemberDecl(); 16215 auto *FD = dyn_cast<FieldDecl>(MD); 16216 // We do not care about non-data members. 16217 if (!FD || FD->isInvalidDecl()) 16218 return; 16219 16220 AnyIsPacked = 16221 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16222 ReverseMemberChain.push_back(FD); 16223 16224 TopME = ME; 16225 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16226 } while (ME); 16227 assert(TopME && "We did not compute a topmost MemberExpr!"); 16228 16229 // Not the scope of this diagnostic. 16230 if (!AnyIsPacked) 16231 return; 16232 16233 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16234 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16235 // TODO: The innermost base of the member expression may be too complicated. 16236 // For now, just disregard these cases. This is left for future 16237 // improvement. 16238 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16239 return; 16240 16241 // Alignment expected by the whole expression. 16242 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16243 16244 // No need to do anything else with this case. 16245 if (ExpectedAlignment.isOne()) 16246 return; 16247 16248 // Synthesize offset of the whole access. 16249 CharUnits Offset; 16250 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16251 I++) { 16252 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16253 } 16254 16255 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16256 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16257 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16258 16259 // The base expression of the innermost MemberExpr may give 16260 // stronger guarantees than the class containing the member. 16261 if (DRE && !TopME->isArrow()) { 16262 const ValueDecl *VD = DRE->getDecl(); 16263 if (!VD->getType()->isReferenceType()) 16264 CompleteObjectAlignment = 16265 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16266 } 16267 16268 // Check if the synthesized offset fulfills the alignment. 16269 if (Offset % ExpectedAlignment != 0 || 16270 // It may fulfill the offset it but the effective alignment may still be 16271 // lower than the expected expression alignment. 16272 CompleteObjectAlignment < ExpectedAlignment) { 16273 // If this happens, we want to determine a sensible culprit of this. 16274 // Intuitively, watching the chain of member expressions from right to 16275 // left, we start with the required alignment (as required by the field 16276 // type) but some packed attribute in that chain has reduced the alignment. 16277 // It may happen that another packed structure increases it again. But if 16278 // we are here such increase has not been enough. So pointing the first 16279 // FieldDecl that either is packed or else its RecordDecl is, 16280 // seems reasonable. 16281 FieldDecl *FD = nullptr; 16282 CharUnits Alignment; 16283 for (FieldDecl *FDI : ReverseMemberChain) { 16284 if (FDI->hasAttr<PackedAttr>() || 16285 FDI->getParent()->hasAttr<PackedAttr>()) { 16286 FD = FDI; 16287 Alignment = std::min( 16288 Context.getTypeAlignInChars(FD->getType()), 16289 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16290 break; 16291 } 16292 } 16293 assert(FD && "We did not find a packed FieldDecl!"); 16294 Action(E, FD->getParent(), FD, Alignment); 16295 } 16296 } 16297 16298 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16299 using namespace std::placeholders; 16300 16301 RefersToMemberWithReducedAlignment( 16302 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16303 _2, _3, _4)); 16304 } 16305 16306 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16307 ExprResult CallResult) { 16308 if (checkArgCount(*this, TheCall, 1)) 16309 return ExprError(); 16310 16311 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16312 if (MatrixArg.isInvalid()) 16313 return MatrixArg; 16314 Expr *Matrix = MatrixArg.get(); 16315 16316 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16317 if (!MType) { 16318 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16319 return ExprError(); 16320 } 16321 16322 // Create returned matrix type by swapping rows and columns of the argument 16323 // matrix type. 16324 QualType ResultType = Context.getConstantMatrixType( 16325 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16326 16327 // Change the return type to the type of the returned matrix. 16328 TheCall->setType(ResultType); 16329 16330 // Update call argument to use the possibly converted matrix argument. 16331 TheCall->setArg(0, Matrix); 16332 return CallResult; 16333 } 16334 16335 // Get and verify the matrix dimensions. 16336 static llvm::Optional<unsigned> 16337 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16338 SourceLocation ErrorPos; 16339 Optional<llvm::APSInt> Value = 16340 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16341 if (!Value) { 16342 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16343 << Name; 16344 return {}; 16345 } 16346 uint64_t Dim = Value->getZExtValue(); 16347 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16348 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16349 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16350 return {}; 16351 } 16352 return Dim; 16353 } 16354 16355 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16356 ExprResult CallResult) { 16357 if (!getLangOpts().MatrixTypes) { 16358 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16359 return ExprError(); 16360 } 16361 16362 if (checkArgCount(*this, TheCall, 4)) 16363 return ExprError(); 16364 16365 unsigned PtrArgIdx = 0; 16366 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16367 Expr *RowsExpr = TheCall->getArg(1); 16368 Expr *ColumnsExpr = TheCall->getArg(2); 16369 Expr *StrideExpr = TheCall->getArg(3); 16370 16371 bool ArgError = false; 16372 16373 // Check pointer argument. 16374 { 16375 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16376 if (PtrConv.isInvalid()) 16377 return PtrConv; 16378 PtrExpr = PtrConv.get(); 16379 TheCall->setArg(0, PtrExpr); 16380 if (PtrExpr->isTypeDependent()) { 16381 TheCall->setType(Context.DependentTy); 16382 return TheCall; 16383 } 16384 } 16385 16386 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16387 QualType ElementTy; 16388 if (!PtrTy) { 16389 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16390 << PtrArgIdx + 1; 16391 ArgError = true; 16392 } else { 16393 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16394 16395 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16396 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16397 << PtrArgIdx + 1; 16398 ArgError = true; 16399 } 16400 } 16401 16402 // Apply default Lvalue conversions and convert the expression to size_t. 16403 auto ApplyArgumentConversions = [this](Expr *E) { 16404 ExprResult Conv = DefaultLvalueConversion(E); 16405 if (Conv.isInvalid()) 16406 return Conv; 16407 16408 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16409 }; 16410 16411 // Apply conversion to row and column expressions. 16412 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16413 if (!RowsConv.isInvalid()) { 16414 RowsExpr = RowsConv.get(); 16415 TheCall->setArg(1, RowsExpr); 16416 } else 16417 RowsExpr = nullptr; 16418 16419 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16420 if (!ColumnsConv.isInvalid()) { 16421 ColumnsExpr = ColumnsConv.get(); 16422 TheCall->setArg(2, ColumnsExpr); 16423 } else 16424 ColumnsExpr = nullptr; 16425 16426 // If any any part of the result matrix type is still pending, just use 16427 // Context.DependentTy, until all parts are resolved. 16428 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16429 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16430 TheCall->setType(Context.DependentTy); 16431 return CallResult; 16432 } 16433 16434 // Check row and column dimenions. 16435 llvm::Optional<unsigned> MaybeRows; 16436 if (RowsExpr) 16437 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16438 16439 llvm::Optional<unsigned> MaybeColumns; 16440 if (ColumnsExpr) 16441 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16442 16443 // Check stride argument. 16444 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16445 if (StrideConv.isInvalid()) 16446 return ExprError(); 16447 StrideExpr = StrideConv.get(); 16448 TheCall->setArg(3, StrideExpr); 16449 16450 if (MaybeRows) { 16451 if (Optional<llvm::APSInt> Value = 16452 StrideExpr->getIntegerConstantExpr(Context)) { 16453 uint64_t Stride = Value->getZExtValue(); 16454 if (Stride < *MaybeRows) { 16455 Diag(StrideExpr->getBeginLoc(), 16456 diag::err_builtin_matrix_stride_too_small); 16457 ArgError = true; 16458 } 16459 } 16460 } 16461 16462 if (ArgError || !MaybeRows || !MaybeColumns) 16463 return ExprError(); 16464 16465 TheCall->setType( 16466 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16467 return CallResult; 16468 } 16469 16470 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16471 ExprResult CallResult) { 16472 if (checkArgCount(*this, TheCall, 3)) 16473 return ExprError(); 16474 16475 unsigned PtrArgIdx = 1; 16476 Expr *MatrixExpr = TheCall->getArg(0); 16477 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16478 Expr *StrideExpr = TheCall->getArg(2); 16479 16480 bool ArgError = false; 16481 16482 { 16483 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16484 if (MatrixConv.isInvalid()) 16485 return MatrixConv; 16486 MatrixExpr = MatrixConv.get(); 16487 TheCall->setArg(0, MatrixExpr); 16488 } 16489 if (MatrixExpr->isTypeDependent()) { 16490 TheCall->setType(Context.DependentTy); 16491 return TheCall; 16492 } 16493 16494 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16495 if (!MatrixTy) { 16496 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16497 ArgError = true; 16498 } 16499 16500 { 16501 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16502 if (PtrConv.isInvalid()) 16503 return PtrConv; 16504 PtrExpr = PtrConv.get(); 16505 TheCall->setArg(1, PtrExpr); 16506 if (PtrExpr->isTypeDependent()) { 16507 TheCall->setType(Context.DependentTy); 16508 return TheCall; 16509 } 16510 } 16511 16512 // Check pointer argument. 16513 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16514 if (!PtrTy) { 16515 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16516 << PtrArgIdx + 1; 16517 ArgError = true; 16518 } else { 16519 QualType ElementTy = PtrTy->getPointeeType(); 16520 if (ElementTy.isConstQualified()) { 16521 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16522 ArgError = true; 16523 } 16524 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16525 if (MatrixTy && 16526 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16527 Diag(PtrExpr->getBeginLoc(), 16528 diag::err_builtin_matrix_pointer_arg_mismatch) 16529 << ElementTy << MatrixTy->getElementType(); 16530 ArgError = true; 16531 } 16532 } 16533 16534 // Apply default Lvalue conversions and convert the stride expression to 16535 // size_t. 16536 { 16537 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16538 if (StrideConv.isInvalid()) 16539 return StrideConv; 16540 16541 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16542 if (StrideConv.isInvalid()) 16543 return StrideConv; 16544 StrideExpr = StrideConv.get(); 16545 TheCall->setArg(2, StrideExpr); 16546 } 16547 16548 // Check stride argument. 16549 if (MatrixTy) { 16550 if (Optional<llvm::APSInt> Value = 16551 StrideExpr->getIntegerConstantExpr(Context)) { 16552 uint64_t Stride = Value->getZExtValue(); 16553 if (Stride < MatrixTy->getNumRows()) { 16554 Diag(StrideExpr->getBeginLoc(), 16555 diag::err_builtin_matrix_stride_too_small); 16556 ArgError = true; 16557 } 16558 } 16559 } 16560 16561 if (ArgError) 16562 return ExprError(); 16563 16564 return CallResult; 16565 } 16566 16567 /// \brief Enforce the bounds of a TCB 16568 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16569 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16570 /// and enforce_tcb_leaf attributes. 16571 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16572 const FunctionDecl *Callee) { 16573 const FunctionDecl *Caller = getCurFunctionDecl(); 16574 16575 // Calls to builtins are not enforced. 16576 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16577 Callee->getBuiltinID() != 0) 16578 return; 16579 16580 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16581 // all TCBs the callee is a part of. 16582 llvm::StringSet<> CalleeTCBs; 16583 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16584 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16585 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16586 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16587 16588 // Go through the TCBs the caller is a part of and emit warnings if Caller 16589 // is in a TCB that the Callee is not. 16590 for_each( 16591 Caller->specific_attrs<EnforceTCBAttr>(), 16592 [&](const auto *A) { 16593 StringRef CallerTCB = A->getTCBName(); 16594 if (CalleeTCBs.count(CallerTCB) == 0) { 16595 this->Diag(TheCall->getExprLoc(), 16596 diag::warn_tcb_enforcement_violation) << Callee 16597 << CallerTCB; 16598 } 16599 }); 16600 } 16601