1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 594 isConstantEvaluated()) 595 return; 596 597 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 598 if (!BuiltinID) 599 return; 600 601 const TargetInfo &TI = getASTContext().getTargetInfo(); 602 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 603 604 auto ComputeExplicitObjectSizeArgument = 605 [&](unsigned Index) -> Optional<llvm::APSInt> { 606 Expr::EvalResult Result; 607 Expr *SizeArg = TheCall->getArg(Index); 608 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 609 return llvm::None; 610 return Result.Val.getInt(); 611 }; 612 613 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 614 // If the parameter has a pass_object_size attribute, then we should use its 615 // (potentially) more strict checking mode. Otherwise, conservatively assume 616 // type 0. 617 int BOSType = 0; 618 if (const auto *POS = 619 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 620 BOSType = POS->getType(); 621 622 const Expr *ObjArg = TheCall->getArg(Index); 623 uint64_t Result; 624 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 625 return llvm::None; 626 627 // Get the object size in the target's size_t width. 628 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 629 }; 630 631 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 632 Expr *ObjArg = TheCall->getArg(Index); 633 uint64_t Result; 634 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 635 return llvm::None; 636 // Add 1 for null byte. 637 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 638 }; 639 640 Optional<llvm::APSInt> SourceSize; 641 Optional<llvm::APSInt> DestinationSize; 642 unsigned DiagID = 0; 643 bool IsChkVariant = false; 644 645 switch (BuiltinID) { 646 default: 647 return; 648 case Builtin::BI__builtin_strcpy: 649 case Builtin::BIstrcpy: { 650 DiagID = diag::warn_fortify_strlen_overflow; 651 SourceSize = ComputeStrLenArgument(1); 652 DestinationSize = ComputeSizeArgument(0); 653 break; 654 } 655 656 case Builtin::BI__builtin___strcpy_chk: { 657 DiagID = diag::warn_fortify_strlen_overflow; 658 SourceSize = ComputeStrLenArgument(1); 659 DestinationSize = ComputeExplicitObjectSizeArgument(2); 660 IsChkVariant = true; 661 break; 662 } 663 664 case Builtin::BIsprintf: 665 case Builtin::BI__builtin___sprintf_chk: { 666 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 667 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 668 669 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 670 671 if (!Format->isAscii() && !Format->isUTF8()) 672 return; 673 674 StringRef FormatStrRef = Format->getString(); 675 EstimateSizeFormatHandler H(FormatStrRef); 676 const char *FormatBytes = FormatStrRef.data(); 677 const ConstantArrayType *T = 678 Context.getAsConstantArrayType(Format->getType()); 679 assert(T && "String literal not of constant array type!"); 680 size_t TypeSize = T->getSize().getZExtValue(); 681 682 // In case there's a null byte somewhere. 683 size_t StrLen = 684 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 685 if (!analyze_format_string::ParsePrintfString( 686 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 687 Context.getTargetInfo(), false)) { 688 DiagID = diag::warn_fortify_source_format_overflow; 689 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 690 .extOrTrunc(SizeTypeWidth); 691 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 692 DestinationSize = ComputeExplicitObjectSizeArgument(2); 693 IsChkVariant = true; 694 } else { 695 DestinationSize = ComputeSizeArgument(0); 696 } 697 break; 698 } 699 } 700 return; 701 } 702 case Builtin::BI__builtin___memcpy_chk: 703 case Builtin::BI__builtin___memmove_chk: 704 case Builtin::BI__builtin___memset_chk: 705 case Builtin::BI__builtin___strlcat_chk: 706 case Builtin::BI__builtin___strlcpy_chk: 707 case Builtin::BI__builtin___strncat_chk: 708 case Builtin::BI__builtin___strncpy_chk: 709 case Builtin::BI__builtin___stpncpy_chk: 710 case Builtin::BI__builtin___memccpy_chk: 711 case Builtin::BI__builtin___mempcpy_chk: { 712 DiagID = diag::warn_builtin_chk_overflow; 713 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 714 DestinationSize = 715 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 716 IsChkVariant = true; 717 break; 718 } 719 720 case Builtin::BI__builtin___snprintf_chk: 721 case Builtin::BI__builtin___vsnprintf_chk: { 722 DiagID = diag::warn_builtin_chk_overflow; 723 SourceSize = ComputeExplicitObjectSizeArgument(1); 724 DestinationSize = ComputeExplicitObjectSizeArgument(3); 725 IsChkVariant = true; 726 break; 727 } 728 729 case Builtin::BIstrncat: 730 case Builtin::BI__builtin_strncat: 731 case Builtin::BIstrncpy: 732 case Builtin::BI__builtin_strncpy: 733 case Builtin::BIstpncpy: 734 case Builtin::BI__builtin_stpncpy: { 735 // Whether these functions overflow depends on the runtime strlen of the 736 // string, not just the buffer size, so emitting the "always overflow" 737 // diagnostic isn't quite right. We should still diagnose passing a buffer 738 // size larger than the destination buffer though; this is a runtime abort 739 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 740 DiagID = diag::warn_fortify_source_size_mismatch; 741 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 742 DestinationSize = ComputeSizeArgument(0); 743 break; 744 } 745 746 case Builtin::BImemcpy: 747 case Builtin::BI__builtin_memcpy: 748 case Builtin::BImemmove: 749 case Builtin::BI__builtin_memmove: 750 case Builtin::BImemset: 751 case Builtin::BI__builtin_memset: 752 case Builtin::BImempcpy: 753 case Builtin::BI__builtin_mempcpy: { 754 DiagID = diag::warn_fortify_source_overflow; 755 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 756 DestinationSize = ComputeSizeArgument(0); 757 break; 758 } 759 case Builtin::BIsnprintf: 760 case Builtin::BI__builtin_snprintf: 761 case Builtin::BIvsnprintf: 762 case Builtin::BI__builtin_vsnprintf: { 763 DiagID = diag::warn_fortify_source_size_mismatch; 764 SourceSize = ComputeExplicitObjectSizeArgument(1); 765 DestinationSize = ComputeSizeArgument(0); 766 break; 767 } 768 } 769 770 if (!SourceSize || !DestinationSize || 771 SourceSize.getValue().ule(DestinationSize.getValue())) 772 return; 773 774 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 775 // Skim off the details of whichever builtin was called to produce a better 776 // diagnostic, as it's unlikely that the user wrote the __builtin explicitly. 777 if (IsChkVariant) { 778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 779 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 780 } else if (FunctionName.startswith("__builtin_")) { 781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 782 } 783 784 SmallString<16> DestinationStr; 785 SmallString<16> SourceStr; 786 DestinationSize->toString(DestinationStr, /*Radix=*/10); 787 SourceSize->toString(SourceStr, /*Radix=*/10); 788 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 789 PDiag(DiagID) 790 << FunctionName << DestinationStr << SourceStr); 791 } 792 793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 794 Scope::ScopeFlags NeededScopeFlags, 795 unsigned DiagID) { 796 // Scopes aren't available during instantiation. Fortunately, builtin 797 // functions cannot be template args so they cannot be formed through template 798 // instantiation. Therefore checking once during the parse is sufficient. 799 if (SemaRef.inTemplateInstantiation()) 800 return false; 801 802 Scope *S = SemaRef.getCurScope(); 803 while (S && !S->isSEHExceptScope()) 804 S = S->getParent(); 805 if (!S || !(S->getFlags() & NeededScopeFlags)) { 806 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 807 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 808 << DRE->getDecl()->getIdentifier(); 809 return true; 810 } 811 812 return false; 813 } 814 815 static inline bool isBlockPointer(Expr *Arg) { 816 return Arg->getType()->isBlockPointerType(); 817 } 818 819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 820 /// void*, which is a requirement of device side enqueue. 821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 822 const BlockPointerType *BPT = 823 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 824 ArrayRef<QualType> Params = 825 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 826 unsigned ArgCounter = 0; 827 bool IllegalParams = false; 828 // Iterate through the block parameters until either one is found that is not 829 // a local void*, or the block is valid. 830 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 831 I != E; ++I, ++ArgCounter) { 832 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 833 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 834 LangAS::opencl_local) { 835 // Get the location of the error. If a block literal has been passed 836 // (BlockExpr) then we can point straight to the offending argument, 837 // else we just point to the variable reference. 838 SourceLocation ErrorLoc; 839 if (isa<BlockExpr>(BlockArg)) { 840 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 841 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 842 } else if (isa<DeclRefExpr>(BlockArg)) { 843 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 844 } 845 S.Diag(ErrorLoc, 846 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 847 IllegalParams = true; 848 } 849 } 850 851 return IllegalParams; 852 } 853 854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 855 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 857 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 858 return true; 859 } 860 return false; 861 } 862 863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 864 if (checkArgCount(S, TheCall, 2)) 865 return true; 866 867 if (checkOpenCLSubgroupExt(S, TheCall)) 868 return true; 869 870 // First argument is an ndrange_t type. 871 Expr *NDRangeArg = TheCall->getArg(0); 872 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 873 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 874 << TheCall->getDirectCallee() << "'ndrange_t'"; 875 return true; 876 } 877 878 Expr *BlockArg = TheCall->getArg(1); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 888 /// get_kernel_work_group_size 889 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 891 if (checkArgCount(S, TheCall, 1)) 892 return true; 893 894 Expr *BlockArg = TheCall->getArg(0); 895 if (!isBlockPointer(BlockArg)) { 896 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 897 << TheCall->getDirectCallee() << "block"; 898 return true; 899 } 900 return checkOpenCLBlockArgs(S, BlockArg); 901 } 902 903 /// Diagnose integer type and any valid implicit conversion to it. 904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 905 const QualType &IntType); 906 907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 908 unsigned Start, unsigned End) { 909 bool IllegalParams = false; 910 for (unsigned I = Start; I <= End; ++I) 911 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 912 S.Context.getSizeType()); 913 return IllegalParams; 914 } 915 916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 917 /// 'local void*' parameter of passed block. 918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 919 Expr *BlockArg, 920 unsigned NumNonVarArgs) { 921 const BlockPointerType *BPT = 922 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 923 unsigned NumBlockParams = 924 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 925 unsigned TotalNumArgs = TheCall->getNumArgs(); 926 927 // For each argument passed to the block, a corresponding uint needs to 928 // be passed to describe the size of the local memory. 929 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 930 S.Diag(TheCall->getBeginLoc(), 931 diag::err_opencl_enqueue_kernel_local_size_args); 932 return true; 933 } 934 935 // Check that the sizes of the local memory are specified by integers. 936 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 937 TotalNumArgs - 1); 938 } 939 940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 941 /// overload formats specified in Table 6.13.17.1. 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// void (^block)(void)) 946 /// int enqueue_kernel(queue_t queue, 947 /// kernel_enqueue_flags_t flags, 948 /// const ndrange_t ndrange, 949 /// uint num_events_in_wait_list, 950 /// clk_event_t *event_wait_list, 951 /// clk_event_t *event_ret, 952 /// void (^block)(void)) 953 /// int enqueue_kernel(queue_t queue, 954 /// kernel_enqueue_flags_t flags, 955 /// const ndrange_t ndrange, 956 /// void (^block)(local void*, ...), 957 /// uint size0, ...) 958 /// int enqueue_kernel(queue_t queue, 959 /// kernel_enqueue_flags_t flags, 960 /// const ndrange_t ndrange, 961 /// uint num_events_in_wait_list, 962 /// clk_event_t *event_wait_list, 963 /// clk_event_t *event_ret, 964 /// void (^block)(local void*, ...), 965 /// uint size0, ...) 966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 967 unsigned NumArgs = TheCall->getNumArgs(); 968 969 if (NumArgs < 4) { 970 S.Diag(TheCall->getBeginLoc(), 971 diag::err_typecheck_call_too_few_args_at_least) 972 << 0 << 4 << NumArgs; 973 return true; 974 } 975 976 Expr *Arg0 = TheCall->getArg(0); 977 Expr *Arg1 = TheCall->getArg(1); 978 Expr *Arg2 = TheCall->getArg(2); 979 Expr *Arg3 = TheCall->getArg(3); 980 981 // First argument always needs to be a queue_t type. 982 if (!Arg0->getType()->isQueueT()) { 983 S.Diag(TheCall->getArg(0)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 986 return true; 987 } 988 989 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 990 if (!Arg1->getType()->isIntegerType()) { 991 S.Diag(TheCall->getArg(1)->getBeginLoc(), 992 diag::err_opencl_builtin_expected_type) 993 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 994 return true; 995 } 996 997 // Third argument is always an ndrange_t type. 998 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 999 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1000 diag::err_opencl_builtin_expected_type) 1001 << TheCall->getDirectCallee() << "'ndrange_t'"; 1002 return true; 1003 } 1004 1005 // With four arguments, there is only one form that the function could be 1006 // called in: no events and no variable arguments. 1007 if (NumArgs == 4) { 1008 // check that the last argument is the right block type. 1009 if (!isBlockPointer(Arg3)) { 1010 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1011 << TheCall->getDirectCallee() << "block"; 1012 return true; 1013 } 1014 // we have a block type, check the prototype 1015 const BlockPointerType *BPT = 1016 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1017 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1018 S.Diag(Arg3->getBeginLoc(), 1019 diag::err_opencl_enqueue_kernel_blocks_no_args); 1020 return true; 1021 } 1022 return false; 1023 } 1024 // we can have block + varargs. 1025 if (isBlockPointer(Arg3)) 1026 return (checkOpenCLBlockArgs(S, Arg3) || 1027 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1028 // last two cases with either exactly 7 args or 7 args and varargs. 1029 if (NumArgs >= 7) { 1030 // check common block argument. 1031 Expr *Arg6 = TheCall->getArg(6); 1032 if (!isBlockPointer(Arg6)) { 1033 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1034 << TheCall->getDirectCallee() << "block"; 1035 return true; 1036 } 1037 if (checkOpenCLBlockArgs(S, Arg6)) 1038 return true; 1039 1040 // Forth argument has to be any integer type. 1041 if (!Arg3->getType()->isIntegerType()) { 1042 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1043 diag::err_opencl_builtin_expected_type) 1044 << TheCall->getDirectCallee() << "integer"; 1045 return true; 1046 } 1047 // check remaining common arguments. 1048 Expr *Arg4 = TheCall->getArg(4); 1049 Expr *Arg5 = TheCall->getArg(5); 1050 1051 // Fifth argument is always passed as a pointer to clk_event_t. 1052 if (!Arg4->isNullPointerConstant(S.Context, 1053 Expr::NPC_ValueDependentIsNotNull) && 1054 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1055 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1056 diag::err_opencl_builtin_expected_type) 1057 << TheCall->getDirectCallee() 1058 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1059 return true; 1060 } 1061 1062 // Sixth argument is always passed as a pointer to clk_event_t. 1063 if (!Arg5->isNullPointerConstant(S.Context, 1064 Expr::NPC_ValueDependentIsNotNull) && 1065 !(Arg5->getType()->isPointerType() && 1066 Arg5->getType()->getPointeeType()->isClkEventT())) { 1067 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1068 diag::err_opencl_builtin_expected_type) 1069 << TheCall->getDirectCallee() 1070 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1071 return true; 1072 } 1073 1074 if (NumArgs == 7) 1075 return false; 1076 1077 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1078 } 1079 1080 // None of the specific case has been detected, give generic error 1081 S.Diag(TheCall->getBeginLoc(), 1082 diag::err_opencl_enqueue_kernel_incorrect_args); 1083 return true; 1084 } 1085 1086 /// Returns OpenCL access qual. 1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1088 return D->getAttr<OpenCLAccessAttr>(); 1089 } 1090 1091 /// Returns true if pipe element type is different from the pointer. 1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1093 const Expr *Arg0 = Call->getArg(0); 1094 // First argument type should always be pipe. 1095 if (!Arg0->getType()->isPipeType()) { 1096 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1097 << Call->getDirectCallee() << Arg0->getSourceRange(); 1098 return true; 1099 } 1100 OpenCLAccessAttr *AccessQual = 1101 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1102 // Validates the access qualifier is compatible with the call. 1103 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1104 // read_only and write_only, and assumed to be read_only if no qualifier is 1105 // specified. 1106 switch (Call->getDirectCallee()->getBuiltinID()) { 1107 case Builtin::BIread_pipe: 1108 case Builtin::BIreserve_read_pipe: 1109 case Builtin::BIcommit_read_pipe: 1110 case Builtin::BIwork_group_reserve_read_pipe: 1111 case Builtin::BIsub_group_reserve_read_pipe: 1112 case Builtin::BIwork_group_commit_read_pipe: 1113 case Builtin::BIsub_group_commit_read_pipe: 1114 if (!(!AccessQual || AccessQual->isReadOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "read_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 case Builtin::BIwrite_pipe: 1122 case Builtin::BIreserve_write_pipe: 1123 case Builtin::BIcommit_write_pipe: 1124 case Builtin::BIwork_group_reserve_write_pipe: 1125 case Builtin::BIsub_group_reserve_write_pipe: 1126 case Builtin::BIwork_group_commit_write_pipe: 1127 case Builtin::BIsub_group_commit_write_pipe: 1128 if (!(AccessQual && AccessQual->isWriteOnly())) { 1129 S.Diag(Arg0->getBeginLoc(), 1130 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1131 << "write_only" << Arg0->getSourceRange(); 1132 return true; 1133 } 1134 break; 1135 default: 1136 break; 1137 } 1138 return false; 1139 } 1140 1141 /// Returns true if pipe element type is different from the pointer. 1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1143 const Expr *Arg0 = Call->getArg(0); 1144 const Expr *ArgIdx = Call->getArg(Idx); 1145 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1146 const QualType EltTy = PipeTy->getElementType(); 1147 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1148 // The Idx argument should be a pointer and the type of the pointer and 1149 // the type of pipe element should also be the same. 1150 if (!ArgTy || 1151 !S.Context.hasSameType( 1152 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1153 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1154 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1155 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 // Performs semantic analysis for the read/write_pipe call. 1162 // \param S Reference to the semantic analyzer. 1163 // \param Call A pointer to the builtin call. 1164 // \return True if a semantic error has been found, false otherwise. 1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1166 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1167 // functions have two forms. 1168 switch (Call->getNumArgs()) { 1169 case 2: 1170 if (checkOpenCLPipeArg(S, Call)) 1171 return true; 1172 // The call with 2 arguments should be 1173 // read/write_pipe(pipe T, T*). 1174 // Check packet type T. 1175 if (checkOpenCLPipePacketType(S, Call, 1)) 1176 return true; 1177 break; 1178 1179 case 4: { 1180 if (checkOpenCLPipeArg(S, Call)) 1181 return true; 1182 // The call with 4 arguments should be 1183 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1184 // Check reserve_id_t. 1185 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1186 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1187 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1188 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1189 return true; 1190 } 1191 1192 // Check the index. 1193 const Expr *Arg2 = Call->getArg(2); 1194 if (!Arg2->getType()->isIntegerType() && 1195 !Arg2->getType()->isUnsignedIntegerType()) { 1196 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1197 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1198 << Arg2->getType() << Arg2->getSourceRange(); 1199 return true; 1200 } 1201 1202 // Check packet type T. 1203 if (checkOpenCLPipePacketType(S, Call, 3)) 1204 return true; 1205 } break; 1206 default: 1207 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1208 << Call->getDirectCallee() << Call->getSourceRange(); 1209 return true; 1210 } 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on the {work_group_/sub_group_ 1216 // /_}reserve_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check the reserve size. 1228 if (!Call->getArg(1)->getType()->isIntegerType() && 1229 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1230 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1231 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1232 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1233 return true; 1234 } 1235 1236 // Since return type of reserve_read/write_pipe built-in function is 1237 // reserve_id_t, which is not defined in the builtin def file , we used int 1238 // as return type and need to override the return type of these functions. 1239 Call->setType(S.Context.OCLReserveIDTy); 1240 1241 return false; 1242 } 1243 1244 // Performs a semantic analysis on {work_group_/sub_group_ 1245 // /_}commit_{read/write}_pipe 1246 // \param S Reference to the semantic analyzer. 1247 // \param Call The call to the builtin function to be analyzed. 1248 // \return True if a semantic error was found, false otherwise. 1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1250 if (checkArgCount(S, Call, 2)) 1251 return true; 1252 1253 if (checkOpenCLPipeArg(S, Call)) 1254 return true; 1255 1256 // Check reserve_id_t. 1257 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1258 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1259 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1260 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1261 return true; 1262 } 1263 1264 return false; 1265 } 1266 1267 // Performs a semantic analysis on the call to built-in Pipe 1268 // Query Functions. 1269 // \param S Reference to the semantic analyzer. 1270 // \param Call The call to the builtin function to be analyzed. 1271 // \return True if a semantic error was found, false otherwise. 1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1273 if (checkArgCount(S, Call, 1)) 1274 return true; 1275 1276 if (!Call->getArg(0)->getType()->isPipeType()) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1278 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1279 return true; 1280 } 1281 1282 return false; 1283 } 1284 1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1286 // Performs semantic analysis for the to_global/local/private call. 1287 // \param S Reference to the semantic analyzer. 1288 // \param BuiltinID ID of the builtin function. 1289 // \param Call A pointer to the builtin call. 1290 // \return True if a semantic error has been found, false otherwise. 1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1292 CallExpr *Call) { 1293 if (checkArgCount(S, Call, 1)) 1294 return true; 1295 1296 auto RT = Call->getArg(0)->getType(); 1297 if (!RT->isPointerType() || RT->getPointeeType() 1298 .getAddressSpace() == LangAS::opencl_constant) { 1299 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1300 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1301 return true; 1302 } 1303 1304 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1305 S.Diag(Call->getArg(0)->getBeginLoc(), 1306 diag::warn_opencl_generic_address_space_arg) 1307 << Call->getDirectCallee()->getNameInfo().getAsString() 1308 << Call->getArg(0)->getSourceRange(); 1309 } 1310 1311 RT = RT->getPointeeType(); 1312 auto Qual = RT.getQualifiers(); 1313 switch (BuiltinID) { 1314 case Builtin::BIto_global: 1315 Qual.setAddressSpace(LangAS::opencl_global); 1316 break; 1317 case Builtin::BIto_local: 1318 Qual.setAddressSpace(LangAS::opencl_local); 1319 break; 1320 case Builtin::BIto_private: 1321 Qual.setAddressSpace(LangAS::opencl_private); 1322 break; 1323 default: 1324 llvm_unreachable("Invalid builtin function"); 1325 } 1326 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1327 RT.getUnqualifiedType(), Qual))); 1328 1329 return false; 1330 } 1331 1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1333 if (checkArgCount(S, TheCall, 1)) 1334 return ExprError(); 1335 1336 // Compute __builtin_launder's parameter type from the argument. 1337 // The parameter type is: 1338 // * The type of the argument if it's not an array or function type, 1339 // Otherwise, 1340 // * The decayed argument type. 1341 QualType ParamTy = [&]() { 1342 QualType ArgTy = TheCall->getArg(0)->getType(); 1343 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1344 return S.Context.getPointerType(Ty->getElementType()); 1345 if (ArgTy->isFunctionType()) { 1346 return S.Context.getPointerType(ArgTy); 1347 } 1348 return ArgTy; 1349 }(); 1350 1351 TheCall->setType(ParamTy); 1352 1353 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1354 if (!ParamTy->isPointerType()) 1355 return 0; 1356 if (ParamTy->isFunctionPointerType()) 1357 return 1; 1358 if (ParamTy->isVoidPointerType()) 1359 return 2; 1360 return llvm::Optional<unsigned>{}; 1361 }(); 1362 if (DiagSelect.hasValue()) { 1363 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1364 << DiagSelect.getValue() << TheCall->getSourceRange(); 1365 return ExprError(); 1366 } 1367 1368 // We either have an incomplete class type, or we have a class template 1369 // whose instantiation has not been forced. Example: 1370 // 1371 // template <class T> struct Foo { T value; }; 1372 // Foo<int> *p = nullptr; 1373 // auto *d = __builtin_launder(p); 1374 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1375 diag::err_incomplete_type)) 1376 return ExprError(); 1377 1378 assert(ParamTy->getPointeeType()->isObjectType() && 1379 "Unhandled non-object pointer case"); 1380 1381 InitializedEntity Entity = 1382 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1383 ExprResult Arg = 1384 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1385 if (Arg.isInvalid()) 1386 return ExprError(); 1387 TheCall->setArg(0, Arg.get()); 1388 1389 return TheCall; 1390 } 1391 1392 // Emit an error and return true if the current architecture is not in the list 1393 // of supported architectures. 1394 static bool 1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1396 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1397 llvm::Triple::ArchType CurArch = 1398 S.getASTContext().getTargetInfo().getTriple().getArch(); 1399 if (llvm::is_contained(SupportedArchs, CurArch)) 1400 return false; 1401 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1402 << TheCall->getSourceRange(); 1403 return true; 1404 } 1405 1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1407 SourceLocation CallSiteLoc); 1408 1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1410 CallExpr *TheCall) { 1411 switch (TI.getTriple().getArch()) { 1412 default: 1413 // Some builtins don't require additional checking, so just consider these 1414 // acceptable. 1415 return false; 1416 case llvm::Triple::arm: 1417 case llvm::Triple::armeb: 1418 case llvm::Triple::thumb: 1419 case llvm::Triple::thumbeb: 1420 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::aarch64: 1422 case llvm::Triple::aarch64_32: 1423 case llvm::Triple::aarch64_be: 1424 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::bpfeb: 1426 case llvm::Triple::bpfel: 1427 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1428 case llvm::Triple::hexagon: 1429 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1430 case llvm::Triple::mips: 1431 case llvm::Triple::mipsel: 1432 case llvm::Triple::mips64: 1433 case llvm::Triple::mips64el: 1434 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 case llvm::Triple::systemz: 1436 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1437 case llvm::Triple::x86: 1438 case llvm::Triple::x86_64: 1439 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1440 case llvm::Triple::ppc: 1441 case llvm::Triple::ppcle: 1442 case llvm::Triple::ppc64: 1443 case llvm::Triple::ppc64le: 1444 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1445 case llvm::Triple::amdgcn: 1446 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1447 case llvm::Triple::riscv32: 1448 case llvm::Triple::riscv64: 1449 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1450 } 1451 } 1452 1453 ExprResult 1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1455 CallExpr *TheCall) { 1456 ExprResult TheCallResult(TheCall); 1457 1458 // Find out if any arguments are required to be integer constant expressions. 1459 unsigned ICEArguments = 0; 1460 ASTContext::GetBuiltinTypeError Error; 1461 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1462 if (Error != ASTContext::GE_None) 1463 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1464 1465 // If any arguments are required to be ICE's, check and diagnose. 1466 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1467 // Skip arguments not required to be ICE's. 1468 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1469 1470 llvm::APSInt Result; 1471 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1472 return true; 1473 ICEArguments &= ~(1 << ArgNo); 1474 } 1475 1476 switch (BuiltinID) { 1477 case Builtin::BI__builtin___CFStringMakeConstantString: 1478 assert(TheCall->getNumArgs() == 1 && 1479 "Wrong # arguments to builtin CFStringMakeConstantString"); 1480 if (CheckObjCString(TheCall->getArg(0))) 1481 return ExprError(); 1482 break; 1483 case Builtin::BI__builtin_ms_va_start: 1484 case Builtin::BI__builtin_stdarg_start: 1485 case Builtin::BI__builtin_va_start: 1486 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1487 return ExprError(); 1488 break; 1489 case Builtin::BI__va_start: { 1490 switch (Context.getTargetInfo().getTriple().getArch()) { 1491 case llvm::Triple::aarch64: 1492 case llvm::Triple::arm: 1493 case llvm::Triple::thumb: 1494 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1495 return ExprError(); 1496 break; 1497 default: 1498 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1499 return ExprError(); 1500 break; 1501 } 1502 break; 1503 } 1504 1505 // The acquire, release, and no fence variants are ARM and AArch64 only. 1506 case Builtin::BI_interlockedbittestandset_acq: 1507 case Builtin::BI_interlockedbittestandset_rel: 1508 case Builtin::BI_interlockedbittestandset_nf: 1509 case Builtin::BI_interlockedbittestandreset_acq: 1510 case Builtin::BI_interlockedbittestandreset_rel: 1511 case Builtin::BI_interlockedbittestandreset_nf: 1512 if (CheckBuiltinTargetSupport( 1513 *this, BuiltinID, TheCall, 1514 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1515 return ExprError(); 1516 break; 1517 1518 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1519 case Builtin::BI_bittest64: 1520 case Builtin::BI_bittestandcomplement64: 1521 case Builtin::BI_bittestandreset64: 1522 case Builtin::BI_bittestandset64: 1523 case Builtin::BI_interlockedbittestandreset64: 1524 case Builtin::BI_interlockedbittestandset64: 1525 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1526 {llvm::Triple::x86_64, llvm::Triple::arm, 1527 llvm::Triple::thumb, llvm::Triple::aarch64})) 1528 return ExprError(); 1529 break; 1530 1531 case Builtin::BI__builtin_isgreater: 1532 case Builtin::BI__builtin_isgreaterequal: 1533 case Builtin::BI__builtin_isless: 1534 case Builtin::BI__builtin_islessequal: 1535 case Builtin::BI__builtin_islessgreater: 1536 case Builtin::BI__builtin_isunordered: 1537 if (SemaBuiltinUnorderedCompare(TheCall)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_fpclassify: 1541 if (SemaBuiltinFPClassification(TheCall, 6)) 1542 return ExprError(); 1543 break; 1544 case Builtin::BI__builtin_isfinite: 1545 case Builtin::BI__builtin_isinf: 1546 case Builtin::BI__builtin_isinf_sign: 1547 case Builtin::BI__builtin_isnan: 1548 case Builtin::BI__builtin_isnormal: 1549 case Builtin::BI__builtin_signbit: 1550 case Builtin::BI__builtin_signbitf: 1551 case Builtin::BI__builtin_signbitl: 1552 if (SemaBuiltinFPClassification(TheCall, 1)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_shufflevector: 1556 return SemaBuiltinShuffleVector(TheCall); 1557 // TheCall will be freed by the smart pointer here, but that's fine, since 1558 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1559 case Builtin::BI__builtin_prefetch: 1560 if (SemaBuiltinPrefetch(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_alloca_with_align: 1564 if (SemaBuiltinAllocaWithAlign(TheCall)) 1565 return ExprError(); 1566 LLVM_FALLTHROUGH; 1567 case Builtin::BI__builtin_alloca: 1568 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1569 << TheCall->getDirectCallee(); 1570 break; 1571 case Builtin::BI__arithmetic_fence: 1572 if (SemaBuiltinArithmeticFence(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__assume: 1576 case Builtin::BI__builtin_assume: 1577 if (SemaBuiltinAssume(TheCall)) 1578 return ExprError(); 1579 break; 1580 case Builtin::BI__builtin_assume_aligned: 1581 if (SemaBuiltinAssumeAligned(TheCall)) 1582 return ExprError(); 1583 break; 1584 case Builtin::BI__builtin_dynamic_object_size: 1585 case Builtin::BI__builtin_object_size: 1586 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BI__builtin_longjmp: 1590 if (SemaBuiltinLongjmp(TheCall)) 1591 return ExprError(); 1592 break; 1593 case Builtin::BI__builtin_setjmp: 1594 if (SemaBuiltinSetjmp(TheCall)) 1595 return ExprError(); 1596 break; 1597 case Builtin::BI__builtin_classify_type: 1598 if (checkArgCount(*this, TheCall, 1)) return true; 1599 TheCall->setType(Context.IntTy); 1600 break; 1601 case Builtin::BI__builtin_complex: 1602 if (SemaBuiltinComplex(TheCall)) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_constant_p: { 1606 if (checkArgCount(*this, TheCall, 1)) return true; 1607 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1608 if (Arg.isInvalid()) return true; 1609 TheCall->setArg(0, Arg.get()); 1610 TheCall->setType(Context.IntTy); 1611 break; 1612 } 1613 case Builtin::BI__builtin_launder: 1614 return SemaBuiltinLaunder(*this, TheCall); 1615 case Builtin::BI__sync_fetch_and_add: 1616 case Builtin::BI__sync_fetch_and_add_1: 1617 case Builtin::BI__sync_fetch_and_add_2: 1618 case Builtin::BI__sync_fetch_and_add_4: 1619 case Builtin::BI__sync_fetch_and_add_8: 1620 case Builtin::BI__sync_fetch_and_add_16: 1621 case Builtin::BI__sync_fetch_and_sub: 1622 case Builtin::BI__sync_fetch_and_sub_1: 1623 case Builtin::BI__sync_fetch_and_sub_2: 1624 case Builtin::BI__sync_fetch_and_sub_4: 1625 case Builtin::BI__sync_fetch_and_sub_8: 1626 case Builtin::BI__sync_fetch_and_sub_16: 1627 case Builtin::BI__sync_fetch_and_or: 1628 case Builtin::BI__sync_fetch_and_or_1: 1629 case Builtin::BI__sync_fetch_and_or_2: 1630 case Builtin::BI__sync_fetch_and_or_4: 1631 case Builtin::BI__sync_fetch_and_or_8: 1632 case Builtin::BI__sync_fetch_and_or_16: 1633 case Builtin::BI__sync_fetch_and_and: 1634 case Builtin::BI__sync_fetch_and_and_1: 1635 case Builtin::BI__sync_fetch_and_and_2: 1636 case Builtin::BI__sync_fetch_and_and_4: 1637 case Builtin::BI__sync_fetch_and_and_8: 1638 case Builtin::BI__sync_fetch_and_and_16: 1639 case Builtin::BI__sync_fetch_and_xor: 1640 case Builtin::BI__sync_fetch_and_xor_1: 1641 case Builtin::BI__sync_fetch_and_xor_2: 1642 case Builtin::BI__sync_fetch_and_xor_4: 1643 case Builtin::BI__sync_fetch_and_xor_8: 1644 case Builtin::BI__sync_fetch_and_xor_16: 1645 case Builtin::BI__sync_fetch_and_nand: 1646 case Builtin::BI__sync_fetch_and_nand_1: 1647 case Builtin::BI__sync_fetch_and_nand_2: 1648 case Builtin::BI__sync_fetch_and_nand_4: 1649 case Builtin::BI__sync_fetch_and_nand_8: 1650 case Builtin::BI__sync_fetch_and_nand_16: 1651 case Builtin::BI__sync_add_and_fetch: 1652 case Builtin::BI__sync_add_and_fetch_1: 1653 case Builtin::BI__sync_add_and_fetch_2: 1654 case Builtin::BI__sync_add_and_fetch_4: 1655 case Builtin::BI__sync_add_and_fetch_8: 1656 case Builtin::BI__sync_add_and_fetch_16: 1657 case Builtin::BI__sync_sub_and_fetch: 1658 case Builtin::BI__sync_sub_and_fetch_1: 1659 case Builtin::BI__sync_sub_and_fetch_2: 1660 case Builtin::BI__sync_sub_and_fetch_4: 1661 case Builtin::BI__sync_sub_and_fetch_8: 1662 case Builtin::BI__sync_sub_and_fetch_16: 1663 case Builtin::BI__sync_and_and_fetch: 1664 case Builtin::BI__sync_and_and_fetch_1: 1665 case Builtin::BI__sync_and_and_fetch_2: 1666 case Builtin::BI__sync_and_and_fetch_4: 1667 case Builtin::BI__sync_and_and_fetch_8: 1668 case Builtin::BI__sync_and_and_fetch_16: 1669 case Builtin::BI__sync_or_and_fetch: 1670 case Builtin::BI__sync_or_and_fetch_1: 1671 case Builtin::BI__sync_or_and_fetch_2: 1672 case Builtin::BI__sync_or_and_fetch_4: 1673 case Builtin::BI__sync_or_and_fetch_8: 1674 case Builtin::BI__sync_or_and_fetch_16: 1675 case Builtin::BI__sync_xor_and_fetch: 1676 case Builtin::BI__sync_xor_and_fetch_1: 1677 case Builtin::BI__sync_xor_and_fetch_2: 1678 case Builtin::BI__sync_xor_and_fetch_4: 1679 case Builtin::BI__sync_xor_and_fetch_8: 1680 case Builtin::BI__sync_xor_and_fetch_16: 1681 case Builtin::BI__sync_nand_and_fetch: 1682 case Builtin::BI__sync_nand_and_fetch_1: 1683 case Builtin::BI__sync_nand_and_fetch_2: 1684 case Builtin::BI__sync_nand_and_fetch_4: 1685 case Builtin::BI__sync_nand_and_fetch_8: 1686 case Builtin::BI__sync_nand_and_fetch_16: 1687 case Builtin::BI__sync_val_compare_and_swap: 1688 case Builtin::BI__sync_val_compare_and_swap_1: 1689 case Builtin::BI__sync_val_compare_and_swap_2: 1690 case Builtin::BI__sync_val_compare_and_swap_4: 1691 case Builtin::BI__sync_val_compare_and_swap_8: 1692 case Builtin::BI__sync_val_compare_and_swap_16: 1693 case Builtin::BI__sync_bool_compare_and_swap: 1694 case Builtin::BI__sync_bool_compare_and_swap_1: 1695 case Builtin::BI__sync_bool_compare_and_swap_2: 1696 case Builtin::BI__sync_bool_compare_and_swap_4: 1697 case Builtin::BI__sync_bool_compare_and_swap_8: 1698 case Builtin::BI__sync_bool_compare_and_swap_16: 1699 case Builtin::BI__sync_lock_test_and_set: 1700 case Builtin::BI__sync_lock_test_and_set_1: 1701 case Builtin::BI__sync_lock_test_and_set_2: 1702 case Builtin::BI__sync_lock_test_and_set_4: 1703 case Builtin::BI__sync_lock_test_and_set_8: 1704 case Builtin::BI__sync_lock_test_and_set_16: 1705 case Builtin::BI__sync_lock_release: 1706 case Builtin::BI__sync_lock_release_1: 1707 case Builtin::BI__sync_lock_release_2: 1708 case Builtin::BI__sync_lock_release_4: 1709 case Builtin::BI__sync_lock_release_8: 1710 case Builtin::BI__sync_lock_release_16: 1711 case Builtin::BI__sync_swap: 1712 case Builtin::BI__sync_swap_1: 1713 case Builtin::BI__sync_swap_2: 1714 case Builtin::BI__sync_swap_4: 1715 case Builtin::BI__sync_swap_8: 1716 case Builtin::BI__sync_swap_16: 1717 return SemaBuiltinAtomicOverloaded(TheCallResult); 1718 case Builtin::BI__sync_synchronize: 1719 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1720 << TheCall->getCallee()->getSourceRange(); 1721 break; 1722 case Builtin::BI__builtin_nontemporal_load: 1723 case Builtin::BI__builtin_nontemporal_store: 1724 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1725 case Builtin::BI__builtin_memcpy_inline: { 1726 clang::Expr *SizeOp = TheCall->getArg(2); 1727 // We warn about copying to or from `nullptr` pointers when `size` is 1728 // greater than 0. When `size` is value dependent we cannot evaluate its 1729 // value so we bail out. 1730 if (SizeOp->isValueDependent()) 1731 break; 1732 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1733 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1734 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1735 } 1736 break; 1737 } 1738 #define BUILTIN(ID, TYPE, ATTRS) 1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1740 case Builtin::BI##ID: \ 1741 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1742 #include "clang/Basic/Builtins.def" 1743 case Builtin::BI__annotation: 1744 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_annotation: 1748 if (SemaBuiltinAnnotation(*this, TheCall)) 1749 return ExprError(); 1750 break; 1751 case Builtin::BI__builtin_addressof: 1752 if (SemaBuiltinAddressof(*this, TheCall)) 1753 return ExprError(); 1754 break; 1755 case Builtin::BI__builtin_is_aligned: 1756 case Builtin::BI__builtin_align_up: 1757 case Builtin::BI__builtin_align_down: 1758 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_add_overflow: 1762 case Builtin::BI__builtin_sub_overflow: 1763 case Builtin::BI__builtin_mul_overflow: 1764 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__builtin_operator_new: 1768 case Builtin::BI__builtin_operator_delete: { 1769 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1770 ExprResult Res = 1771 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1772 if (Res.isInvalid()) 1773 CorrectDelayedTyposInExpr(TheCallResult.get()); 1774 return Res; 1775 } 1776 case Builtin::BI__builtin_dump_struct: { 1777 // We first want to ensure we are called with 2 arguments 1778 if (checkArgCount(*this, TheCall, 2)) 1779 return ExprError(); 1780 // Ensure that the first argument is of type 'struct XX *' 1781 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1782 const QualType PtrArgType = PtrArg->getType(); 1783 if (!PtrArgType->isPointerType() || 1784 !PtrArgType->getPointeeType()->isRecordType()) { 1785 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1786 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1787 << "structure pointer"; 1788 return ExprError(); 1789 } 1790 1791 // Ensure that the second argument is of type 'FunctionType' 1792 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1793 const QualType FnPtrArgType = FnPtrArg->getType(); 1794 if (!FnPtrArgType->isPointerType()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1797 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 1801 const auto *FuncType = 1802 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1803 1804 if (!FuncType) { 1805 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1806 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1807 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1808 return ExprError(); 1809 } 1810 1811 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1812 if (!FT->getNumParams()) { 1813 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1814 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1815 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1816 return ExprError(); 1817 } 1818 QualType PT = FT->getParamType(0); 1819 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1820 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1821 !PT->getPointeeType().isConstQualified()) { 1822 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1823 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1824 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1825 return ExprError(); 1826 } 1827 } 1828 1829 TheCall->setType(Context.IntTy); 1830 break; 1831 } 1832 case Builtin::BI__builtin_expect_with_probability: { 1833 // We first want to ensure we are called with 3 arguments 1834 if (checkArgCount(*this, TheCall, 3)) 1835 return ExprError(); 1836 // then check probability is constant float in range [0.0, 1.0] 1837 const Expr *ProbArg = TheCall->getArg(2); 1838 SmallVector<PartialDiagnosticAt, 8> Notes; 1839 Expr::EvalResult Eval; 1840 Eval.Diag = &Notes; 1841 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1842 !Eval.Val.isFloat()) { 1843 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1844 << ProbArg->getSourceRange(); 1845 for (const PartialDiagnosticAt &PDiag : Notes) 1846 Diag(PDiag.first, PDiag.second); 1847 return ExprError(); 1848 } 1849 llvm::APFloat Probability = Eval.Val.getFloat(); 1850 bool LoseInfo = false; 1851 Probability.convert(llvm::APFloat::IEEEdouble(), 1852 llvm::RoundingMode::Dynamic, &LoseInfo); 1853 if (!(Probability >= llvm::APFloat(0.0) && 1854 Probability <= llvm::APFloat(1.0))) { 1855 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1856 << ProbArg->getSourceRange(); 1857 return ExprError(); 1858 } 1859 break; 1860 } 1861 case Builtin::BI__builtin_preserve_access_index: 1862 if (SemaBuiltinPreserveAI(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BI__builtin_call_with_static_chain: 1866 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__exception_code: 1870 case Builtin::BI_exception_code: 1871 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1872 diag::err_seh___except_block)) 1873 return ExprError(); 1874 break; 1875 case Builtin::BI__exception_info: 1876 case Builtin::BI_exception_info: 1877 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1878 diag::err_seh___except_filter)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BI__GetExceptionInfo: 1882 if (checkArgCount(*this, TheCall, 1)) 1883 return ExprError(); 1884 1885 if (CheckCXXThrowOperand( 1886 TheCall->getBeginLoc(), 1887 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1888 TheCall)) 1889 return ExprError(); 1890 1891 TheCall->setType(Context.VoidPtrTy); 1892 break; 1893 // OpenCL v2.0, s6.13.16 - Pipe functions 1894 case Builtin::BIread_pipe: 1895 case Builtin::BIwrite_pipe: 1896 // Since those two functions are declared with var args, we need a semantic 1897 // check for the argument. 1898 if (SemaBuiltinRWPipe(*this, TheCall)) 1899 return ExprError(); 1900 break; 1901 case Builtin::BIreserve_read_pipe: 1902 case Builtin::BIreserve_write_pipe: 1903 case Builtin::BIwork_group_reserve_read_pipe: 1904 case Builtin::BIwork_group_reserve_write_pipe: 1905 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIsub_group_reserve_read_pipe: 1909 case Builtin::BIsub_group_reserve_write_pipe: 1910 if (checkOpenCLSubgroupExt(*this, TheCall) || 1911 SemaBuiltinReserveRWPipe(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIcommit_read_pipe: 1915 case Builtin::BIcommit_write_pipe: 1916 case Builtin::BIwork_group_commit_read_pipe: 1917 case Builtin::BIwork_group_commit_write_pipe: 1918 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1919 return ExprError(); 1920 break; 1921 case Builtin::BIsub_group_commit_read_pipe: 1922 case Builtin::BIsub_group_commit_write_pipe: 1923 if (checkOpenCLSubgroupExt(*this, TheCall) || 1924 SemaBuiltinCommitRWPipe(*this, TheCall)) 1925 return ExprError(); 1926 break; 1927 case Builtin::BIget_pipe_num_packets: 1928 case Builtin::BIget_pipe_max_packets: 1929 if (SemaBuiltinPipePackets(*this, TheCall)) 1930 return ExprError(); 1931 break; 1932 case Builtin::BIto_global: 1933 case Builtin::BIto_local: 1934 case Builtin::BIto_private: 1935 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1936 return ExprError(); 1937 break; 1938 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1939 case Builtin::BIenqueue_kernel: 1940 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1941 return ExprError(); 1942 break; 1943 case Builtin::BIget_kernel_work_group_size: 1944 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1945 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1946 return ExprError(); 1947 break; 1948 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1949 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1950 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1951 return ExprError(); 1952 break; 1953 case Builtin::BI__builtin_os_log_format: 1954 Cleanup.setExprNeedsCleanups(true); 1955 LLVM_FALLTHROUGH; 1956 case Builtin::BI__builtin_os_log_format_buffer_size: 1957 if (SemaBuiltinOSLogFormat(TheCall)) 1958 return ExprError(); 1959 break; 1960 case Builtin::BI__builtin_frame_address: 1961 case Builtin::BI__builtin_return_address: { 1962 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1963 return ExprError(); 1964 1965 // -Wframe-address warning if non-zero passed to builtin 1966 // return/frame address. 1967 Expr::EvalResult Result; 1968 if (!TheCall->getArg(0)->isValueDependent() && 1969 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1970 Result.Val.getInt() != 0) 1971 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1972 << ((BuiltinID == Builtin::BI__builtin_return_address) 1973 ? "__builtin_return_address" 1974 : "__builtin_frame_address") 1975 << TheCall->getSourceRange(); 1976 break; 1977 } 1978 1979 case Builtin::BI__builtin_matrix_transpose: 1980 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1981 1982 case Builtin::BI__builtin_matrix_column_major_load: 1983 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1984 1985 case Builtin::BI__builtin_matrix_column_major_store: 1986 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1987 1988 case Builtin::BI__builtin_get_device_side_mangled_name: { 1989 auto Check = [](CallExpr *TheCall) { 1990 if (TheCall->getNumArgs() != 1) 1991 return false; 1992 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1993 if (!DRE) 1994 return false; 1995 auto *D = DRE->getDecl(); 1996 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1997 return false; 1998 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1999 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2000 }; 2001 if (!Check(TheCall)) { 2002 Diag(TheCall->getBeginLoc(), 2003 diag::err_hip_invalid_args_builtin_mangled_name); 2004 return ExprError(); 2005 } 2006 } 2007 } 2008 2009 // Since the target specific builtins for each arch overlap, only check those 2010 // of the arch we are compiling for. 2011 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2012 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2013 assert(Context.getAuxTargetInfo() && 2014 "Aux Target Builtin, but not an aux target?"); 2015 2016 if (CheckTSBuiltinFunctionCall( 2017 *Context.getAuxTargetInfo(), 2018 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2019 return ExprError(); 2020 } else { 2021 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2022 TheCall)) 2023 return ExprError(); 2024 } 2025 } 2026 2027 return TheCallResult; 2028 } 2029 2030 // Get the valid immediate range for the specified NEON type code. 2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2032 NeonTypeFlags Type(t); 2033 int IsQuad = ForceQuad ? true : Type.isQuad(); 2034 switch (Type.getEltType()) { 2035 case NeonTypeFlags::Int8: 2036 case NeonTypeFlags::Poly8: 2037 return shift ? 7 : (8 << IsQuad) - 1; 2038 case NeonTypeFlags::Int16: 2039 case NeonTypeFlags::Poly16: 2040 return shift ? 15 : (4 << IsQuad) - 1; 2041 case NeonTypeFlags::Int32: 2042 return shift ? 31 : (2 << IsQuad) - 1; 2043 case NeonTypeFlags::Int64: 2044 case NeonTypeFlags::Poly64: 2045 return shift ? 63 : (1 << IsQuad) - 1; 2046 case NeonTypeFlags::Poly128: 2047 return shift ? 127 : (1 << IsQuad) - 1; 2048 case NeonTypeFlags::Float16: 2049 assert(!shift && "cannot shift float types!"); 2050 return (4 << IsQuad) - 1; 2051 case NeonTypeFlags::Float32: 2052 assert(!shift && "cannot shift float types!"); 2053 return (2 << IsQuad) - 1; 2054 case NeonTypeFlags::Float64: 2055 assert(!shift && "cannot shift float types!"); 2056 return (1 << IsQuad) - 1; 2057 case NeonTypeFlags::BFloat16: 2058 assert(!shift && "cannot shift float types!"); 2059 return (4 << IsQuad) - 1; 2060 } 2061 llvm_unreachable("Invalid NeonTypeFlag!"); 2062 } 2063 2064 /// getNeonEltType - Return the QualType corresponding to the elements of 2065 /// the vector type specified by the NeonTypeFlags. This is used to check 2066 /// the pointer arguments for Neon load/store intrinsics. 2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2068 bool IsPolyUnsigned, bool IsInt64Long) { 2069 switch (Flags.getEltType()) { 2070 case NeonTypeFlags::Int8: 2071 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2072 case NeonTypeFlags::Int16: 2073 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2074 case NeonTypeFlags::Int32: 2075 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2076 case NeonTypeFlags::Int64: 2077 if (IsInt64Long) 2078 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2079 else 2080 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2081 : Context.LongLongTy; 2082 case NeonTypeFlags::Poly8: 2083 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2084 case NeonTypeFlags::Poly16: 2085 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2086 case NeonTypeFlags::Poly64: 2087 if (IsInt64Long) 2088 return Context.UnsignedLongTy; 2089 else 2090 return Context.UnsignedLongLongTy; 2091 case NeonTypeFlags::Poly128: 2092 break; 2093 case NeonTypeFlags::Float16: 2094 return Context.HalfTy; 2095 case NeonTypeFlags::Float32: 2096 return Context.FloatTy; 2097 case NeonTypeFlags::Float64: 2098 return Context.DoubleTy; 2099 case NeonTypeFlags::BFloat16: 2100 return Context.BFloat16Ty; 2101 } 2102 llvm_unreachable("Invalid NeonTypeFlag!"); 2103 } 2104 2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2106 // Range check SVE intrinsics that take immediate values. 2107 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2108 2109 switch (BuiltinID) { 2110 default: 2111 return false; 2112 #define GET_SVE_IMMEDIATE_CHECK 2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2114 #undef GET_SVE_IMMEDIATE_CHECK 2115 } 2116 2117 // Perform all the immediate checks for this builtin call. 2118 bool HasError = false; 2119 for (auto &I : ImmChecks) { 2120 int ArgNum, CheckTy, ElementSizeInBits; 2121 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2122 2123 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2124 2125 // Function that checks whether the operand (ArgNum) is an immediate 2126 // that is one of the predefined values. 2127 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2128 int ErrDiag) -> bool { 2129 // We can't check the value of a dependent argument. 2130 Expr *Arg = TheCall->getArg(ArgNum); 2131 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2132 return false; 2133 2134 // Check constant-ness first. 2135 llvm::APSInt Imm; 2136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2137 return true; 2138 2139 if (!CheckImm(Imm.getSExtValue())) 2140 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2141 return false; 2142 }; 2143 2144 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2145 case SVETypeFlags::ImmCheck0_31: 2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheck0_13: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2151 HasError = true; 2152 break; 2153 case SVETypeFlags::ImmCheck1_16: 2154 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheck0_7: 2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckExtract: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 (2048 / ElementSizeInBits) - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckShiftRight: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2168 HasError = true; 2169 break; 2170 case SVETypeFlags::ImmCheckShiftRightNarrow: 2171 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2172 ElementSizeInBits / 2)) 2173 HasError = true; 2174 break; 2175 case SVETypeFlags::ImmCheckShiftLeft: 2176 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2177 ElementSizeInBits - 1)) 2178 HasError = true; 2179 break; 2180 case SVETypeFlags::ImmCheckLaneIndex: 2181 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2182 (128 / (1 * ElementSizeInBits)) - 1)) 2183 HasError = true; 2184 break; 2185 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2186 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2187 (128 / (2 * ElementSizeInBits)) - 1)) 2188 HasError = true; 2189 break; 2190 case SVETypeFlags::ImmCheckLaneIndexDot: 2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2192 (128 / (4 * ElementSizeInBits)) - 1)) 2193 HasError = true; 2194 break; 2195 case SVETypeFlags::ImmCheckComplexRot90_270: 2196 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2197 diag::err_rotation_argument_to_cadd)) 2198 HasError = true; 2199 break; 2200 case SVETypeFlags::ImmCheckComplexRotAll90: 2201 if (CheckImmediateInSet( 2202 [](int64_t V) { 2203 return V == 0 || V == 90 || V == 180 || V == 270; 2204 }, 2205 diag::err_rotation_argument_to_cmla)) 2206 HasError = true; 2207 break; 2208 case SVETypeFlags::ImmCheck0_1: 2209 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2210 HasError = true; 2211 break; 2212 case SVETypeFlags::ImmCheck0_2: 2213 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2214 HasError = true; 2215 break; 2216 case SVETypeFlags::ImmCheck0_3: 2217 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2218 HasError = true; 2219 break; 2220 } 2221 } 2222 2223 return HasError; 2224 } 2225 2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2227 unsigned BuiltinID, CallExpr *TheCall) { 2228 llvm::APSInt Result; 2229 uint64_t mask = 0; 2230 unsigned TV = 0; 2231 int PtrArgNum = -1; 2232 bool HasConstPtr = false; 2233 switch (BuiltinID) { 2234 #define GET_NEON_OVERLOAD_CHECK 2235 #include "clang/Basic/arm_neon.inc" 2236 #include "clang/Basic/arm_fp16.inc" 2237 #undef GET_NEON_OVERLOAD_CHECK 2238 } 2239 2240 // For NEON intrinsics which are overloaded on vector element type, validate 2241 // the immediate which specifies which variant to emit. 2242 unsigned ImmArg = TheCall->getNumArgs()-1; 2243 if (mask) { 2244 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2245 return true; 2246 2247 TV = Result.getLimitedValue(64); 2248 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2249 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2250 << TheCall->getArg(ImmArg)->getSourceRange(); 2251 } 2252 2253 if (PtrArgNum >= 0) { 2254 // Check that pointer arguments have the specified type. 2255 Expr *Arg = TheCall->getArg(PtrArgNum); 2256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2257 Arg = ICE->getSubExpr(); 2258 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2259 QualType RHSTy = RHS.get()->getType(); 2260 2261 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2262 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2263 Arch == llvm::Triple::aarch64_32 || 2264 Arch == llvm::Triple::aarch64_be; 2265 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2266 QualType EltTy = 2267 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2268 if (HasConstPtr) 2269 EltTy = EltTy.withConst(); 2270 QualType LHSTy = Context.getPointerType(EltTy); 2271 AssignConvertType ConvTy; 2272 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2273 if (RHS.isInvalid()) 2274 return true; 2275 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2276 RHS.get(), AA_Assigning)) 2277 return true; 2278 } 2279 2280 // For NEON intrinsics which take an immediate value as part of the 2281 // instruction, range check them here. 2282 unsigned i = 0, l = 0, u = 0; 2283 switch (BuiltinID) { 2284 default: 2285 return false; 2286 #define GET_NEON_IMMEDIATE_CHECK 2287 #include "clang/Basic/arm_neon.inc" 2288 #include "clang/Basic/arm_fp16.inc" 2289 #undef GET_NEON_IMMEDIATE_CHECK 2290 } 2291 2292 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2293 } 2294 2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2296 switch (BuiltinID) { 2297 default: 2298 return false; 2299 #include "clang/Basic/arm_mve_builtin_sema.inc" 2300 } 2301 } 2302 2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2304 CallExpr *TheCall) { 2305 bool Err = false; 2306 switch (BuiltinID) { 2307 default: 2308 return false; 2309 #include "clang/Basic/arm_cde_builtin_sema.inc" 2310 } 2311 2312 if (Err) 2313 return true; 2314 2315 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2316 } 2317 2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2319 const Expr *CoprocArg, bool WantCDE) { 2320 if (isConstantEvaluated()) 2321 return false; 2322 2323 // We can't check the value of a dependent argument. 2324 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2325 return false; 2326 2327 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2328 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2329 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2330 2331 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2332 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2333 2334 if (IsCDECoproc != WantCDE) 2335 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2336 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2337 2338 return false; 2339 } 2340 2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2342 unsigned MaxWidth) { 2343 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2344 BuiltinID == ARM::BI__builtin_arm_ldaex || 2345 BuiltinID == ARM::BI__builtin_arm_strex || 2346 BuiltinID == ARM::BI__builtin_arm_stlex || 2347 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2348 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2349 BuiltinID == AArch64::BI__builtin_arm_strex || 2350 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2351 "unexpected ARM builtin"); 2352 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2353 BuiltinID == ARM::BI__builtin_arm_ldaex || 2354 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2355 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2356 2357 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2358 2359 // Ensure that we have the proper number of arguments. 2360 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2361 return true; 2362 2363 // Inspect the pointer argument of the atomic builtin. This should always be 2364 // a pointer type, whose element is an integral scalar or pointer type. 2365 // Because it is a pointer type, we don't have to worry about any implicit 2366 // casts here. 2367 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2368 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2369 if (PointerArgRes.isInvalid()) 2370 return true; 2371 PointerArg = PointerArgRes.get(); 2372 2373 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2374 if (!pointerType) { 2375 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2376 << PointerArg->getType() << PointerArg->getSourceRange(); 2377 return true; 2378 } 2379 2380 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2381 // task is to insert the appropriate casts into the AST. First work out just 2382 // what the appropriate type is. 2383 QualType ValType = pointerType->getPointeeType(); 2384 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2385 if (IsLdrex) 2386 AddrType.addConst(); 2387 2388 // Issue a warning if the cast is dodgy. 2389 CastKind CastNeeded = CK_NoOp; 2390 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2391 CastNeeded = CK_BitCast; 2392 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2393 << PointerArg->getType() << Context.getPointerType(AddrType) 2394 << AA_Passing << PointerArg->getSourceRange(); 2395 } 2396 2397 // Finally, do the cast and replace the argument with the corrected version. 2398 AddrType = Context.getPointerType(AddrType); 2399 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2400 if (PointerArgRes.isInvalid()) 2401 return true; 2402 PointerArg = PointerArgRes.get(); 2403 2404 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2405 2406 // In general, we allow ints, floats and pointers to be loaded and stored. 2407 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2408 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2409 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2410 << PointerArg->getType() << PointerArg->getSourceRange(); 2411 return true; 2412 } 2413 2414 // But ARM doesn't have instructions to deal with 128-bit versions. 2415 if (Context.getTypeSize(ValType) > MaxWidth) { 2416 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2417 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2418 << PointerArg->getType() << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 switch (ValType.getObjCLifetime()) { 2423 case Qualifiers::OCL_None: 2424 case Qualifiers::OCL_ExplicitNone: 2425 // okay 2426 break; 2427 2428 case Qualifiers::OCL_Weak: 2429 case Qualifiers::OCL_Strong: 2430 case Qualifiers::OCL_Autoreleasing: 2431 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2432 << ValType << PointerArg->getSourceRange(); 2433 return true; 2434 } 2435 2436 if (IsLdrex) { 2437 TheCall->setType(ValType); 2438 return false; 2439 } 2440 2441 // Initialize the argument to be stored. 2442 ExprResult ValArg = TheCall->getArg(0); 2443 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2444 Context, ValType, /*consume*/ false); 2445 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2446 if (ValArg.isInvalid()) 2447 return true; 2448 TheCall->setArg(0, ValArg.get()); 2449 2450 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2451 // but the custom checker bypasses all default analysis. 2452 TheCall->setType(Context.IntTy); 2453 return false; 2454 } 2455 2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2457 CallExpr *TheCall) { 2458 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2459 BuiltinID == ARM::BI__builtin_arm_ldaex || 2460 BuiltinID == ARM::BI__builtin_arm_strex || 2461 BuiltinID == ARM::BI__builtin_arm_stlex) { 2462 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2463 } 2464 2465 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2466 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2467 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2468 } 2469 2470 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2471 BuiltinID == ARM::BI__builtin_arm_wsr64) 2472 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2473 2474 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2475 BuiltinID == ARM::BI__builtin_arm_rsrp || 2476 BuiltinID == ARM::BI__builtin_arm_wsr || 2477 BuiltinID == ARM::BI__builtin_arm_wsrp) 2478 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2479 2480 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2481 return true; 2482 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2483 return true; 2484 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2485 return true; 2486 2487 // For intrinsics which take an immediate value as part of the instruction, 2488 // range check them here. 2489 // FIXME: VFP Intrinsics should error if VFP not present. 2490 switch (BuiltinID) { 2491 default: return false; 2492 case ARM::BI__builtin_arm_ssat: 2493 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2494 case ARM::BI__builtin_arm_usat: 2495 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2496 case ARM::BI__builtin_arm_ssat16: 2497 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2498 case ARM::BI__builtin_arm_usat16: 2499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2500 case ARM::BI__builtin_arm_vcvtr_f: 2501 case ARM::BI__builtin_arm_vcvtr_d: 2502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2503 case ARM::BI__builtin_arm_dmb: 2504 case ARM::BI__builtin_arm_dsb: 2505 case ARM::BI__builtin_arm_isb: 2506 case ARM::BI__builtin_arm_dbg: 2507 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2508 case ARM::BI__builtin_arm_cdp: 2509 case ARM::BI__builtin_arm_cdp2: 2510 case ARM::BI__builtin_arm_mcr: 2511 case ARM::BI__builtin_arm_mcr2: 2512 case ARM::BI__builtin_arm_mrc: 2513 case ARM::BI__builtin_arm_mrc2: 2514 case ARM::BI__builtin_arm_mcrr: 2515 case ARM::BI__builtin_arm_mcrr2: 2516 case ARM::BI__builtin_arm_mrrc: 2517 case ARM::BI__builtin_arm_mrrc2: 2518 case ARM::BI__builtin_arm_ldc: 2519 case ARM::BI__builtin_arm_ldcl: 2520 case ARM::BI__builtin_arm_ldc2: 2521 case ARM::BI__builtin_arm_ldc2l: 2522 case ARM::BI__builtin_arm_stc: 2523 case ARM::BI__builtin_arm_stcl: 2524 case ARM::BI__builtin_arm_stc2: 2525 case ARM::BI__builtin_arm_stc2l: 2526 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2527 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2528 /*WantCDE*/ false); 2529 } 2530 } 2531 2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2533 unsigned BuiltinID, 2534 CallExpr *TheCall) { 2535 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2536 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2537 BuiltinID == AArch64::BI__builtin_arm_strex || 2538 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2539 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2540 } 2541 2542 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2543 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2544 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2545 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2546 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2550 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2551 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2552 2553 // Memory Tagging Extensions (MTE) Intrinsics 2554 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2555 BuiltinID == AArch64::BI__builtin_arm_addg || 2556 BuiltinID == AArch64::BI__builtin_arm_gmi || 2557 BuiltinID == AArch64::BI__builtin_arm_ldg || 2558 BuiltinID == AArch64::BI__builtin_arm_stg || 2559 BuiltinID == AArch64::BI__builtin_arm_subp) { 2560 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2561 } 2562 2563 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2564 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2565 BuiltinID == AArch64::BI__builtin_arm_wsr || 2566 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2567 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2568 2569 // Only check the valid encoding range. Any constant in this range would be 2570 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2571 // an exception for incorrect registers. This matches MSVC behavior. 2572 if (BuiltinID == AArch64::BI_ReadStatusReg || 2573 BuiltinID == AArch64::BI_WriteStatusReg) 2574 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2575 2576 if (BuiltinID == AArch64::BI__getReg) 2577 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2578 2579 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2580 return true; 2581 2582 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2583 return true; 2584 2585 // For intrinsics which take an immediate value as part of the instruction, 2586 // range check them here. 2587 unsigned i = 0, l = 0, u = 0; 2588 switch (BuiltinID) { 2589 default: return false; 2590 case AArch64::BI__builtin_arm_dmb: 2591 case AArch64::BI__builtin_arm_dsb: 2592 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2593 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2594 } 2595 2596 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2597 } 2598 2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2600 if (Arg->getType()->getAsPlaceholderType()) 2601 return false; 2602 2603 // The first argument needs to be a record field access. 2604 // If it is an array element access, we delay decision 2605 // to BPF backend to check whether the access is a 2606 // field access or not. 2607 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2608 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2609 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2610 } 2611 2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2613 QualType VectorTy, QualType EltTy) { 2614 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2615 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2616 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2617 << Call->getSourceRange() << VectorEltTy << EltTy; 2618 return false; 2619 } 2620 return true; 2621 } 2622 2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2624 QualType ArgType = Arg->getType(); 2625 if (ArgType->getAsPlaceholderType()) 2626 return false; 2627 2628 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2629 // format: 2630 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2631 // 2. <type> var; 2632 // __builtin_preserve_type_info(var, flag); 2633 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2634 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2635 return false; 2636 2637 // Typedef type. 2638 if (ArgType->getAs<TypedefType>()) 2639 return true; 2640 2641 // Record type or Enum type. 2642 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2643 if (const auto *RT = Ty->getAs<RecordType>()) { 2644 if (!RT->getDecl()->getDeclName().isEmpty()) 2645 return true; 2646 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2647 if (!ET->getDecl()->getDeclName().isEmpty()) 2648 return true; 2649 } 2650 2651 return false; 2652 } 2653 2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2655 QualType ArgType = Arg->getType(); 2656 if (ArgType->getAsPlaceholderType()) 2657 return false; 2658 2659 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2660 // format: 2661 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2662 // flag); 2663 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2664 if (!UO) 2665 return false; 2666 2667 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2668 if (!CE) 2669 return false; 2670 if (CE->getCastKind() != CK_IntegralToPointer && 2671 CE->getCastKind() != CK_NullToPointer) 2672 return false; 2673 2674 // The integer must be from an EnumConstantDecl. 2675 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2676 if (!DR) 2677 return false; 2678 2679 const EnumConstantDecl *Enumerator = 2680 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2681 if (!Enumerator) 2682 return false; 2683 2684 // The type must be EnumType. 2685 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2686 const auto *ET = Ty->getAs<EnumType>(); 2687 if (!ET) 2688 return false; 2689 2690 // The enum value must be supported. 2691 for (auto *EDI : ET->getDecl()->enumerators()) { 2692 if (EDI == Enumerator) 2693 return true; 2694 } 2695 2696 return false; 2697 } 2698 2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2700 CallExpr *TheCall) { 2701 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2702 BuiltinID == BPF::BI__builtin_btf_type_id || 2703 BuiltinID == BPF::BI__builtin_preserve_type_info || 2704 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2705 "unexpected BPF builtin"); 2706 2707 if (checkArgCount(*this, TheCall, 2)) 2708 return true; 2709 2710 // The second argument needs to be a constant int 2711 Expr *Arg = TheCall->getArg(1); 2712 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2713 diag::kind kind; 2714 if (!Value) { 2715 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2716 kind = diag::err_preserve_field_info_not_const; 2717 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2718 kind = diag::err_btf_type_id_not_const; 2719 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2720 kind = diag::err_preserve_type_info_not_const; 2721 else 2722 kind = diag::err_preserve_enum_value_not_const; 2723 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2724 return true; 2725 } 2726 2727 // The first argument 2728 Arg = TheCall->getArg(0); 2729 bool InvalidArg = false; 2730 bool ReturnUnsignedInt = true; 2731 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2732 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2733 InvalidArg = true; 2734 kind = diag::err_preserve_field_info_not_field; 2735 } 2736 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2737 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2738 InvalidArg = true; 2739 kind = diag::err_preserve_type_info_invalid; 2740 } 2741 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2742 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2743 InvalidArg = true; 2744 kind = diag::err_preserve_enum_value_invalid; 2745 } 2746 ReturnUnsignedInt = false; 2747 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2748 ReturnUnsignedInt = false; 2749 } 2750 2751 if (InvalidArg) { 2752 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2753 return true; 2754 } 2755 2756 if (ReturnUnsignedInt) 2757 TheCall->setType(Context.UnsignedIntTy); 2758 else 2759 TheCall->setType(Context.UnsignedLongTy); 2760 return false; 2761 } 2762 2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2764 struct ArgInfo { 2765 uint8_t OpNum; 2766 bool IsSigned; 2767 uint8_t BitWidth; 2768 uint8_t Align; 2769 }; 2770 struct BuiltinInfo { 2771 unsigned BuiltinID; 2772 ArgInfo Infos[2]; 2773 }; 2774 2775 static BuiltinInfo Infos[] = { 2776 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2777 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2778 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2779 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2780 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2782 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2783 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2784 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2785 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2786 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2787 2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2799 2800 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2852 {{ 1, false, 6, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2860 {{ 1, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2867 { 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2869 { 2, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2871 { 3, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2873 { 3, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2890 {{ 2, false, 4, 0 }, 2891 { 3, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2893 {{ 2, false, 4, 0 }, 2894 { 3, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2896 {{ 2, false, 4, 0 }, 2897 { 3, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2899 {{ 2, false, 4, 0 }, 2900 { 3, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2912 { 2, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2914 { 2, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2924 {{ 1, false, 4, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2927 {{ 1, false, 4, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2948 {{ 3, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2953 {{ 3, false, 1, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2958 {{ 3, false, 1, 0 }} }, 2959 }; 2960 2961 // Use a dynamically initialized static to sort the table exactly once on 2962 // first run. 2963 static const bool SortOnce = 2964 (llvm::sort(Infos, 2965 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2966 return LHS.BuiltinID < RHS.BuiltinID; 2967 }), 2968 true); 2969 (void)SortOnce; 2970 2971 const BuiltinInfo *F = llvm::partition_point( 2972 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2973 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2974 return false; 2975 2976 bool Error = false; 2977 2978 for (const ArgInfo &A : F->Infos) { 2979 // Ignore empty ArgInfo elements. 2980 if (A.BitWidth == 0) 2981 continue; 2982 2983 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2984 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2985 if (!A.Align) { 2986 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2987 } else { 2988 unsigned M = 1 << A.Align; 2989 Min *= M; 2990 Max *= M; 2991 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2992 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2993 } 2994 } 2995 return Error; 2996 } 2997 2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2999 CallExpr *TheCall) { 3000 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3001 } 3002 3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3004 unsigned BuiltinID, CallExpr *TheCall) { 3005 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3006 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3007 } 3008 3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3010 CallExpr *TheCall) { 3011 3012 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3013 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3014 if (!TI.hasFeature("dsp")) 3015 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3016 } 3017 3018 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3019 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3020 if (!TI.hasFeature("dspr2")) 3021 return Diag(TheCall->getBeginLoc(), 3022 diag::err_mips_builtin_requires_dspr2); 3023 } 3024 3025 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3026 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3027 if (!TI.hasFeature("msa")) 3028 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3029 } 3030 3031 return false; 3032 } 3033 3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3036 // ordering for DSP is unspecified. MSA is ordered by the data format used 3037 // by the underlying instruction i.e., df/m, df/n and then by size. 3038 // 3039 // FIXME: The size tests here should instead be tablegen'd along with the 3040 // definitions from include/clang/Basic/BuiltinsMips.def. 3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3042 // be too. 3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3044 unsigned i = 0, l = 0, u = 0, m = 0; 3045 switch (BuiltinID) { 3046 default: return false; 3047 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3048 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3049 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3050 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3051 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3052 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3053 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3054 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3055 // df/m field. 3056 // These intrinsics take an unsigned 3 bit immediate. 3057 case Mips::BI__builtin_msa_bclri_b: 3058 case Mips::BI__builtin_msa_bnegi_b: 3059 case Mips::BI__builtin_msa_bseti_b: 3060 case Mips::BI__builtin_msa_sat_s_b: 3061 case Mips::BI__builtin_msa_sat_u_b: 3062 case Mips::BI__builtin_msa_slli_b: 3063 case Mips::BI__builtin_msa_srai_b: 3064 case Mips::BI__builtin_msa_srari_b: 3065 case Mips::BI__builtin_msa_srli_b: 3066 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3067 case Mips::BI__builtin_msa_binsli_b: 3068 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3069 // These intrinsics take an unsigned 4 bit immediate. 3070 case Mips::BI__builtin_msa_bclri_h: 3071 case Mips::BI__builtin_msa_bnegi_h: 3072 case Mips::BI__builtin_msa_bseti_h: 3073 case Mips::BI__builtin_msa_sat_s_h: 3074 case Mips::BI__builtin_msa_sat_u_h: 3075 case Mips::BI__builtin_msa_slli_h: 3076 case Mips::BI__builtin_msa_srai_h: 3077 case Mips::BI__builtin_msa_srari_h: 3078 case Mips::BI__builtin_msa_srli_h: 3079 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3080 case Mips::BI__builtin_msa_binsli_h: 3081 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3082 // These intrinsics take an unsigned 5 bit immediate. 3083 // The first block of intrinsics actually have an unsigned 5 bit field, 3084 // not a df/n field. 3085 case Mips::BI__builtin_msa_cfcmsa: 3086 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3087 case Mips::BI__builtin_msa_clei_u_b: 3088 case Mips::BI__builtin_msa_clei_u_h: 3089 case Mips::BI__builtin_msa_clei_u_w: 3090 case Mips::BI__builtin_msa_clei_u_d: 3091 case Mips::BI__builtin_msa_clti_u_b: 3092 case Mips::BI__builtin_msa_clti_u_h: 3093 case Mips::BI__builtin_msa_clti_u_w: 3094 case Mips::BI__builtin_msa_clti_u_d: 3095 case Mips::BI__builtin_msa_maxi_u_b: 3096 case Mips::BI__builtin_msa_maxi_u_h: 3097 case Mips::BI__builtin_msa_maxi_u_w: 3098 case Mips::BI__builtin_msa_maxi_u_d: 3099 case Mips::BI__builtin_msa_mini_u_b: 3100 case Mips::BI__builtin_msa_mini_u_h: 3101 case Mips::BI__builtin_msa_mini_u_w: 3102 case Mips::BI__builtin_msa_mini_u_d: 3103 case Mips::BI__builtin_msa_addvi_b: 3104 case Mips::BI__builtin_msa_addvi_h: 3105 case Mips::BI__builtin_msa_addvi_w: 3106 case Mips::BI__builtin_msa_addvi_d: 3107 case Mips::BI__builtin_msa_bclri_w: 3108 case Mips::BI__builtin_msa_bnegi_w: 3109 case Mips::BI__builtin_msa_bseti_w: 3110 case Mips::BI__builtin_msa_sat_s_w: 3111 case Mips::BI__builtin_msa_sat_u_w: 3112 case Mips::BI__builtin_msa_slli_w: 3113 case Mips::BI__builtin_msa_srai_w: 3114 case Mips::BI__builtin_msa_srari_w: 3115 case Mips::BI__builtin_msa_srli_w: 3116 case Mips::BI__builtin_msa_srlri_w: 3117 case Mips::BI__builtin_msa_subvi_b: 3118 case Mips::BI__builtin_msa_subvi_h: 3119 case Mips::BI__builtin_msa_subvi_w: 3120 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3121 case Mips::BI__builtin_msa_binsli_w: 3122 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3123 // These intrinsics take an unsigned 6 bit immediate. 3124 case Mips::BI__builtin_msa_bclri_d: 3125 case Mips::BI__builtin_msa_bnegi_d: 3126 case Mips::BI__builtin_msa_bseti_d: 3127 case Mips::BI__builtin_msa_sat_s_d: 3128 case Mips::BI__builtin_msa_sat_u_d: 3129 case Mips::BI__builtin_msa_slli_d: 3130 case Mips::BI__builtin_msa_srai_d: 3131 case Mips::BI__builtin_msa_srari_d: 3132 case Mips::BI__builtin_msa_srli_d: 3133 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3134 case Mips::BI__builtin_msa_binsli_d: 3135 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3136 // These intrinsics take a signed 5 bit immediate. 3137 case Mips::BI__builtin_msa_ceqi_b: 3138 case Mips::BI__builtin_msa_ceqi_h: 3139 case Mips::BI__builtin_msa_ceqi_w: 3140 case Mips::BI__builtin_msa_ceqi_d: 3141 case Mips::BI__builtin_msa_clti_s_b: 3142 case Mips::BI__builtin_msa_clti_s_h: 3143 case Mips::BI__builtin_msa_clti_s_w: 3144 case Mips::BI__builtin_msa_clti_s_d: 3145 case Mips::BI__builtin_msa_clei_s_b: 3146 case Mips::BI__builtin_msa_clei_s_h: 3147 case Mips::BI__builtin_msa_clei_s_w: 3148 case Mips::BI__builtin_msa_clei_s_d: 3149 case Mips::BI__builtin_msa_maxi_s_b: 3150 case Mips::BI__builtin_msa_maxi_s_h: 3151 case Mips::BI__builtin_msa_maxi_s_w: 3152 case Mips::BI__builtin_msa_maxi_s_d: 3153 case Mips::BI__builtin_msa_mini_s_b: 3154 case Mips::BI__builtin_msa_mini_s_h: 3155 case Mips::BI__builtin_msa_mini_s_w: 3156 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3157 // These intrinsics take an unsigned 8 bit immediate. 3158 case Mips::BI__builtin_msa_andi_b: 3159 case Mips::BI__builtin_msa_nori_b: 3160 case Mips::BI__builtin_msa_ori_b: 3161 case Mips::BI__builtin_msa_shf_b: 3162 case Mips::BI__builtin_msa_shf_h: 3163 case Mips::BI__builtin_msa_shf_w: 3164 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3165 case Mips::BI__builtin_msa_bseli_b: 3166 case Mips::BI__builtin_msa_bmnzi_b: 3167 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3168 // df/n format 3169 // These intrinsics take an unsigned 4 bit immediate. 3170 case Mips::BI__builtin_msa_copy_s_b: 3171 case Mips::BI__builtin_msa_copy_u_b: 3172 case Mips::BI__builtin_msa_insve_b: 3173 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3174 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3175 // These intrinsics take an unsigned 3 bit immediate. 3176 case Mips::BI__builtin_msa_copy_s_h: 3177 case Mips::BI__builtin_msa_copy_u_h: 3178 case Mips::BI__builtin_msa_insve_h: 3179 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3180 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3181 // These intrinsics take an unsigned 2 bit immediate. 3182 case Mips::BI__builtin_msa_copy_s_w: 3183 case Mips::BI__builtin_msa_copy_u_w: 3184 case Mips::BI__builtin_msa_insve_w: 3185 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3186 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3187 // These intrinsics take an unsigned 1 bit immediate. 3188 case Mips::BI__builtin_msa_copy_s_d: 3189 case Mips::BI__builtin_msa_copy_u_d: 3190 case Mips::BI__builtin_msa_insve_d: 3191 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3192 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3193 // Memory offsets and immediate loads. 3194 // These intrinsics take a signed 10 bit immediate. 3195 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3196 case Mips::BI__builtin_msa_ldi_h: 3197 case Mips::BI__builtin_msa_ldi_w: 3198 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3199 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3200 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3201 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3202 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3203 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3204 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3205 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3206 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3207 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3208 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3209 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3210 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3211 } 3212 3213 if (!m) 3214 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3215 3216 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3217 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3218 } 3219 3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3221 /// advancing the pointer over the consumed characters. The decoded type is 3222 /// returned. If the decoded type represents a constant integer with a 3223 /// constraint on its value then Mask is set to that value. The type descriptors 3224 /// used in Str are specific to PPC MMA builtins and are documented in the file 3225 /// defining the PPC builtins. 3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3227 unsigned &Mask) { 3228 bool RequireICE = false; 3229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3230 switch (*Str++) { 3231 case 'V': 3232 return Context.getVectorType(Context.UnsignedCharTy, 16, 3233 VectorType::VectorKind::AltiVecVector); 3234 case 'i': { 3235 char *End; 3236 unsigned size = strtoul(Str, &End, 10); 3237 assert(End != Str && "Missing constant parameter constraint"); 3238 Str = End; 3239 Mask = size; 3240 return Context.IntTy; 3241 } 3242 case 'W': { 3243 char *End; 3244 unsigned size = strtoul(Str, &End, 10); 3245 assert(End != Str && "Missing PowerPC MMA type size"); 3246 Str = End; 3247 QualType Type; 3248 switch (size) { 3249 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3250 case size: Type = Context.Id##Ty; break; 3251 #include "clang/Basic/PPCTypes.def" 3252 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3253 } 3254 bool CheckVectorArgs = false; 3255 while (!CheckVectorArgs) { 3256 switch (*Str++) { 3257 case '*': 3258 Type = Context.getPointerType(Type); 3259 break; 3260 case 'C': 3261 Type = Type.withConst(); 3262 break; 3263 default: 3264 CheckVectorArgs = true; 3265 --Str; 3266 break; 3267 } 3268 } 3269 return Type; 3270 } 3271 default: 3272 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3273 } 3274 } 3275 3276 static bool isPPC_64Builtin(unsigned BuiltinID) { 3277 // These builtins only work on PPC 64bit targets. 3278 switch (BuiltinID) { 3279 case PPC::BI__builtin_divde: 3280 case PPC::BI__builtin_divdeu: 3281 case PPC::BI__builtin_bpermd: 3282 case PPC::BI__builtin_ppc_ldarx: 3283 case PPC::BI__builtin_ppc_stdcx: 3284 case PPC::BI__builtin_ppc_tdw: 3285 case PPC::BI__builtin_ppc_trapd: 3286 case PPC::BI__builtin_ppc_cmpeqb: 3287 case PPC::BI__builtin_ppc_setb: 3288 case PPC::BI__builtin_ppc_mulhd: 3289 case PPC::BI__builtin_ppc_mulhdu: 3290 case PPC::BI__builtin_ppc_maddhd: 3291 case PPC::BI__builtin_ppc_maddhdu: 3292 case PPC::BI__builtin_ppc_maddld: 3293 case PPC::BI__builtin_ppc_load8r: 3294 case PPC::BI__builtin_ppc_store8r: 3295 case PPC::BI__builtin_ppc_insert_exp: 3296 case PPC::BI__builtin_ppc_extract_sig: 3297 case PPC::BI__builtin_ppc_addex: 3298 case PPC::BI__builtin_darn: 3299 case PPC::BI__builtin_darn_raw: 3300 case PPC::BI__builtin_ppc_compare_and_swaplp: 3301 case PPC::BI__builtin_ppc_fetch_and_addlp: 3302 case PPC::BI__builtin_ppc_fetch_and_andlp: 3303 case PPC::BI__builtin_ppc_fetch_and_orlp: 3304 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3305 return true; 3306 } 3307 return false; 3308 } 3309 3310 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3311 StringRef FeatureToCheck, unsigned DiagID, 3312 StringRef DiagArg = "") { 3313 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3314 return false; 3315 3316 if (DiagArg.empty()) 3317 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3318 else 3319 S.Diag(TheCall->getBeginLoc(), DiagID) 3320 << DiagArg << TheCall->getSourceRange(); 3321 3322 return true; 3323 } 3324 3325 /// Returns true if the argument consists of one contiguous run of 1s with any 3326 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3327 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3328 /// since all 1s are not contiguous. 3329 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3330 llvm::APSInt Result; 3331 // We can't check the value of a dependent argument. 3332 Expr *Arg = TheCall->getArg(ArgNum); 3333 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3334 return false; 3335 3336 // Check constant-ness first. 3337 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3338 return true; 3339 3340 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3341 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3342 return false; 3343 3344 return Diag(TheCall->getBeginLoc(), 3345 diag::err_argument_not_contiguous_bit_field) 3346 << ArgNum << Arg->getSourceRange(); 3347 } 3348 3349 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3350 CallExpr *TheCall) { 3351 unsigned i = 0, l = 0, u = 0; 3352 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3353 llvm::APSInt Result; 3354 3355 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3356 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3357 << TheCall->getSourceRange(); 3358 3359 switch (BuiltinID) { 3360 default: return false; 3361 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3362 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3363 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3364 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3365 case PPC::BI__builtin_altivec_dss: 3366 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3367 case PPC::BI__builtin_tbegin: 3368 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3369 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3370 case PPC::BI__builtin_tabortwc: 3371 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3372 case PPC::BI__builtin_tabortwci: 3373 case PPC::BI__builtin_tabortdci: 3374 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3375 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3376 case PPC::BI__builtin_altivec_dst: 3377 case PPC::BI__builtin_altivec_dstt: 3378 case PPC::BI__builtin_altivec_dstst: 3379 case PPC::BI__builtin_altivec_dststt: 3380 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3381 case PPC::BI__builtin_vsx_xxpermdi: 3382 case PPC::BI__builtin_vsx_xxsldwi: 3383 return SemaBuiltinVSX(TheCall); 3384 case PPC::BI__builtin_divwe: 3385 case PPC::BI__builtin_divweu: 3386 case PPC::BI__builtin_divde: 3387 case PPC::BI__builtin_divdeu: 3388 return SemaFeatureCheck(*this, TheCall, "extdiv", 3389 diag::err_ppc_builtin_only_on_arch, "7"); 3390 case PPC::BI__builtin_bpermd: 3391 return SemaFeatureCheck(*this, TheCall, "bpermd", 3392 diag::err_ppc_builtin_only_on_arch, "7"); 3393 case PPC::BI__builtin_unpack_vector_int128: 3394 return SemaFeatureCheck(*this, TheCall, "vsx", 3395 diag::err_ppc_builtin_only_on_arch, "7") || 3396 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3397 case PPC::BI__builtin_pack_vector_int128: 3398 return SemaFeatureCheck(*this, TheCall, "vsx", 3399 diag::err_ppc_builtin_only_on_arch, "7"); 3400 case PPC::BI__builtin_altivec_vgnb: 3401 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3402 case PPC::BI__builtin_altivec_vec_replace_elt: 3403 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3404 QualType VecTy = TheCall->getArg(0)->getType(); 3405 QualType EltTy = TheCall->getArg(1)->getType(); 3406 unsigned Width = Context.getIntWidth(EltTy); 3407 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3408 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3409 } 3410 case PPC::BI__builtin_vsx_xxeval: 3411 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3412 case PPC::BI__builtin_altivec_vsldbi: 3413 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3414 case PPC::BI__builtin_altivec_vsrdbi: 3415 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3416 case PPC::BI__builtin_vsx_xxpermx: 3417 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3418 case PPC::BI__builtin_ppc_tw: 3419 case PPC::BI__builtin_ppc_tdw: 3420 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3421 case PPC::BI__builtin_ppc_cmpeqb: 3422 case PPC::BI__builtin_ppc_setb: 3423 case PPC::BI__builtin_ppc_maddhd: 3424 case PPC::BI__builtin_ppc_maddhdu: 3425 case PPC::BI__builtin_ppc_maddld: 3426 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3427 diag::err_ppc_builtin_only_on_arch, "9"); 3428 case PPC::BI__builtin_ppc_cmprb: 3429 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3430 diag::err_ppc_builtin_only_on_arch, "9") || 3431 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3432 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3433 // be a constant that represents a contiguous bit field. 3434 case PPC::BI__builtin_ppc_rlwnm: 3435 return SemaValueIsRunOfOnes(TheCall, 2); 3436 case PPC::BI__builtin_ppc_rlwimi: 3437 case PPC::BI__builtin_ppc_rldimi: 3438 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3439 SemaValueIsRunOfOnes(TheCall, 3); 3440 case PPC::BI__builtin_ppc_extract_exp: 3441 case PPC::BI__builtin_ppc_extract_sig: 3442 case PPC::BI__builtin_ppc_insert_exp: 3443 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3444 diag::err_ppc_builtin_only_on_arch, "9"); 3445 case PPC::BI__builtin_ppc_addex: { 3446 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3447 diag::err_ppc_builtin_only_on_arch, "9") || 3448 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3449 return true; 3450 // Output warning for reserved values 1 to 3. 3451 int ArgValue = 3452 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3453 if (ArgValue != 0) 3454 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3455 << ArgValue; 3456 return false; 3457 } 3458 case PPC::BI__builtin_ppc_mtfsb0: 3459 case PPC::BI__builtin_ppc_mtfsb1: 3460 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3461 case PPC::BI__builtin_ppc_mtfsf: 3462 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3463 case PPC::BI__builtin_ppc_mtfsfi: 3464 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3465 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3466 case PPC::BI__builtin_ppc_alignx: 3467 return SemaBuiltinConstantArgPower2(TheCall, 0); 3468 case PPC::BI__builtin_ppc_rdlam: 3469 return SemaValueIsRunOfOnes(TheCall, 2); 3470 case PPC::BI__builtin_ppc_icbt: 3471 case PPC::BI__builtin_ppc_sthcx: 3472 case PPC::BI__builtin_ppc_stbcx: 3473 case PPC::BI__builtin_ppc_lharx: 3474 case PPC::BI__builtin_ppc_lbarx: 3475 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3476 diag::err_ppc_builtin_only_on_arch, "8"); 3477 case PPC::BI__builtin_vsx_ldrmb: 3478 case PPC::BI__builtin_vsx_strmb: 3479 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3480 diag::err_ppc_builtin_only_on_arch, "8") || 3481 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3482 case PPC::BI__builtin_altivec_vcntmbb: 3483 case PPC::BI__builtin_altivec_vcntmbh: 3484 case PPC::BI__builtin_altivec_vcntmbw: 3485 case PPC::BI__builtin_altivec_vcntmbd: 3486 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3487 case PPC::BI__builtin_darn: 3488 case PPC::BI__builtin_darn_raw: 3489 case PPC::BI__builtin_darn_32: 3490 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3491 diag::err_ppc_builtin_only_on_arch, "9"); 3492 case PPC::BI__builtin_vsx_xxgenpcvbm: 3493 case PPC::BI__builtin_vsx_xxgenpcvhm: 3494 case PPC::BI__builtin_vsx_xxgenpcvwm: 3495 case PPC::BI__builtin_vsx_xxgenpcvdm: 3496 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3497 case PPC::BI__builtin_ppc_compare_exp_uo: 3498 case PPC::BI__builtin_ppc_compare_exp_lt: 3499 case PPC::BI__builtin_ppc_compare_exp_gt: 3500 case PPC::BI__builtin_ppc_compare_exp_eq: 3501 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3502 diag::err_ppc_builtin_only_on_arch, "9") || 3503 SemaFeatureCheck(*this, TheCall, "vsx", 3504 diag::err_ppc_builtin_requires_vsx); 3505 case PPC::BI__builtin_ppc_test_data_class: { 3506 // Check if the first argument of the __builtin_ppc_test_data_class call is 3507 // valid. The argument must be either a 'float' or a 'double'. 3508 QualType ArgType = TheCall->getArg(0)->getType(); 3509 if (ArgType != QualType(Context.FloatTy) && 3510 ArgType != QualType(Context.DoubleTy)) 3511 return Diag(TheCall->getBeginLoc(), 3512 diag::err_ppc_invalid_test_data_class_type); 3513 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3514 diag::err_ppc_builtin_only_on_arch, "9") || 3515 SemaFeatureCheck(*this, TheCall, "vsx", 3516 diag::err_ppc_builtin_requires_vsx) || 3517 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3518 } 3519 case PPC::BI__builtin_ppc_load8r: 3520 case PPC::BI__builtin_ppc_store8r: 3521 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3522 diag::err_ppc_builtin_only_on_arch, "7"); 3523 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3524 case PPC::BI__builtin_##Name: \ 3525 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3526 #include "clang/Basic/BuiltinsPPC.def" 3527 } 3528 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3529 } 3530 3531 // Check if the given type is a non-pointer PPC MMA type. This function is used 3532 // in Sema to prevent invalid uses of restricted PPC MMA types. 3533 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3534 if (Type->isPointerType() || Type->isArrayType()) 3535 return false; 3536 3537 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3538 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3539 if (false 3540 #include "clang/Basic/PPCTypes.def" 3541 ) { 3542 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3543 return true; 3544 } 3545 return false; 3546 } 3547 3548 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3549 CallExpr *TheCall) { 3550 // position of memory order and scope arguments in the builtin 3551 unsigned OrderIndex, ScopeIndex; 3552 switch (BuiltinID) { 3553 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3554 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3555 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3556 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3557 OrderIndex = 2; 3558 ScopeIndex = 3; 3559 break; 3560 case AMDGPU::BI__builtin_amdgcn_fence: 3561 OrderIndex = 0; 3562 ScopeIndex = 1; 3563 break; 3564 default: 3565 return false; 3566 } 3567 3568 ExprResult Arg = TheCall->getArg(OrderIndex); 3569 auto ArgExpr = Arg.get(); 3570 Expr::EvalResult ArgResult; 3571 3572 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3573 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3574 << ArgExpr->getType(); 3575 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3576 3577 // Check validity of memory ordering as per C11 / C++11's memody model. 3578 // Only fence needs check. Atomic dec/inc allow all memory orders. 3579 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3580 return Diag(ArgExpr->getBeginLoc(), 3581 diag::warn_atomic_op_has_invalid_memory_order) 3582 << ArgExpr->getSourceRange(); 3583 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3584 case llvm::AtomicOrderingCABI::relaxed: 3585 case llvm::AtomicOrderingCABI::consume: 3586 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3587 return Diag(ArgExpr->getBeginLoc(), 3588 diag::warn_atomic_op_has_invalid_memory_order) 3589 << ArgExpr->getSourceRange(); 3590 break; 3591 case llvm::AtomicOrderingCABI::acquire: 3592 case llvm::AtomicOrderingCABI::release: 3593 case llvm::AtomicOrderingCABI::acq_rel: 3594 case llvm::AtomicOrderingCABI::seq_cst: 3595 break; 3596 } 3597 3598 Arg = TheCall->getArg(ScopeIndex); 3599 ArgExpr = Arg.get(); 3600 Expr::EvalResult ArgResult1; 3601 // Check that sync scope is a constant literal 3602 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3603 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3604 << ArgExpr->getType(); 3605 3606 return false; 3607 } 3608 3609 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3610 llvm::APSInt Result; 3611 3612 // We can't check the value of a dependent argument. 3613 Expr *Arg = TheCall->getArg(ArgNum); 3614 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3615 return false; 3616 3617 // Check constant-ness first. 3618 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3619 return true; 3620 3621 int64_t Val = Result.getSExtValue(); 3622 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3623 return false; 3624 3625 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3626 << Arg->getSourceRange(); 3627 } 3628 3629 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3630 unsigned BuiltinID, 3631 CallExpr *TheCall) { 3632 // CodeGenFunction can also detect this, but this gives a better error 3633 // message. 3634 bool FeatureMissing = false; 3635 SmallVector<StringRef> ReqFeatures; 3636 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3637 Features.split(ReqFeatures, ','); 3638 3639 // Check if each required feature is included 3640 for (StringRef F : ReqFeatures) { 3641 if (TI.hasFeature(F)) 3642 continue; 3643 3644 // If the feature is 64bit, alter the string so it will print better in 3645 // the diagnostic. 3646 if (F == "64bit") 3647 F = "RV64"; 3648 3649 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3650 F.consume_front("experimental-"); 3651 std::string FeatureStr = F.str(); 3652 FeatureStr[0] = std::toupper(FeatureStr[0]); 3653 3654 // Error message 3655 FeatureMissing = true; 3656 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3657 << TheCall->getSourceRange() << StringRef(FeatureStr); 3658 } 3659 3660 if (FeatureMissing) 3661 return true; 3662 3663 switch (BuiltinID) { 3664 case RISCVVector::BI__builtin_rvv_vsetvli: 3665 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3666 CheckRISCVLMUL(TheCall, 2); 3667 case RISCVVector::BI__builtin_rvv_vsetvlimax: 3668 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3669 CheckRISCVLMUL(TheCall, 1); 3670 case RISCVVector::BI__builtin_rvv_vget_v_i8m2_i8m1: 3671 case RISCVVector::BI__builtin_rvv_vget_v_i16m2_i16m1: 3672 case RISCVVector::BI__builtin_rvv_vget_v_i32m2_i32m1: 3673 case RISCVVector::BI__builtin_rvv_vget_v_i64m2_i64m1: 3674 case RISCVVector::BI__builtin_rvv_vget_v_f32m2_f32m1: 3675 case RISCVVector::BI__builtin_rvv_vget_v_f64m2_f64m1: 3676 case RISCVVector::BI__builtin_rvv_vget_v_u8m2_u8m1: 3677 case RISCVVector::BI__builtin_rvv_vget_v_u16m2_u16m1: 3678 case RISCVVector::BI__builtin_rvv_vget_v_u32m2_u32m1: 3679 case RISCVVector::BI__builtin_rvv_vget_v_u64m2_u64m1: 3680 case RISCVVector::BI__builtin_rvv_vget_v_i8m4_i8m2: 3681 case RISCVVector::BI__builtin_rvv_vget_v_i16m4_i16m2: 3682 case RISCVVector::BI__builtin_rvv_vget_v_i32m4_i32m2: 3683 case RISCVVector::BI__builtin_rvv_vget_v_i64m4_i64m2: 3684 case RISCVVector::BI__builtin_rvv_vget_v_f32m4_f32m2: 3685 case RISCVVector::BI__builtin_rvv_vget_v_f64m4_f64m2: 3686 case RISCVVector::BI__builtin_rvv_vget_v_u8m4_u8m2: 3687 case RISCVVector::BI__builtin_rvv_vget_v_u16m4_u16m2: 3688 case RISCVVector::BI__builtin_rvv_vget_v_u32m4_u32m2: 3689 case RISCVVector::BI__builtin_rvv_vget_v_u64m4_u64m2: 3690 case RISCVVector::BI__builtin_rvv_vget_v_i8m8_i8m4: 3691 case RISCVVector::BI__builtin_rvv_vget_v_i16m8_i16m4: 3692 case RISCVVector::BI__builtin_rvv_vget_v_i32m8_i32m4: 3693 case RISCVVector::BI__builtin_rvv_vget_v_i64m8_i64m4: 3694 case RISCVVector::BI__builtin_rvv_vget_v_f32m8_f32m4: 3695 case RISCVVector::BI__builtin_rvv_vget_v_f64m8_f64m4: 3696 case RISCVVector::BI__builtin_rvv_vget_v_u8m8_u8m4: 3697 case RISCVVector::BI__builtin_rvv_vget_v_u16m8_u16m4: 3698 case RISCVVector::BI__builtin_rvv_vget_v_u32m8_u32m4: 3699 case RISCVVector::BI__builtin_rvv_vget_v_u64m8_u64m4: 3700 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3701 case RISCVVector::BI__builtin_rvv_vget_v_i8m4_i8m1: 3702 case RISCVVector::BI__builtin_rvv_vget_v_i16m4_i16m1: 3703 case RISCVVector::BI__builtin_rvv_vget_v_i32m4_i32m1: 3704 case RISCVVector::BI__builtin_rvv_vget_v_i64m4_i64m1: 3705 case RISCVVector::BI__builtin_rvv_vget_v_f32m4_f32m1: 3706 case RISCVVector::BI__builtin_rvv_vget_v_f64m4_f64m1: 3707 case RISCVVector::BI__builtin_rvv_vget_v_u8m4_u8m1: 3708 case RISCVVector::BI__builtin_rvv_vget_v_u16m4_u16m1: 3709 case RISCVVector::BI__builtin_rvv_vget_v_u32m4_u32m1: 3710 case RISCVVector::BI__builtin_rvv_vget_v_u64m4_u64m1: 3711 case RISCVVector::BI__builtin_rvv_vget_v_i8m8_i8m2: 3712 case RISCVVector::BI__builtin_rvv_vget_v_i16m8_i16m2: 3713 case RISCVVector::BI__builtin_rvv_vget_v_i32m8_i32m2: 3714 case RISCVVector::BI__builtin_rvv_vget_v_i64m8_i64m2: 3715 case RISCVVector::BI__builtin_rvv_vget_v_f32m8_f32m2: 3716 case RISCVVector::BI__builtin_rvv_vget_v_f64m8_f64m2: 3717 case RISCVVector::BI__builtin_rvv_vget_v_u8m8_u8m2: 3718 case RISCVVector::BI__builtin_rvv_vget_v_u16m8_u16m2: 3719 case RISCVVector::BI__builtin_rvv_vget_v_u32m8_u32m2: 3720 case RISCVVector::BI__builtin_rvv_vget_v_u64m8_u64m2: 3721 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3722 case RISCVVector::BI__builtin_rvv_vget_v_i8m8_i8m1: 3723 case RISCVVector::BI__builtin_rvv_vget_v_i16m8_i16m1: 3724 case RISCVVector::BI__builtin_rvv_vget_v_i32m8_i32m1: 3725 case RISCVVector::BI__builtin_rvv_vget_v_i64m8_i64m1: 3726 case RISCVVector::BI__builtin_rvv_vget_v_f32m8_f32m1: 3727 case RISCVVector::BI__builtin_rvv_vget_v_f64m8_f64m1: 3728 case RISCVVector::BI__builtin_rvv_vget_v_u8m8_u8m1: 3729 case RISCVVector::BI__builtin_rvv_vget_v_u16m8_u16m1: 3730 case RISCVVector::BI__builtin_rvv_vget_v_u32m8_u32m1: 3731 case RISCVVector::BI__builtin_rvv_vget_v_u64m8_u64m1: 3732 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3733 case RISCVVector::BI__builtin_rvv_vset_v_i8m1_i8m2: 3734 case RISCVVector::BI__builtin_rvv_vset_v_i16m1_i16m2: 3735 case RISCVVector::BI__builtin_rvv_vset_v_i32m1_i32m2: 3736 case RISCVVector::BI__builtin_rvv_vset_v_i64m1_i64m2: 3737 case RISCVVector::BI__builtin_rvv_vset_v_f32m1_f32m2: 3738 case RISCVVector::BI__builtin_rvv_vset_v_f64m1_f64m2: 3739 case RISCVVector::BI__builtin_rvv_vset_v_u8m1_u8m2: 3740 case RISCVVector::BI__builtin_rvv_vset_v_u16m1_u16m2: 3741 case RISCVVector::BI__builtin_rvv_vset_v_u32m1_u32m2: 3742 case RISCVVector::BI__builtin_rvv_vset_v_u64m1_u64m2: 3743 case RISCVVector::BI__builtin_rvv_vset_v_i8m2_i8m4: 3744 case RISCVVector::BI__builtin_rvv_vset_v_i16m2_i16m4: 3745 case RISCVVector::BI__builtin_rvv_vset_v_i32m2_i32m4: 3746 case RISCVVector::BI__builtin_rvv_vset_v_i64m2_i64m4: 3747 case RISCVVector::BI__builtin_rvv_vset_v_f32m2_f32m4: 3748 case RISCVVector::BI__builtin_rvv_vset_v_f64m2_f64m4: 3749 case RISCVVector::BI__builtin_rvv_vset_v_u8m2_u8m4: 3750 case RISCVVector::BI__builtin_rvv_vset_v_u16m2_u16m4: 3751 case RISCVVector::BI__builtin_rvv_vset_v_u32m2_u32m4: 3752 case RISCVVector::BI__builtin_rvv_vset_v_u64m2_u64m4: 3753 case RISCVVector::BI__builtin_rvv_vset_v_i8m4_i8m8: 3754 case RISCVVector::BI__builtin_rvv_vset_v_i16m4_i16m8: 3755 case RISCVVector::BI__builtin_rvv_vset_v_i32m4_i32m8: 3756 case RISCVVector::BI__builtin_rvv_vset_v_i64m4_i64m8: 3757 case RISCVVector::BI__builtin_rvv_vset_v_f32m4_f32m8: 3758 case RISCVVector::BI__builtin_rvv_vset_v_f64m4_f64m8: 3759 case RISCVVector::BI__builtin_rvv_vset_v_u8m4_u8m8: 3760 case RISCVVector::BI__builtin_rvv_vset_v_u16m4_u16m8: 3761 case RISCVVector::BI__builtin_rvv_vset_v_u32m4_u32m8: 3762 case RISCVVector::BI__builtin_rvv_vset_v_u64m4_u64m8: 3763 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3764 case RISCVVector::BI__builtin_rvv_vset_v_i8m1_i8m4: 3765 case RISCVVector::BI__builtin_rvv_vset_v_i16m1_i16m4: 3766 case RISCVVector::BI__builtin_rvv_vset_v_i32m1_i32m4: 3767 case RISCVVector::BI__builtin_rvv_vset_v_i64m1_i64m4: 3768 case RISCVVector::BI__builtin_rvv_vset_v_f32m1_f32m4: 3769 case RISCVVector::BI__builtin_rvv_vset_v_f64m1_f64m4: 3770 case RISCVVector::BI__builtin_rvv_vset_v_u8m1_u8m4: 3771 case RISCVVector::BI__builtin_rvv_vset_v_u16m1_u16m4: 3772 case RISCVVector::BI__builtin_rvv_vset_v_u32m1_u32m4: 3773 case RISCVVector::BI__builtin_rvv_vset_v_u64m1_u64m4: 3774 case RISCVVector::BI__builtin_rvv_vset_v_i8m2_i8m8: 3775 case RISCVVector::BI__builtin_rvv_vset_v_i16m2_i16m8: 3776 case RISCVVector::BI__builtin_rvv_vset_v_i32m2_i32m8: 3777 case RISCVVector::BI__builtin_rvv_vset_v_i64m2_i64m8: 3778 case RISCVVector::BI__builtin_rvv_vset_v_f32m2_f32m8: 3779 case RISCVVector::BI__builtin_rvv_vset_v_f64m2_f64m8: 3780 case RISCVVector::BI__builtin_rvv_vset_v_u8m2_u8m8: 3781 case RISCVVector::BI__builtin_rvv_vset_v_u16m2_u16m8: 3782 case RISCVVector::BI__builtin_rvv_vset_v_u32m2_u32m8: 3783 case RISCVVector::BI__builtin_rvv_vset_v_u64m2_u64m8: 3784 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3785 case RISCVVector::BI__builtin_rvv_vset_v_i8m1_i8m8: 3786 case RISCVVector::BI__builtin_rvv_vset_v_i16m1_i16m8: 3787 case RISCVVector::BI__builtin_rvv_vset_v_i32m1_i32m8: 3788 case RISCVVector::BI__builtin_rvv_vset_v_i64m1_i64m8: 3789 case RISCVVector::BI__builtin_rvv_vset_v_f32m1_f32m8: 3790 case RISCVVector::BI__builtin_rvv_vset_v_f64m1_f64m8: 3791 case RISCVVector::BI__builtin_rvv_vset_v_u8m1_u8m8: 3792 case RISCVVector::BI__builtin_rvv_vset_v_u16m1_u16m8: 3793 case RISCVVector::BI__builtin_rvv_vset_v_u32m1_u32m8: 3794 case RISCVVector::BI__builtin_rvv_vset_v_u64m1_u64m8: 3795 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3796 } 3797 3798 return false; 3799 } 3800 3801 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3802 CallExpr *TheCall) { 3803 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3804 Expr *Arg = TheCall->getArg(0); 3805 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3806 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3807 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3808 << Arg->getSourceRange(); 3809 } 3810 3811 // For intrinsics which take an immediate value as part of the instruction, 3812 // range check them here. 3813 unsigned i = 0, l = 0, u = 0; 3814 switch (BuiltinID) { 3815 default: return false; 3816 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3817 case SystemZ::BI__builtin_s390_verimb: 3818 case SystemZ::BI__builtin_s390_verimh: 3819 case SystemZ::BI__builtin_s390_verimf: 3820 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3821 case SystemZ::BI__builtin_s390_vfaeb: 3822 case SystemZ::BI__builtin_s390_vfaeh: 3823 case SystemZ::BI__builtin_s390_vfaef: 3824 case SystemZ::BI__builtin_s390_vfaebs: 3825 case SystemZ::BI__builtin_s390_vfaehs: 3826 case SystemZ::BI__builtin_s390_vfaefs: 3827 case SystemZ::BI__builtin_s390_vfaezb: 3828 case SystemZ::BI__builtin_s390_vfaezh: 3829 case SystemZ::BI__builtin_s390_vfaezf: 3830 case SystemZ::BI__builtin_s390_vfaezbs: 3831 case SystemZ::BI__builtin_s390_vfaezhs: 3832 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3833 case SystemZ::BI__builtin_s390_vfisb: 3834 case SystemZ::BI__builtin_s390_vfidb: 3835 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3837 case SystemZ::BI__builtin_s390_vftcisb: 3838 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3839 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3840 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3841 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3842 case SystemZ::BI__builtin_s390_vstrcb: 3843 case SystemZ::BI__builtin_s390_vstrch: 3844 case SystemZ::BI__builtin_s390_vstrcf: 3845 case SystemZ::BI__builtin_s390_vstrczb: 3846 case SystemZ::BI__builtin_s390_vstrczh: 3847 case SystemZ::BI__builtin_s390_vstrczf: 3848 case SystemZ::BI__builtin_s390_vstrcbs: 3849 case SystemZ::BI__builtin_s390_vstrchs: 3850 case SystemZ::BI__builtin_s390_vstrcfs: 3851 case SystemZ::BI__builtin_s390_vstrczbs: 3852 case SystemZ::BI__builtin_s390_vstrczhs: 3853 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3854 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3855 case SystemZ::BI__builtin_s390_vfminsb: 3856 case SystemZ::BI__builtin_s390_vfmaxsb: 3857 case SystemZ::BI__builtin_s390_vfmindb: 3858 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3859 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3860 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3861 case SystemZ::BI__builtin_s390_vclfnhs: 3862 case SystemZ::BI__builtin_s390_vclfnls: 3863 case SystemZ::BI__builtin_s390_vcfn: 3864 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3865 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3866 } 3867 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3868 } 3869 3870 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3871 /// This checks that the target supports __builtin_cpu_supports and 3872 /// that the string argument is constant and valid. 3873 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3874 CallExpr *TheCall) { 3875 Expr *Arg = TheCall->getArg(0); 3876 3877 // Check if the argument is a string literal. 3878 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3879 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3880 << Arg->getSourceRange(); 3881 3882 // Check the contents of the string. 3883 StringRef Feature = 3884 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3885 if (!TI.validateCpuSupports(Feature)) 3886 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3887 << Arg->getSourceRange(); 3888 return false; 3889 } 3890 3891 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3892 /// This checks that the target supports __builtin_cpu_is and 3893 /// that the string argument is constant and valid. 3894 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3895 Expr *Arg = TheCall->getArg(0); 3896 3897 // Check if the argument is a string literal. 3898 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3899 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3900 << Arg->getSourceRange(); 3901 3902 // Check the contents of the string. 3903 StringRef Feature = 3904 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3905 if (!TI.validateCpuIs(Feature)) 3906 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3907 << Arg->getSourceRange(); 3908 return false; 3909 } 3910 3911 // Check if the rounding mode is legal. 3912 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3913 // Indicates if this instruction has rounding control or just SAE. 3914 bool HasRC = false; 3915 3916 unsigned ArgNum = 0; 3917 switch (BuiltinID) { 3918 default: 3919 return false; 3920 case X86::BI__builtin_ia32_vcvttsd2si32: 3921 case X86::BI__builtin_ia32_vcvttsd2si64: 3922 case X86::BI__builtin_ia32_vcvttsd2usi32: 3923 case X86::BI__builtin_ia32_vcvttsd2usi64: 3924 case X86::BI__builtin_ia32_vcvttss2si32: 3925 case X86::BI__builtin_ia32_vcvttss2si64: 3926 case X86::BI__builtin_ia32_vcvttss2usi32: 3927 case X86::BI__builtin_ia32_vcvttss2usi64: 3928 case X86::BI__builtin_ia32_vcvttsh2si32: 3929 case X86::BI__builtin_ia32_vcvttsh2si64: 3930 case X86::BI__builtin_ia32_vcvttsh2usi32: 3931 case X86::BI__builtin_ia32_vcvttsh2usi64: 3932 ArgNum = 1; 3933 break; 3934 case X86::BI__builtin_ia32_maxpd512: 3935 case X86::BI__builtin_ia32_maxps512: 3936 case X86::BI__builtin_ia32_minpd512: 3937 case X86::BI__builtin_ia32_minps512: 3938 case X86::BI__builtin_ia32_maxph512: 3939 case X86::BI__builtin_ia32_minph512: 3940 ArgNum = 2; 3941 break; 3942 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3943 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3944 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3945 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3946 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3947 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3948 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3949 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3950 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3951 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3952 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3953 case X86::BI__builtin_ia32_vcvttph2w512_mask: 3954 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 3955 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 3956 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 3957 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 3958 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 3959 case X86::BI__builtin_ia32_exp2pd_mask: 3960 case X86::BI__builtin_ia32_exp2ps_mask: 3961 case X86::BI__builtin_ia32_getexppd512_mask: 3962 case X86::BI__builtin_ia32_getexpps512_mask: 3963 case X86::BI__builtin_ia32_getexpph512_mask: 3964 case X86::BI__builtin_ia32_rcp28pd_mask: 3965 case X86::BI__builtin_ia32_rcp28ps_mask: 3966 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3967 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3968 case X86::BI__builtin_ia32_vcomisd: 3969 case X86::BI__builtin_ia32_vcomiss: 3970 case X86::BI__builtin_ia32_vcomish: 3971 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3972 ArgNum = 3; 3973 break; 3974 case X86::BI__builtin_ia32_cmppd512_mask: 3975 case X86::BI__builtin_ia32_cmpps512_mask: 3976 case X86::BI__builtin_ia32_cmpsd_mask: 3977 case X86::BI__builtin_ia32_cmpss_mask: 3978 case X86::BI__builtin_ia32_cmpsh_mask: 3979 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 3980 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 3981 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3982 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3983 case X86::BI__builtin_ia32_getexpss128_round_mask: 3984 case X86::BI__builtin_ia32_getexpsh128_round_mask: 3985 case X86::BI__builtin_ia32_getmantpd512_mask: 3986 case X86::BI__builtin_ia32_getmantps512_mask: 3987 case X86::BI__builtin_ia32_getmantph512_mask: 3988 case X86::BI__builtin_ia32_maxsd_round_mask: 3989 case X86::BI__builtin_ia32_maxss_round_mask: 3990 case X86::BI__builtin_ia32_maxsh_round_mask: 3991 case X86::BI__builtin_ia32_minsd_round_mask: 3992 case X86::BI__builtin_ia32_minss_round_mask: 3993 case X86::BI__builtin_ia32_minsh_round_mask: 3994 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3995 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3996 case X86::BI__builtin_ia32_reducepd512_mask: 3997 case X86::BI__builtin_ia32_reduceps512_mask: 3998 case X86::BI__builtin_ia32_reduceph512_mask: 3999 case X86::BI__builtin_ia32_rndscalepd_mask: 4000 case X86::BI__builtin_ia32_rndscaleps_mask: 4001 case X86::BI__builtin_ia32_rndscaleph_mask: 4002 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4003 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4004 ArgNum = 4; 4005 break; 4006 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4007 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4008 case X86::BI__builtin_ia32_fixupimmps512_mask: 4009 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4010 case X86::BI__builtin_ia32_fixupimmsd_mask: 4011 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4012 case X86::BI__builtin_ia32_fixupimmss_mask: 4013 case X86::BI__builtin_ia32_fixupimmss_maskz: 4014 case X86::BI__builtin_ia32_getmantsd_round_mask: 4015 case X86::BI__builtin_ia32_getmantss_round_mask: 4016 case X86::BI__builtin_ia32_getmantsh_round_mask: 4017 case X86::BI__builtin_ia32_rangepd512_mask: 4018 case X86::BI__builtin_ia32_rangeps512_mask: 4019 case X86::BI__builtin_ia32_rangesd128_round_mask: 4020 case X86::BI__builtin_ia32_rangess128_round_mask: 4021 case X86::BI__builtin_ia32_reducesd_mask: 4022 case X86::BI__builtin_ia32_reducess_mask: 4023 case X86::BI__builtin_ia32_reducesh_mask: 4024 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4025 case X86::BI__builtin_ia32_rndscaless_round_mask: 4026 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4027 ArgNum = 5; 4028 break; 4029 case X86::BI__builtin_ia32_vcvtsd2si64: 4030 case X86::BI__builtin_ia32_vcvtsd2si32: 4031 case X86::BI__builtin_ia32_vcvtsd2usi32: 4032 case X86::BI__builtin_ia32_vcvtsd2usi64: 4033 case X86::BI__builtin_ia32_vcvtss2si32: 4034 case X86::BI__builtin_ia32_vcvtss2si64: 4035 case X86::BI__builtin_ia32_vcvtss2usi32: 4036 case X86::BI__builtin_ia32_vcvtss2usi64: 4037 case X86::BI__builtin_ia32_vcvtsh2si32: 4038 case X86::BI__builtin_ia32_vcvtsh2si64: 4039 case X86::BI__builtin_ia32_vcvtsh2usi32: 4040 case X86::BI__builtin_ia32_vcvtsh2usi64: 4041 case X86::BI__builtin_ia32_sqrtpd512: 4042 case X86::BI__builtin_ia32_sqrtps512: 4043 case X86::BI__builtin_ia32_sqrtph512: 4044 ArgNum = 1; 4045 HasRC = true; 4046 break; 4047 case X86::BI__builtin_ia32_addph512: 4048 case X86::BI__builtin_ia32_divph512: 4049 case X86::BI__builtin_ia32_mulph512: 4050 case X86::BI__builtin_ia32_subph512: 4051 case X86::BI__builtin_ia32_addpd512: 4052 case X86::BI__builtin_ia32_addps512: 4053 case X86::BI__builtin_ia32_divpd512: 4054 case X86::BI__builtin_ia32_divps512: 4055 case X86::BI__builtin_ia32_mulpd512: 4056 case X86::BI__builtin_ia32_mulps512: 4057 case X86::BI__builtin_ia32_subpd512: 4058 case X86::BI__builtin_ia32_subps512: 4059 case X86::BI__builtin_ia32_cvtsi2sd64: 4060 case X86::BI__builtin_ia32_cvtsi2ss32: 4061 case X86::BI__builtin_ia32_cvtsi2ss64: 4062 case X86::BI__builtin_ia32_cvtusi2sd64: 4063 case X86::BI__builtin_ia32_cvtusi2ss32: 4064 case X86::BI__builtin_ia32_cvtusi2ss64: 4065 case X86::BI__builtin_ia32_vcvtusi2sh: 4066 case X86::BI__builtin_ia32_vcvtusi642sh: 4067 case X86::BI__builtin_ia32_vcvtsi2sh: 4068 case X86::BI__builtin_ia32_vcvtsi642sh: 4069 ArgNum = 2; 4070 HasRC = true; 4071 break; 4072 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4073 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4074 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4075 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4076 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4077 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4078 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4079 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4080 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4081 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4082 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4083 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4084 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4085 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4086 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4087 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4088 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4089 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4090 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4091 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4092 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4093 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4094 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4095 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4096 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4097 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4098 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4099 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4100 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4101 ArgNum = 3; 4102 HasRC = true; 4103 break; 4104 case X86::BI__builtin_ia32_addsh_round_mask: 4105 case X86::BI__builtin_ia32_addss_round_mask: 4106 case X86::BI__builtin_ia32_addsd_round_mask: 4107 case X86::BI__builtin_ia32_divsh_round_mask: 4108 case X86::BI__builtin_ia32_divss_round_mask: 4109 case X86::BI__builtin_ia32_divsd_round_mask: 4110 case X86::BI__builtin_ia32_mulsh_round_mask: 4111 case X86::BI__builtin_ia32_mulss_round_mask: 4112 case X86::BI__builtin_ia32_mulsd_round_mask: 4113 case X86::BI__builtin_ia32_subsh_round_mask: 4114 case X86::BI__builtin_ia32_subss_round_mask: 4115 case X86::BI__builtin_ia32_subsd_round_mask: 4116 case X86::BI__builtin_ia32_scalefph512_mask: 4117 case X86::BI__builtin_ia32_scalefpd512_mask: 4118 case X86::BI__builtin_ia32_scalefps512_mask: 4119 case X86::BI__builtin_ia32_scalefsd_round_mask: 4120 case X86::BI__builtin_ia32_scalefss_round_mask: 4121 case X86::BI__builtin_ia32_scalefsh_round_mask: 4122 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4123 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4124 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4125 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4126 case X86::BI__builtin_ia32_sqrtss_round_mask: 4127 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4128 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4129 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4130 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4131 case X86::BI__builtin_ia32_vfmaddss3_mask: 4132 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4133 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4134 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4135 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4136 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4137 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4138 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4139 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4140 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4141 case X86::BI__builtin_ia32_vfmaddps512_mask: 4142 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4143 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4144 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4145 case X86::BI__builtin_ia32_vfmaddph512_mask: 4146 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4147 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4148 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4149 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4150 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4151 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4152 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4153 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4154 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4155 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4156 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4157 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4158 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4159 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4160 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4161 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4162 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4163 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4164 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4165 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4166 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4167 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4168 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4169 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4170 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4171 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4172 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4173 case X86::BI__builtin_ia32_vfmulcsh_mask: 4174 case X86::BI__builtin_ia32_vfmulcph512_mask: 4175 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4176 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4177 ArgNum = 4; 4178 HasRC = true; 4179 break; 4180 } 4181 4182 llvm::APSInt Result; 4183 4184 // We can't check the value of a dependent argument. 4185 Expr *Arg = TheCall->getArg(ArgNum); 4186 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4187 return false; 4188 4189 // Check constant-ness first. 4190 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4191 return true; 4192 4193 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4194 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4195 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4196 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4197 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4198 Result == 8/*ROUND_NO_EXC*/ || 4199 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4200 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4201 return false; 4202 4203 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4204 << Arg->getSourceRange(); 4205 } 4206 4207 // Check if the gather/scatter scale is legal. 4208 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4209 CallExpr *TheCall) { 4210 unsigned ArgNum = 0; 4211 switch (BuiltinID) { 4212 default: 4213 return false; 4214 case X86::BI__builtin_ia32_gatherpfdpd: 4215 case X86::BI__builtin_ia32_gatherpfdps: 4216 case X86::BI__builtin_ia32_gatherpfqpd: 4217 case X86::BI__builtin_ia32_gatherpfqps: 4218 case X86::BI__builtin_ia32_scatterpfdpd: 4219 case X86::BI__builtin_ia32_scatterpfdps: 4220 case X86::BI__builtin_ia32_scatterpfqpd: 4221 case X86::BI__builtin_ia32_scatterpfqps: 4222 ArgNum = 3; 4223 break; 4224 case X86::BI__builtin_ia32_gatherd_pd: 4225 case X86::BI__builtin_ia32_gatherd_pd256: 4226 case X86::BI__builtin_ia32_gatherq_pd: 4227 case X86::BI__builtin_ia32_gatherq_pd256: 4228 case X86::BI__builtin_ia32_gatherd_ps: 4229 case X86::BI__builtin_ia32_gatherd_ps256: 4230 case X86::BI__builtin_ia32_gatherq_ps: 4231 case X86::BI__builtin_ia32_gatherq_ps256: 4232 case X86::BI__builtin_ia32_gatherd_q: 4233 case X86::BI__builtin_ia32_gatherd_q256: 4234 case X86::BI__builtin_ia32_gatherq_q: 4235 case X86::BI__builtin_ia32_gatherq_q256: 4236 case X86::BI__builtin_ia32_gatherd_d: 4237 case X86::BI__builtin_ia32_gatherd_d256: 4238 case X86::BI__builtin_ia32_gatherq_d: 4239 case X86::BI__builtin_ia32_gatherq_d256: 4240 case X86::BI__builtin_ia32_gather3div2df: 4241 case X86::BI__builtin_ia32_gather3div2di: 4242 case X86::BI__builtin_ia32_gather3div4df: 4243 case X86::BI__builtin_ia32_gather3div4di: 4244 case X86::BI__builtin_ia32_gather3div4sf: 4245 case X86::BI__builtin_ia32_gather3div4si: 4246 case X86::BI__builtin_ia32_gather3div8sf: 4247 case X86::BI__builtin_ia32_gather3div8si: 4248 case X86::BI__builtin_ia32_gather3siv2df: 4249 case X86::BI__builtin_ia32_gather3siv2di: 4250 case X86::BI__builtin_ia32_gather3siv4df: 4251 case X86::BI__builtin_ia32_gather3siv4di: 4252 case X86::BI__builtin_ia32_gather3siv4sf: 4253 case X86::BI__builtin_ia32_gather3siv4si: 4254 case X86::BI__builtin_ia32_gather3siv8sf: 4255 case X86::BI__builtin_ia32_gather3siv8si: 4256 case X86::BI__builtin_ia32_gathersiv8df: 4257 case X86::BI__builtin_ia32_gathersiv16sf: 4258 case X86::BI__builtin_ia32_gatherdiv8df: 4259 case X86::BI__builtin_ia32_gatherdiv16sf: 4260 case X86::BI__builtin_ia32_gathersiv8di: 4261 case X86::BI__builtin_ia32_gathersiv16si: 4262 case X86::BI__builtin_ia32_gatherdiv8di: 4263 case X86::BI__builtin_ia32_gatherdiv16si: 4264 case X86::BI__builtin_ia32_scatterdiv2df: 4265 case X86::BI__builtin_ia32_scatterdiv2di: 4266 case X86::BI__builtin_ia32_scatterdiv4df: 4267 case X86::BI__builtin_ia32_scatterdiv4di: 4268 case X86::BI__builtin_ia32_scatterdiv4sf: 4269 case X86::BI__builtin_ia32_scatterdiv4si: 4270 case X86::BI__builtin_ia32_scatterdiv8sf: 4271 case X86::BI__builtin_ia32_scatterdiv8si: 4272 case X86::BI__builtin_ia32_scattersiv2df: 4273 case X86::BI__builtin_ia32_scattersiv2di: 4274 case X86::BI__builtin_ia32_scattersiv4df: 4275 case X86::BI__builtin_ia32_scattersiv4di: 4276 case X86::BI__builtin_ia32_scattersiv4sf: 4277 case X86::BI__builtin_ia32_scattersiv4si: 4278 case X86::BI__builtin_ia32_scattersiv8sf: 4279 case X86::BI__builtin_ia32_scattersiv8si: 4280 case X86::BI__builtin_ia32_scattersiv8df: 4281 case X86::BI__builtin_ia32_scattersiv16sf: 4282 case X86::BI__builtin_ia32_scatterdiv8df: 4283 case X86::BI__builtin_ia32_scatterdiv16sf: 4284 case X86::BI__builtin_ia32_scattersiv8di: 4285 case X86::BI__builtin_ia32_scattersiv16si: 4286 case X86::BI__builtin_ia32_scatterdiv8di: 4287 case X86::BI__builtin_ia32_scatterdiv16si: 4288 ArgNum = 4; 4289 break; 4290 } 4291 4292 llvm::APSInt Result; 4293 4294 // We can't check the value of a dependent argument. 4295 Expr *Arg = TheCall->getArg(ArgNum); 4296 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4297 return false; 4298 4299 // Check constant-ness first. 4300 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4301 return true; 4302 4303 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4304 return false; 4305 4306 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4307 << Arg->getSourceRange(); 4308 } 4309 4310 enum { TileRegLow = 0, TileRegHigh = 7 }; 4311 4312 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4313 ArrayRef<int> ArgNums) { 4314 for (int ArgNum : ArgNums) { 4315 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4316 return true; 4317 } 4318 return false; 4319 } 4320 4321 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4322 ArrayRef<int> ArgNums) { 4323 // Because the max number of tile register is TileRegHigh + 1, so here we use 4324 // each bit to represent the usage of them in bitset. 4325 std::bitset<TileRegHigh + 1> ArgValues; 4326 for (int ArgNum : ArgNums) { 4327 Expr *Arg = TheCall->getArg(ArgNum); 4328 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4329 continue; 4330 4331 llvm::APSInt Result; 4332 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4333 return true; 4334 int ArgExtValue = Result.getExtValue(); 4335 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4336 "Incorrect tile register num."); 4337 if (ArgValues.test(ArgExtValue)) 4338 return Diag(TheCall->getBeginLoc(), 4339 diag::err_x86_builtin_tile_arg_duplicate) 4340 << TheCall->getArg(ArgNum)->getSourceRange(); 4341 ArgValues.set(ArgExtValue); 4342 } 4343 return false; 4344 } 4345 4346 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4347 ArrayRef<int> ArgNums) { 4348 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4349 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4350 } 4351 4352 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4353 switch (BuiltinID) { 4354 default: 4355 return false; 4356 case X86::BI__builtin_ia32_tileloadd64: 4357 case X86::BI__builtin_ia32_tileloaddt164: 4358 case X86::BI__builtin_ia32_tilestored64: 4359 case X86::BI__builtin_ia32_tilezero: 4360 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4361 case X86::BI__builtin_ia32_tdpbssd: 4362 case X86::BI__builtin_ia32_tdpbsud: 4363 case X86::BI__builtin_ia32_tdpbusd: 4364 case X86::BI__builtin_ia32_tdpbuud: 4365 case X86::BI__builtin_ia32_tdpbf16ps: 4366 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4367 } 4368 } 4369 static bool isX86_32Builtin(unsigned BuiltinID) { 4370 // These builtins only work on x86-32 targets. 4371 switch (BuiltinID) { 4372 case X86::BI__builtin_ia32_readeflags_u32: 4373 case X86::BI__builtin_ia32_writeeflags_u32: 4374 return true; 4375 } 4376 4377 return false; 4378 } 4379 4380 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4381 CallExpr *TheCall) { 4382 if (BuiltinID == X86::BI__builtin_cpu_supports) 4383 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4384 4385 if (BuiltinID == X86::BI__builtin_cpu_is) 4386 return SemaBuiltinCpuIs(*this, TI, TheCall); 4387 4388 // Check for 32-bit only builtins on a 64-bit target. 4389 const llvm::Triple &TT = TI.getTriple(); 4390 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4391 return Diag(TheCall->getCallee()->getBeginLoc(), 4392 diag::err_32_bit_builtin_64_bit_tgt); 4393 4394 // If the intrinsic has rounding or SAE make sure its valid. 4395 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4396 return true; 4397 4398 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4399 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4400 return true; 4401 4402 // If the intrinsic has a tile arguments, make sure they are valid. 4403 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4404 return true; 4405 4406 // For intrinsics which take an immediate value as part of the instruction, 4407 // range check them here. 4408 int i = 0, l = 0, u = 0; 4409 switch (BuiltinID) { 4410 default: 4411 return false; 4412 case X86::BI__builtin_ia32_vec_ext_v2si: 4413 case X86::BI__builtin_ia32_vec_ext_v2di: 4414 case X86::BI__builtin_ia32_vextractf128_pd256: 4415 case X86::BI__builtin_ia32_vextractf128_ps256: 4416 case X86::BI__builtin_ia32_vextractf128_si256: 4417 case X86::BI__builtin_ia32_extract128i256: 4418 case X86::BI__builtin_ia32_extractf64x4_mask: 4419 case X86::BI__builtin_ia32_extracti64x4_mask: 4420 case X86::BI__builtin_ia32_extractf32x8_mask: 4421 case X86::BI__builtin_ia32_extracti32x8_mask: 4422 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4423 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4424 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4425 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4426 i = 1; l = 0; u = 1; 4427 break; 4428 case X86::BI__builtin_ia32_vec_set_v2di: 4429 case X86::BI__builtin_ia32_vinsertf128_pd256: 4430 case X86::BI__builtin_ia32_vinsertf128_ps256: 4431 case X86::BI__builtin_ia32_vinsertf128_si256: 4432 case X86::BI__builtin_ia32_insert128i256: 4433 case X86::BI__builtin_ia32_insertf32x8: 4434 case X86::BI__builtin_ia32_inserti32x8: 4435 case X86::BI__builtin_ia32_insertf64x4: 4436 case X86::BI__builtin_ia32_inserti64x4: 4437 case X86::BI__builtin_ia32_insertf64x2_256: 4438 case X86::BI__builtin_ia32_inserti64x2_256: 4439 case X86::BI__builtin_ia32_insertf32x4_256: 4440 case X86::BI__builtin_ia32_inserti32x4_256: 4441 i = 2; l = 0; u = 1; 4442 break; 4443 case X86::BI__builtin_ia32_vpermilpd: 4444 case X86::BI__builtin_ia32_vec_ext_v4hi: 4445 case X86::BI__builtin_ia32_vec_ext_v4si: 4446 case X86::BI__builtin_ia32_vec_ext_v4sf: 4447 case X86::BI__builtin_ia32_vec_ext_v4di: 4448 case X86::BI__builtin_ia32_extractf32x4_mask: 4449 case X86::BI__builtin_ia32_extracti32x4_mask: 4450 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4451 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4452 i = 1; l = 0; u = 3; 4453 break; 4454 case X86::BI_mm_prefetch: 4455 case X86::BI__builtin_ia32_vec_ext_v8hi: 4456 case X86::BI__builtin_ia32_vec_ext_v8si: 4457 i = 1; l = 0; u = 7; 4458 break; 4459 case X86::BI__builtin_ia32_sha1rnds4: 4460 case X86::BI__builtin_ia32_blendpd: 4461 case X86::BI__builtin_ia32_shufpd: 4462 case X86::BI__builtin_ia32_vec_set_v4hi: 4463 case X86::BI__builtin_ia32_vec_set_v4si: 4464 case X86::BI__builtin_ia32_vec_set_v4di: 4465 case X86::BI__builtin_ia32_shuf_f32x4_256: 4466 case X86::BI__builtin_ia32_shuf_f64x2_256: 4467 case X86::BI__builtin_ia32_shuf_i32x4_256: 4468 case X86::BI__builtin_ia32_shuf_i64x2_256: 4469 case X86::BI__builtin_ia32_insertf64x2_512: 4470 case X86::BI__builtin_ia32_inserti64x2_512: 4471 case X86::BI__builtin_ia32_insertf32x4: 4472 case X86::BI__builtin_ia32_inserti32x4: 4473 i = 2; l = 0; u = 3; 4474 break; 4475 case X86::BI__builtin_ia32_vpermil2pd: 4476 case X86::BI__builtin_ia32_vpermil2pd256: 4477 case X86::BI__builtin_ia32_vpermil2ps: 4478 case X86::BI__builtin_ia32_vpermil2ps256: 4479 i = 3; l = 0; u = 3; 4480 break; 4481 case X86::BI__builtin_ia32_cmpb128_mask: 4482 case X86::BI__builtin_ia32_cmpw128_mask: 4483 case X86::BI__builtin_ia32_cmpd128_mask: 4484 case X86::BI__builtin_ia32_cmpq128_mask: 4485 case X86::BI__builtin_ia32_cmpb256_mask: 4486 case X86::BI__builtin_ia32_cmpw256_mask: 4487 case X86::BI__builtin_ia32_cmpd256_mask: 4488 case X86::BI__builtin_ia32_cmpq256_mask: 4489 case X86::BI__builtin_ia32_cmpb512_mask: 4490 case X86::BI__builtin_ia32_cmpw512_mask: 4491 case X86::BI__builtin_ia32_cmpd512_mask: 4492 case X86::BI__builtin_ia32_cmpq512_mask: 4493 case X86::BI__builtin_ia32_ucmpb128_mask: 4494 case X86::BI__builtin_ia32_ucmpw128_mask: 4495 case X86::BI__builtin_ia32_ucmpd128_mask: 4496 case X86::BI__builtin_ia32_ucmpq128_mask: 4497 case X86::BI__builtin_ia32_ucmpb256_mask: 4498 case X86::BI__builtin_ia32_ucmpw256_mask: 4499 case X86::BI__builtin_ia32_ucmpd256_mask: 4500 case X86::BI__builtin_ia32_ucmpq256_mask: 4501 case X86::BI__builtin_ia32_ucmpb512_mask: 4502 case X86::BI__builtin_ia32_ucmpw512_mask: 4503 case X86::BI__builtin_ia32_ucmpd512_mask: 4504 case X86::BI__builtin_ia32_ucmpq512_mask: 4505 case X86::BI__builtin_ia32_vpcomub: 4506 case X86::BI__builtin_ia32_vpcomuw: 4507 case X86::BI__builtin_ia32_vpcomud: 4508 case X86::BI__builtin_ia32_vpcomuq: 4509 case X86::BI__builtin_ia32_vpcomb: 4510 case X86::BI__builtin_ia32_vpcomw: 4511 case X86::BI__builtin_ia32_vpcomd: 4512 case X86::BI__builtin_ia32_vpcomq: 4513 case X86::BI__builtin_ia32_vec_set_v8hi: 4514 case X86::BI__builtin_ia32_vec_set_v8si: 4515 i = 2; l = 0; u = 7; 4516 break; 4517 case X86::BI__builtin_ia32_vpermilpd256: 4518 case X86::BI__builtin_ia32_roundps: 4519 case X86::BI__builtin_ia32_roundpd: 4520 case X86::BI__builtin_ia32_roundps256: 4521 case X86::BI__builtin_ia32_roundpd256: 4522 case X86::BI__builtin_ia32_getmantpd128_mask: 4523 case X86::BI__builtin_ia32_getmantpd256_mask: 4524 case X86::BI__builtin_ia32_getmantps128_mask: 4525 case X86::BI__builtin_ia32_getmantps256_mask: 4526 case X86::BI__builtin_ia32_getmantpd512_mask: 4527 case X86::BI__builtin_ia32_getmantps512_mask: 4528 case X86::BI__builtin_ia32_getmantph128_mask: 4529 case X86::BI__builtin_ia32_getmantph256_mask: 4530 case X86::BI__builtin_ia32_getmantph512_mask: 4531 case X86::BI__builtin_ia32_vec_ext_v16qi: 4532 case X86::BI__builtin_ia32_vec_ext_v16hi: 4533 i = 1; l = 0; u = 15; 4534 break; 4535 case X86::BI__builtin_ia32_pblendd128: 4536 case X86::BI__builtin_ia32_blendps: 4537 case X86::BI__builtin_ia32_blendpd256: 4538 case X86::BI__builtin_ia32_shufpd256: 4539 case X86::BI__builtin_ia32_roundss: 4540 case X86::BI__builtin_ia32_roundsd: 4541 case X86::BI__builtin_ia32_rangepd128_mask: 4542 case X86::BI__builtin_ia32_rangepd256_mask: 4543 case X86::BI__builtin_ia32_rangepd512_mask: 4544 case X86::BI__builtin_ia32_rangeps128_mask: 4545 case X86::BI__builtin_ia32_rangeps256_mask: 4546 case X86::BI__builtin_ia32_rangeps512_mask: 4547 case X86::BI__builtin_ia32_getmantsd_round_mask: 4548 case X86::BI__builtin_ia32_getmantss_round_mask: 4549 case X86::BI__builtin_ia32_getmantsh_round_mask: 4550 case X86::BI__builtin_ia32_vec_set_v16qi: 4551 case X86::BI__builtin_ia32_vec_set_v16hi: 4552 i = 2; l = 0; u = 15; 4553 break; 4554 case X86::BI__builtin_ia32_vec_ext_v32qi: 4555 i = 1; l = 0; u = 31; 4556 break; 4557 case X86::BI__builtin_ia32_cmpps: 4558 case X86::BI__builtin_ia32_cmpss: 4559 case X86::BI__builtin_ia32_cmppd: 4560 case X86::BI__builtin_ia32_cmpsd: 4561 case X86::BI__builtin_ia32_cmpps256: 4562 case X86::BI__builtin_ia32_cmppd256: 4563 case X86::BI__builtin_ia32_cmpps128_mask: 4564 case X86::BI__builtin_ia32_cmppd128_mask: 4565 case X86::BI__builtin_ia32_cmpps256_mask: 4566 case X86::BI__builtin_ia32_cmppd256_mask: 4567 case X86::BI__builtin_ia32_cmpps512_mask: 4568 case X86::BI__builtin_ia32_cmppd512_mask: 4569 case X86::BI__builtin_ia32_cmpsd_mask: 4570 case X86::BI__builtin_ia32_cmpss_mask: 4571 case X86::BI__builtin_ia32_vec_set_v32qi: 4572 i = 2; l = 0; u = 31; 4573 break; 4574 case X86::BI__builtin_ia32_permdf256: 4575 case X86::BI__builtin_ia32_permdi256: 4576 case X86::BI__builtin_ia32_permdf512: 4577 case X86::BI__builtin_ia32_permdi512: 4578 case X86::BI__builtin_ia32_vpermilps: 4579 case X86::BI__builtin_ia32_vpermilps256: 4580 case X86::BI__builtin_ia32_vpermilpd512: 4581 case X86::BI__builtin_ia32_vpermilps512: 4582 case X86::BI__builtin_ia32_pshufd: 4583 case X86::BI__builtin_ia32_pshufd256: 4584 case X86::BI__builtin_ia32_pshufd512: 4585 case X86::BI__builtin_ia32_pshufhw: 4586 case X86::BI__builtin_ia32_pshufhw256: 4587 case X86::BI__builtin_ia32_pshufhw512: 4588 case X86::BI__builtin_ia32_pshuflw: 4589 case X86::BI__builtin_ia32_pshuflw256: 4590 case X86::BI__builtin_ia32_pshuflw512: 4591 case X86::BI__builtin_ia32_vcvtps2ph: 4592 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4593 case X86::BI__builtin_ia32_vcvtps2ph256: 4594 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4595 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4596 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4597 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4598 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4599 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4600 case X86::BI__builtin_ia32_rndscaleps_mask: 4601 case X86::BI__builtin_ia32_rndscalepd_mask: 4602 case X86::BI__builtin_ia32_rndscaleph_mask: 4603 case X86::BI__builtin_ia32_reducepd128_mask: 4604 case X86::BI__builtin_ia32_reducepd256_mask: 4605 case X86::BI__builtin_ia32_reducepd512_mask: 4606 case X86::BI__builtin_ia32_reduceps128_mask: 4607 case X86::BI__builtin_ia32_reduceps256_mask: 4608 case X86::BI__builtin_ia32_reduceps512_mask: 4609 case X86::BI__builtin_ia32_reduceph128_mask: 4610 case X86::BI__builtin_ia32_reduceph256_mask: 4611 case X86::BI__builtin_ia32_reduceph512_mask: 4612 case X86::BI__builtin_ia32_prold512: 4613 case X86::BI__builtin_ia32_prolq512: 4614 case X86::BI__builtin_ia32_prold128: 4615 case X86::BI__builtin_ia32_prold256: 4616 case X86::BI__builtin_ia32_prolq128: 4617 case X86::BI__builtin_ia32_prolq256: 4618 case X86::BI__builtin_ia32_prord512: 4619 case X86::BI__builtin_ia32_prorq512: 4620 case X86::BI__builtin_ia32_prord128: 4621 case X86::BI__builtin_ia32_prord256: 4622 case X86::BI__builtin_ia32_prorq128: 4623 case X86::BI__builtin_ia32_prorq256: 4624 case X86::BI__builtin_ia32_fpclasspd128_mask: 4625 case X86::BI__builtin_ia32_fpclasspd256_mask: 4626 case X86::BI__builtin_ia32_fpclassps128_mask: 4627 case X86::BI__builtin_ia32_fpclassps256_mask: 4628 case X86::BI__builtin_ia32_fpclassps512_mask: 4629 case X86::BI__builtin_ia32_fpclasspd512_mask: 4630 case X86::BI__builtin_ia32_fpclassph128_mask: 4631 case X86::BI__builtin_ia32_fpclassph256_mask: 4632 case X86::BI__builtin_ia32_fpclassph512_mask: 4633 case X86::BI__builtin_ia32_fpclasssd_mask: 4634 case X86::BI__builtin_ia32_fpclassss_mask: 4635 case X86::BI__builtin_ia32_fpclasssh_mask: 4636 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4637 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4638 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4639 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4640 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4641 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4642 case X86::BI__builtin_ia32_kshiftliqi: 4643 case X86::BI__builtin_ia32_kshiftlihi: 4644 case X86::BI__builtin_ia32_kshiftlisi: 4645 case X86::BI__builtin_ia32_kshiftlidi: 4646 case X86::BI__builtin_ia32_kshiftriqi: 4647 case X86::BI__builtin_ia32_kshiftrihi: 4648 case X86::BI__builtin_ia32_kshiftrisi: 4649 case X86::BI__builtin_ia32_kshiftridi: 4650 i = 1; l = 0; u = 255; 4651 break; 4652 case X86::BI__builtin_ia32_vperm2f128_pd256: 4653 case X86::BI__builtin_ia32_vperm2f128_ps256: 4654 case X86::BI__builtin_ia32_vperm2f128_si256: 4655 case X86::BI__builtin_ia32_permti256: 4656 case X86::BI__builtin_ia32_pblendw128: 4657 case X86::BI__builtin_ia32_pblendw256: 4658 case X86::BI__builtin_ia32_blendps256: 4659 case X86::BI__builtin_ia32_pblendd256: 4660 case X86::BI__builtin_ia32_palignr128: 4661 case X86::BI__builtin_ia32_palignr256: 4662 case X86::BI__builtin_ia32_palignr512: 4663 case X86::BI__builtin_ia32_alignq512: 4664 case X86::BI__builtin_ia32_alignd512: 4665 case X86::BI__builtin_ia32_alignd128: 4666 case X86::BI__builtin_ia32_alignd256: 4667 case X86::BI__builtin_ia32_alignq128: 4668 case X86::BI__builtin_ia32_alignq256: 4669 case X86::BI__builtin_ia32_vcomisd: 4670 case X86::BI__builtin_ia32_vcomiss: 4671 case X86::BI__builtin_ia32_shuf_f32x4: 4672 case X86::BI__builtin_ia32_shuf_f64x2: 4673 case X86::BI__builtin_ia32_shuf_i32x4: 4674 case X86::BI__builtin_ia32_shuf_i64x2: 4675 case X86::BI__builtin_ia32_shufpd512: 4676 case X86::BI__builtin_ia32_shufps: 4677 case X86::BI__builtin_ia32_shufps256: 4678 case X86::BI__builtin_ia32_shufps512: 4679 case X86::BI__builtin_ia32_dbpsadbw128: 4680 case X86::BI__builtin_ia32_dbpsadbw256: 4681 case X86::BI__builtin_ia32_dbpsadbw512: 4682 case X86::BI__builtin_ia32_vpshldd128: 4683 case X86::BI__builtin_ia32_vpshldd256: 4684 case X86::BI__builtin_ia32_vpshldd512: 4685 case X86::BI__builtin_ia32_vpshldq128: 4686 case X86::BI__builtin_ia32_vpshldq256: 4687 case X86::BI__builtin_ia32_vpshldq512: 4688 case X86::BI__builtin_ia32_vpshldw128: 4689 case X86::BI__builtin_ia32_vpshldw256: 4690 case X86::BI__builtin_ia32_vpshldw512: 4691 case X86::BI__builtin_ia32_vpshrdd128: 4692 case X86::BI__builtin_ia32_vpshrdd256: 4693 case X86::BI__builtin_ia32_vpshrdd512: 4694 case X86::BI__builtin_ia32_vpshrdq128: 4695 case X86::BI__builtin_ia32_vpshrdq256: 4696 case X86::BI__builtin_ia32_vpshrdq512: 4697 case X86::BI__builtin_ia32_vpshrdw128: 4698 case X86::BI__builtin_ia32_vpshrdw256: 4699 case X86::BI__builtin_ia32_vpshrdw512: 4700 i = 2; l = 0; u = 255; 4701 break; 4702 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4703 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4704 case X86::BI__builtin_ia32_fixupimmps512_mask: 4705 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4706 case X86::BI__builtin_ia32_fixupimmsd_mask: 4707 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4708 case X86::BI__builtin_ia32_fixupimmss_mask: 4709 case X86::BI__builtin_ia32_fixupimmss_maskz: 4710 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4711 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4712 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4713 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4714 case X86::BI__builtin_ia32_fixupimmps128_mask: 4715 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4716 case X86::BI__builtin_ia32_fixupimmps256_mask: 4717 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4718 case X86::BI__builtin_ia32_pternlogd512_mask: 4719 case X86::BI__builtin_ia32_pternlogd512_maskz: 4720 case X86::BI__builtin_ia32_pternlogq512_mask: 4721 case X86::BI__builtin_ia32_pternlogq512_maskz: 4722 case X86::BI__builtin_ia32_pternlogd128_mask: 4723 case X86::BI__builtin_ia32_pternlogd128_maskz: 4724 case X86::BI__builtin_ia32_pternlogd256_mask: 4725 case X86::BI__builtin_ia32_pternlogd256_maskz: 4726 case X86::BI__builtin_ia32_pternlogq128_mask: 4727 case X86::BI__builtin_ia32_pternlogq128_maskz: 4728 case X86::BI__builtin_ia32_pternlogq256_mask: 4729 case X86::BI__builtin_ia32_pternlogq256_maskz: 4730 i = 3; l = 0; u = 255; 4731 break; 4732 case X86::BI__builtin_ia32_gatherpfdpd: 4733 case X86::BI__builtin_ia32_gatherpfdps: 4734 case X86::BI__builtin_ia32_gatherpfqpd: 4735 case X86::BI__builtin_ia32_gatherpfqps: 4736 case X86::BI__builtin_ia32_scatterpfdpd: 4737 case X86::BI__builtin_ia32_scatterpfdps: 4738 case X86::BI__builtin_ia32_scatterpfqpd: 4739 case X86::BI__builtin_ia32_scatterpfqps: 4740 i = 4; l = 2; u = 3; 4741 break; 4742 case X86::BI__builtin_ia32_reducesd_mask: 4743 case X86::BI__builtin_ia32_reducess_mask: 4744 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4745 case X86::BI__builtin_ia32_rndscaless_round_mask: 4746 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4747 case X86::BI__builtin_ia32_reducesh_mask: 4748 i = 4; l = 0; u = 255; 4749 break; 4750 } 4751 4752 // Note that we don't force a hard error on the range check here, allowing 4753 // template-generated or macro-generated dead code to potentially have out-of- 4754 // range values. These need to code generate, but don't need to necessarily 4755 // make any sense. We use a warning that defaults to an error. 4756 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4757 } 4758 4759 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4760 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4761 /// Returns true when the format fits the function and the FormatStringInfo has 4762 /// been populated. 4763 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4764 FormatStringInfo *FSI) { 4765 FSI->HasVAListArg = Format->getFirstArg() == 0; 4766 FSI->FormatIdx = Format->getFormatIdx() - 1; 4767 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4768 4769 // The way the format attribute works in GCC, the implicit this argument 4770 // of member functions is counted. However, it doesn't appear in our own 4771 // lists, so decrement format_idx in that case. 4772 if (IsCXXMember) { 4773 if(FSI->FormatIdx == 0) 4774 return false; 4775 --FSI->FormatIdx; 4776 if (FSI->FirstDataArg != 0) 4777 --FSI->FirstDataArg; 4778 } 4779 return true; 4780 } 4781 4782 /// Checks if a the given expression evaluates to null. 4783 /// 4784 /// Returns true if the value evaluates to null. 4785 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4786 // If the expression has non-null type, it doesn't evaluate to null. 4787 if (auto nullability 4788 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4789 if (*nullability == NullabilityKind::NonNull) 4790 return false; 4791 } 4792 4793 // As a special case, transparent unions initialized with zero are 4794 // considered null for the purposes of the nonnull attribute. 4795 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4796 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4797 if (const CompoundLiteralExpr *CLE = 4798 dyn_cast<CompoundLiteralExpr>(Expr)) 4799 if (const InitListExpr *ILE = 4800 dyn_cast<InitListExpr>(CLE->getInitializer())) 4801 Expr = ILE->getInit(0); 4802 } 4803 4804 bool Result; 4805 return (!Expr->isValueDependent() && 4806 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4807 !Result); 4808 } 4809 4810 static void CheckNonNullArgument(Sema &S, 4811 const Expr *ArgExpr, 4812 SourceLocation CallSiteLoc) { 4813 if (CheckNonNullExpr(S, ArgExpr)) 4814 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4815 S.PDiag(diag::warn_null_arg) 4816 << ArgExpr->getSourceRange()); 4817 } 4818 4819 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4820 FormatStringInfo FSI; 4821 if ((GetFormatStringType(Format) == FST_NSString) && 4822 getFormatStringInfo(Format, false, &FSI)) { 4823 Idx = FSI.FormatIdx; 4824 return true; 4825 } 4826 return false; 4827 } 4828 4829 /// Diagnose use of %s directive in an NSString which is being passed 4830 /// as formatting string to formatting method. 4831 static void 4832 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4833 const NamedDecl *FDecl, 4834 Expr **Args, 4835 unsigned NumArgs) { 4836 unsigned Idx = 0; 4837 bool Format = false; 4838 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4839 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4840 Idx = 2; 4841 Format = true; 4842 } 4843 else 4844 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4845 if (S.GetFormatNSStringIdx(I, Idx)) { 4846 Format = true; 4847 break; 4848 } 4849 } 4850 if (!Format || NumArgs <= Idx) 4851 return; 4852 const Expr *FormatExpr = Args[Idx]; 4853 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4854 FormatExpr = CSCE->getSubExpr(); 4855 const StringLiteral *FormatString; 4856 if (const ObjCStringLiteral *OSL = 4857 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4858 FormatString = OSL->getString(); 4859 else 4860 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4861 if (!FormatString) 4862 return; 4863 if (S.FormatStringHasSArg(FormatString)) { 4864 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4865 << "%s" << 1 << 1; 4866 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4867 << FDecl->getDeclName(); 4868 } 4869 } 4870 4871 /// Determine whether the given type has a non-null nullability annotation. 4872 static bool isNonNullType(ASTContext &ctx, QualType type) { 4873 if (auto nullability = type->getNullability(ctx)) 4874 return *nullability == NullabilityKind::NonNull; 4875 4876 return false; 4877 } 4878 4879 static void CheckNonNullArguments(Sema &S, 4880 const NamedDecl *FDecl, 4881 const FunctionProtoType *Proto, 4882 ArrayRef<const Expr *> Args, 4883 SourceLocation CallSiteLoc) { 4884 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4885 4886 // Already checked by by constant evaluator. 4887 if (S.isConstantEvaluated()) 4888 return; 4889 // Check the attributes attached to the method/function itself. 4890 llvm::SmallBitVector NonNullArgs; 4891 if (FDecl) { 4892 // Handle the nonnull attribute on the function/method declaration itself. 4893 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4894 if (!NonNull->args_size()) { 4895 // Easy case: all pointer arguments are nonnull. 4896 for (const auto *Arg : Args) 4897 if (S.isValidPointerAttrType(Arg->getType())) 4898 CheckNonNullArgument(S, Arg, CallSiteLoc); 4899 return; 4900 } 4901 4902 for (const ParamIdx &Idx : NonNull->args()) { 4903 unsigned IdxAST = Idx.getASTIndex(); 4904 if (IdxAST >= Args.size()) 4905 continue; 4906 if (NonNullArgs.empty()) 4907 NonNullArgs.resize(Args.size()); 4908 NonNullArgs.set(IdxAST); 4909 } 4910 } 4911 } 4912 4913 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4914 // Handle the nonnull attribute on the parameters of the 4915 // function/method. 4916 ArrayRef<ParmVarDecl*> parms; 4917 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4918 parms = FD->parameters(); 4919 else 4920 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4921 4922 unsigned ParamIndex = 0; 4923 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4924 I != E; ++I, ++ParamIndex) { 4925 const ParmVarDecl *PVD = *I; 4926 if (PVD->hasAttr<NonNullAttr>() || 4927 isNonNullType(S.Context, PVD->getType())) { 4928 if (NonNullArgs.empty()) 4929 NonNullArgs.resize(Args.size()); 4930 4931 NonNullArgs.set(ParamIndex); 4932 } 4933 } 4934 } else { 4935 // If we have a non-function, non-method declaration but no 4936 // function prototype, try to dig out the function prototype. 4937 if (!Proto) { 4938 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4939 QualType type = VD->getType().getNonReferenceType(); 4940 if (auto pointerType = type->getAs<PointerType>()) 4941 type = pointerType->getPointeeType(); 4942 else if (auto blockType = type->getAs<BlockPointerType>()) 4943 type = blockType->getPointeeType(); 4944 // FIXME: data member pointers? 4945 4946 // Dig out the function prototype, if there is one. 4947 Proto = type->getAs<FunctionProtoType>(); 4948 } 4949 } 4950 4951 // Fill in non-null argument information from the nullability 4952 // information on the parameter types (if we have them). 4953 if (Proto) { 4954 unsigned Index = 0; 4955 for (auto paramType : Proto->getParamTypes()) { 4956 if (isNonNullType(S.Context, paramType)) { 4957 if (NonNullArgs.empty()) 4958 NonNullArgs.resize(Args.size()); 4959 4960 NonNullArgs.set(Index); 4961 } 4962 4963 ++Index; 4964 } 4965 } 4966 } 4967 4968 // Check for non-null arguments. 4969 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4970 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4971 if (NonNullArgs[ArgIndex]) 4972 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4973 } 4974 } 4975 4976 /// Warn if a pointer or reference argument passed to a function points to an 4977 /// object that is less aligned than the parameter. This can happen when 4978 /// creating a typedef with a lower alignment than the original type and then 4979 /// calling functions defined in terms of the original type. 4980 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4981 StringRef ParamName, QualType ArgTy, 4982 QualType ParamTy) { 4983 4984 // If a function accepts a pointer or reference type 4985 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4986 return; 4987 4988 // If the parameter is a pointer type, get the pointee type for the 4989 // argument too. If the parameter is a reference type, don't try to get 4990 // the pointee type for the argument. 4991 if (ParamTy->isPointerType()) 4992 ArgTy = ArgTy->getPointeeType(); 4993 4994 // Remove reference or pointer 4995 ParamTy = ParamTy->getPointeeType(); 4996 4997 // Find expected alignment, and the actual alignment of the passed object. 4998 // getTypeAlignInChars requires complete types 4999 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5000 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5001 ArgTy->isUndeducedType()) 5002 return; 5003 5004 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5005 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5006 5007 // If the argument is less aligned than the parameter, there is a 5008 // potential alignment issue. 5009 if (ArgAlign < ParamAlign) 5010 Diag(Loc, diag::warn_param_mismatched_alignment) 5011 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5012 << ParamName << FDecl; 5013 } 5014 5015 /// Handles the checks for format strings, non-POD arguments to vararg 5016 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5017 /// attributes. 5018 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5019 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5020 bool IsMemberFunction, SourceLocation Loc, 5021 SourceRange Range, VariadicCallType CallType) { 5022 // FIXME: We should check as much as we can in the template definition. 5023 if (CurContext->isDependentContext()) 5024 return; 5025 5026 // Printf and scanf checking. 5027 llvm::SmallBitVector CheckedVarArgs; 5028 if (FDecl) { 5029 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5030 // Only create vector if there are format attributes. 5031 CheckedVarArgs.resize(Args.size()); 5032 5033 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5034 CheckedVarArgs); 5035 } 5036 } 5037 5038 // Refuse POD arguments that weren't caught by the format string 5039 // checks above. 5040 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5041 if (CallType != VariadicDoesNotApply && 5042 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5043 unsigned NumParams = Proto ? Proto->getNumParams() 5044 : FDecl && isa<FunctionDecl>(FDecl) 5045 ? cast<FunctionDecl>(FDecl)->getNumParams() 5046 : FDecl && isa<ObjCMethodDecl>(FDecl) 5047 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5048 : 0; 5049 5050 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5051 // Args[ArgIdx] can be null in malformed code. 5052 if (const Expr *Arg = Args[ArgIdx]) { 5053 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5054 checkVariadicArgument(Arg, CallType); 5055 } 5056 } 5057 } 5058 5059 if (FDecl || Proto) { 5060 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5061 5062 // Type safety checking. 5063 if (FDecl) { 5064 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5065 CheckArgumentWithTypeTag(I, Args, Loc); 5066 } 5067 } 5068 5069 // Check that passed arguments match the alignment of original arguments. 5070 // Try to get the missing prototype from the declaration. 5071 if (!Proto && FDecl) { 5072 const auto *FT = FDecl->getFunctionType(); 5073 if (isa_and_nonnull<FunctionProtoType>(FT)) 5074 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5075 } 5076 if (Proto) { 5077 // For variadic functions, we may have more args than parameters. 5078 // For some K&R functions, we may have less args than parameters. 5079 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5080 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5081 // Args[ArgIdx] can be null in malformed code. 5082 if (const Expr *Arg = Args[ArgIdx]) { 5083 if (Arg->containsErrors()) 5084 continue; 5085 5086 QualType ParamTy = Proto->getParamType(ArgIdx); 5087 QualType ArgTy = Arg->getType(); 5088 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5089 ArgTy, ParamTy); 5090 } 5091 } 5092 } 5093 5094 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5095 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5096 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5097 if (!Arg->isValueDependent()) { 5098 Expr::EvalResult Align; 5099 if (Arg->EvaluateAsInt(Align, Context)) { 5100 const llvm::APSInt &I = Align.Val.getInt(); 5101 if (!I.isPowerOf2()) 5102 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5103 << Arg->getSourceRange(); 5104 5105 if (I > Sema::MaximumAlignment) 5106 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5107 << Arg->getSourceRange() << Sema::MaximumAlignment; 5108 } 5109 } 5110 } 5111 5112 if (FD) 5113 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5114 } 5115 5116 /// CheckConstructorCall - Check a constructor call for correctness and safety 5117 /// properties not enforced by the C type system. 5118 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5119 ArrayRef<const Expr *> Args, 5120 const FunctionProtoType *Proto, 5121 SourceLocation Loc) { 5122 VariadicCallType CallType = 5123 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5124 5125 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5126 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5127 Context.getPointerType(Ctor->getThisObjectType())); 5128 5129 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5130 Loc, SourceRange(), CallType); 5131 } 5132 5133 /// CheckFunctionCall - Check a direct function call for various correctness 5134 /// and safety properties not strictly enforced by the C type system. 5135 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5136 const FunctionProtoType *Proto) { 5137 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5138 isa<CXXMethodDecl>(FDecl); 5139 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5140 IsMemberOperatorCall; 5141 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5142 TheCall->getCallee()); 5143 Expr** Args = TheCall->getArgs(); 5144 unsigned NumArgs = TheCall->getNumArgs(); 5145 5146 Expr *ImplicitThis = nullptr; 5147 if (IsMemberOperatorCall) { 5148 // If this is a call to a member operator, hide the first argument 5149 // from checkCall. 5150 // FIXME: Our choice of AST representation here is less than ideal. 5151 ImplicitThis = Args[0]; 5152 ++Args; 5153 --NumArgs; 5154 } else if (IsMemberFunction) 5155 ImplicitThis = 5156 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5157 5158 if (ImplicitThis) { 5159 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5160 // used. 5161 QualType ThisType = ImplicitThis->getType(); 5162 if (!ThisType->isPointerType()) { 5163 assert(!ThisType->isReferenceType()); 5164 ThisType = Context.getPointerType(ThisType); 5165 } 5166 5167 QualType ThisTypeFromDecl = 5168 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5169 5170 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5171 ThisTypeFromDecl); 5172 } 5173 5174 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5175 IsMemberFunction, TheCall->getRParenLoc(), 5176 TheCall->getCallee()->getSourceRange(), CallType); 5177 5178 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5179 // None of the checks below are needed for functions that don't have 5180 // simple names (e.g., C++ conversion functions). 5181 if (!FnInfo) 5182 return false; 5183 5184 CheckTCBEnforcement(TheCall, FDecl); 5185 5186 CheckAbsoluteValueFunction(TheCall, FDecl); 5187 CheckMaxUnsignedZero(TheCall, FDecl); 5188 5189 if (getLangOpts().ObjC) 5190 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5191 5192 unsigned CMId = FDecl->getMemoryFunctionKind(); 5193 5194 // Handle memory setting and copying functions. 5195 switch (CMId) { 5196 case 0: 5197 return false; 5198 case Builtin::BIstrlcpy: // fallthrough 5199 case Builtin::BIstrlcat: 5200 CheckStrlcpycatArguments(TheCall, FnInfo); 5201 break; 5202 case Builtin::BIstrncat: 5203 CheckStrncatArguments(TheCall, FnInfo); 5204 break; 5205 case Builtin::BIfree: 5206 CheckFreeArguments(TheCall); 5207 break; 5208 default: 5209 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5210 } 5211 5212 return false; 5213 } 5214 5215 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5216 ArrayRef<const Expr *> Args) { 5217 VariadicCallType CallType = 5218 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5219 5220 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5221 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5222 CallType); 5223 5224 return false; 5225 } 5226 5227 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5228 const FunctionProtoType *Proto) { 5229 QualType Ty; 5230 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5231 Ty = V->getType().getNonReferenceType(); 5232 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5233 Ty = F->getType().getNonReferenceType(); 5234 else 5235 return false; 5236 5237 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5238 !Ty->isFunctionProtoType()) 5239 return false; 5240 5241 VariadicCallType CallType; 5242 if (!Proto || !Proto->isVariadic()) { 5243 CallType = VariadicDoesNotApply; 5244 } else if (Ty->isBlockPointerType()) { 5245 CallType = VariadicBlock; 5246 } else { // Ty->isFunctionPointerType() 5247 CallType = VariadicFunction; 5248 } 5249 5250 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5251 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5252 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5253 TheCall->getCallee()->getSourceRange(), CallType); 5254 5255 return false; 5256 } 5257 5258 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5259 /// such as function pointers returned from functions. 5260 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5261 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5262 TheCall->getCallee()); 5263 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5264 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5265 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5266 TheCall->getCallee()->getSourceRange(), CallType); 5267 5268 return false; 5269 } 5270 5271 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5272 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5273 return false; 5274 5275 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5276 switch (Op) { 5277 case AtomicExpr::AO__c11_atomic_init: 5278 case AtomicExpr::AO__opencl_atomic_init: 5279 llvm_unreachable("There is no ordering argument for an init"); 5280 5281 case AtomicExpr::AO__c11_atomic_load: 5282 case AtomicExpr::AO__opencl_atomic_load: 5283 case AtomicExpr::AO__atomic_load_n: 5284 case AtomicExpr::AO__atomic_load: 5285 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5286 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5287 5288 case AtomicExpr::AO__c11_atomic_store: 5289 case AtomicExpr::AO__opencl_atomic_store: 5290 case AtomicExpr::AO__atomic_store: 5291 case AtomicExpr::AO__atomic_store_n: 5292 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5293 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5294 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5295 5296 default: 5297 return true; 5298 } 5299 } 5300 5301 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5302 AtomicExpr::AtomicOp Op) { 5303 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5304 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5305 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5306 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5307 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5308 Op); 5309 } 5310 5311 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5312 SourceLocation RParenLoc, MultiExprArg Args, 5313 AtomicExpr::AtomicOp Op, 5314 AtomicArgumentOrder ArgOrder) { 5315 // All the non-OpenCL operations take one of the following forms. 5316 // The OpenCL operations take the __c11 forms with one extra argument for 5317 // synchronization scope. 5318 enum { 5319 // C __c11_atomic_init(A *, C) 5320 Init, 5321 5322 // C __c11_atomic_load(A *, int) 5323 Load, 5324 5325 // void __atomic_load(A *, CP, int) 5326 LoadCopy, 5327 5328 // void __atomic_store(A *, CP, int) 5329 Copy, 5330 5331 // C __c11_atomic_add(A *, M, int) 5332 Arithmetic, 5333 5334 // C __atomic_exchange_n(A *, CP, int) 5335 Xchg, 5336 5337 // void __atomic_exchange(A *, C *, CP, int) 5338 GNUXchg, 5339 5340 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5341 C11CmpXchg, 5342 5343 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5344 GNUCmpXchg 5345 } Form = Init; 5346 5347 const unsigned NumForm = GNUCmpXchg + 1; 5348 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5349 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5350 // where: 5351 // C is an appropriate type, 5352 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5353 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5354 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5355 // the int parameters are for orderings. 5356 5357 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5358 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5359 "need to update code for modified forms"); 5360 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5361 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5362 AtomicExpr::AO__atomic_load, 5363 "need to update code for modified C11 atomics"); 5364 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5365 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5366 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5367 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5368 IsOpenCL; 5369 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5370 Op == AtomicExpr::AO__atomic_store_n || 5371 Op == AtomicExpr::AO__atomic_exchange_n || 5372 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5373 bool IsAddSub = false; 5374 5375 switch (Op) { 5376 case AtomicExpr::AO__c11_atomic_init: 5377 case AtomicExpr::AO__opencl_atomic_init: 5378 Form = Init; 5379 break; 5380 5381 case AtomicExpr::AO__c11_atomic_load: 5382 case AtomicExpr::AO__opencl_atomic_load: 5383 case AtomicExpr::AO__atomic_load_n: 5384 Form = Load; 5385 break; 5386 5387 case AtomicExpr::AO__atomic_load: 5388 Form = LoadCopy; 5389 break; 5390 5391 case AtomicExpr::AO__c11_atomic_store: 5392 case AtomicExpr::AO__opencl_atomic_store: 5393 case AtomicExpr::AO__atomic_store: 5394 case AtomicExpr::AO__atomic_store_n: 5395 Form = Copy; 5396 break; 5397 5398 case AtomicExpr::AO__c11_atomic_fetch_add: 5399 case AtomicExpr::AO__c11_atomic_fetch_sub: 5400 case AtomicExpr::AO__opencl_atomic_fetch_add: 5401 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5402 case AtomicExpr::AO__atomic_fetch_add: 5403 case AtomicExpr::AO__atomic_fetch_sub: 5404 case AtomicExpr::AO__atomic_add_fetch: 5405 case AtomicExpr::AO__atomic_sub_fetch: 5406 IsAddSub = true; 5407 Form = Arithmetic; 5408 break; 5409 case AtomicExpr::AO__c11_atomic_fetch_and: 5410 case AtomicExpr::AO__c11_atomic_fetch_or: 5411 case AtomicExpr::AO__c11_atomic_fetch_xor: 5412 case AtomicExpr::AO__opencl_atomic_fetch_and: 5413 case AtomicExpr::AO__opencl_atomic_fetch_or: 5414 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5415 case AtomicExpr::AO__atomic_fetch_and: 5416 case AtomicExpr::AO__atomic_fetch_or: 5417 case AtomicExpr::AO__atomic_fetch_xor: 5418 case AtomicExpr::AO__atomic_fetch_nand: 5419 case AtomicExpr::AO__atomic_and_fetch: 5420 case AtomicExpr::AO__atomic_or_fetch: 5421 case AtomicExpr::AO__atomic_xor_fetch: 5422 case AtomicExpr::AO__atomic_nand_fetch: 5423 Form = Arithmetic; 5424 break; 5425 case AtomicExpr::AO__c11_atomic_fetch_min: 5426 case AtomicExpr::AO__c11_atomic_fetch_max: 5427 case AtomicExpr::AO__opencl_atomic_fetch_min: 5428 case AtomicExpr::AO__opencl_atomic_fetch_max: 5429 case AtomicExpr::AO__atomic_min_fetch: 5430 case AtomicExpr::AO__atomic_max_fetch: 5431 case AtomicExpr::AO__atomic_fetch_min: 5432 case AtomicExpr::AO__atomic_fetch_max: 5433 Form = Arithmetic; 5434 break; 5435 5436 case AtomicExpr::AO__c11_atomic_exchange: 5437 case AtomicExpr::AO__opencl_atomic_exchange: 5438 case AtomicExpr::AO__atomic_exchange_n: 5439 Form = Xchg; 5440 break; 5441 5442 case AtomicExpr::AO__atomic_exchange: 5443 Form = GNUXchg; 5444 break; 5445 5446 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5447 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5448 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5449 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5450 Form = C11CmpXchg; 5451 break; 5452 5453 case AtomicExpr::AO__atomic_compare_exchange: 5454 case AtomicExpr::AO__atomic_compare_exchange_n: 5455 Form = GNUCmpXchg; 5456 break; 5457 } 5458 5459 unsigned AdjustedNumArgs = NumArgs[Form]; 5460 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5461 ++AdjustedNumArgs; 5462 // Check we have the right number of arguments. 5463 if (Args.size() < AdjustedNumArgs) { 5464 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5465 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5466 << ExprRange; 5467 return ExprError(); 5468 } else if (Args.size() > AdjustedNumArgs) { 5469 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5470 diag::err_typecheck_call_too_many_args) 5471 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5472 << ExprRange; 5473 return ExprError(); 5474 } 5475 5476 // Inspect the first argument of the atomic operation. 5477 Expr *Ptr = Args[0]; 5478 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5479 if (ConvertedPtr.isInvalid()) 5480 return ExprError(); 5481 5482 Ptr = ConvertedPtr.get(); 5483 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5484 if (!pointerType) { 5485 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5486 << Ptr->getType() << Ptr->getSourceRange(); 5487 return ExprError(); 5488 } 5489 5490 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5491 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5492 QualType ValType = AtomTy; // 'C' 5493 if (IsC11) { 5494 if (!AtomTy->isAtomicType()) { 5495 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5496 << Ptr->getType() << Ptr->getSourceRange(); 5497 return ExprError(); 5498 } 5499 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5500 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5501 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5502 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5503 << Ptr->getSourceRange(); 5504 return ExprError(); 5505 } 5506 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5507 } else if (Form != Load && Form != LoadCopy) { 5508 if (ValType.isConstQualified()) { 5509 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5510 << Ptr->getType() << Ptr->getSourceRange(); 5511 return ExprError(); 5512 } 5513 } 5514 5515 // For an arithmetic operation, the implied arithmetic must be well-formed. 5516 if (Form == Arithmetic) { 5517 // gcc does not enforce these rules for GNU atomics, but we do so for 5518 // sanity. 5519 auto IsAllowedValueType = [&](QualType ValType) { 5520 if (ValType->isIntegerType()) 5521 return true; 5522 if (ValType->isPointerType()) 5523 return true; 5524 if (!ValType->isFloatingType()) 5525 return false; 5526 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5527 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5528 &Context.getTargetInfo().getLongDoubleFormat() == 5529 &llvm::APFloat::x87DoubleExtended()) 5530 return false; 5531 return true; 5532 }; 5533 if (IsAddSub && !IsAllowedValueType(ValType)) { 5534 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5535 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5536 return ExprError(); 5537 } 5538 if (!IsAddSub && !ValType->isIntegerType()) { 5539 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5540 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5541 return ExprError(); 5542 } 5543 if (IsC11 && ValType->isPointerType() && 5544 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5545 diag::err_incomplete_type)) { 5546 return ExprError(); 5547 } 5548 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5549 // For __atomic_*_n operations, the value type must be a scalar integral or 5550 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5551 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5552 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5553 return ExprError(); 5554 } 5555 5556 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5557 !AtomTy->isScalarType()) { 5558 // For GNU atomics, require a trivially-copyable type. This is not part of 5559 // the GNU atomics specification, but we enforce it for sanity. 5560 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5561 << Ptr->getType() << Ptr->getSourceRange(); 5562 return ExprError(); 5563 } 5564 5565 switch (ValType.getObjCLifetime()) { 5566 case Qualifiers::OCL_None: 5567 case Qualifiers::OCL_ExplicitNone: 5568 // okay 5569 break; 5570 5571 case Qualifiers::OCL_Weak: 5572 case Qualifiers::OCL_Strong: 5573 case Qualifiers::OCL_Autoreleasing: 5574 // FIXME: Can this happen? By this point, ValType should be known 5575 // to be trivially copyable. 5576 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5577 << ValType << Ptr->getSourceRange(); 5578 return ExprError(); 5579 } 5580 5581 // All atomic operations have an overload which takes a pointer to a volatile 5582 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5583 // into the result or the other operands. Similarly atomic_load takes a 5584 // pointer to a const 'A'. 5585 ValType.removeLocalVolatile(); 5586 ValType.removeLocalConst(); 5587 QualType ResultType = ValType; 5588 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5589 Form == Init) 5590 ResultType = Context.VoidTy; 5591 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5592 ResultType = Context.BoolTy; 5593 5594 // The type of a parameter passed 'by value'. In the GNU atomics, such 5595 // arguments are actually passed as pointers. 5596 QualType ByValType = ValType; // 'CP' 5597 bool IsPassedByAddress = false; 5598 if (!IsC11 && !IsN) { 5599 ByValType = Ptr->getType(); 5600 IsPassedByAddress = true; 5601 } 5602 5603 SmallVector<Expr *, 5> APIOrderedArgs; 5604 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5605 APIOrderedArgs.push_back(Args[0]); 5606 switch (Form) { 5607 case Init: 5608 case Load: 5609 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5610 break; 5611 case LoadCopy: 5612 case Copy: 5613 case Arithmetic: 5614 case Xchg: 5615 APIOrderedArgs.push_back(Args[2]); // Val1 5616 APIOrderedArgs.push_back(Args[1]); // Order 5617 break; 5618 case GNUXchg: 5619 APIOrderedArgs.push_back(Args[2]); // Val1 5620 APIOrderedArgs.push_back(Args[3]); // Val2 5621 APIOrderedArgs.push_back(Args[1]); // Order 5622 break; 5623 case C11CmpXchg: 5624 APIOrderedArgs.push_back(Args[2]); // Val1 5625 APIOrderedArgs.push_back(Args[4]); // Val2 5626 APIOrderedArgs.push_back(Args[1]); // Order 5627 APIOrderedArgs.push_back(Args[3]); // OrderFail 5628 break; 5629 case GNUCmpXchg: 5630 APIOrderedArgs.push_back(Args[2]); // Val1 5631 APIOrderedArgs.push_back(Args[4]); // Val2 5632 APIOrderedArgs.push_back(Args[5]); // Weak 5633 APIOrderedArgs.push_back(Args[1]); // Order 5634 APIOrderedArgs.push_back(Args[3]); // OrderFail 5635 break; 5636 } 5637 } else 5638 APIOrderedArgs.append(Args.begin(), Args.end()); 5639 5640 // The first argument's non-CV pointer type is used to deduce the type of 5641 // subsequent arguments, except for: 5642 // - weak flag (always converted to bool) 5643 // - memory order (always converted to int) 5644 // - scope (always converted to int) 5645 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5646 QualType Ty; 5647 if (i < NumVals[Form] + 1) { 5648 switch (i) { 5649 case 0: 5650 // The first argument is always a pointer. It has a fixed type. 5651 // It is always dereferenced, a nullptr is undefined. 5652 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5653 // Nothing else to do: we already know all we want about this pointer. 5654 continue; 5655 case 1: 5656 // The second argument is the non-atomic operand. For arithmetic, this 5657 // is always passed by value, and for a compare_exchange it is always 5658 // passed by address. For the rest, GNU uses by-address and C11 uses 5659 // by-value. 5660 assert(Form != Load); 5661 if (Form == Arithmetic && ValType->isPointerType()) 5662 Ty = Context.getPointerDiffType(); 5663 else if (Form == Init || Form == Arithmetic) 5664 Ty = ValType; 5665 else if (Form == Copy || Form == Xchg) { 5666 if (IsPassedByAddress) { 5667 // The value pointer is always dereferenced, a nullptr is undefined. 5668 CheckNonNullArgument(*this, APIOrderedArgs[i], 5669 ExprRange.getBegin()); 5670 } 5671 Ty = ByValType; 5672 } else { 5673 Expr *ValArg = APIOrderedArgs[i]; 5674 // The value pointer is always dereferenced, a nullptr is undefined. 5675 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5676 LangAS AS = LangAS::Default; 5677 // Keep address space of non-atomic pointer type. 5678 if (const PointerType *PtrTy = 5679 ValArg->getType()->getAs<PointerType>()) { 5680 AS = PtrTy->getPointeeType().getAddressSpace(); 5681 } 5682 Ty = Context.getPointerType( 5683 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5684 } 5685 break; 5686 case 2: 5687 // The third argument to compare_exchange / GNU exchange is the desired 5688 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5689 if (IsPassedByAddress) 5690 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5691 Ty = ByValType; 5692 break; 5693 case 3: 5694 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5695 Ty = Context.BoolTy; 5696 break; 5697 } 5698 } else { 5699 // The order(s) and scope are always converted to int. 5700 Ty = Context.IntTy; 5701 } 5702 5703 InitializedEntity Entity = 5704 InitializedEntity::InitializeParameter(Context, Ty, false); 5705 ExprResult Arg = APIOrderedArgs[i]; 5706 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5707 if (Arg.isInvalid()) 5708 return true; 5709 APIOrderedArgs[i] = Arg.get(); 5710 } 5711 5712 // Permute the arguments into a 'consistent' order. 5713 SmallVector<Expr*, 5> SubExprs; 5714 SubExprs.push_back(Ptr); 5715 switch (Form) { 5716 case Init: 5717 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5718 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5719 break; 5720 case Load: 5721 SubExprs.push_back(APIOrderedArgs[1]); // Order 5722 break; 5723 case LoadCopy: 5724 case Copy: 5725 case Arithmetic: 5726 case Xchg: 5727 SubExprs.push_back(APIOrderedArgs[2]); // Order 5728 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5729 break; 5730 case GNUXchg: 5731 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5732 SubExprs.push_back(APIOrderedArgs[3]); // Order 5733 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5734 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5735 break; 5736 case C11CmpXchg: 5737 SubExprs.push_back(APIOrderedArgs[3]); // Order 5738 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5739 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5740 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5741 break; 5742 case GNUCmpXchg: 5743 SubExprs.push_back(APIOrderedArgs[4]); // Order 5744 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5745 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5746 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5747 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5748 break; 5749 } 5750 5751 if (SubExprs.size() >= 2 && Form != Init) { 5752 if (Optional<llvm::APSInt> Result = 5753 SubExprs[1]->getIntegerConstantExpr(Context)) 5754 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5755 Diag(SubExprs[1]->getBeginLoc(), 5756 diag::warn_atomic_op_has_invalid_memory_order) 5757 << SubExprs[1]->getSourceRange(); 5758 } 5759 5760 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5761 auto *Scope = Args[Args.size() - 1]; 5762 if (Optional<llvm::APSInt> Result = 5763 Scope->getIntegerConstantExpr(Context)) { 5764 if (!ScopeModel->isValid(Result->getZExtValue())) 5765 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5766 << Scope->getSourceRange(); 5767 } 5768 SubExprs.push_back(Scope); 5769 } 5770 5771 AtomicExpr *AE = new (Context) 5772 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5773 5774 if ((Op == AtomicExpr::AO__c11_atomic_load || 5775 Op == AtomicExpr::AO__c11_atomic_store || 5776 Op == AtomicExpr::AO__opencl_atomic_load || 5777 Op == AtomicExpr::AO__opencl_atomic_store ) && 5778 Context.AtomicUsesUnsupportedLibcall(AE)) 5779 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5780 << ((Op == AtomicExpr::AO__c11_atomic_load || 5781 Op == AtomicExpr::AO__opencl_atomic_load) 5782 ? 0 5783 : 1); 5784 5785 if (ValType->isExtIntType()) { 5786 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5787 return ExprError(); 5788 } 5789 5790 return AE; 5791 } 5792 5793 /// checkBuiltinArgument - Given a call to a builtin function, perform 5794 /// normal type-checking on the given argument, updating the call in 5795 /// place. This is useful when a builtin function requires custom 5796 /// type-checking for some of its arguments but not necessarily all of 5797 /// them. 5798 /// 5799 /// Returns true on error. 5800 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5801 FunctionDecl *Fn = E->getDirectCallee(); 5802 assert(Fn && "builtin call without direct callee!"); 5803 5804 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5805 InitializedEntity Entity = 5806 InitializedEntity::InitializeParameter(S.Context, Param); 5807 5808 ExprResult Arg = E->getArg(0); 5809 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5810 if (Arg.isInvalid()) 5811 return true; 5812 5813 E->setArg(ArgIndex, Arg.get()); 5814 return false; 5815 } 5816 5817 /// We have a call to a function like __sync_fetch_and_add, which is an 5818 /// overloaded function based on the pointer type of its first argument. 5819 /// The main BuildCallExpr routines have already promoted the types of 5820 /// arguments because all of these calls are prototyped as void(...). 5821 /// 5822 /// This function goes through and does final semantic checking for these 5823 /// builtins, as well as generating any warnings. 5824 ExprResult 5825 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5826 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5827 Expr *Callee = TheCall->getCallee(); 5828 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5829 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5830 5831 // Ensure that we have at least one argument to do type inference from. 5832 if (TheCall->getNumArgs() < 1) { 5833 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5834 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5835 return ExprError(); 5836 } 5837 5838 // Inspect the first argument of the atomic builtin. This should always be 5839 // a pointer type, whose element is an integral scalar or pointer type. 5840 // Because it is a pointer type, we don't have to worry about any implicit 5841 // casts here. 5842 // FIXME: We don't allow floating point scalars as input. 5843 Expr *FirstArg = TheCall->getArg(0); 5844 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5845 if (FirstArgResult.isInvalid()) 5846 return ExprError(); 5847 FirstArg = FirstArgResult.get(); 5848 TheCall->setArg(0, FirstArg); 5849 5850 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5851 if (!pointerType) { 5852 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5853 << FirstArg->getType() << FirstArg->getSourceRange(); 5854 return ExprError(); 5855 } 5856 5857 QualType ValType = pointerType->getPointeeType(); 5858 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5859 !ValType->isBlockPointerType()) { 5860 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5861 << FirstArg->getType() << FirstArg->getSourceRange(); 5862 return ExprError(); 5863 } 5864 5865 if (ValType.isConstQualified()) { 5866 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5867 << FirstArg->getType() << FirstArg->getSourceRange(); 5868 return ExprError(); 5869 } 5870 5871 switch (ValType.getObjCLifetime()) { 5872 case Qualifiers::OCL_None: 5873 case Qualifiers::OCL_ExplicitNone: 5874 // okay 5875 break; 5876 5877 case Qualifiers::OCL_Weak: 5878 case Qualifiers::OCL_Strong: 5879 case Qualifiers::OCL_Autoreleasing: 5880 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5881 << ValType << FirstArg->getSourceRange(); 5882 return ExprError(); 5883 } 5884 5885 // Strip any qualifiers off ValType. 5886 ValType = ValType.getUnqualifiedType(); 5887 5888 // The majority of builtins return a value, but a few have special return 5889 // types, so allow them to override appropriately below. 5890 QualType ResultType = ValType; 5891 5892 // We need to figure out which concrete builtin this maps onto. For example, 5893 // __sync_fetch_and_add with a 2 byte object turns into 5894 // __sync_fetch_and_add_2. 5895 #define BUILTIN_ROW(x) \ 5896 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5897 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5898 5899 static const unsigned BuiltinIndices[][5] = { 5900 BUILTIN_ROW(__sync_fetch_and_add), 5901 BUILTIN_ROW(__sync_fetch_and_sub), 5902 BUILTIN_ROW(__sync_fetch_and_or), 5903 BUILTIN_ROW(__sync_fetch_and_and), 5904 BUILTIN_ROW(__sync_fetch_and_xor), 5905 BUILTIN_ROW(__sync_fetch_and_nand), 5906 5907 BUILTIN_ROW(__sync_add_and_fetch), 5908 BUILTIN_ROW(__sync_sub_and_fetch), 5909 BUILTIN_ROW(__sync_and_and_fetch), 5910 BUILTIN_ROW(__sync_or_and_fetch), 5911 BUILTIN_ROW(__sync_xor_and_fetch), 5912 BUILTIN_ROW(__sync_nand_and_fetch), 5913 5914 BUILTIN_ROW(__sync_val_compare_and_swap), 5915 BUILTIN_ROW(__sync_bool_compare_and_swap), 5916 BUILTIN_ROW(__sync_lock_test_and_set), 5917 BUILTIN_ROW(__sync_lock_release), 5918 BUILTIN_ROW(__sync_swap) 5919 }; 5920 #undef BUILTIN_ROW 5921 5922 // Determine the index of the size. 5923 unsigned SizeIndex; 5924 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5925 case 1: SizeIndex = 0; break; 5926 case 2: SizeIndex = 1; break; 5927 case 4: SizeIndex = 2; break; 5928 case 8: SizeIndex = 3; break; 5929 case 16: SizeIndex = 4; break; 5930 default: 5931 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5932 << FirstArg->getType() << FirstArg->getSourceRange(); 5933 return ExprError(); 5934 } 5935 5936 // Each of these builtins has one pointer argument, followed by some number of 5937 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5938 // that we ignore. Find out which row of BuiltinIndices to read from as well 5939 // as the number of fixed args. 5940 unsigned BuiltinID = FDecl->getBuiltinID(); 5941 unsigned BuiltinIndex, NumFixed = 1; 5942 bool WarnAboutSemanticsChange = false; 5943 switch (BuiltinID) { 5944 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5945 case Builtin::BI__sync_fetch_and_add: 5946 case Builtin::BI__sync_fetch_and_add_1: 5947 case Builtin::BI__sync_fetch_and_add_2: 5948 case Builtin::BI__sync_fetch_and_add_4: 5949 case Builtin::BI__sync_fetch_and_add_8: 5950 case Builtin::BI__sync_fetch_and_add_16: 5951 BuiltinIndex = 0; 5952 break; 5953 5954 case Builtin::BI__sync_fetch_and_sub: 5955 case Builtin::BI__sync_fetch_and_sub_1: 5956 case Builtin::BI__sync_fetch_and_sub_2: 5957 case Builtin::BI__sync_fetch_and_sub_4: 5958 case Builtin::BI__sync_fetch_and_sub_8: 5959 case Builtin::BI__sync_fetch_and_sub_16: 5960 BuiltinIndex = 1; 5961 break; 5962 5963 case Builtin::BI__sync_fetch_and_or: 5964 case Builtin::BI__sync_fetch_and_or_1: 5965 case Builtin::BI__sync_fetch_and_or_2: 5966 case Builtin::BI__sync_fetch_and_or_4: 5967 case Builtin::BI__sync_fetch_and_or_8: 5968 case Builtin::BI__sync_fetch_and_or_16: 5969 BuiltinIndex = 2; 5970 break; 5971 5972 case Builtin::BI__sync_fetch_and_and: 5973 case Builtin::BI__sync_fetch_and_and_1: 5974 case Builtin::BI__sync_fetch_and_and_2: 5975 case Builtin::BI__sync_fetch_and_and_4: 5976 case Builtin::BI__sync_fetch_and_and_8: 5977 case Builtin::BI__sync_fetch_and_and_16: 5978 BuiltinIndex = 3; 5979 break; 5980 5981 case Builtin::BI__sync_fetch_and_xor: 5982 case Builtin::BI__sync_fetch_and_xor_1: 5983 case Builtin::BI__sync_fetch_and_xor_2: 5984 case Builtin::BI__sync_fetch_and_xor_4: 5985 case Builtin::BI__sync_fetch_and_xor_8: 5986 case Builtin::BI__sync_fetch_and_xor_16: 5987 BuiltinIndex = 4; 5988 break; 5989 5990 case Builtin::BI__sync_fetch_and_nand: 5991 case Builtin::BI__sync_fetch_and_nand_1: 5992 case Builtin::BI__sync_fetch_and_nand_2: 5993 case Builtin::BI__sync_fetch_and_nand_4: 5994 case Builtin::BI__sync_fetch_and_nand_8: 5995 case Builtin::BI__sync_fetch_and_nand_16: 5996 BuiltinIndex = 5; 5997 WarnAboutSemanticsChange = true; 5998 break; 5999 6000 case Builtin::BI__sync_add_and_fetch: 6001 case Builtin::BI__sync_add_and_fetch_1: 6002 case Builtin::BI__sync_add_and_fetch_2: 6003 case Builtin::BI__sync_add_and_fetch_4: 6004 case Builtin::BI__sync_add_and_fetch_8: 6005 case Builtin::BI__sync_add_and_fetch_16: 6006 BuiltinIndex = 6; 6007 break; 6008 6009 case Builtin::BI__sync_sub_and_fetch: 6010 case Builtin::BI__sync_sub_and_fetch_1: 6011 case Builtin::BI__sync_sub_and_fetch_2: 6012 case Builtin::BI__sync_sub_and_fetch_4: 6013 case Builtin::BI__sync_sub_and_fetch_8: 6014 case Builtin::BI__sync_sub_and_fetch_16: 6015 BuiltinIndex = 7; 6016 break; 6017 6018 case Builtin::BI__sync_and_and_fetch: 6019 case Builtin::BI__sync_and_and_fetch_1: 6020 case Builtin::BI__sync_and_and_fetch_2: 6021 case Builtin::BI__sync_and_and_fetch_4: 6022 case Builtin::BI__sync_and_and_fetch_8: 6023 case Builtin::BI__sync_and_and_fetch_16: 6024 BuiltinIndex = 8; 6025 break; 6026 6027 case Builtin::BI__sync_or_and_fetch: 6028 case Builtin::BI__sync_or_and_fetch_1: 6029 case Builtin::BI__sync_or_and_fetch_2: 6030 case Builtin::BI__sync_or_and_fetch_4: 6031 case Builtin::BI__sync_or_and_fetch_8: 6032 case Builtin::BI__sync_or_and_fetch_16: 6033 BuiltinIndex = 9; 6034 break; 6035 6036 case Builtin::BI__sync_xor_and_fetch: 6037 case Builtin::BI__sync_xor_and_fetch_1: 6038 case Builtin::BI__sync_xor_and_fetch_2: 6039 case Builtin::BI__sync_xor_and_fetch_4: 6040 case Builtin::BI__sync_xor_and_fetch_8: 6041 case Builtin::BI__sync_xor_and_fetch_16: 6042 BuiltinIndex = 10; 6043 break; 6044 6045 case Builtin::BI__sync_nand_and_fetch: 6046 case Builtin::BI__sync_nand_and_fetch_1: 6047 case Builtin::BI__sync_nand_and_fetch_2: 6048 case Builtin::BI__sync_nand_and_fetch_4: 6049 case Builtin::BI__sync_nand_and_fetch_8: 6050 case Builtin::BI__sync_nand_and_fetch_16: 6051 BuiltinIndex = 11; 6052 WarnAboutSemanticsChange = true; 6053 break; 6054 6055 case Builtin::BI__sync_val_compare_and_swap: 6056 case Builtin::BI__sync_val_compare_and_swap_1: 6057 case Builtin::BI__sync_val_compare_and_swap_2: 6058 case Builtin::BI__sync_val_compare_and_swap_4: 6059 case Builtin::BI__sync_val_compare_and_swap_8: 6060 case Builtin::BI__sync_val_compare_and_swap_16: 6061 BuiltinIndex = 12; 6062 NumFixed = 2; 6063 break; 6064 6065 case Builtin::BI__sync_bool_compare_and_swap: 6066 case Builtin::BI__sync_bool_compare_and_swap_1: 6067 case Builtin::BI__sync_bool_compare_and_swap_2: 6068 case Builtin::BI__sync_bool_compare_and_swap_4: 6069 case Builtin::BI__sync_bool_compare_and_swap_8: 6070 case Builtin::BI__sync_bool_compare_and_swap_16: 6071 BuiltinIndex = 13; 6072 NumFixed = 2; 6073 ResultType = Context.BoolTy; 6074 break; 6075 6076 case Builtin::BI__sync_lock_test_and_set: 6077 case Builtin::BI__sync_lock_test_and_set_1: 6078 case Builtin::BI__sync_lock_test_and_set_2: 6079 case Builtin::BI__sync_lock_test_and_set_4: 6080 case Builtin::BI__sync_lock_test_and_set_8: 6081 case Builtin::BI__sync_lock_test_and_set_16: 6082 BuiltinIndex = 14; 6083 break; 6084 6085 case Builtin::BI__sync_lock_release: 6086 case Builtin::BI__sync_lock_release_1: 6087 case Builtin::BI__sync_lock_release_2: 6088 case Builtin::BI__sync_lock_release_4: 6089 case Builtin::BI__sync_lock_release_8: 6090 case Builtin::BI__sync_lock_release_16: 6091 BuiltinIndex = 15; 6092 NumFixed = 0; 6093 ResultType = Context.VoidTy; 6094 break; 6095 6096 case Builtin::BI__sync_swap: 6097 case Builtin::BI__sync_swap_1: 6098 case Builtin::BI__sync_swap_2: 6099 case Builtin::BI__sync_swap_4: 6100 case Builtin::BI__sync_swap_8: 6101 case Builtin::BI__sync_swap_16: 6102 BuiltinIndex = 16; 6103 break; 6104 } 6105 6106 // Now that we know how many fixed arguments we expect, first check that we 6107 // have at least that many. 6108 if (TheCall->getNumArgs() < 1+NumFixed) { 6109 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6110 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6111 << Callee->getSourceRange(); 6112 return ExprError(); 6113 } 6114 6115 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6116 << Callee->getSourceRange(); 6117 6118 if (WarnAboutSemanticsChange) { 6119 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6120 << Callee->getSourceRange(); 6121 } 6122 6123 // Get the decl for the concrete builtin from this, we can tell what the 6124 // concrete integer type we should convert to is. 6125 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6126 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6127 FunctionDecl *NewBuiltinDecl; 6128 if (NewBuiltinID == BuiltinID) 6129 NewBuiltinDecl = FDecl; 6130 else { 6131 // Perform builtin lookup to avoid redeclaring it. 6132 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6133 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6134 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6135 assert(Res.getFoundDecl()); 6136 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6137 if (!NewBuiltinDecl) 6138 return ExprError(); 6139 } 6140 6141 // The first argument --- the pointer --- has a fixed type; we 6142 // deduce the types of the rest of the arguments accordingly. Walk 6143 // the remaining arguments, converting them to the deduced value type. 6144 for (unsigned i = 0; i != NumFixed; ++i) { 6145 ExprResult Arg = TheCall->getArg(i+1); 6146 6147 // GCC does an implicit conversion to the pointer or integer ValType. This 6148 // can fail in some cases (1i -> int**), check for this error case now. 6149 // Initialize the argument. 6150 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6151 ValType, /*consume*/ false); 6152 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6153 if (Arg.isInvalid()) 6154 return ExprError(); 6155 6156 // Okay, we have something that *can* be converted to the right type. Check 6157 // to see if there is a potentially weird extension going on here. This can 6158 // happen when you do an atomic operation on something like an char* and 6159 // pass in 42. The 42 gets converted to char. This is even more strange 6160 // for things like 45.123 -> char, etc. 6161 // FIXME: Do this check. 6162 TheCall->setArg(i+1, Arg.get()); 6163 } 6164 6165 // Create a new DeclRefExpr to refer to the new decl. 6166 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6167 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6168 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6169 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6170 6171 // Set the callee in the CallExpr. 6172 // FIXME: This loses syntactic information. 6173 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6174 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6175 CK_BuiltinFnToFnPtr); 6176 TheCall->setCallee(PromotedCall.get()); 6177 6178 // Change the result type of the call to match the original value type. This 6179 // is arbitrary, but the codegen for these builtins ins design to handle it 6180 // gracefully. 6181 TheCall->setType(ResultType); 6182 6183 // Prohibit use of _ExtInt with atomic builtins. 6184 // The arguments would have already been converted to the first argument's 6185 // type, so only need to check the first argument. 6186 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6187 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6188 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6189 return ExprError(); 6190 } 6191 6192 return TheCallResult; 6193 } 6194 6195 /// SemaBuiltinNontemporalOverloaded - We have a call to 6196 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6197 /// overloaded function based on the pointer type of its last argument. 6198 /// 6199 /// This function goes through and does final semantic checking for these 6200 /// builtins. 6201 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6202 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6203 DeclRefExpr *DRE = 6204 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6205 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6206 unsigned BuiltinID = FDecl->getBuiltinID(); 6207 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6208 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6209 "Unexpected nontemporal load/store builtin!"); 6210 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6211 unsigned numArgs = isStore ? 2 : 1; 6212 6213 // Ensure that we have the proper number of arguments. 6214 if (checkArgCount(*this, TheCall, numArgs)) 6215 return ExprError(); 6216 6217 // Inspect the last argument of the nontemporal builtin. This should always 6218 // be a pointer type, from which we imply the type of the memory access. 6219 // Because it is a pointer type, we don't have to worry about any implicit 6220 // casts here. 6221 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6222 ExprResult PointerArgResult = 6223 DefaultFunctionArrayLvalueConversion(PointerArg); 6224 6225 if (PointerArgResult.isInvalid()) 6226 return ExprError(); 6227 PointerArg = PointerArgResult.get(); 6228 TheCall->setArg(numArgs - 1, PointerArg); 6229 6230 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6231 if (!pointerType) { 6232 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6233 << PointerArg->getType() << PointerArg->getSourceRange(); 6234 return ExprError(); 6235 } 6236 6237 QualType ValType = pointerType->getPointeeType(); 6238 6239 // Strip any qualifiers off ValType. 6240 ValType = ValType.getUnqualifiedType(); 6241 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6242 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6243 !ValType->isVectorType()) { 6244 Diag(DRE->getBeginLoc(), 6245 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6246 << PointerArg->getType() << PointerArg->getSourceRange(); 6247 return ExprError(); 6248 } 6249 6250 if (!isStore) { 6251 TheCall->setType(ValType); 6252 return TheCallResult; 6253 } 6254 6255 ExprResult ValArg = TheCall->getArg(0); 6256 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6257 Context, ValType, /*consume*/ false); 6258 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6259 if (ValArg.isInvalid()) 6260 return ExprError(); 6261 6262 TheCall->setArg(0, ValArg.get()); 6263 TheCall->setType(Context.VoidTy); 6264 return TheCallResult; 6265 } 6266 6267 /// CheckObjCString - Checks that the argument to the builtin 6268 /// CFString constructor is correct 6269 /// Note: It might also make sense to do the UTF-16 conversion here (would 6270 /// simplify the backend). 6271 bool Sema::CheckObjCString(Expr *Arg) { 6272 Arg = Arg->IgnoreParenCasts(); 6273 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6274 6275 if (!Literal || !Literal->isAscii()) { 6276 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6277 << Arg->getSourceRange(); 6278 return true; 6279 } 6280 6281 if (Literal->containsNonAsciiOrNull()) { 6282 StringRef String = Literal->getString(); 6283 unsigned NumBytes = String.size(); 6284 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6285 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6286 llvm::UTF16 *ToPtr = &ToBuf[0]; 6287 6288 llvm::ConversionResult Result = 6289 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6290 ToPtr + NumBytes, llvm::strictConversion); 6291 // Check for conversion failure. 6292 if (Result != llvm::conversionOK) 6293 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6294 << Arg->getSourceRange(); 6295 } 6296 return false; 6297 } 6298 6299 /// CheckObjCString - Checks that the format string argument to the os_log() 6300 /// and os_trace() functions is correct, and converts it to const char *. 6301 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6302 Arg = Arg->IgnoreParenCasts(); 6303 auto *Literal = dyn_cast<StringLiteral>(Arg); 6304 if (!Literal) { 6305 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6306 Literal = ObjcLiteral->getString(); 6307 } 6308 } 6309 6310 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6311 return ExprError( 6312 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6313 << Arg->getSourceRange()); 6314 } 6315 6316 ExprResult Result(Literal); 6317 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6318 InitializedEntity Entity = 6319 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6320 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6321 return Result; 6322 } 6323 6324 /// Check that the user is calling the appropriate va_start builtin for the 6325 /// target and calling convention. 6326 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6327 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6328 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6329 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6330 TT.getArch() == llvm::Triple::aarch64_32); 6331 bool IsWindows = TT.isOSWindows(); 6332 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6333 if (IsX64 || IsAArch64) { 6334 CallingConv CC = CC_C; 6335 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6336 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6337 if (IsMSVAStart) { 6338 // Don't allow this in System V ABI functions. 6339 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6340 return S.Diag(Fn->getBeginLoc(), 6341 diag::err_ms_va_start_used_in_sysv_function); 6342 } else { 6343 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6344 // On x64 Windows, don't allow this in System V ABI functions. 6345 // (Yes, that means there's no corresponding way to support variadic 6346 // System V ABI functions on Windows.) 6347 if ((IsWindows && CC == CC_X86_64SysV) || 6348 (!IsWindows && CC == CC_Win64)) 6349 return S.Diag(Fn->getBeginLoc(), 6350 diag::err_va_start_used_in_wrong_abi_function) 6351 << !IsWindows; 6352 } 6353 return false; 6354 } 6355 6356 if (IsMSVAStart) 6357 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6358 return false; 6359 } 6360 6361 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6362 ParmVarDecl **LastParam = nullptr) { 6363 // Determine whether the current function, block, or obj-c method is variadic 6364 // and get its parameter list. 6365 bool IsVariadic = false; 6366 ArrayRef<ParmVarDecl *> Params; 6367 DeclContext *Caller = S.CurContext; 6368 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6369 IsVariadic = Block->isVariadic(); 6370 Params = Block->parameters(); 6371 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6372 IsVariadic = FD->isVariadic(); 6373 Params = FD->parameters(); 6374 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6375 IsVariadic = MD->isVariadic(); 6376 // FIXME: This isn't correct for methods (results in bogus warning). 6377 Params = MD->parameters(); 6378 } else if (isa<CapturedDecl>(Caller)) { 6379 // We don't support va_start in a CapturedDecl. 6380 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6381 return true; 6382 } else { 6383 // This must be some other declcontext that parses exprs. 6384 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6385 return true; 6386 } 6387 6388 if (!IsVariadic) { 6389 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6390 return true; 6391 } 6392 6393 if (LastParam) 6394 *LastParam = Params.empty() ? nullptr : Params.back(); 6395 6396 return false; 6397 } 6398 6399 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6400 /// for validity. Emit an error and return true on failure; return false 6401 /// on success. 6402 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6403 Expr *Fn = TheCall->getCallee(); 6404 6405 if (checkVAStartABI(*this, BuiltinID, Fn)) 6406 return true; 6407 6408 if (checkArgCount(*this, TheCall, 2)) 6409 return true; 6410 6411 // Type-check the first argument normally. 6412 if (checkBuiltinArgument(*this, TheCall, 0)) 6413 return true; 6414 6415 // Check that the current function is variadic, and get its last parameter. 6416 ParmVarDecl *LastParam; 6417 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6418 return true; 6419 6420 // Verify that the second argument to the builtin is the last argument of the 6421 // current function or method. 6422 bool SecondArgIsLastNamedArgument = false; 6423 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6424 6425 // These are valid if SecondArgIsLastNamedArgument is false after the next 6426 // block. 6427 QualType Type; 6428 SourceLocation ParamLoc; 6429 bool IsCRegister = false; 6430 6431 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6432 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6433 SecondArgIsLastNamedArgument = PV == LastParam; 6434 6435 Type = PV->getType(); 6436 ParamLoc = PV->getLocation(); 6437 IsCRegister = 6438 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6439 } 6440 } 6441 6442 if (!SecondArgIsLastNamedArgument) 6443 Diag(TheCall->getArg(1)->getBeginLoc(), 6444 diag::warn_second_arg_of_va_start_not_last_named_param); 6445 else if (IsCRegister || Type->isReferenceType() || 6446 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6447 // Promotable integers are UB, but enumerations need a bit of 6448 // extra checking to see what their promotable type actually is. 6449 if (!Type->isPromotableIntegerType()) 6450 return false; 6451 if (!Type->isEnumeralType()) 6452 return true; 6453 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6454 return !(ED && 6455 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6456 }()) { 6457 unsigned Reason = 0; 6458 if (Type->isReferenceType()) Reason = 1; 6459 else if (IsCRegister) Reason = 2; 6460 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6461 Diag(ParamLoc, diag::note_parameter_type) << Type; 6462 } 6463 6464 TheCall->setType(Context.VoidTy); 6465 return false; 6466 } 6467 6468 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6469 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6470 const LangOptions &LO = getLangOpts(); 6471 6472 if (LO.CPlusPlus) 6473 return Arg->getType() 6474 .getCanonicalType() 6475 .getTypePtr() 6476 ->getPointeeType() 6477 .withoutLocalFastQualifiers() == Context.CharTy; 6478 6479 // In C, allow aliasing through `char *`, this is required for AArch64 at 6480 // least. 6481 return true; 6482 }; 6483 6484 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6485 // const char *named_addr); 6486 6487 Expr *Func = Call->getCallee(); 6488 6489 if (Call->getNumArgs() < 3) 6490 return Diag(Call->getEndLoc(), 6491 diag::err_typecheck_call_too_few_args_at_least) 6492 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6493 6494 // Type-check the first argument normally. 6495 if (checkBuiltinArgument(*this, Call, 0)) 6496 return true; 6497 6498 // Check that the current function is variadic. 6499 if (checkVAStartIsInVariadicFunction(*this, Func)) 6500 return true; 6501 6502 // __va_start on Windows does not validate the parameter qualifiers 6503 6504 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6505 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6506 6507 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6508 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6509 6510 const QualType &ConstCharPtrTy = 6511 Context.getPointerType(Context.CharTy.withConst()); 6512 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6513 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6514 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6515 << 0 /* qualifier difference */ 6516 << 3 /* parameter mismatch */ 6517 << 2 << Arg1->getType() << ConstCharPtrTy; 6518 6519 const QualType SizeTy = Context.getSizeType(); 6520 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6521 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6522 << Arg2->getType() << SizeTy << 1 /* different class */ 6523 << 0 /* qualifier difference */ 6524 << 3 /* parameter mismatch */ 6525 << 3 << Arg2->getType() << SizeTy; 6526 6527 return false; 6528 } 6529 6530 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6531 /// friends. This is declared to take (...), so we have to check everything. 6532 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6533 if (checkArgCount(*this, TheCall, 2)) 6534 return true; 6535 6536 ExprResult OrigArg0 = TheCall->getArg(0); 6537 ExprResult OrigArg1 = TheCall->getArg(1); 6538 6539 // Do standard promotions between the two arguments, returning their common 6540 // type. 6541 QualType Res = UsualArithmeticConversions( 6542 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6543 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6544 return true; 6545 6546 // Make sure any conversions are pushed back into the call; this is 6547 // type safe since unordered compare builtins are declared as "_Bool 6548 // foo(...)". 6549 TheCall->setArg(0, OrigArg0.get()); 6550 TheCall->setArg(1, OrigArg1.get()); 6551 6552 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6553 return false; 6554 6555 // If the common type isn't a real floating type, then the arguments were 6556 // invalid for this operation. 6557 if (Res.isNull() || !Res->isRealFloatingType()) 6558 return Diag(OrigArg0.get()->getBeginLoc(), 6559 diag::err_typecheck_call_invalid_ordered_compare) 6560 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6561 << SourceRange(OrigArg0.get()->getBeginLoc(), 6562 OrigArg1.get()->getEndLoc()); 6563 6564 return false; 6565 } 6566 6567 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6568 /// __builtin_isnan and friends. This is declared to take (...), so we have 6569 /// to check everything. We expect the last argument to be a floating point 6570 /// value. 6571 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6572 if (checkArgCount(*this, TheCall, NumArgs)) 6573 return true; 6574 6575 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6576 // on all preceding parameters just being int. Try all of those. 6577 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6578 Expr *Arg = TheCall->getArg(i); 6579 6580 if (Arg->isTypeDependent()) 6581 return false; 6582 6583 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6584 6585 if (Res.isInvalid()) 6586 return true; 6587 TheCall->setArg(i, Res.get()); 6588 } 6589 6590 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6591 6592 if (OrigArg->isTypeDependent()) 6593 return false; 6594 6595 // Usual Unary Conversions will convert half to float, which we want for 6596 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6597 // type how it is, but do normal L->Rvalue conversions. 6598 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6599 OrigArg = UsualUnaryConversions(OrigArg).get(); 6600 else 6601 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6602 TheCall->setArg(NumArgs - 1, OrigArg); 6603 6604 // This operation requires a non-_Complex floating-point number. 6605 if (!OrigArg->getType()->isRealFloatingType()) 6606 return Diag(OrigArg->getBeginLoc(), 6607 diag::err_typecheck_call_invalid_unary_fp) 6608 << OrigArg->getType() << OrigArg->getSourceRange(); 6609 6610 return false; 6611 } 6612 6613 /// Perform semantic analysis for a call to __builtin_complex. 6614 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6615 if (checkArgCount(*this, TheCall, 2)) 6616 return true; 6617 6618 bool Dependent = false; 6619 for (unsigned I = 0; I != 2; ++I) { 6620 Expr *Arg = TheCall->getArg(I); 6621 QualType T = Arg->getType(); 6622 if (T->isDependentType()) { 6623 Dependent = true; 6624 continue; 6625 } 6626 6627 // Despite supporting _Complex int, GCC requires a real floating point type 6628 // for the operands of __builtin_complex. 6629 if (!T->isRealFloatingType()) { 6630 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6631 << Arg->getType() << Arg->getSourceRange(); 6632 } 6633 6634 ExprResult Converted = DefaultLvalueConversion(Arg); 6635 if (Converted.isInvalid()) 6636 return true; 6637 TheCall->setArg(I, Converted.get()); 6638 } 6639 6640 if (Dependent) { 6641 TheCall->setType(Context.DependentTy); 6642 return false; 6643 } 6644 6645 Expr *Real = TheCall->getArg(0); 6646 Expr *Imag = TheCall->getArg(1); 6647 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6648 return Diag(Real->getBeginLoc(), 6649 diag::err_typecheck_call_different_arg_types) 6650 << Real->getType() << Imag->getType() 6651 << Real->getSourceRange() << Imag->getSourceRange(); 6652 } 6653 6654 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6655 // don't allow this builtin to form those types either. 6656 // FIXME: Should we allow these types? 6657 if (Real->getType()->isFloat16Type()) 6658 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6659 << "_Float16"; 6660 if (Real->getType()->isHalfType()) 6661 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6662 << "half"; 6663 6664 TheCall->setType(Context.getComplexType(Real->getType())); 6665 return false; 6666 } 6667 6668 // Customized Sema Checking for VSX builtins that have the following signature: 6669 // vector [...] builtinName(vector [...], vector [...], const int); 6670 // Which takes the same type of vectors (any legal vector type) for the first 6671 // two arguments and takes compile time constant for the third argument. 6672 // Example builtins are : 6673 // vector double vec_xxpermdi(vector double, vector double, int); 6674 // vector short vec_xxsldwi(vector short, vector short, int); 6675 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6676 unsigned ExpectedNumArgs = 3; 6677 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6678 return true; 6679 6680 // Check the third argument is a compile time constant 6681 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6682 return Diag(TheCall->getBeginLoc(), 6683 diag::err_vsx_builtin_nonconstant_argument) 6684 << 3 /* argument index */ << TheCall->getDirectCallee() 6685 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6686 TheCall->getArg(2)->getEndLoc()); 6687 6688 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6689 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6690 6691 // Check the type of argument 1 and argument 2 are vectors. 6692 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6693 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6694 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6695 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6696 << TheCall->getDirectCallee() 6697 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6698 TheCall->getArg(1)->getEndLoc()); 6699 } 6700 6701 // Check the first two arguments are the same type. 6702 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6703 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6704 << TheCall->getDirectCallee() 6705 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6706 TheCall->getArg(1)->getEndLoc()); 6707 } 6708 6709 // When default clang type checking is turned off and the customized type 6710 // checking is used, the returning type of the function must be explicitly 6711 // set. Otherwise it is _Bool by default. 6712 TheCall->setType(Arg1Ty); 6713 6714 return false; 6715 } 6716 6717 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6718 // This is declared to take (...), so we have to check everything. 6719 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6720 if (TheCall->getNumArgs() < 2) 6721 return ExprError(Diag(TheCall->getEndLoc(), 6722 diag::err_typecheck_call_too_few_args_at_least) 6723 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6724 << TheCall->getSourceRange()); 6725 6726 // Determine which of the following types of shufflevector we're checking: 6727 // 1) unary, vector mask: (lhs, mask) 6728 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6729 QualType resType = TheCall->getArg(0)->getType(); 6730 unsigned numElements = 0; 6731 6732 if (!TheCall->getArg(0)->isTypeDependent() && 6733 !TheCall->getArg(1)->isTypeDependent()) { 6734 QualType LHSType = TheCall->getArg(0)->getType(); 6735 QualType RHSType = TheCall->getArg(1)->getType(); 6736 6737 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6738 return ExprError( 6739 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6740 << TheCall->getDirectCallee() 6741 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6742 TheCall->getArg(1)->getEndLoc())); 6743 6744 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6745 unsigned numResElements = TheCall->getNumArgs() - 2; 6746 6747 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6748 // with mask. If so, verify that RHS is an integer vector type with the 6749 // same number of elts as lhs. 6750 if (TheCall->getNumArgs() == 2) { 6751 if (!RHSType->hasIntegerRepresentation() || 6752 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6753 return ExprError(Diag(TheCall->getBeginLoc(), 6754 diag::err_vec_builtin_incompatible_vector) 6755 << TheCall->getDirectCallee() 6756 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6757 TheCall->getArg(1)->getEndLoc())); 6758 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6759 return ExprError(Diag(TheCall->getBeginLoc(), 6760 diag::err_vec_builtin_incompatible_vector) 6761 << TheCall->getDirectCallee() 6762 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6763 TheCall->getArg(1)->getEndLoc())); 6764 } else if (numElements != numResElements) { 6765 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6766 resType = Context.getVectorType(eltType, numResElements, 6767 VectorType::GenericVector); 6768 } 6769 } 6770 6771 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6772 if (TheCall->getArg(i)->isTypeDependent() || 6773 TheCall->getArg(i)->isValueDependent()) 6774 continue; 6775 6776 Optional<llvm::APSInt> Result; 6777 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6778 return ExprError(Diag(TheCall->getBeginLoc(), 6779 diag::err_shufflevector_nonconstant_argument) 6780 << TheCall->getArg(i)->getSourceRange()); 6781 6782 // Allow -1 which will be translated to undef in the IR. 6783 if (Result->isSigned() && Result->isAllOnes()) 6784 continue; 6785 6786 if (Result->getActiveBits() > 64 || 6787 Result->getZExtValue() >= numElements * 2) 6788 return ExprError(Diag(TheCall->getBeginLoc(), 6789 diag::err_shufflevector_argument_too_large) 6790 << TheCall->getArg(i)->getSourceRange()); 6791 } 6792 6793 SmallVector<Expr*, 32> exprs; 6794 6795 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6796 exprs.push_back(TheCall->getArg(i)); 6797 TheCall->setArg(i, nullptr); 6798 } 6799 6800 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6801 TheCall->getCallee()->getBeginLoc(), 6802 TheCall->getRParenLoc()); 6803 } 6804 6805 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6806 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6807 SourceLocation BuiltinLoc, 6808 SourceLocation RParenLoc) { 6809 ExprValueKind VK = VK_PRValue; 6810 ExprObjectKind OK = OK_Ordinary; 6811 QualType DstTy = TInfo->getType(); 6812 QualType SrcTy = E->getType(); 6813 6814 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6815 return ExprError(Diag(BuiltinLoc, 6816 diag::err_convertvector_non_vector) 6817 << E->getSourceRange()); 6818 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6819 return ExprError(Diag(BuiltinLoc, 6820 diag::err_convertvector_non_vector_type)); 6821 6822 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6823 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6824 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6825 if (SrcElts != DstElts) 6826 return ExprError(Diag(BuiltinLoc, 6827 diag::err_convertvector_incompatible_vector) 6828 << E->getSourceRange()); 6829 } 6830 6831 return new (Context) 6832 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6833 } 6834 6835 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6836 // This is declared to take (const void*, ...) and can take two 6837 // optional constant int args. 6838 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6839 unsigned NumArgs = TheCall->getNumArgs(); 6840 6841 if (NumArgs > 3) 6842 return Diag(TheCall->getEndLoc(), 6843 diag::err_typecheck_call_too_many_args_at_most) 6844 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6845 6846 // Argument 0 is checked for us and the remaining arguments must be 6847 // constant integers. 6848 for (unsigned i = 1; i != NumArgs; ++i) 6849 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6850 return true; 6851 6852 return false; 6853 } 6854 6855 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6856 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6857 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6858 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6859 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6860 if (checkArgCount(*this, TheCall, 1)) 6861 return true; 6862 Expr *Arg = TheCall->getArg(0); 6863 if (Arg->isInstantiationDependent()) 6864 return false; 6865 6866 QualType ArgTy = Arg->getType(); 6867 if (!ArgTy->hasFloatingRepresentation()) 6868 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6869 << ArgTy; 6870 if (Arg->isLValue()) { 6871 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6872 TheCall->setArg(0, FirstArg.get()); 6873 } 6874 TheCall->setType(TheCall->getArg(0)->getType()); 6875 return false; 6876 } 6877 6878 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6879 // __assume does not evaluate its arguments, and should warn if its argument 6880 // has side effects. 6881 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6882 Expr *Arg = TheCall->getArg(0); 6883 if (Arg->isInstantiationDependent()) return false; 6884 6885 if (Arg->HasSideEffects(Context)) 6886 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6887 << Arg->getSourceRange() 6888 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6889 6890 return false; 6891 } 6892 6893 /// Handle __builtin_alloca_with_align. This is declared 6894 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6895 /// than 8. 6896 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6897 // The alignment must be a constant integer. 6898 Expr *Arg = TheCall->getArg(1); 6899 6900 // We can't check the value of a dependent argument. 6901 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6902 if (const auto *UE = 6903 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6904 if (UE->getKind() == UETT_AlignOf || 6905 UE->getKind() == UETT_PreferredAlignOf) 6906 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6907 << Arg->getSourceRange(); 6908 6909 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6910 6911 if (!Result.isPowerOf2()) 6912 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6913 << Arg->getSourceRange(); 6914 6915 if (Result < Context.getCharWidth()) 6916 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6917 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6918 6919 if (Result > std::numeric_limits<int32_t>::max()) 6920 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6921 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6922 } 6923 6924 return false; 6925 } 6926 6927 /// Handle __builtin_assume_aligned. This is declared 6928 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6929 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6930 unsigned NumArgs = TheCall->getNumArgs(); 6931 6932 if (NumArgs > 3) 6933 return Diag(TheCall->getEndLoc(), 6934 diag::err_typecheck_call_too_many_args_at_most) 6935 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6936 6937 // The alignment must be a constant integer. 6938 Expr *Arg = TheCall->getArg(1); 6939 6940 // We can't check the value of a dependent argument. 6941 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6942 llvm::APSInt Result; 6943 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6944 return true; 6945 6946 if (!Result.isPowerOf2()) 6947 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6948 << Arg->getSourceRange(); 6949 6950 if (Result > Sema::MaximumAlignment) 6951 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6952 << Arg->getSourceRange() << Sema::MaximumAlignment; 6953 } 6954 6955 if (NumArgs > 2) { 6956 ExprResult Arg(TheCall->getArg(2)); 6957 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6958 Context.getSizeType(), false); 6959 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6960 if (Arg.isInvalid()) return true; 6961 TheCall->setArg(2, Arg.get()); 6962 } 6963 6964 return false; 6965 } 6966 6967 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6968 unsigned BuiltinID = 6969 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6970 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6971 6972 unsigned NumArgs = TheCall->getNumArgs(); 6973 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6974 if (NumArgs < NumRequiredArgs) { 6975 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6976 << 0 /* function call */ << NumRequiredArgs << NumArgs 6977 << TheCall->getSourceRange(); 6978 } 6979 if (NumArgs >= NumRequiredArgs + 0x100) { 6980 return Diag(TheCall->getEndLoc(), 6981 diag::err_typecheck_call_too_many_args_at_most) 6982 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6983 << TheCall->getSourceRange(); 6984 } 6985 unsigned i = 0; 6986 6987 // For formatting call, check buffer arg. 6988 if (!IsSizeCall) { 6989 ExprResult Arg(TheCall->getArg(i)); 6990 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6991 Context, Context.VoidPtrTy, false); 6992 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6993 if (Arg.isInvalid()) 6994 return true; 6995 TheCall->setArg(i, Arg.get()); 6996 i++; 6997 } 6998 6999 // Check string literal arg. 7000 unsigned FormatIdx = i; 7001 { 7002 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7003 if (Arg.isInvalid()) 7004 return true; 7005 TheCall->setArg(i, Arg.get()); 7006 i++; 7007 } 7008 7009 // Make sure variadic args are scalar. 7010 unsigned FirstDataArg = i; 7011 while (i < NumArgs) { 7012 ExprResult Arg = DefaultVariadicArgumentPromotion( 7013 TheCall->getArg(i), VariadicFunction, nullptr); 7014 if (Arg.isInvalid()) 7015 return true; 7016 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7017 if (ArgSize.getQuantity() >= 0x100) { 7018 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7019 << i << (int)ArgSize.getQuantity() << 0xff 7020 << TheCall->getSourceRange(); 7021 } 7022 TheCall->setArg(i, Arg.get()); 7023 i++; 7024 } 7025 7026 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7027 // call to avoid duplicate diagnostics. 7028 if (!IsSizeCall) { 7029 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7030 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7031 bool Success = CheckFormatArguments( 7032 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7033 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7034 CheckedVarArgs); 7035 if (!Success) 7036 return true; 7037 } 7038 7039 if (IsSizeCall) { 7040 TheCall->setType(Context.getSizeType()); 7041 } else { 7042 TheCall->setType(Context.VoidPtrTy); 7043 } 7044 return false; 7045 } 7046 7047 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7048 /// TheCall is a constant expression. 7049 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7050 llvm::APSInt &Result) { 7051 Expr *Arg = TheCall->getArg(ArgNum); 7052 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7053 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7054 7055 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7056 7057 Optional<llvm::APSInt> R; 7058 if (!(R = Arg->getIntegerConstantExpr(Context))) 7059 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7060 << FDecl->getDeclName() << Arg->getSourceRange(); 7061 Result = *R; 7062 return false; 7063 } 7064 7065 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7066 /// TheCall is a constant expression in the range [Low, High]. 7067 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7068 int Low, int High, bool RangeIsError) { 7069 if (isConstantEvaluated()) 7070 return false; 7071 llvm::APSInt Result; 7072 7073 // We can't check the value of a dependent argument. 7074 Expr *Arg = TheCall->getArg(ArgNum); 7075 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7076 return false; 7077 7078 // Check constant-ness first. 7079 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7080 return true; 7081 7082 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7083 if (RangeIsError) 7084 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7085 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7086 else 7087 // Defer the warning until we know if the code will be emitted so that 7088 // dead code can ignore this. 7089 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7090 PDiag(diag::warn_argument_invalid_range) 7091 << toString(Result, 10) << Low << High 7092 << Arg->getSourceRange()); 7093 } 7094 7095 return false; 7096 } 7097 7098 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7099 /// TheCall is a constant expression is a multiple of Num.. 7100 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7101 unsigned Num) { 7102 llvm::APSInt Result; 7103 7104 // We can't check the value of a dependent argument. 7105 Expr *Arg = TheCall->getArg(ArgNum); 7106 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7107 return false; 7108 7109 // Check constant-ness first. 7110 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7111 return true; 7112 7113 if (Result.getSExtValue() % Num != 0) 7114 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7115 << Num << Arg->getSourceRange(); 7116 7117 return false; 7118 } 7119 7120 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7121 /// constant expression representing a power of 2. 7122 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7123 llvm::APSInt Result; 7124 7125 // We can't check the value of a dependent argument. 7126 Expr *Arg = TheCall->getArg(ArgNum); 7127 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7128 return false; 7129 7130 // Check constant-ness first. 7131 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7132 return true; 7133 7134 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7135 // and only if x is a power of 2. 7136 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7137 return false; 7138 7139 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7140 << Arg->getSourceRange(); 7141 } 7142 7143 static bool IsShiftedByte(llvm::APSInt Value) { 7144 if (Value.isNegative()) 7145 return false; 7146 7147 // Check if it's a shifted byte, by shifting it down 7148 while (true) { 7149 // If the value fits in the bottom byte, the check passes. 7150 if (Value < 0x100) 7151 return true; 7152 7153 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7154 // fails. 7155 if ((Value & 0xFF) != 0) 7156 return false; 7157 7158 // If the bottom 8 bits are all 0, but something above that is nonzero, 7159 // then shifting the value right by 8 bits won't affect whether it's a 7160 // shifted byte or not. So do that, and go round again. 7161 Value >>= 8; 7162 } 7163 } 7164 7165 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7166 /// a constant expression representing an arbitrary byte value shifted left by 7167 /// a multiple of 8 bits. 7168 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7169 unsigned ArgBits) { 7170 llvm::APSInt Result; 7171 7172 // We can't check the value of a dependent argument. 7173 Expr *Arg = TheCall->getArg(ArgNum); 7174 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7175 return false; 7176 7177 // Check constant-ness first. 7178 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7179 return true; 7180 7181 // Truncate to the given size. 7182 Result = Result.getLoBits(ArgBits); 7183 Result.setIsUnsigned(true); 7184 7185 if (IsShiftedByte(Result)) 7186 return false; 7187 7188 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7189 << Arg->getSourceRange(); 7190 } 7191 7192 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7193 /// TheCall is a constant expression representing either a shifted byte value, 7194 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7195 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7196 /// Arm MVE intrinsics. 7197 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7198 int ArgNum, 7199 unsigned ArgBits) { 7200 llvm::APSInt Result; 7201 7202 // We can't check the value of a dependent argument. 7203 Expr *Arg = TheCall->getArg(ArgNum); 7204 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7205 return false; 7206 7207 // Check constant-ness first. 7208 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7209 return true; 7210 7211 // Truncate to the given size. 7212 Result = Result.getLoBits(ArgBits); 7213 Result.setIsUnsigned(true); 7214 7215 // Check to see if it's in either of the required forms. 7216 if (IsShiftedByte(Result) || 7217 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7218 return false; 7219 7220 return Diag(TheCall->getBeginLoc(), 7221 diag::err_argument_not_shifted_byte_or_xxff) 7222 << Arg->getSourceRange(); 7223 } 7224 7225 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7226 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7227 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7228 if (checkArgCount(*this, TheCall, 2)) 7229 return true; 7230 Expr *Arg0 = TheCall->getArg(0); 7231 Expr *Arg1 = TheCall->getArg(1); 7232 7233 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7234 if (FirstArg.isInvalid()) 7235 return true; 7236 QualType FirstArgType = FirstArg.get()->getType(); 7237 if (!FirstArgType->isAnyPointerType()) 7238 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7239 << "first" << FirstArgType << Arg0->getSourceRange(); 7240 TheCall->setArg(0, FirstArg.get()); 7241 7242 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7243 if (SecArg.isInvalid()) 7244 return true; 7245 QualType SecArgType = SecArg.get()->getType(); 7246 if (!SecArgType->isIntegerType()) 7247 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7248 << "second" << SecArgType << Arg1->getSourceRange(); 7249 7250 // Derive the return type from the pointer argument. 7251 TheCall->setType(FirstArgType); 7252 return false; 7253 } 7254 7255 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7256 if (checkArgCount(*this, TheCall, 2)) 7257 return true; 7258 7259 Expr *Arg0 = TheCall->getArg(0); 7260 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7261 if (FirstArg.isInvalid()) 7262 return true; 7263 QualType FirstArgType = FirstArg.get()->getType(); 7264 if (!FirstArgType->isAnyPointerType()) 7265 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7266 << "first" << FirstArgType << Arg0->getSourceRange(); 7267 TheCall->setArg(0, FirstArg.get()); 7268 7269 // Derive the return type from the pointer argument. 7270 TheCall->setType(FirstArgType); 7271 7272 // Second arg must be an constant in range [0,15] 7273 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7274 } 7275 7276 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7277 if (checkArgCount(*this, TheCall, 2)) 7278 return true; 7279 Expr *Arg0 = TheCall->getArg(0); 7280 Expr *Arg1 = TheCall->getArg(1); 7281 7282 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7283 if (FirstArg.isInvalid()) 7284 return true; 7285 QualType FirstArgType = FirstArg.get()->getType(); 7286 if (!FirstArgType->isAnyPointerType()) 7287 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7288 << "first" << FirstArgType << Arg0->getSourceRange(); 7289 7290 QualType SecArgType = Arg1->getType(); 7291 if (!SecArgType->isIntegerType()) 7292 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7293 << "second" << SecArgType << Arg1->getSourceRange(); 7294 TheCall->setType(Context.IntTy); 7295 return false; 7296 } 7297 7298 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7299 BuiltinID == AArch64::BI__builtin_arm_stg) { 7300 if (checkArgCount(*this, TheCall, 1)) 7301 return true; 7302 Expr *Arg0 = TheCall->getArg(0); 7303 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7304 if (FirstArg.isInvalid()) 7305 return true; 7306 7307 QualType FirstArgType = FirstArg.get()->getType(); 7308 if (!FirstArgType->isAnyPointerType()) 7309 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7310 << "first" << FirstArgType << Arg0->getSourceRange(); 7311 TheCall->setArg(0, FirstArg.get()); 7312 7313 // Derive the return type from the pointer argument. 7314 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7315 TheCall->setType(FirstArgType); 7316 return false; 7317 } 7318 7319 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7320 Expr *ArgA = TheCall->getArg(0); 7321 Expr *ArgB = TheCall->getArg(1); 7322 7323 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7324 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7325 7326 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7327 return true; 7328 7329 QualType ArgTypeA = ArgExprA.get()->getType(); 7330 QualType ArgTypeB = ArgExprB.get()->getType(); 7331 7332 auto isNull = [&] (Expr *E) -> bool { 7333 return E->isNullPointerConstant( 7334 Context, Expr::NPC_ValueDependentIsNotNull); }; 7335 7336 // argument should be either a pointer or null 7337 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7338 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7339 << "first" << ArgTypeA << ArgA->getSourceRange(); 7340 7341 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7342 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7343 << "second" << ArgTypeB << ArgB->getSourceRange(); 7344 7345 // Ensure Pointee types are compatible 7346 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7347 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7348 QualType pointeeA = ArgTypeA->getPointeeType(); 7349 QualType pointeeB = ArgTypeB->getPointeeType(); 7350 if (!Context.typesAreCompatible( 7351 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7352 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7353 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7354 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7355 << ArgB->getSourceRange(); 7356 } 7357 } 7358 7359 // at least one argument should be pointer type 7360 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7361 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7362 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7363 7364 if (isNull(ArgA)) // adopt type of the other pointer 7365 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7366 7367 if (isNull(ArgB)) 7368 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7369 7370 TheCall->setArg(0, ArgExprA.get()); 7371 TheCall->setArg(1, ArgExprB.get()); 7372 TheCall->setType(Context.LongLongTy); 7373 return false; 7374 } 7375 assert(false && "Unhandled ARM MTE intrinsic"); 7376 return true; 7377 } 7378 7379 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7380 /// TheCall is an ARM/AArch64 special register string literal. 7381 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7382 int ArgNum, unsigned ExpectedFieldNum, 7383 bool AllowName) { 7384 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7385 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7386 BuiltinID == ARM::BI__builtin_arm_rsr || 7387 BuiltinID == ARM::BI__builtin_arm_rsrp || 7388 BuiltinID == ARM::BI__builtin_arm_wsr || 7389 BuiltinID == ARM::BI__builtin_arm_wsrp; 7390 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7391 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7392 BuiltinID == AArch64::BI__builtin_arm_rsr || 7393 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7394 BuiltinID == AArch64::BI__builtin_arm_wsr || 7395 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7396 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7397 7398 // We can't check the value of a dependent argument. 7399 Expr *Arg = TheCall->getArg(ArgNum); 7400 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7401 return false; 7402 7403 // Check if the argument is a string literal. 7404 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7405 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7406 << Arg->getSourceRange(); 7407 7408 // Check the type of special register given. 7409 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7410 SmallVector<StringRef, 6> Fields; 7411 Reg.split(Fields, ":"); 7412 7413 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7414 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7415 << Arg->getSourceRange(); 7416 7417 // If the string is the name of a register then we cannot check that it is 7418 // valid here but if the string is of one the forms described in ACLE then we 7419 // can check that the supplied fields are integers and within the valid 7420 // ranges. 7421 if (Fields.size() > 1) { 7422 bool FiveFields = Fields.size() == 5; 7423 7424 bool ValidString = true; 7425 if (IsARMBuiltin) { 7426 ValidString &= Fields[0].startswith_insensitive("cp") || 7427 Fields[0].startswith_insensitive("p"); 7428 if (ValidString) 7429 Fields[0] = Fields[0].drop_front( 7430 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7431 7432 ValidString &= Fields[2].startswith_insensitive("c"); 7433 if (ValidString) 7434 Fields[2] = Fields[2].drop_front(1); 7435 7436 if (FiveFields) { 7437 ValidString &= Fields[3].startswith_insensitive("c"); 7438 if (ValidString) 7439 Fields[3] = Fields[3].drop_front(1); 7440 } 7441 } 7442 7443 SmallVector<int, 5> Ranges; 7444 if (FiveFields) 7445 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7446 else 7447 Ranges.append({15, 7, 15}); 7448 7449 for (unsigned i=0; i<Fields.size(); ++i) { 7450 int IntField; 7451 ValidString &= !Fields[i].getAsInteger(10, IntField); 7452 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7453 } 7454 7455 if (!ValidString) 7456 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7457 << Arg->getSourceRange(); 7458 } else if (IsAArch64Builtin && Fields.size() == 1) { 7459 // If the register name is one of those that appear in the condition below 7460 // and the special register builtin being used is one of the write builtins, 7461 // then we require that the argument provided for writing to the register 7462 // is an integer constant expression. This is because it will be lowered to 7463 // an MSR (immediate) instruction, so we need to know the immediate at 7464 // compile time. 7465 if (TheCall->getNumArgs() != 2) 7466 return false; 7467 7468 std::string RegLower = Reg.lower(); 7469 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7470 RegLower != "pan" && RegLower != "uao") 7471 return false; 7472 7473 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7474 } 7475 7476 return false; 7477 } 7478 7479 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7480 /// Emit an error and return true on failure; return false on success. 7481 /// TypeStr is a string containing the type descriptor of the value returned by 7482 /// the builtin and the descriptors of the expected type of the arguments. 7483 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7484 const char *TypeStr) { 7485 7486 assert((TypeStr[0] != '\0') && 7487 "Invalid types in PPC MMA builtin declaration"); 7488 7489 switch (BuiltinID) { 7490 default: 7491 // This function is called in CheckPPCBuiltinFunctionCall where the 7492 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7493 // we are isolating the pair vector memop builtins that can be used with mma 7494 // off so the default case is every builtin that requires mma and paired 7495 // vector memops. 7496 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7497 diag::err_ppc_builtin_only_on_arch, "10") || 7498 SemaFeatureCheck(*this, TheCall, "mma", 7499 diag::err_ppc_builtin_only_on_arch, "10")) 7500 return true; 7501 break; 7502 case PPC::BI__builtin_vsx_lxvp: 7503 case PPC::BI__builtin_vsx_stxvp: 7504 case PPC::BI__builtin_vsx_assemble_pair: 7505 case PPC::BI__builtin_vsx_disassemble_pair: 7506 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7507 diag::err_ppc_builtin_only_on_arch, "10")) 7508 return true; 7509 break; 7510 } 7511 7512 unsigned Mask = 0; 7513 unsigned ArgNum = 0; 7514 7515 // The first type in TypeStr is the type of the value returned by the 7516 // builtin. So we first read that type and change the type of TheCall. 7517 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7518 TheCall->setType(type); 7519 7520 while (*TypeStr != '\0') { 7521 Mask = 0; 7522 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7523 if (ArgNum >= TheCall->getNumArgs()) { 7524 ArgNum++; 7525 break; 7526 } 7527 7528 Expr *Arg = TheCall->getArg(ArgNum); 7529 QualType PassedType = Arg->getType(); 7530 QualType StrippedRVType = PassedType.getCanonicalType(); 7531 7532 // Strip Restrict/Volatile qualifiers. 7533 if (StrippedRVType.isRestrictQualified() || 7534 StrippedRVType.isVolatileQualified()) 7535 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7536 7537 // The only case where the argument type and expected type are allowed to 7538 // mismatch is if the argument type is a non-void pointer and expected type 7539 // is a void pointer. 7540 if (StrippedRVType != ExpectedType) 7541 if (!(ExpectedType->isVoidPointerType() && 7542 StrippedRVType->isPointerType())) 7543 return Diag(Arg->getBeginLoc(), 7544 diag::err_typecheck_convert_incompatible) 7545 << PassedType << ExpectedType << 1 << 0 << 0; 7546 7547 // If the value of the Mask is not 0, we have a constraint in the size of 7548 // the integer argument so here we ensure the argument is a constant that 7549 // is in the valid range. 7550 if (Mask != 0 && 7551 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7552 return true; 7553 7554 ArgNum++; 7555 } 7556 7557 // In case we exited early from the previous loop, there are other types to 7558 // read from TypeStr. So we need to read them all to ensure we have the right 7559 // number of arguments in TheCall and if it is not the case, to display a 7560 // better error message. 7561 while (*TypeStr != '\0') { 7562 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7563 ArgNum++; 7564 } 7565 if (checkArgCount(*this, TheCall, ArgNum)) 7566 return true; 7567 7568 return false; 7569 } 7570 7571 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7572 /// This checks that the target supports __builtin_longjmp and 7573 /// that val is a constant 1. 7574 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7575 if (!Context.getTargetInfo().hasSjLjLowering()) 7576 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7577 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7578 7579 Expr *Arg = TheCall->getArg(1); 7580 llvm::APSInt Result; 7581 7582 // TODO: This is less than ideal. Overload this to take a value. 7583 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7584 return true; 7585 7586 if (Result != 1) 7587 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7588 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7589 7590 return false; 7591 } 7592 7593 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7594 /// This checks that the target supports __builtin_setjmp. 7595 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7596 if (!Context.getTargetInfo().hasSjLjLowering()) 7597 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7598 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7599 return false; 7600 } 7601 7602 namespace { 7603 7604 class UncoveredArgHandler { 7605 enum { Unknown = -1, AllCovered = -2 }; 7606 7607 signed FirstUncoveredArg = Unknown; 7608 SmallVector<const Expr *, 4> DiagnosticExprs; 7609 7610 public: 7611 UncoveredArgHandler() = default; 7612 7613 bool hasUncoveredArg() const { 7614 return (FirstUncoveredArg >= 0); 7615 } 7616 7617 unsigned getUncoveredArg() const { 7618 assert(hasUncoveredArg() && "no uncovered argument"); 7619 return FirstUncoveredArg; 7620 } 7621 7622 void setAllCovered() { 7623 // A string has been found with all arguments covered, so clear out 7624 // the diagnostics. 7625 DiagnosticExprs.clear(); 7626 FirstUncoveredArg = AllCovered; 7627 } 7628 7629 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7630 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7631 7632 // Don't update if a previous string covers all arguments. 7633 if (FirstUncoveredArg == AllCovered) 7634 return; 7635 7636 // UncoveredArgHandler tracks the highest uncovered argument index 7637 // and with it all the strings that match this index. 7638 if (NewFirstUncoveredArg == FirstUncoveredArg) 7639 DiagnosticExprs.push_back(StrExpr); 7640 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7641 DiagnosticExprs.clear(); 7642 DiagnosticExprs.push_back(StrExpr); 7643 FirstUncoveredArg = NewFirstUncoveredArg; 7644 } 7645 } 7646 7647 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7648 }; 7649 7650 enum StringLiteralCheckType { 7651 SLCT_NotALiteral, 7652 SLCT_UncheckedLiteral, 7653 SLCT_CheckedLiteral 7654 }; 7655 7656 } // namespace 7657 7658 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7659 BinaryOperatorKind BinOpKind, 7660 bool AddendIsRight) { 7661 unsigned BitWidth = Offset.getBitWidth(); 7662 unsigned AddendBitWidth = Addend.getBitWidth(); 7663 // There might be negative interim results. 7664 if (Addend.isUnsigned()) { 7665 Addend = Addend.zext(++AddendBitWidth); 7666 Addend.setIsSigned(true); 7667 } 7668 // Adjust the bit width of the APSInts. 7669 if (AddendBitWidth > BitWidth) { 7670 Offset = Offset.sext(AddendBitWidth); 7671 BitWidth = AddendBitWidth; 7672 } else if (BitWidth > AddendBitWidth) { 7673 Addend = Addend.sext(BitWidth); 7674 } 7675 7676 bool Ov = false; 7677 llvm::APSInt ResOffset = Offset; 7678 if (BinOpKind == BO_Add) 7679 ResOffset = Offset.sadd_ov(Addend, Ov); 7680 else { 7681 assert(AddendIsRight && BinOpKind == BO_Sub && 7682 "operator must be add or sub with addend on the right"); 7683 ResOffset = Offset.ssub_ov(Addend, Ov); 7684 } 7685 7686 // We add an offset to a pointer here so we should support an offset as big as 7687 // possible. 7688 if (Ov) { 7689 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7690 "index (intermediate) result too big"); 7691 Offset = Offset.sext(2 * BitWidth); 7692 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7693 return; 7694 } 7695 7696 Offset = ResOffset; 7697 } 7698 7699 namespace { 7700 7701 // This is a wrapper class around StringLiteral to support offsetted string 7702 // literals as format strings. It takes the offset into account when returning 7703 // the string and its length or the source locations to display notes correctly. 7704 class FormatStringLiteral { 7705 const StringLiteral *FExpr; 7706 int64_t Offset; 7707 7708 public: 7709 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7710 : FExpr(fexpr), Offset(Offset) {} 7711 7712 StringRef getString() const { 7713 return FExpr->getString().drop_front(Offset); 7714 } 7715 7716 unsigned getByteLength() const { 7717 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7718 } 7719 7720 unsigned getLength() const { return FExpr->getLength() - Offset; } 7721 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7722 7723 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7724 7725 QualType getType() const { return FExpr->getType(); } 7726 7727 bool isAscii() const { return FExpr->isAscii(); } 7728 bool isWide() const { return FExpr->isWide(); } 7729 bool isUTF8() const { return FExpr->isUTF8(); } 7730 bool isUTF16() const { return FExpr->isUTF16(); } 7731 bool isUTF32() const { return FExpr->isUTF32(); } 7732 bool isPascal() const { return FExpr->isPascal(); } 7733 7734 SourceLocation getLocationOfByte( 7735 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7736 const TargetInfo &Target, unsigned *StartToken = nullptr, 7737 unsigned *StartTokenByteOffset = nullptr) const { 7738 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7739 StartToken, StartTokenByteOffset); 7740 } 7741 7742 SourceLocation getBeginLoc() const LLVM_READONLY { 7743 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7744 } 7745 7746 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7747 }; 7748 7749 } // namespace 7750 7751 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7752 const Expr *OrigFormatExpr, 7753 ArrayRef<const Expr *> Args, 7754 bool HasVAListArg, unsigned format_idx, 7755 unsigned firstDataArg, 7756 Sema::FormatStringType Type, 7757 bool inFunctionCall, 7758 Sema::VariadicCallType CallType, 7759 llvm::SmallBitVector &CheckedVarArgs, 7760 UncoveredArgHandler &UncoveredArg, 7761 bool IgnoreStringsWithoutSpecifiers); 7762 7763 // Determine if an expression is a string literal or constant string. 7764 // If this function returns false on the arguments to a function expecting a 7765 // format string, we will usually need to emit a warning. 7766 // True string literals are then checked by CheckFormatString. 7767 static StringLiteralCheckType 7768 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7769 bool HasVAListArg, unsigned format_idx, 7770 unsigned firstDataArg, Sema::FormatStringType Type, 7771 Sema::VariadicCallType CallType, bool InFunctionCall, 7772 llvm::SmallBitVector &CheckedVarArgs, 7773 UncoveredArgHandler &UncoveredArg, 7774 llvm::APSInt Offset, 7775 bool IgnoreStringsWithoutSpecifiers = false) { 7776 if (S.isConstantEvaluated()) 7777 return SLCT_NotALiteral; 7778 tryAgain: 7779 assert(Offset.isSigned() && "invalid offset"); 7780 7781 if (E->isTypeDependent() || E->isValueDependent()) 7782 return SLCT_NotALiteral; 7783 7784 E = E->IgnoreParenCasts(); 7785 7786 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7787 // Technically -Wformat-nonliteral does not warn about this case. 7788 // The behavior of printf and friends in this case is implementation 7789 // dependent. Ideally if the format string cannot be null then 7790 // it should have a 'nonnull' attribute in the function prototype. 7791 return SLCT_UncheckedLiteral; 7792 7793 switch (E->getStmtClass()) { 7794 case Stmt::BinaryConditionalOperatorClass: 7795 case Stmt::ConditionalOperatorClass: { 7796 // The expression is a literal if both sub-expressions were, and it was 7797 // completely checked only if both sub-expressions were checked. 7798 const AbstractConditionalOperator *C = 7799 cast<AbstractConditionalOperator>(E); 7800 7801 // Determine whether it is necessary to check both sub-expressions, for 7802 // example, because the condition expression is a constant that can be 7803 // evaluated at compile time. 7804 bool CheckLeft = true, CheckRight = true; 7805 7806 bool Cond; 7807 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7808 S.isConstantEvaluated())) { 7809 if (Cond) 7810 CheckRight = false; 7811 else 7812 CheckLeft = false; 7813 } 7814 7815 // We need to maintain the offsets for the right and the left hand side 7816 // separately to check if every possible indexed expression is a valid 7817 // string literal. They might have different offsets for different string 7818 // literals in the end. 7819 StringLiteralCheckType Left; 7820 if (!CheckLeft) 7821 Left = SLCT_UncheckedLiteral; 7822 else { 7823 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7824 HasVAListArg, format_idx, firstDataArg, 7825 Type, CallType, InFunctionCall, 7826 CheckedVarArgs, UncoveredArg, Offset, 7827 IgnoreStringsWithoutSpecifiers); 7828 if (Left == SLCT_NotALiteral || !CheckRight) { 7829 return Left; 7830 } 7831 } 7832 7833 StringLiteralCheckType Right = checkFormatStringExpr( 7834 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7835 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7836 IgnoreStringsWithoutSpecifiers); 7837 7838 return (CheckLeft && Left < Right) ? Left : Right; 7839 } 7840 7841 case Stmt::ImplicitCastExprClass: 7842 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7843 goto tryAgain; 7844 7845 case Stmt::OpaqueValueExprClass: 7846 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7847 E = src; 7848 goto tryAgain; 7849 } 7850 return SLCT_NotALiteral; 7851 7852 case Stmt::PredefinedExprClass: 7853 // While __func__, etc., are technically not string literals, they 7854 // cannot contain format specifiers and thus are not a security 7855 // liability. 7856 return SLCT_UncheckedLiteral; 7857 7858 case Stmt::DeclRefExprClass: { 7859 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7860 7861 // As an exception, do not flag errors for variables binding to 7862 // const string literals. 7863 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7864 bool isConstant = false; 7865 QualType T = DR->getType(); 7866 7867 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7868 isConstant = AT->getElementType().isConstant(S.Context); 7869 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7870 isConstant = T.isConstant(S.Context) && 7871 PT->getPointeeType().isConstant(S.Context); 7872 } else if (T->isObjCObjectPointerType()) { 7873 // In ObjC, there is usually no "const ObjectPointer" type, 7874 // so don't check if the pointee type is constant. 7875 isConstant = T.isConstant(S.Context); 7876 } 7877 7878 if (isConstant) { 7879 if (const Expr *Init = VD->getAnyInitializer()) { 7880 // Look through initializers like const char c[] = { "foo" } 7881 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7882 if (InitList->isStringLiteralInit()) 7883 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7884 } 7885 return checkFormatStringExpr(S, Init, Args, 7886 HasVAListArg, format_idx, 7887 firstDataArg, Type, CallType, 7888 /*InFunctionCall*/ false, CheckedVarArgs, 7889 UncoveredArg, Offset); 7890 } 7891 } 7892 7893 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7894 // special check to see if the format string is a function parameter 7895 // of the function calling the printf function. If the function 7896 // has an attribute indicating it is a printf-like function, then we 7897 // should suppress warnings concerning non-literals being used in a call 7898 // to a vprintf function. For example: 7899 // 7900 // void 7901 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7902 // va_list ap; 7903 // va_start(ap, fmt); 7904 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7905 // ... 7906 // } 7907 if (HasVAListArg) { 7908 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7909 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7910 int PVIndex = PV->getFunctionScopeIndex() + 1; 7911 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7912 // adjust for implicit parameter 7913 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7914 if (MD->isInstance()) 7915 ++PVIndex; 7916 // We also check if the formats are compatible. 7917 // We can't pass a 'scanf' string to a 'printf' function. 7918 if (PVIndex == PVFormat->getFormatIdx() && 7919 Type == S.GetFormatStringType(PVFormat)) 7920 return SLCT_UncheckedLiteral; 7921 } 7922 } 7923 } 7924 } 7925 } 7926 7927 return SLCT_NotALiteral; 7928 } 7929 7930 case Stmt::CallExprClass: 7931 case Stmt::CXXMemberCallExprClass: { 7932 const CallExpr *CE = cast<CallExpr>(E); 7933 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7934 bool IsFirst = true; 7935 StringLiteralCheckType CommonResult; 7936 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7937 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7938 StringLiteralCheckType Result = checkFormatStringExpr( 7939 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7940 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7941 IgnoreStringsWithoutSpecifiers); 7942 if (IsFirst) { 7943 CommonResult = Result; 7944 IsFirst = false; 7945 } 7946 } 7947 if (!IsFirst) 7948 return CommonResult; 7949 7950 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7951 unsigned BuiltinID = FD->getBuiltinID(); 7952 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7953 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7954 const Expr *Arg = CE->getArg(0); 7955 return checkFormatStringExpr(S, Arg, Args, 7956 HasVAListArg, format_idx, 7957 firstDataArg, Type, CallType, 7958 InFunctionCall, CheckedVarArgs, 7959 UncoveredArg, Offset, 7960 IgnoreStringsWithoutSpecifiers); 7961 } 7962 } 7963 } 7964 7965 return SLCT_NotALiteral; 7966 } 7967 case Stmt::ObjCMessageExprClass: { 7968 const auto *ME = cast<ObjCMessageExpr>(E); 7969 if (const auto *MD = ME->getMethodDecl()) { 7970 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7971 // As a special case heuristic, if we're using the method -[NSBundle 7972 // localizedStringForKey:value:table:], ignore any key strings that lack 7973 // format specifiers. The idea is that if the key doesn't have any 7974 // format specifiers then its probably just a key to map to the 7975 // localized strings. If it does have format specifiers though, then its 7976 // likely that the text of the key is the format string in the 7977 // programmer's language, and should be checked. 7978 const ObjCInterfaceDecl *IFace; 7979 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7980 IFace->getIdentifier()->isStr("NSBundle") && 7981 MD->getSelector().isKeywordSelector( 7982 {"localizedStringForKey", "value", "table"})) { 7983 IgnoreStringsWithoutSpecifiers = true; 7984 } 7985 7986 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7987 return checkFormatStringExpr( 7988 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7989 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7990 IgnoreStringsWithoutSpecifiers); 7991 } 7992 } 7993 7994 return SLCT_NotALiteral; 7995 } 7996 case Stmt::ObjCStringLiteralClass: 7997 case Stmt::StringLiteralClass: { 7998 const StringLiteral *StrE = nullptr; 7999 8000 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8001 StrE = ObjCFExpr->getString(); 8002 else 8003 StrE = cast<StringLiteral>(E); 8004 8005 if (StrE) { 8006 if (Offset.isNegative() || Offset > StrE->getLength()) { 8007 // TODO: It would be better to have an explicit warning for out of 8008 // bounds literals. 8009 return SLCT_NotALiteral; 8010 } 8011 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8012 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8013 firstDataArg, Type, InFunctionCall, CallType, 8014 CheckedVarArgs, UncoveredArg, 8015 IgnoreStringsWithoutSpecifiers); 8016 return SLCT_CheckedLiteral; 8017 } 8018 8019 return SLCT_NotALiteral; 8020 } 8021 case Stmt::BinaryOperatorClass: { 8022 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8023 8024 // A string literal + an int offset is still a string literal. 8025 if (BinOp->isAdditiveOp()) { 8026 Expr::EvalResult LResult, RResult; 8027 8028 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8029 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8030 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8031 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8032 8033 if (LIsInt != RIsInt) { 8034 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8035 8036 if (LIsInt) { 8037 if (BinOpKind == BO_Add) { 8038 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8039 E = BinOp->getRHS(); 8040 goto tryAgain; 8041 } 8042 } else { 8043 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8044 E = BinOp->getLHS(); 8045 goto tryAgain; 8046 } 8047 } 8048 } 8049 8050 return SLCT_NotALiteral; 8051 } 8052 case Stmt::UnaryOperatorClass: { 8053 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8054 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8055 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8056 Expr::EvalResult IndexResult; 8057 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8058 Expr::SE_NoSideEffects, 8059 S.isConstantEvaluated())) { 8060 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8061 /*RHS is int*/ true); 8062 E = ASE->getBase(); 8063 goto tryAgain; 8064 } 8065 } 8066 8067 return SLCT_NotALiteral; 8068 } 8069 8070 default: 8071 return SLCT_NotALiteral; 8072 } 8073 } 8074 8075 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8076 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8077 .Case("scanf", FST_Scanf) 8078 .Cases("printf", "printf0", FST_Printf) 8079 .Cases("NSString", "CFString", FST_NSString) 8080 .Case("strftime", FST_Strftime) 8081 .Case("strfmon", FST_Strfmon) 8082 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8083 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8084 .Case("os_trace", FST_OSLog) 8085 .Case("os_log", FST_OSLog) 8086 .Default(FST_Unknown); 8087 } 8088 8089 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8090 /// functions) for correct use of format strings. 8091 /// Returns true if a format string has been fully checked. 8092 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8093 ArrayRef<const Expr *> Args, 8094 bool IsCXXMember, 8095 VariadicCallType CallType, 8096 SourceLocation Loc, SourceRange Range, 8097 llvm::SmallBitVector &CheckedVarArgs) { 8098 FormatStringInfo FSI; 8099 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8100 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8101 FSI.FirstDataArg, GetFormatStringType(Format), 8102 CallType, Loc, Range, CheckedVarArgs); 8103 return false; 8104 } 8105 8106 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8107 bool HasVAListArg, unsigned format_idx, 8108 unsigned firstDataArg, FormatStringType Type, 8109 VariadicCallType CallType, 8110 SourceLocation Loc, SourceRange Range, 8111 llvm::SmallBitVector &CheckedVarArgs) { 8112 // CHECK: printf/scanf-like function is called with no format string. 8113 if (format_idx >= Args.size()) { 8114 Diag(Loc, diag::warn_missing_format_string) << Range; 8115 return false; 8116 } 8117 8118 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8119 8120 // CHECK: format string is not a string literal. 8121 // 8122 // Dynamically generated format strings are difficult to 8123 // automatically vet at compile time. Requiring that format strings 8124 // are string literals: (1) permits the checking of format strings by 8125 // the compiler and thereby (2) can practically remove the source of 8126 // many format string exploits. 8127 8128 // Format string can be either ObjC string (e.g. @"%d") or 8129 // C string (e.g. "%d") 8130 // ObjC string uses the same format specifiers as C string, so we can use 8131 // the same format string checking logic for both ObjC and C strings. 8132 UncoveredArgHandler UncoveredArg; 8133 StringLiteralCheckType CT = 8134 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8135 format_idx, firstDataArg, Type, CallType, 8136 /*IsFunctionCall*/ true, CheckedVarArgs, 8137 UncoveredArg, 8138 /*no string offset*/ llvm::APSInt(64, false) = 0); 8139 8140 // Generate a diagnostic where an uncovered argument is detected. 8141 if (UncoveredArg.hasUncoveredArg()) { 8142 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8143 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8144 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8145 } 8146 8147 if (CT != SLCT_NotALiteral) 8148 // Literal format string found, check done! 8149 return CT == SLCT_CheckedLiteral; 8150 8151 // Strftime is particular as it always uses a single 'time' argument, 8152 // so it is safe to pass a non-literal string. 8153 if (Type == FST_Strftime) 8154 return false; 8155 8156 // Do not emit diag when the string param is a macro expansion and the 8157 // format is either NSString or CFString. This is a hack to prevent 8158 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8159 // which are usually used in place of NS and CF string literals. 8160 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8161 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8162 return false; 8163 8164 // If there are no arguments specified, warn with -Wformat-security, otherwise 8165 // warn only with -Wformat-nonliteral. 8166 if (Args.size() == firstDataArg) { 8167 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8168 << OrigFormatExpr->getSourceRange(); 8169 switch (Type) { 8170 default: 8171 break; 8172 case FST_Kprintf: 8173 case FST_FreeBSDKPrintf: 8174 case FST_Printf: 8175 Diag(FormatLoc, diag::note_format_security_fixit) 8176 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8177 break; 8178 case FST_NSString: 8179 Diag(FormatLoc, diag::note_format_security_fixit) 8180 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8181 break; 8182 } 8183 } else { 8184 Diag(FormatLoc, diag::warn_format_nonliteral) 8185 << OrigFormatExpr->getSourceRange(); 8186 } 8187 return false; 8188 } 8189 8190 namespace { 8191 8192 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8193 protected: 8194 Sema &S; 8195 const FormatStringLiteral *FExpr; 8196 const Expr *OrigFormatExpr; 8197 const Sema::FormatStringType FSType; 8198 const unsigned FirstDataArg; 8199 const unsigned NumDataArgs; 8200 const char *Beg; // Start of format string. 8201 const bool HasVAListArg; 8202 ArrayRef<const Expr *> Args; 8203 unsigned FormatIdx; 8204 llvm::SmallBitVector CoveredArgs; 8205 bool usesPositionalArgs = false; 8206 bool atFirstArg = true; 8207 bool inFunctionCall; 8208 Sema::VariadicCallType CallType; 8209 llvm::SmallBitVector &CheckedVarArgs; 8210 UncoveredArgHandler &UncoveredArg; 8211 8212 public: 8213 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8214 const Expr *origFormatExpr, 8215 const Sema::FormatStringType type, unsigned firstDataArg, 8216 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8217 ArrayRef<const Expr *> Args, unsigned formatIdx, 8218 bool inFunctionCall, Sema::VariadicCallType callType, 8219 llvm::SmallBitVector &CheckedVarArgs, 8220 UncoveredArgHandler &UncoveredArg) 8221 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8222 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8223 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8224 inFunctionCall(inFunctionCall), CallType(callType), 8225 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8226 CoveredArgs.resize(numDataArgs); 8227 CoveredArgs.reset(); 8228 } 8229 8230 void DoneProcessing(); 8231 8232 void HandleIncompleteSpecifier(const char *startSpecifier, 8233 unsigned specifierLen) override; 8234 8235 void HandleInvalidLengthModifier( 8236 const analyze_format_string::FormatSpecifier &FS, 8237 const analyze_format_string::ConversionSpecifier &CS, 8238 const char *startSpecifier, unsigned specifierLen, 8239 unsigned DiagID); 8240 8241 void HandleNonStandardLengthModifier( 8242 const analyze_format_string::FormatSpecifier &FS, 8243 const char *startSpecifier, unsigned specifierLen); 8244 8245 void HandleNonStandardConversionSpecifier( 8246 const analyze_format_string::ConversionSpecifier &CS, 8247 const char *startSpecifier, unsigned specifierLen); 8248 8249 void HandlePosition(const char *startPos, unsigned posLen) override; 8250 8251 void HandleInvalidPosition(const char *startSpecifier, 8252 unsigned specifierLen, 8253 analyze_format_string::PositionContext p) override; 8254 8255 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8256 8257 void HandleNullChar(const char *nullCharacter) override; 8258 8259 template <typename Range> 8260 static void 8261 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8262 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8263 bool IsStringLocation, Range StringRange, 8264 ArrayRef<FixItHint> Fixit = None); 8265 8266 protected: 8267 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8268 const char *startSpec, 8269 unsigned specifierLen, 8270 const char *csStart, unsigned csLen); 8271 8272 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8273 const char *startSpec, 8274 unsigned specifierLen); 8275 8276 SourceRange getFormatStringRange(); 8277 CharSourceRange getSpecifierRange(const char *startSpecifier, 8278 unsigned specifierLen); 8279 SourceLocation getLocationOfByte(const char *x); 8280 8281 const Expr *getDataArg(unsigned i) const; 8282 8283 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8284 const analyze_format_string::ConversionSpecifier &CS, 8285 const char *startSpecifier, unsigned specifierLen, 8286 unsigned argIndex); 8287 8288 template <typename Range> 8289 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8290 bool IsStringLocation, Range StringRange, 8291 ArrayRef<FixItHint> Fixit = None); 8292 }; 8293 8294 } // namespace 8295 8296 SourceRange CheckFormatHandler::getFormatStringRange() { 8297 return OrigFormatExpr->getSourceRange(); 8298 } 8299 8300 CharSourceRange CheckFormatHandler:: 8301 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8302 SourceLocation Start = getLocationOfByte(startSpecifier); 8303 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8304 8305 // Advance the end SourceLocation by one due to half-open ranges. 8306 End = End.getLocWithOffset(1); 8307 8308 return CharSourceRange::getCharRange(Start, End); 8309 } 8310 8311 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8312 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8313 S.getLangOpts(), S.Context.getTargetInfo()); 8314 } 8315 8316 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8317 unsigned specifierLen){ 8318 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8319 getLocationOfByte(startSpecifier), 8320 /*IsStringLocation*/true, 8321 getSpecifierRange(startSpecifier, specifierLen)); 8322 } 8323 8324 void CheckFormatHandler::HandleInvalidLengthModifier( 8325 const analyze_format_string::FormatSpecifier &FS, 8326 const analyze_format_string::ConversionSpecifier &CS, 8327 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8328 using namespace analyze_format_string; 8329 8330 const LengthModifier &LM = FS.getLengthModifier(); 8331 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8332 8333 // See if we know how to fix this length modifier. 8334 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8335 if (FixedLM) { 8336 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8337 getLocationOfByte(LM.getStart()), 8338 /*IsStringLocation*/true, 8339 getSpecifierRange(startSpecifier, specifierLen)); 8340 8341 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8342 << FixedLM->toString() 8343 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8344 8345 } else { 8346 FixItHint Hint; 8347 if (DiagID == diag::warn_format_nonsensical_length) 8348 Hint = FixItHint::CreateRemoval(LMRange); 8349 8350 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8351 getLocationOfByte(LM.getStart()), 8352 /*IsStringLocation*/true, 8353 getSpecifierRange(startSpecifier, specifierLen), 8354 Hint); 8355 } 8356 } 8357 8358 void CheckFormatHandler::HandleNonStandardLengthModifier( 8359 const analyze_format_string::FormatSpecifier &FS, 8360 const char *startSpecifier, unsigned specifierLen) { 8361 using namespace analyze_format_string; 8362 8363 const LengthModifier &LM = FS.getLengthModifier(); 8364 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8365 8366 // See if we know how to fix this length modifier. 8367 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8368 if (FixedLM) { 8369 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8370 << LM.toString() << 0, 8371 getLocationOfByte(LM.getStart()), 8372 /*IsStringLocation*/true, 8373 getSpecifierRange(startSpecifier, specifierLen)); 8374 8375 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8376 << FixedLM->toString() 8377 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8378 8379 } else { 8380 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8381 << LM.toString() << 0, 8382 getLocationOfByte(LM.getStart()), 8383 /*IsStringLocation*/true, 8384 getSpecifierRange(startSpecifier, specifierLen)); 8385 } 8386 } 8387 8388 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8389 const analyze_format_string::ConversionSpecifier &CS, 8390 const char *startSpecifier, unsigned specifierLen) { 8391 using namespace analyze_format_string; 8392 8393 // See if we know how to fix this conversion specifier. 8394 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8395 if (FixedCS) { 8396 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8397 << CS.toString() << /*conversion specifier*/1, 8398 getLocationOfByte(CS.getStart()), 8399 /*IsStringLocation*/true, 8400 getSpecifierRange(startSpecifier, specifierLen)); 8401 8402 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8403 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8404 << FixedCS->toString() 8405 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8406 } else { 8407 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8408 << CS.toString() << /*conversion specifier*/1, 8409 getLocationOfByte(CS.getStart()), 8410 /*IsStringLocation*/true, 8411 getSpecifierRange(startSpecifier, specifierLen)); 8412 } 8413 } 8414 8415 void CheckFormatHandler::HandlePosition(const char *startPos, 8416 unsigned posLen) { 8417 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8418 getLocationOfByte(startPos), 8419 /*IsStringLocation*/true, 8420 getSpecifierRange(startPos, posLen)); 8421 } 8422 8423 void 8424 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8425 analyze_format_string::PositionContext p) { 8426 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8427 << (unsigned) p, 8428 getLocationOfByte(startPos), /*IsStringLocation*/true, 8429 getSpecifierRange(startPos, posLen)); 8430 } 8431 8432 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8433 unsigned posLen) { 8434 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8435 getLocationOfByte(startPos), 8436 /*IsStringLocation*/true, 8437 getSpecifierRange(startPos, posLen)); 8438 } 8439 8440 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8441 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8442 // The presence of a null character is likely an error. 8443 EmitFormatDiagnostic( 8444 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8445 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8446 getFormatStringRange()); 8447 } 8448 } 8449 8450 // Note that this may return NULL if there was an error parsing or building 8451 // one of the argument expressions. 8452 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8453 return Args[FirstDataArg + i]; 8454 } 8455 8456 void CheckFormatHandler::DoneProcessing() { 8457 // Does the number of data arguments exceed the number of 8458 // format conversions in the format string? 8459 if (!HasVAListArg) { 8460 // Find any arguments that weren't covered. 8461 CoveredArgs.flip(); 8462 signed notCoveredArg = CoveredArgs.find_first(); 8463 if (notCoveredArg >= 0) { 8464 assert((unsigned)notCoveredArg < NumDataArgs); 8465 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8466 } else { 8467 UncoveredArg.setAllCovered(); 8468 } 8469 } 8470 } 8471 8472 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8473 const Expr *ArgExpr) { 8474 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8475 "Invalid state"); 8476 8477 if (!ArgExpr) 8478 return; 8479 8480 SourceLocation Loc = ArgExpr->getBeginLoc(); 8481 8482 if (S.getSourceManager().isInSystemMacro(Loc)) 8483 return; 8484 8485 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8486 for (auto E : DiagnosticExprs) 8487 PDiag << E->getSourceRange(); 8488 8489 CheckFormatHandler::EmitFormatDiagnostic( 8490 S, IsFunctionCall, DiagnosticExprs[0], 8491 PDiag, Loc, /*IsStringLocation*/false, 8492 DiagnosticExprs[0]->getSourceRange()); 8493 } 8494 8495 bool 8496 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8497 SourceLocation Loc, 8498 const char *startSpec, 8499 unsigned specifierLen, 8500 const char *csStart, 8501 unsigned csLen) { 8502 bool keepGoing = true; 8503 if (argIndex < NumDataArgs) { 8504 // Consider the argument coverered, even though the specifier doesn't 8505 // make sense. 8506 CoveredArgs.set(argIndex); 8507 } 8508 else { 8509 // If argIndex exceeds the number of data arguments we 8510 // don't issue a warning because that is just a cascade of warnings (and 8511 // they may have intended '%%' anyway). We don't want to continue processing 8512 // the format string after this point, however, as we will like just get 8513 // gibberish when trying to match arguments. 8514 keepGoing = false; 8515 } 8516 8517 StringRef Specifier(csStart, csLen); 8518 8519 // If the specifier in non-printable, it could be the first byte of a UTF-8 8520 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8521 // hex value. 8522 std::string CodePointStr; 8523 if (!llvm::sys::locale::isPrint(*csStart)) { 8524 llvm::UTF32 CodePoint; 8525 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8526 const llvm::UTF8 *E = 8527 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8528 llvm::ConversionResult Result = 8529 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8530 8531 if (Result != llvm::conversionOK) { 8532 unsigned char FirstChar = *csStart; 8533 CodePoint = (llvm::UTF32)FirstChar; 8534 } 8535 8536 llvm::raw_string_ostream OS(CodePointStr); 8537 if (CodePoint < 256) 8538 OS << "\\x" << llvm::format("%02x", CodePoint); 8539 else if (CodePoint <= 0xFFFF) 8540 OS << "\\u" << llvm::format("%04x", CodePoint); 8541 else 8542 OS << "\\U" << llvm::format("%08x", CodePoint); 8543 OS.flush(); 8544 Specifier = CodePointStr; 8545 } 8546 8547 EmitFormatDiagnostic( 8548 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8549 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8550 8551 return keepGoing; 8552 } 8553 8554 void 8555 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8556 const char *startSpec, 8557 unsigned specifierLen) { 8558 EmitFormatDiagnostic( 8559 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8560 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8561 } 8562 8563 bool 8564 CheckFormatHandler::CheckNumArgs( 8565 const analyze_format_string::FormatSpecifier &FS, 8566 const analyze_format_string::ConversionSpecifier &CS, 8567 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8568 8569 if (argIndex >= NumDataArgs) { 8570 PartialDiagnostic PDiag = FS.usesPositionalArg() 8571 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8572 << (argIndex+1) << NumDataArgs) 8573 : S.PDiag(diag::warn_printf_insufficient_data_args); 8574 EmitFormatDiagnostic( 8575 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8576 getSpecifierRange(startSpecifier, specifierLen)); 8577 8578 // Since more arguments than conversion tokens are given, by extension 8579 // all arguments are covered, so mark this as so. 8580 UncoveredArg.setAllCovered(); 8581 return false; 8582 } 8583 return true; 8584 } 8585 8586 template<typename Range> 8587 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8588 SourceLocation Loc, 8589 bool IsStringLocation, 8590 Range StringRange, 8591 ArrayRef<FixItHint> FixIt) { 8592 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8593 Loc, IsStringLocation, StringRange, FixIt); 8594 } 8595 8596 /// If the format string is not within the function call, emit a note 8597 /// so that the function call and string are in diagnostic messages. 8598 /// 8599 /// \param InFunctionCall if true, the format string is within the function 8600 /// call and only one diagnostic message will be produced. Otherwise, an 8601 /// extra note will be emitted pointing to location of the format string. 8602 /// 8603 /// \param ArgumentExpr the expression that is passed as the format string 8604 /// argument in the function call. Used for getting locations when two 8605 /// diagnostics are emitted. 8606 /// 8607 /// \param PDiag the callee should already have provided any strings for the 8608 /// diagnostic message. This function only adds locations and fixits 8609 /// to diagnostics. 8610 /// 8611 /// \param Loc primary location for diagnostic. If two diagnostics are 8612 /// required, one will be at Loc and a new SourceLocation will be created for 8613 /// the other one. 8614 /// 8615 /// \param IsStringLocation if true, Loc points to the format string should be 8616 /// used for the note. Otherwise, Loc points to the argument list and will 8617 /// be used with PDiag. 8618 /// 8619 /// \param StringRange some or all of the string to highlight. This is 8620 /// templated so it can accept either a CharSourceRange or a SourceRange. 8621 /// 8622 /// \param FixIt optional fix it hint for the format string. 8623 template <typename Range> 8624 void CheckFormatHandler::EmitFormatDiagnostic( 8625 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8626 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8627 Range StringRange, ArrayRef<FixItHint> FixIt) { 8628 if (InFunctionCall) { 8629 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8630 D << StringRange; 8631 D << FixIt; 8632 } else { 8633 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8634 << ArgumentExpr->getSourceRange(); 8635 8636 const Sema::SemaDiagnosticBuilder &Note = 8637 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8638 diag::note_format_string_defined); 8639 8640 Note << StringRange; 8641 Note << FixIt; 8642 } 8643 } 8644 8645 //===--- CHECK: Printf format string checking ------------------------------===// 8646 8647 namespace { 8648 8649 class CheckPrintfHandler : public CheckFormatHandler { 8650 public: 8651 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8652 const Expr *origFormatExpr, 8653 const Sema::FormatStringType type, unsigned firstDataArg, 8654 unsigned numDataArgs, bool isObjC, const char *beg, 8655 bool hasVAListArg, ArrayRef<const Expr *> Args, 8656 unsigned formatIdx, bool inFunctionCall, 8657 Sema::VariadicCallType CallType, 8658 llvm::SmallBitVector &CheckedVarArgs, 8659 UncoveredArgHandler &UncoveredArg) 8660 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8661 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8662 inFunctionCall, CallType, CheckedVarArgs, 8663 UncoveredArg) {} 8664 8665 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8666 8667 /// Returns true if '%@' specifiers are allowed in the format string. 8668 bool allowsObjCArg() const { 8669 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8670 FSType == Sema::FST_OSTrace; 8671 } 8672 8673 bool HandleInvalidPrintfConversionSpecifier( 8674 const analyze_printf::PrintfSpecifier &FS, 8675 const char *startSpecifier, 8676 unsigned specifierLen) override; 8677 8678 void handleInvalidMaskType(StringRef MaskType) override; 8679 8680 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8681 const char *startSpecifier, 8682 unsigned specifierLen) override; 8683 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8684 const char *StartSpecifier, 8685 unsigned SpecifierLen, 8686 const Expr *E); 8687 8688 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8689 const char *startSpecifier, unsigned specifierLen); 8690 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8691 const analyze_printf::OptionalAmount &Amt, 8692 unsigned type, 8693 const char *startSpecifier, unsigned specifierLen); 8694 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8695 const analyze_printf::OptionalFlag &flag, 8696 const char *startSpecifier, unsigned specifierLen); 8697 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8698 const analyze_printf::OptionalFlag &ignoredFlag, 8699 const analyze_printf::OptionalFlag &flag, 8700 const char *startSpecifier, unsigned specifierLen); 8701 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8702 const Expr *E); 8703 8704 void HandleEmptyObjCModifierFlag(const char *startFlag, 8705 unsigned flagLen) override; 8706 8707 void HandleInvalidObjCModifierFlag(const char *startFlag, 8708 unsigned flagLen) override; 8709 8710 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8711 const char *flagsEnd, 8712 const char *conversionPosition) 8713 override; 8714 }; 8715 8716 } // namespace 8717 8718 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8719 const analyze_printf::PrintfSpecifier &FS, 8720 const char *startSpecifier, 8721 unsigned specifierLen) { 8722 const analyze_printf::PrintfConversionSpecifier &CS = 8723 FS.getConversionSpecifier(); 8724 8725 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8726 getLocationOfByte(CS.getStart()), 8727 startSpecifier, specifierLen, 8728 CS.getStart(), CS.getLength()); 8729 } 8730 8731 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8732 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8733 } 8734 8735 bool CheckPrintfHandler::HandleAmount( 8736 const analyze_format_string::OptionalAmount &Amt, 8737 unsigned k, const char *startSpecifier, 8738 unsigned specifierLen) { 8739 if (Amt.hasDataArgument()) { 8740 if (!HasVAListArg) { 8741 unsigned argIndex = Amt.getArgIndex(); 8742 if (argIndex >= NumDataArgs) { 8743 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8744 << k, 8745 getLocationOfByte(Amt.getStart()), 8746 /*IsStringLocation*/true, 8747 getSpecifierRange(startSpecifier, specifierLen)); 8748 // Don't do any more checking. We will just emit 8749 // spurious errors. 8750 return false; 8751 } 8752 8753 // Type check the data argument. It should be an 'int'. 8754 // Although not in conformance with C99, we also allow the argument to be 8755 // an 'unsigned int' as that is a reasonably safe case. GCC also 8756 // doesn't emit a warning for that case. 8757 CoveredArgs.set(argIndex); 8758 const Expr *Arg = getDataArg(argIndex); 8759 if (!Arg) 8760 return false; 8761 8762 QualType T = Arg->getType(); 8763 8764 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8765 assert(AT.isValid()); 8766 8767 if (!AT.matchesType(S.Context, T)) { 8768 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8769 << k << AT.getRepresentativeTypeName(S.Context) 8770 << T << Arg->getSourceRange(), 8771 getLocationOfByte(Amt.getStart()), 8772 /*IsStringLocation*/true, 8773 getSpecifierRange(startSpecifier, specifierLen)); 8774 // Don't do any more checking. We will just emit 8775 // spurious errors. 8776 return false; 8777 } 8778 } 8779 } 8780 return true; 8781 } 8782 8783 void CheckPrintfHandler::HandleInvalidAmount( 8784 const analyze_printf::PrintfSpecifier &FS, 8785 const analyze_printf::OptionalAmount &Amt, 8786 unsigned type, 8787 const char *startSpecifier, 8788 unsigned specifierLen) { 8789 const analyze_printf::PrintfConversionSpecifier &CS = 8790 FS.getConversionSpecifier(); 8791 8792 FixItHint fixit = 8793 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8794 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8795 Amt.getConstantLength())) 8796 : FixItHint(); 8797 8798 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8799 << type << CS.toString(), 8800 getLocationOfByte(Amt.getStart()), 8801 /*IsStringLocation*/true, 8802 getSpecifierRange(startSpecifier, specifierLen), 8803 fixit); 8804 } 8805 8806 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8807 const analyze_printf::OptionalFlag &flag, 8808 const char *startSpecifier, 8809 unsigned specifierLen) { 8810 // Warn about pointless flag with a fixit removal. 8811 const analyze_printf::PrintfConversionSpecifier &CS = 8812 FS.getConversionSpecifier(); 8813 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8814 << flag.toString() << CS.toString(), 8815 getLocationOfByte(flag.getPosition()), 8816 /*IsStringLocation*/true, 8817 getSpecifierRange(startSpecifier, specifierLen), 8818 FixItHint::CreateRemoval( 8819 getSpecifierRange(flag.getPosition(), 1))); 8820 } 8821 8822 void CheckPrintfHandler::HandleIgnoredFlag( 8823 const analyze_printf::PrintfSpecifier &FS, 8824 const analyze_printf::OptionalFlag &ignoredFlag, 8825 const analyze_printf::OptionalFlag &flag, 8826 const char *startSpecifier, 8827 unsigned specifierLen) { 8828 // Warn about ignored flag with a fixit removal. 8829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8830 << ignoredFlag.toString() << flag.toString(), 8831 getLocationOfByte(ignoredFlag.getPosition()), 8832 /*IsStringLocation*/true, 8833 getSpecifierRange(startSpecifier, specifierLen), 8834 FixItHint::CreateRemoval( 8835 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8836 } 8837 8838 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8839 unsigned flagLen) { 8840 // Warn about an empty flag. 8841 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8842 getLocationOfByte(startFlag), 8843 /*IsStringLocation*/true, 8844 getSpecifierRange(startFlag, flagLen)); 8845 } 8846 8847 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8848 unsigned flagLen) { 8849 // Warn about an invalid flag. 8850 auto Range = getSpecifierRange(startFlag, flagLen); 8851 StringRef flag(startFlag, flagLen); 8852 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8853 getLocationOfByte(startFlag), 8854 /*IsStringLocation*/true, 8855 Range, FixItHint::CreateRemoval(Range)); 8856 } 8857 8858 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8859 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8860 // Warn about using '[...]' without a '@' conversion. 8861 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8862 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8863 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8864 getLocationOfByte(conversionPosition), 8865 /*IsStringLocation*/true, 8866 Range, FixItHint::CreateRemoval(Range)); 8867 } 8868 8869 // Determines if the specified is a C++ class or struct containing 8870 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8871 // "c_str()"). 8872 template<typename MemberKind> 8873 static llvm::SmallPtrSet<MemberKind*, 1> 8874 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8875 const RecordType *RT = Ty->getAs<RecordType>(); 8876 llvm::SmallPtrSet<MemberKind*, 1> Results; 8877 8878 if (!RT) 8879 return Results; 8880 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8881 if (!RD || !RD->getDefinition()) 8882 return Results; 8883 8884 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8885 Sema::LookupMemberName); 8886 R.suppressDiagnostics(); 8887 8888 // We just need to include all members of the right kind turned up by the 8889 // filter, at this point. 8890 if (S.LookupQualifiedName(R, RT->getDecl())) 8891 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8892 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8893 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8894 Results.insert(FK); 8895 } 8896 return Results; 8897 } 8898 8899 /// Check if we could call '.c_str()' on an object. 8900 /// 8901 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8902 /// allow the call, or if it would be ambiguous). 8903 bool Sema::hasCStrMethod(const Expr *E) { 8904 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8905 8906 MethodSet Results = 8907 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8908 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8909 MI != ME; ++MI) 8910 if ((*MI)->getMinRequiredArguments() == 0) 8911 return true; 8912 return false; 8913 } 8914 8915 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8916 // better diagnostic if so. AT is assumed to be valid. 8917 // Returns true when a c_str() conversion method is found. 8918 bool CheckPrintfHandler::checkForCStrMembers( 8919 const analyze_printf::ArgType &AT, const Expr *E) { 8920 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8921 8922 MethodSet Results = 8923 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8924 8925 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8926 MI != ME; ++MI) { 8927 const CXXMethodDecl *Method = *MI; 8928 if (Method->getMinRequiredArguments() == 0 && 8929 AT.matchesType(S.Context, Method->getReturnType())) { 8930 // FIXME: Suggest parens if the expression needs them. 8931 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8932 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8933 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8934 return true; 8935 } 8936 } 8937 8938 return false; 8939 } 8940 8941 bool 8942 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8943 &FS, 8944 const char *startSpecifier, 8945 unsigned specifierLen) { 8946 using namespace analyze_format_string; 8947 using namespace analyze_printf; 8948 8949 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8950 8951 if (FS.consumesDataArgument()) { 8952 if (atFirstArg) { 8953 atFirstArg = false; 8954 usesPositionalArgs = FS.usesPositionalArg(); 8955 } 8956 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8957 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8958 startSpecifier, specifierLen); 8959 return false; 8960 } 8961 } 8962 8963 // First check if the field width, precision, and conversion specifier 8964 // have matching data arguments. 8965 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8966 startSpecifier, specifierLen)) { 8967 return false; 8968 } 8969 8970 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8971 startSpecifier, specifierLen)) { 8972 return false; 8973 } 8974 8975 if (!CS.consumesDataArgument()) { 8976 // FIXME: Technically specifying a precision or field width here 8977 // makes no sense. Worth issuing a warning at some point. 8978 return true; 8979 } 8980 8981 // Consume the argument. 8982 unsigned argIndex = FS.getArgIndex(); 8983 if (argIndex < NumDataArgs) { 8984 // The check to see if the argIndex is valid will come later. 8985 // We set the bit here because we may exit early from this 8986 // function if we encounter some other error. 8987 CoveredArgs.set(argIndex); 8988 } 8989 8990 // FreeBSD kernel extensions. 8991 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8992 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8993 // We need at least two arguments. 8994 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8995 return false; 8996 8997 // Claim the second argument. 8998 CoveredArgs.set(argIndex + 1); 8999 9000 // Type check the first argument (int for %b, pointer for %D) 9001 const Expr *Ex = getDataArg(argIndex); 9002 const analyze_printf::ArgType &AT = 9003 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9004 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9005 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9006 EmitFormatDiagnostic( 9007 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9008 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9009 << false << Ex->getSourceRange(), 9010 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9011 getSpecifierRange(startSpecifier, specifierLen)); 9012 9013 // Type check the second argument (char * for both %b and %D) 9014 Ex = getDataArg(argIndex + 1); 9015 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9016 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9017 EmitFormatDiagnostic( 9018 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9019 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9020 << false << Ex->getSourceRange(), 9021 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9022 getSpecifierRange(startSpecifier, specifierLen)); 9023 9024 return true; 9025 } 9026 9027 // Check for using an Objective-C specific conversion specifier 9028 // in a non-ObjC literal. 9029 if (!allowsObjCArg() && CS.isObjCArg()) { 9030 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9031 specifierLen); 9032 } 9033 9034 // %P can only be used with os_log. 9035 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9036 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9037 specifierLen); 9038 } 9039 9040 // %n is not allowed with os_log. 9041 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9042 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9043 getLocationOfByte(CS.getStart()), 9044 /*IsStringLocation*/ false, 9045 getSpecifierRange(startSpecifier, specifierLen)); 9046 9047 return true; 9048 } 9049 9050 // Only scalars are allowed for os_trace. 9051 if (FSType == Sema::FST_OSTrace && 9052 (CS.getKind() == ConversionSpecifier::PArg || 9053 CS.getKind() == ConversionSpecifier::sArg || 9054 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9055 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9056 specifierLen); 9057 } 9058 9059 // Check for use of public/private annotation outside of os_log(). 9060 if (FSType != Sema::FST_OSLog) { 9061 if (FS.isPublic().isSet()) { 9062 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9063 << "public", 9064 getLocationOfByte(FS.isPublic().getPosition()), 9065 /*IsStringLocation*/ false, 9066 getSpecifierRange(startSpecifier, specifierLen)); 9067 } 9068 if (FS.isPrivate().isSet()) { 9069 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9070 << "private", 9071 getLocationOfByte(FS.isPrivate().getPosition()), 9072 /*IsStringLocation*/ false, 9073 getSpecifierRange(startSpecifier, specifierLen)); 9074 } 9075 } 9076 9077 // Check for invalid use of field width 9078 if (!FS.hasValidFieldWidth()) { 9079 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9080 startSpecifier, specifierLen); 9081 } 9082 9083 // Check for invalid use of precision 9084 if (!FS.hasValidPrecision()) { 9085 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9086 startSpecifier, specifierLen); 9087 } 9088 9089 // Precision is mandatory for %P specifier. 9090 if (CS.getKind() == ConversionSpecifier::PArg && 9091 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9092 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9093 getLocationOfByte(startSpecifier), 9094 /*IsStringLocation*/ false, 9095 getSpecifierRange(startSpecifier, specifierLen)); 9096 } 9097 9098 // Check each flag does not conflict with any other component. 9099 if (!FS.hasValidThousandsGroupingPrefix()) 9100 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9101 if (!FS.hasValidLeadingZeros()) 9102 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9103 if (!FS.hasValidPlusPrefix()) 9104 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9105 if (!FS.hasValidSpacePrefix()) 9106 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9107 if (!FS.hasValidAlternativeForm()) 9108 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9109 if (!FS.hasValidLeftJustified()) 9110 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9111 9112 // Check that flags are not ignored by another flag 9113 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9114 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9115 startSpecifier, specifierLen); 9116 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9117 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9118 startSpecifier, specifierLen); 9119 9120 // Check the length modifier is valid with the given conversion specifier. 9121 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9122 S.getLangOpts())) 9123 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9124 diag::warn_format_nonsensical_length); 9125 else if (!FS.hasStandardLengthModifier()) 9126 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9127 else if (!FS.hasStandardLengthConversionCombination()) 9128 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9129 diag::warn_format_non_standard_conversion_spec); 9130 9131 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9132 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9133 9134 // The remaining checks depend on the data arguments. 9135 if (HasVAListArg) 9136 return true; 9137 9138 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9139 return false; 9140 9141 const Expr *Arg = getDataArg(argIndex); 9142 if (!Arg) 9143 return true; 9144 9145 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9146 } 9147 9148 static bool requiresParensToAddCast(const Expr *E) { 9149 // FIXME: We should have a general way to reason about operator 9150 // precedence and whether parens are actually needed here. 9151 // Take care of a few common cases where they aren't. 9152 const Expr *Inside = E->IgnoreImpCasts(); 9153 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9154 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9155 9156 switch (Inside->getStmtClass()) { 9157 case Stmt::ArraySubscriptExprClass: 9158 case Stmt::CallExprClass: 9159 case Stmt::CharacterLiteralClass: 9160 case Stmt::CXXBoolLiteralExprClass: 9161 case Stmt::DeclRefExprClass: 9162 case Stmt::FloatingLiteralClass: 9163 case Stmt::IntegerLiteralClass: 9164 case Stmt::MemberExprClass: 9165 case Stmt::ObjCArrayLiteralClass: 9166 case Stmt::ObjCBoolLiteralExprClass: 9167 case Stmt::ObjCBoxedExprClass: 9168 case Stmt::ObjCDictionaryLiteralClass: 9169 case Stmt::ObjCEncodeExprClass: 9170 case Stmt::ObjCIvarRefExprClass: 9171 case Stmt::ObjCMessageExprClass: 9172 case Stmt::ObjCPropertyRefExprClass: 9173 case Stmt::ObjCStringLiteralClass: 9174 case Stmt::ObjCSubscriptRefExprClass: 9175 case Stmt::ParenExprClass: 9176 case Stmt::StringLiteralClass: 9177 case Stmt::UnaryOperatorClass: 9178 return false; 9179 default: 9180 return true; 9181 } 9182 } 9183 9184 static std::pair<QualType, StringRef> 9185 shouldNotPrintDirectly(const ASTContext &Context, 9186 QualType IntendedTy, 9187 const Expr *E) { 9188 // Use a 'while' to peel off layers of typedefs. 9189 QualType TyTy = IntendedTy; 9190 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9191 StringRef Name = UserTy->getDecl()->getName(); 9192 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9193 .Case("CFIndex", Context.getNSIntegerType()) 9194 .Case("NSInteger", Context.getNSIntegerType()) 9195 .Case("NSUInteger", Context.getNSUIntegerType()) 9196 .Case("SInt32", Context.IntTy) 9197 .Case("UInt32", Context.UnsignedIntTy) 9198 .Default(QualType()); 9199 9200 if (!CastTy.isNull()) 9201 return std::make_pair(CastTy, Name); 9202 9203 TyTy = UserTy->desugar(); 9204 } 9205 9206 // Strip parens if necessary. 9207 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9208 return shouldNotPrintDirectly(Context, 9209 PE->getSubExpr()->getType(), 9210 PE->getSubExpr()); 9211 9212 // If this is a conditional expression, then its result type is constructed 9213 // via usual arithmetic conversions and thus there might be no necessary 9214 // typedef sugar there. Recurse to operands to check for NSInteger & 9215 // Co. usage condition. 9216 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9217 QualType TrueTy, FalseTy; 9218 StringRef TrueName, FalseName; 9219 9220 std::tie(TrueTy, TrueName) = 9221 shouldNotPrintDirectly(Context, 9222 CO->getTrueExpr()->getType(), 9223 CO->getTrueExpr()); 9224 std::tie(FalseTy, FalseName) = 9225 shouldNotPrintDirectly(Context, 9226 CO->getFalseExpr()->getType(), 9227 CO->getFalseExpr()); 9228 9229 if (TrueTy == FalseTy) 9230 return std::make_pair(TrueTy, TrueName); 9231 else if (TrueTy.isNull()) 9232 return std::make_pair(FalseTy, FalseName); 9233 else if (FalseTy.isNull()) 9234 return std::make_pair(TrueTy, TrueName); 9235 } 9236 9237 return std::make_pair(QualType(), StringRef()); 9238 } 9239 9240 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9241 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9242 /// type do not count. 9243 static bool 9244 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9245 QualType From = ICE->getSubExpr()->getType(); 9246 QualType To = ICE->getType(); 9247 // It's an integer promotion if the destination type is the promoted 9248 // source type. 9249 if (ICE->getCastKind() == CK_IntegralCast && 9250 From->isPromotableIntegerType() && 9251 S.Context.getPromotedIntegerType(From) == To) 9252 return true; 9253 // Look through vector types, since we do default argument promotion for 9254 // those in OpenCL. 9255 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9256 From = VecTy->getElementType(); 9257 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9258 To = VecTy->getElementType(); 9259 // It's a floating promotion if the source type is a lower rank. 9260 return ICE->getCastKind() == CK_FloatingCast && 9261 S.Context.getFloatingTypeOrder(From, To) < 0; 9262 } 9263 9264 bool 9265 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9266 const char *StartSpecifier, 9267 unsigned SpecifierLen, 9268 const Expr *E) { 9269 using namespace analyze_format_string; 9270 using namespace analyze_printf; 9271 9272 // Now type check the data expression that matches the 9273 // format specifier. 9274 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9275 if (!AT.isValid()) 9276 return true; 9277 9278 QualType ExprTy = E->getType(); 9279 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9280 ExprTy = TET->getUnderlyingExpr()->getType(); 9281 } 9282 9283 // Diagnose attempts to print a boolean value as a character. Unlike other 9284 // -Wformat diagnostics, this is fine from a type perspective, but it still 9285 // doesn't make sense. 9286 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9287 E->isKnownToHaveBooleanValue()) { 9288 const CharSourceRange &CSR = 9289 getSpecifierRange(StartSpecifier, SpecifierLen); 9290 SmallString<4> FSString; 9291 llvm::raw_svector_ostream os(FSString); 9292 FS.toString(os); 9293 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9294 << FSString, 9295 E->getExprLoc(), false, CSR); 9296 return true; 9297 } 9298 9299 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9300 if (Match == analyze_printf::ArgType::Match) 9301 return true; 9302 9303 // Look through argument promotions for our error message's reported type. 9304 // This includes the integral and floating promotions, but excludes array 9305 // and function pointer decay (seeing that an argument intended to be a 9306 // string has type 'char [6]' is probably more confusing than 'char *') and 9307 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9308 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9309 if (isArithmeticArgumentPromotion(S, ICE)) { 9310 E = ICE->getSubExpr(); 9311 ExprTy = E->getType(); 9312 9313 // Check if we didn't match because of an implicit cast from a 'char' 9314 // or 'short' to an 'int'. This is done because printf is a varargs 9315 // function. 9316 if (ICE->getType() == S.Context.IntTy || 9317 ICE->getType() == S.Context.UnsignedIntTy) { 9318 // All further checking is done on the subexpression 9319 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9320 AT.matchesType(S.Context, ExprTy); 9321 if (ImplicitMatch == analyze_printf::ArgType::Match) 9322 return true; 9323 if (ImplicitMatch == ArgType::NoMatchPedantic || 9324 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9325 Match = ImplicitMatch; 9326 } 9327 } 9328 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9329 // Special case for 'a', which has type 'int' in C. 9330 // Note, however, that we do /not/ want to treat multibyte constants like 9331 // 'MooV' as characters! This form is deprecated but still exists. In 9332 // addition, don't treat expressions as of type 'char' if one byte length 9333 // modifier is provided. 9334 if (ExprTy == S.Context.IntTy && 9335 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9336 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9337 ExprTy = S.Context.CharTy; 9338 } 9339 9340 // Look through enums to their underlying type. 9341 bool IsEnum = false; 9342 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9343 ExprTy = EnumTy->getDecl()->getIntegerType(); 9344 IsEnum = true; 9345 } 9346 9347 // %C in an Objective-C context prints a unichar, not a wchar_t. 9348 // If the argument is an integer of some kind, believe the %C and suggest 9349 // a cast instead of changing the conversion specifier. 9350 QualType IntendedTy = ExprTy; 9351 if (isObjCContext() && 9352 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9353 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9354 !ExprTy->isCharType()) { 9355 // 'unichar' is defined as a typedef of unsigned short, but we should 9356 // prefer using the typedef if it is visible. 9357 IntendedTy = S.Context.UnsignedShortTy; 9358 9359 // While we are here, check if the value is an IntegerLiteral that happens 9360 // to be within the valid range. 9361 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9362 const llvm::APInt &V = IL->getValue(); 9363 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9364 return true; 9365 } 9366 9367 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9368 Sema::LookupOrdinaryName); 9369 if (S.LookupName(Result, S.getCurScope())) { 9370 NamedDecl *ND = Result.getFoundDecl(); 9371 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9372 if (TD->getUnderlyingType() == IntendedTy) 9373 IntendedTy = S.Context.getTypedefType(TD); 9374 } 9375 } 9376 } 9377 9378 // Special-case some of Darwin's platform-independence types by suggesting 9379 // casts to primitive types that are known to be large enough. 9380 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9381 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9382 QualType CastTy; 9383 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9384 if (!CastTy.isNull()) { 9385 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9386 // (long in ASTContext). Only complain to pedants. 9387 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9388 (AT.isSizeT() || AT.isPtrdiffT()) && 9389 AT.matchesType(S.Context, CastTy)) 9390 Match = ArgType::NoMatchPedantic; 9391 IntendedTy = CastTy; 9392 ShouldNotPrintDirectly = true; 9393 } 9394 } 9395 9396 // We may be able to offer a FixItHint if it is a supported type. 9397 PrintfSpecifier fixedFS = FS; 9398 bool Success = 9399 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9400 9401 if (Success) { 9402 // Get the fix string from the fixed format specifier 9403 SmallString<16> buf; 9404 llvm::raw_svector_ostream os(buf); 9405 fixedFS.toString(os); 9406 9407 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9408 9409 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9410 unsigned Diag; 9411 switch (Match) { 9412 case ArgType::Match: llvm_unreachable("expected non-matching"); 9413 case ArgType::NoMatchPedantic: 9414 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9415 break; 9416 case ArgType::NoMatchTypeConfusion: 9417 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9418 break; 9419 case ArgType::NoMatch: 9420 Diag = diag::warn_format_conversion_argument_type_mismatch; 9421 break; 9422 } 9423 9424 // In this case, the specifier is wrong and should be changed to match 9425 // the argument. 9426 EmitFormatDiagnostic(S.PDiag(Diag) 9427 << AT.getRepresentativeTypeName(S.Context) 9428 << IntendedTy << IsEnum << E->getSourceRange(), 9429 E->getBeginLoc(), 9430 /*IsStringLocation*/ false, SpecRange, 9431 FixItHint::CreateReplacement(SpecRange, os.str())); 9432 } else { 9433 // The canonical type for formatting this value is different from the 9434 // actual type of the expression. (This occurs, for example, with Darwin's 9435 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9436 // should be printed as 'long' for 64-bit compatibility.) 9437 // Rather than emitting a normal format/argument mismatch, we want to 9438 // add a cast to the recommended type (and correct the format string 9439 // if necessary). 9440 SmallString<16> CastBuf; 9441 llvm::raw_svector_ostream CastFix(CastBuf); 9442 CastFix << "("; 9443 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9444 CastFix << ")"; 9445 9446 SmallVector<FixItHint,4> Hints; 9447 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9448 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9449 9450 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9451 // If there's already a cast present, just replace it. 9452 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9453 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9454 9455 } else if (!requiresParensToAddCast(E)) { 9456 // If the expression has high enough precedence, 9457 // just write the C-style cast. 9458 Hints.push_back( 9459 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9460 } else { 9461 // Otherwise, add parens around the expression as well as the cast. 9462 CastFix << "("; 9463 Hints.push_back( 9464 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9465 9466 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9467 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9468 } 9469 9470 if (ShouldNotPrintDirectly) { 9471 // The expression has a type that should not be printed directly. 9472 // We extract the name from the typedef because we don't want to show 9473 // the underlying type in the diagnostic. 9474 StringRef Name; 9475 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9476 Name = TypedefTy->getDecl()->getName(); 9477 else 9478 Name = CastTyName; 9479 unsigned Diag = Match == ArgType::NoMatchPedantic 9480 ? diag::warn_format_argument_needs_cast_pedantic 9481 : diag::warn_format_argument_needs_cast; 9482 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9483 << E->getSourceRange(), 9484 E->getBeginLoc(), /*IsStringLocation=*/false, 9485 SpecRange, Hints); 9486 } else { 9487 // In this case, the expression could be printed using a different 9488 // specifier, but we've decided that the specifier is probably correct 9489 // and we should cast instead. Just use the normal warning message. 9490 EmitFormatDiagnostic( 9491 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9492 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9493 << E->getSourceRange(), 9494 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9495 } 9496 } 9497 } else { 9498 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9499 SpecifierLen); 9500 // Since the warning for passing non-POD types to variadic functions 9501 // was deferred until now, we emit a warning for non-POD 9502 // arguments here. 9503 switch (S.isValidVarArgType(ExprTy)) { 9504 case Sema::VAK_Valid: 9505 case Sema::VAK_ValidInCXX11: { 9506 unsigned Diag; 9507 switch (Match) { 9508 case ArgType::Match: llvm_unreachable("expected non-matching"); 9509 case ArgType::NoMatchPedantic: 9510 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9511 break; 9512 case ArgType::NoMatchTypeConfusion: 9513 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9514 break; 9515 case ArgType::NoMatch: 9516 Diag = diag::warn_format_conversion_argument_type_mismatch; 9517 break; 9518 } 9519 9520 EmitFormatDiagnostic( 9521 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9522 << IsEnum << CSR << E->getSourceRange(), 9523 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9524 break; 9525 } 9526 case Sema::VAK_Undefined: 9527 case Sema::VAK_MSVCUndefined: 9528 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9529 << S.getLangOpts().CPlusPlus11 << ExprTy 9530 << CallType 9531 << AT.getRepresentativeTypeName(S.Context) << CSR 9532 << E->getSourceRange(), 9533 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9534 checkForCStrMembers(AT, E); 9535 break; 9536 9537 case Sema::VAK_Invalid: 9538 if (ExprTy->isObjCObjectType()) 9539 EmitFormatDiagnostic( 9540 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9541 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9542 << AT.getRepresentativeTypeName(S.Context) << CSR 9543 << E->getSourceRange(), 9544 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9545 else 9546 // FIXME: If this is an initializer list, suggest removing the braces 9547 // or inserting a cast to the target type. 9548 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9549 << isa<InitListExpr>(E) << ExprTy << CallType 9550 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9551 break; 9552 } 9553 9554 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9555 "format string specifier index out of range"); 9556 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9557 } 9558 9559 return true; 9560 } 9561 9562 //===--- CHECK: Scanf format string checking ------------------------------===// 9563 9564 namespace { 9565 9566 class CheckScanfHandler : public CheckFormatHandler { 9567 public: 9568 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9569 const Expr *origFormatExpr, Sema::FormatStringType type, 9570 unsigned firstDataArg, unsigned numDataArgs, 9571 const char *beg, bool hasVAListArg, 9572 ArrayRef<const Expr *> Args, unsigned formatIdx, 9573 bool inFunctionCall, Sema::VariadicCallType CallType, 9574 llvm::SmallBitVector &CheckedVarArgs, 9575 UncoveredArgHandler &UncoveredArg) 9576 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9577 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9578 inFunctionCall, CallType, CheckedVarArgs, 9579 UncoveredArg) {} 9580 9581 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9582 const char *startSpecifier, 9583 unsigned specifierLen) override; 9584 9585 bool HandleInvalidScanfConversionSpecifier( 9586 const analyze_scanf::ScanfSpecifier &FS, 9587 const char *startSpecifier, 9588 unsigned specifierLen) override; 9589 9590 void HandleIncompleteScanList(const char *start, const char *end) override; 9591 }; 9592 9593 } // namespace 9594 9595 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9596 const char *end) { 9597 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9598 getLocationOfByte(end), /*IsStringLocation*/true, 9599 getSpecifierRange(start, end - start)); 9600 } 9601 9602 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9603 const analyze_scanf::ScanfSpecifier &FS, 9604 const char *startSpecifier, 9605 unsigned specifierLen) { 9606 const analyze_scanf::ScanfConversionSpecifier &CS = 9607 FS.getConversionSpecifier(); 9608 9609 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9610 getLocationOfByte(CS.getStart()), 9611 startSpecifier, specifierLen, 9612 CS.getStart(), CS.getLength()); 9613 } 9614 9615 bool CheckScanfHandler::HandleScanfSpecifier( 9616 const analyze_scanf::ScanfSpecifier &FS, 9617 const char *startSpecifier, 9618 unsigned specifierLen) { 9619 using namespace analyze_scanf; 9620 using namespace analyze_format_string; 9621 9622 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9623 9624 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9625 // be used to decide if we are using positional arguments consistently. 9626 if (FS.consumesDataArgument()) { 9627 if (atFirstArg) { 9628 atFirstArg = false; 9629 usesPositionalArgs = FS.usesPositionalArg(); 9630 } 9631 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9632 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9633 startSpecifier, specifierLen); 9634 return false; 9635 } 9636 } 9637 9638 // Check if the field with is non-zero. 9639 const OptionalAmount &Amt = FS.getFieldWidth(); 9640 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9641 if (Amt.getConstantAmount() == 0) { 9642 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9643 Amt.getConstantLength()); 9644 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9645 getLocationOfByte(Amt.getStart()), 9646 /*IsStringLocation*/true, R, 9647 FixItHint::CreateRemoval(R)); 9648 } 9649 } 9650 9651 if (!FS.consumesDataArgument()) { 9652 // FIXME: Technically specifying a precision or field width here 9653 // makes no sense. Worth issuing a warning at some point. 9654 return true; 9655 } 9656 9657 // Consume the argument. 9658 unsigned argIndex = FS.getArgIndex(); 9659 if (argIndex < NumDataArgs) { 9660 // The check to see if the argIndex is valid will come later. 9661 // We set the bit here because we may exit early from this 9662 // function if we encounter some other error. 9663 CoveredArgs.set(argIndex); 9664 } 9665 9666 // Check the length modifier is valid with the given conversion specifier. 9667 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9668 S.getLangOpts())) 9669 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9670 diag::warn_format_nonsensical_length); 9671 else if (!FS.hasStandardLengthModifier()) 9672 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9673 else if (!FS.hasStandardLengthConversionCombination()) 9674 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9675 diag::warn_format_non_standard_conversion_spec); 9676 9677 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9678 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9679 9680 // The remaining checks depend on the data arguments. 9681 if (HasVAListArg) 9682 return true; 9683 9684 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9685 return false; 9686 9687 // Check that the argument type matches the format specifier. 9688 const Expr *Ex = getDataArg(argIndex); 9689 if (!Ex) 9690 return true; 9691 9692 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9693 9694 if (!AT.isValid()) { 9695 return true; 9696 } 9697 9698 analyze_format_string::ArgType::MatchKind Match = 9699 AT.matchesType(S.Context, Ex->getType()); 9700 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9701 if (Match == analyze_format_string::ArgType::Match) 9702 return true; 9703 9704 ScanfSpecifier fixedFS = FS; 9705 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9706 S.getLangOpts(), S.Context); 9707 9708 unsigned Diag = 9709 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9710 : diag::warn_format_conversion_argument_type_mismatch; 9711 9712 if (Success) { 9713 // Get the fix string from the fixed format specifier. 9714 SmallString<128> buf; 9715 llvm::raw_svector_ostream os(buf); 9716 fixedFS.toString(os); 9717 9718 EmitFormatDiagnostic( 9719 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9720 << Ex->getType() << false << Ex->getSourceRange(), 9721 Ex->getBeginLoc(), 9722 /*IsStringLocation*/ false, 9723 getSpecifierRange(startSpecifier, specifierLen), 9724 FixItHint::CreateReplacement( 9725 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9726 } else { 9727 EmitFormatDiagnostic(S.PDiag(Diag) 9728 << AT.getRepresentativeTypeName(S.Context) 9729 << Ex->getType() << false << Ex->getSourceRange(), 9730 Ex->getBeginLoc(), 9731 /*IsStringLocation*/ false, 9732 getSpecifierRange(startSpecifier, specifierLen)); 9733 } 9734 9735 return true; 9736 } 9737 9738 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9739 const Expr *OrigFormatExpr, 9740 ArrayRef<const Expr *> Args, 9741 bool HasVAListArg, unsigned format_idx, 9742 unsigned firstDataArg, 9743 Sema::FormatStringType Type, 9744 bool inFunctionCall, 9745 Sema::VariadicCallType CallType, 9746 llvm::SmallBitVector &CheckedVarArgs, 9747 UncoveredArgHandler &UncoveredArg, 9748 bool IgnoreStringsWithoutSpecifiers) { 9749 // CHECK: is the format string a wide literal? 9750 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9751 CheckFormatHandler::EmitFormatDiagnostic( 9752 S, inFunctionCall, Args[format_idx], 9753 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9754 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9755 return; 9756 } 9757 9758 // Str - The format string. NOTE: this is NOT null-terminated! 9759 StringRef StrRef = FExpr->getString(); 9760 const char *Str = StrRef.data(); 9761 // Account for cases where the string literal is truncated in a declaration. 9762 const ConstantArrayType *T = 9763 S.Context.getAsConstantArrayType(FExpr->getType()); 9764 assert(T && "String literal not of constant array type!"); 9765 size_t TypeSize = T->getSize().getZExtValue(); 9766 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9767 const unsigned numDataArgs = Args.size() - firstDataArg; 9768 9769 if (IgnoreStringsWithoutSpecifiers && 9770 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9771 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9772 return; 9773 9774 // Emit a warning if the string literal is truncated and does not contain an 9775 // embedded null character. 9776 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 9777 CheckFormatHandler::EmitFormatDiagnostic( 9778 S, inFunctionCall, Args[format_idx], 9779 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9780 FExpr->getBeginLoc(), 9781 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9782 return; 9783 } 9784 9785 // CHECK: empty format string? 9786 if (StrLen == 0 && numDataArgs > 0) { 9787 CheckFormatHandler::EmitFormatDiagnostic( 9788 S, inFunctionCall, Args[format_idx], 9789 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9790 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9791 return; 9792 } 9793 9794 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9795 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9796 Type == Sema::FST_OSTrace) { 9797 CheckPrintfHandler H( 9798 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9799 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9800 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9801 CheckedVarArgs, UncoveredArg); 9802 9803 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9804 S.getLangOpts(), 9805 S.Context.getTargetInfo(), 9806 Type == Sema::FST_FreeBSDKPrintf)) 9807 H.DoneProcessing(); 9808 } else if (Type == Sema::FST_Scanf) { 9809 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9810 numDataArgs, Str, HasVAListArg, Args, format_idx, 9811 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9812 9813 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9814 S.getLangOpts(), 9815 S.Context.getTargetInfo())) 9816 H.DoneProcessing(); 9817 } // TODO: handle other formats 9818 } 9819 9820 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9821 // Str - The format string. NOTE: this is NOT null-terminated! 9822 StringRef StrRef = FExpr->getString(); 9823 const char *Str = StrRef.data(); 9824 // Account for cases where the string literal is truncated in a declaration. 9825 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9826 assert(T && "String literal not of constant array type!"); 9827 size_t TypeSize = T->getSize().getZExtValue(); 9828 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9829 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9830 getLangOpts(), 9831 Context.getTargetInfo()); 9832 } 9833 9834 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9835 9836 // Returns the related absolute value function that is larger, of 0 if one 9837 // does not exist. 9838 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9839 switch (AbsFunction) { 9840 default: 9841 return 0; 9842 9843 case Builtin::BI__builtin_abs: 9844 return Builtin::BI__builtin_labs; 9845 case Builtin::BI__builtin_labs: 9846 return Builtin::BI__builtin_llabs; 9847 case Builtin::BI__builtin_llabs: 9848 return 0; 9849 9850 case Builtin::BI__builtin_fabsf: 9851 return Builtin::BI__builtin_fabs; 9852 case Builtin::BI__builtin_fabs: 9853 return Builtin::BI__builtin_fabsl; 9854 case Builtin::BI__builtin_fabsl: 9855 return 0; 9856 9857 case Builtin::BI__builtin_cabsf: 9858 return Builtin::BI__builtin_cabs; 9859 case Builtin::BI__builtin_cabs: 9860 return Builtin::BI__builtin_cabsl; 9861 case Builtin::BI__builtin_cabsl: 9862 return 0; 9863 9864 case Builtin::BIabs: 9865 return Builtin::BIlabs; 9866 case Builtin::BIlabs: 9867 return Builtin::BIllabs; 9868 case Builtin::BIllabs: 9869 return 0; 9870 9871 case Builtin::BIfabsf: 9872 return Builtin::BIfabs; 9873 case Builtin::BIfabs: 9874 return Builtin::BIfabsl; 9875 case Builtin::BIfabsl: 9876 return 0; 9877 9878 case Builtin::BIcabsf: 9879 return Builtin::BIcabs; 9880 case Builtin::BIcabs: 9881 return Builtin::BIcabsl; 9882 case Builtin::BIcabsl: 9883 return 0; 9884 } 9885 } 9886 9887 // Returns the argument type of the absolute value function. 9888 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9889 unsigned AbsType) { 9890 if (AbsType == 0) 9891 return QualType(); 9892 9893 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9894 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9895 if (Error != ASTContext::GE_None) 9896 return QualType(); 9897 9898 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9899 if (!FT) 9900 return QualType(); 9901 9902 if (FT->getNumParams() != 1) 9903 return QualType(); 9904 9905 return FT->getParamType(0); 9906 } 9907 9908 // Returns the best absolute value function, or zero, based on type and 9909 // current absolute value function. 9910 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9911 unsigned AbsFunctionKind) { 9912 unsigned BestKind = 0; 9913 uint64_t ArgSize = Context.getTypeSize(ArgType); 9914 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9915 Kind = getLargerAbsoluteValueFunction(Kind)) { 9916 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9917 if (Context.getTypeSize(ParamType) >= ArgSize) { 9918 if (BestKind == 0) 9919 BestKind = Kind; 9920 else if (Context.hasSameType(ParamType, ArgType)) { 9921 BestKind = Kind; 9922 break; 9923 } 9924 } 9925 } 9926 return BestKind; 9927 } 9928 9929 enum AbsoluteValueKind { 9930 AVK_Integer, 9931 AVK_Floating, 9932 AVK_Complex 9933 }; 9934 9935 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9936 if (T->isIntegralOrEnumerationType()) 9937 return AVK_Integer; 9938 if (T->isRealFloatingType()) 9939 return AVK_Floating; 9940 if (T->isAnyComplexType()) 9941 return AVK_Complex; 9942 9943 llvm_unreachable("Type not integer, floating, or complex"); 9944 } 9945 9946 // Changes the absolute value function to a different type. Preserves whether 9947 // the function is a builtin. 9948 static unsigned changeAbsFunction(unsigned AbsKind, 9949 AbsoluteValueKind ValueKind) { 9950 switch (ValueKind) { 9951 case AVK_Integer: 9952 switch (AbsKind) { 9953 default: 9954 return 0; 9955 case Builtin::BI__builtin_fabsf: 9956 case Builtin::BI__builtin_fabs: 9957 case Builtin::BI__builtin_fabsl: 9958 case Builtin::BI__builtin_cabsf: 9959 case Builtin::BI__builtin_cabs: 9960 case Builtin::BI__builtin_cabsl: 9961 return Builtin::BI__builtin_abs; 9962 case Builtin::BIfabsf: 9963 case Builtin::BIfabs: 9964 case Builtin::BIfabsl: 9965 case Builtin::BIcabsf: 9966 case Builtin::BIcabs: 9967 case Builtin::BIcabsl: 9968 return Builtin::BIabs; 9969 } 9970 case AVK_Floating: 9971 switch (AbsKind) { 9972 default: 9973 return 0; 9974 case Builtin::BI__builtin_abs: 9975 case Builtin::BI__builtin_labs: 9976 case Builtin::BI__builtin_llabs: 9977 case Builtin::BI__builtin_cabsf: 9978 case Builtin::BI__builtin_cabs: 9979 case Builtin::BI__builtin_cabsl: 9980 return Builtin::BI__builtin_fabsf; 9981 case Builtin::BIabs: 9982 case Builtin::BIlabs: 9983 case Builtin::BIllabs: 9984 case Builtin::BIcabsf: 9985 case Builtin::BIcabs: 9986 case Builtin::BIcabsl: 9987 return Builtin::BIfabsf; 9988 } 9989 case AVK_Complex: 9990 switch (AbsKind) { 9991 default: 9992 return 0; 9993 case Builtin::BI__builtin_abs: 9994 case Builtin::BI__builtin_labs: 9995 case Builtin::BI__builtin_llabs: 9996 case Builtin::BI__builtin_fabsf: 9997 case Builtin::BI__builtin_fabs: 9998 case Builtin::BI__builtin_fabsl: 9999 return Builtin::BI__builtin_cabsf; 10000 case Builtin::BIabs: 10001 case Builtin::BIlabs: 10002 case Builtin::BIllabs: 10003 case Builtin::BIfabsf: 10004 case Builtin::BIfabs: 10005 case Builtin::BIfabsl: 10006 return Builtin::BIcabsf; 10007 } 10008 } 10009 llvm_unreachable("Unable to convert function"); 10010 } 10011 10012 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10013 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10014 if (!FnInfo) 10015 return 0; 10016 10017 switch (FDecl->getBuiltinID()) { 10018 default: 10019 return 0; 10020 case Builtin::BI__builtin_abs: 10021 case Builtin::BI__builtin_fabs: 10022 case Builtin::BI__builtin_fabsf: 10023 case Builtin::BI__builtin_fabsl: 10024 case Builtin::BI__builtin_labs: 10025 case Builtin::BI__builtin_llabs: 10026 case Builtin::BI__builtin_cabs: 10027 case Builtin::BI__builtin_cabsf: 10028 case Builtin::BI__builtin_cabsl: 10029 case Builtin::BIabs: 10030 case Builtin::BIlabs: 10031 case Builtin::BIllabs: 10032 case Builtin::BIfabs: 10033 case Builtin::BIfabsf: 10034 case Builtin::BIfabsl: 10035 case Builtin::BIcabs: 10036 case Builtin::BIcabsf: 10037 case Builtin::BIcabsl: 10038 return FDecl->getBuiltinID(); 10039 } 10040 llvm_unreachable("Unknown Builtin type"); 10041 } 10042 10043 // If the replacement is valid, emit a note with replacement function. 10044 // Additionally, suggest including the proper header if not already included. 10045 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10046 unsigned AbsKind, QualType ArgType) { 10047 bool EmitHeaderHint = true; 10048 const char *HeaderName = nullptr; 10049 const char *FunctionName = nullptr; 10050 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10051 FunctionName = "std::abs"; 10052 if (ArgType->isIntegralOrEnumerationType()) { 10053 HeaderName = "cstdlib"; 10054 } else if (ArgType->isRealFloatingType()) { 10055 HeaderName = "cmath"; 10056 } else { 10057 llvm_unreachable("Invalid Type"); 10058 } 10059 10060 // Lookup all std::abs 10061 if (NamespaceDecl *Std = S.getStdNamespace()) { 10062 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10063 R.suppressDiagnostics(); 10064 S.LookupQualifiedName(R, Std); 10065 10066 for (const auto *I : R) { 10067 const FunctionDecl *FDecl = nullptr; 10068 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10069 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10070 } else { 10071 FDecl = dyn_cast<FunctionDecl>(I); 10072 } 10073 if (!FDecl) 10074 continue; 10075 10076 // Found std::abs(), check that they are the right ones. 10077 if (FDecl->getNumParams() != 1) 10078 continue; 10079 10080 // Check that the parameter type can handle the argument. 10081 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10082 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10083 S.Context.getTypeSize(ArgType) <= 10084 S.Context.getTypeSize(ParamType)) { 10085 // Found a function, don't need the header hint. 10086 EmitHeaderHint = false; 10087 break; 10088 } 10089 } 10090 } 10091 } else { 10092 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10093 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10094 10095 if (HeaderName) { 10096 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10097 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10098 R.suppressDiagnostics(); 10099 S.LookupName(R, S.getCurScope()); 10100 10101 if (R.isSingleResult()) { 10102 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10103 if (FD && FD->getBuiltinID() == AbsKind) { 10104 EmitHeaderHint = false; 10105 } else { 10106 return; 10107 } 10108 } else if (!R.empty()) { 10109 return; 10110 } 10111 } 10112 } 10113 10114 S.Diag(Loc, diag::note_replace_abs_function) 10115 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10116 10117 if (!HeaderName) 10118 return; 10119 10120 if (!EmitHeaderHint) 10121 return; 10122 10123 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10124 << FunctionName; 10125 } 10126 10127 template <std::size_t StrLen> 10128 static bool IsStdFunction(const FunctionDecl *FDecl, 10129 const char (&Str)[StrLen]) { 10130 if (!FDecl) 10131 return false; 10132 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10133 return false; 10134 if (!FDecl->isInStdNamespace()) 10135 return false; 10136 10137 return true; 10138 } 10139 10140 // Warn when using the wrong abs() function. 10141 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10142 const FunctionDecl *FDecl) { 10143 if (Call->getNumArgs() != 1) 10144 return; 10145 10146 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10147 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10148 if (AbsKind == 0 && !IsStdAbs) 10149 return; 10150 10151 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10152 QualType ParamType = Call->getArg(0)->getType(); 10153 10154 // Unsigned types cannot be negative. Suggest removing the absolute value 10155 // function call. 10156 if (ArgType->isUnsignedIntegerType()) { 10157 const char *FunctionName = 10158 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10159 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10160 Diag(Call->getExprLoc(), diag::note_remove_abs) 10161 << FunctionName 10162 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10163 return; 10164 } 10165 10166 // Taking the absolute value of a pointer is very suspicious, they probably 10167 // wanted to index into an array, dereference a pointer, call a function, etc. 10168 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10169 unsigned DiagType = 0; 10170 if (ArgType->isFunctionType()) 10171 DiagType = 1; 10172 else if (ArgType->isArrayType()) 10173 DiagType = 2; 10174 10175 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10176 return; 10177 } 10178 10179 // std::abs has overloads which prevent most of the absolute value problems 10180 // from occurring. 10181 if (IsStdAbs) 10182 return; 10183 10184 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10185 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10186 10187 // The argument and parameter are the same kind. Check if they are the right 10188 // size. 10189 if (ArgValueKind == ParamValueKind) { 10190 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10191 return; 10192 10193 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10194 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10195 << FDecl << ArgType << ParamType; 10196 10197 if (NewAbsKind == 0) 10198 return; 10199 10200 emitReplacement(*this, Call->getExprLoc(), 10201 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10202 return; 10203 } 10204 10205 // ArgValueKind != ParamValueKind 10206 // The wrong type of absolute value function was used. Attempt to find the 10207 // proper one. 10208 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10209 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10210 if (NewAbsKind == 0) 10211 return; 10212 10213 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10214 << FDecl << ParamValueKind << ArgValueKind; 10215 10216 emitReplacement(*this, Call->getExprLoc(), 10217 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10218 } 10219 10220 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10221 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10222 const FunctionDecl *FDecl) { 10223 if (!Call || !FDecl) return; 10224 10225 // Ignore template specializations and macros. 10226 if (inTemplateInstantiation()) return; 10227 if (Call->getExprLoc().isMacroID()) return; 10228 10229 // Only care about the one template argument, two function parameter std::max 10230 if (Call->getNumArgs() != 2) return; 10231 if (!IsStdFunction(FDecl, "max")) return; 10232 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10233 if (!ArgList) return; 10234 if (ArgList->size() != 1) return; 10235 10236 // Check that template type argument is unsigned integer. 10237 const auto& TA = ArgList->get(0); 10238 if (TA.getKind() != TemplateArgument::Type) return; 10239 QualType ArgType = TA.getAsType(); 10240 if (!ArgType->isUnsignedIntegerType()) return; 10241 10242 // See if either argument is a literal zero. 10243 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10244 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10245 if (!MTE) return false; 10246 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10247 if (!Num) return false; 10248 if (Num->getValue() != 0) return false; 10249 return true; 10250 }; 10251 10252 const Expr *FirstArg = Call->getArg(0); 10253 const Expr *SecondArg = Call->getArg(1); 10254 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10255 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10256 10257 // Only warn when exactly one argument is zero. 10258 if (IsFirstArgZero == IsSecondArgZero) return; 10259 10260 SourceRange FirstRange = FirstArg->getSourceRange(); 10261 SourceRange SecondRange = SecondArg->getSourceRange(); 10262 10263 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10264 10265 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10266 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10267 10268 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10269 SourceRange RemovalRange; 10270 if (IsFirstArgZero) { 10271 RemovalRange = SourceRange(FirstRange.getBegin(), 10272 SecondRange.getBegin().getLocWithOffset(-1)); 10273 } else { 10274 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10275 SecondRange.getEnd()); 10276 } 10277 10278 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10279 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10280 << FixItHint::CreateRemoval(RemovalRange); 10281 } 10282 10283 //===--- CHECK: Standard memory functions ---------------------------------===// 10284 10285 /// Takes the expression passed to the size_t parameter of functions 10286 /// such as memcmp, strncat, etc and warns if it's a comparison. 10287 /// 10288 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10289 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10290 IdentifierInfo *FnName, 10291 SourceLocation FnLoc, 10292 SourceLocation RParenLoc) { 10293 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10294 if (!Size) 10295 return false; 10296 10297 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10298 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10299 return false; 10300 10301 SourceRange SizeRange = Size->getSourceRange(); 10302 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10303 << SizeRange << FnName; 10304 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10305 << FnName 10306 << FixItHint::CreateInsertion( 10307 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10308 << FixItHint::CreateRemoval(RParenLoc); 10309 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10310 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10311 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10312 ")"); 10313 10314 return true; 10315 } 10316 10317 /// Determine whether the given type is or contains a dynamic class type 10318 /// (e.g., whether it has a vtable). 10319 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10320 bool &IsContained) { 10321 // Look through array types while ignoring qualifiers. 10322 const Type *Ty = T->getBaseElementTypeUnsafe(); 10323 IsContained = false; 10324 10325 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10326 RD = RD ? RD->getDefinition() : nullptr; 10327 if (!RD || RD->isInvalidDecl()) 10328 return nullptr; 10329 10330 if (RD->isDynamicClass()) 10331 return RD; 10332 10333 // Check all the fields. If any bases were dynamic, the class is dynamic. 10334 // It's impossible for a class to transitively contain itself by value, so 10335 // infinite recursion is impossible. 10336 for (auto *FD : RD->fields()) { 10337 bool SubContained; 10338 if (const CXXRecordDecl *ContainedRD = 10339 getContainedDynamicClass(FD->getType(), SubContained)) { 10340 IsContained = true; 10341 return ContainedRD; 10342 } 10343 } 10344 10345 return nullptr; 10346 } 10347 10348 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10349 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10350 if (Unary->getKind() == UETT_SizeOf) 10351 return Unary; 10352 return nullptr; 10353 } 10354 10355 /// If E is a sizeof expression, returns its argument expression, 10356 /// otherwise returns NULL. 10357 static const Expr *getSizeOfExprArg(const Expr *E) { 10358 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10359 if (!SizeOf->isArgumentType()) 10360 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10361 return nullptr; 10362 } 10363 10364 /// If E is a sizeof expression, returns its argument type. 10365 static QualType getSizeOfArgType(const Expr *E) { 10366 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10367 return SizeOf->getTypeOfArgument(); 10368 return QualType(); 10369 } 10370 10371 namespace { 10372 10373 struct SearchNonTrivialToInitializeField 10374 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10375 using Super = 10376 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10377 10378 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10379 10380 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10381 SourceLocation SL) { 10382 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10383 asDerived().visitArray(PDIK, AT, SL); 10384 return; 10385 } 10386 10387 Super::visitWithKind(PDIK, FT, SL); 10388 } 10389 10390 void visitARCStrong(QualType FT, SourceLocation SL) { 10391 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10392 } 10393 void visitARCWeak(QualType FT, SourceLocation SL) { 10394 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10395 } 10396 void visitStruct(QualType FT, SourceLocation SL) { 10397 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10398 visit(FD->getType(), FD->getLocation()); 10399 } 10400 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10401 const ArrayType *AT, SourceLocation SL) { 10402 visit(getContext().getBaseElementType(AT), SL); 10403 } 10404 void visitTrivial(QualType FT, SourceLocation SL) {} 10405 10406 static void diag(QualType RT, const Expr *E, Sema &S) { 10407 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10408 } 10409 10410 ASTContext &getContext() { return S.getASTContext(); } 10411 10412 const Expr *E; 10413 Sema &S; 10414 }; 10415 10416 struct SearchNonTrivialToCopyField 10417 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10418 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10419 10420 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10421 10422 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10423 SourceLocation SL) { 10424 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10425 asDerived().visitArray(PCK, AT, SL); 10426 return; 10427 } 10428 10429 Super::visitWithKind(PCK, FT, SL); 10430 } 10431 10432 void visitARCStrong(QualType FT, SourceLocation SL) { 10433 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10434 } 10435 void visitARCWeak(QualType FT, SourceLocation SL) { 10436 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10437 } 10438 void visitStruct(QualType FT, SourceLocation SL) { 10439 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10440 visit(FD->getType(), FD->getLocation()); 10441 } 10442 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10443 SourceLocation SL) { 10444 visit(getContext().getBaseElementType(AT), SL); 10445 } 10446 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10447 SourceLocation SL) {} 10448 void visitTrivial(QualType FT, SourceLocation SL) {} 10449 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10450 10451 static void diag(QualType RT, const Expr *E, Sema &S) { 10452 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10453 } 10454 10455 ASTContext &getContext() { return S.getASTContext(); } 10456 10457 const Expr *E; 10458 Sema &S; 10459 }; 10460 10461 } 10462 10463 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10464 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10465 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10466 10467 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10468 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10469 return false; 10470 10471 return doesExprLikelyComputeSize(BO->getLHS()) || 10472 doesExprLikelyComputeSize(BO->getRHS()); 10473 } 10474 10475 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10476 } 10477 10478 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10479 /// 10480 /// \code 10481 /// #define MACRO 0 10482 /// foo(MACRO); 10483 /// foo(0); 10484 /// \endcode 10485 /// 10486 /// This should return true for the first call to foo, but not for the second 10487 /// (regardless of whether foo is a macro or function). 10488 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10489 SourceLocation CallLoc, 10490 SourceLocation ArgLoc) { 10491 if (!CallLoc.isMacroID()) 10492 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10493 10494 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10495 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10496 } 10497 10498 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10499 /// last two arguments transposed. 10500 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10501 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10502 return; 10503 10504 const Expr *SizeArg = 10505 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10506 10507 auto isLiteralZero = [](const Expr *E) { 10508 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10509 }; 10510 10511 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10512 SourceLocation CallLoc = Call->getRParenLoc(); 10513 SourceManager &SM = S.getSourceManager(); 10514 if (isLiteralZero(SizeArg) && 10515 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10516 10517 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10518 10519 // Some platforms #define bzero to __builtin_memset. See if this is the 10520 // case, and if so, emit a better diagnostic. 10521 if (BId == Builtin::BIbzero || 10522 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10523 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10524 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10525 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10526 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10527 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10528 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10529 } 10530 return; 10531 } 10532 10533 // If the second argument to a memset is a sizeof expression and the third 10534 // isn't, this is also likely an error. This should catch 10535 // 'memset(buf, sizeof(buf), 0xff)'. 10536 if (BId == Builtin::BImemset && 10537 doesExprLikelyComputeSize(Call->getArg(1)) && 10538 !doesExprLikelyComputeSize(Call->getArg(2))) { 10539 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10540 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10541 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10542 return; 10543 } 10544 } 10545 10546 /// Check for dangerous or invalid arguments to memset(). 10547 /// 10548 /// This issues warnings on known problematic, dangerous or unspecified 10549 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10550 /// function calls. 10551 /// 10552 /// \param Call The call expression to diagnose. 10553 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10554 unsigned BId, 10555 IdentifierInfo *FnName) { 10556 assert(BId != 0); 10557 10558 // It is possible to have a non-standard definition of memset. Validate 10559 // we have enough arguments, and if not, abort further checking. 10560 unsigned ExpectedNumArgs = 10561 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10562 if (Call->getNumArgs() < ExpectedNumArgs) 10563 return; 10564 10565 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10566 BId == Builtin::BIstrndup ? 1 : 2); 10567 unsigned LenArg = 10568 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10569 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10570 10571 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10572 Call->getBeginLoc(), Call->getRParenLoc())) 10573 return; 10574 10575 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10576 CheckMemaccessSize(*this, BId, Call); 10577 10578 // We have special checking when the length is a sizeof expression. 10579 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10580 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10581 llvm::FoldingSetNodeID SizeOfArgID; 10582 10583 // Although widely used, 'bzero' is not a standard function. Be more strict 10584 // with the argument types before allowing diagnostics and only allow the 10585 // form bzero(ptr, sizeof(...)). 10586 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10587 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10588 return; 10589 10590 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10591 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10592 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10593 10594 QualType DestTy = Dest->getType(); 10595 QualType PointeeTy; 10596 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10597 PointeeTy = DestPtrTy->getPointeeType(); 10598 10599 // Never warn about void type pointers. This can be used to suppress 10600 // false positives. 10601 if (PointeeTy->isVoidType()) 10602 continue; 10603 10604 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10605 // actually comparing the expressions for equality. Because computing the 10606 // expression IDs can be expensive, we only do this if the diagnostic is 10607 // enabled. 10608 if (SizeOfArg && 10609 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10610 SizeOfArg->getExprLoc())) { 10611 // We only compute IDs for expressions if the warning is enabled, and 10612 // cache the sizeof arg's ID. 10613 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10614 SizeOfArg->Profile(SizeOfArgID, Context, true); 10615 llvm::FoldingSetNodeID DestID; 10616 Dest->Profile(DestID, Context, true); 10617 if (DestID == SizeOfArgID) { 10618 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10619 // over sizeof(src) as well. 10620 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10621 StringRef ReadableName = FnName->getName(); 10622 10623 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10624 if (UnaryOp->getOpcode() == UO_AddrOf) 10625 ActionIdx = 1; // If its an address-of operator, just remove it. 10626 if (!PointeeTy->isIncompleteType() && 10627 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10628 ActionIdx = 2; // If the pointee's size is sizeof(char), 10629 // suggest an explicit length. 10630 10631 // If the function is defined as a builtin macro, do not show macro 10632 // expansion. 10633 SourceLocation SL = SizeOfArg->getExprLoc(); 10634 SourceRange DSR = Dest->getSourceRange(); 10635 SourceRange SSR = SizeOfArg->getSourceRange(); 10636 SourceManager &SM = getSourceManager(); 10637 10638 if (SM.isMacroArgExpansion(SL)) { 10639 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10640 SL = SM.getSpellingLoc(SL); 10641 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10642 SM.getSpellingLoc(DSR.getEnd())); 10643 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10644 SM.getSpellingLoc(SSR.getEnd())); 10645 } 10646 10647 DiagRuntimeBehavior(SL, SizeOfArg, 10648 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10649 << ReadableName 10650 << PointeeTy 10651 << DestTy 10652 << DSR 10653 << SSR); 10654 DiagRuntimeBehavior(SL, SizeOfArg, 10655 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10656 << ActionIdx 10657 << SSR); 10658 10659 break; 10660 } 10661 } 10662 10663 // Also check for cases where the sizeof argument is the exact same 10664 // type as the memory argument, and where it points to a user-defined 10665 // record type. 10666 if (SizeOfArgTy != QualType()) { 10667 if (PointeeTy->isRecordType() && 10668 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10669 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10670 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10671 << FnName << SizeOfArgTy << ArgIdx 10672 << PointeeTy << Dest->getSourceRange() 10673 << LenExpr->getSourceRange()); 10674 break; 10675 } 10676 } 10677 } else if (DestTy->isArrayType()) { 10678 PointeeTy = DestTy; 10679 } 10680 10681 if (PointeeTy == QualType()) 10682 continue; 10683 10684 // Always complain about dynamic classes. 10685 bool IsContained; 10686 if (const CXXRecordDecl *ContainedRD = 10687 getContainedDynamicClass(PointeeTy, IsContained)) { 10688 10689 unsigned OperationType = 0; 10690 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10691 // "overwritten" if we're warning about the destination for any call 10692 // but memcmp; otherwise a verb appropriate to the call. 10693 if (ArgIdx != 0 || IsCmp) { 10694 if (BId == Builtin::BImemcpy) 10695 OperationType = 1; 10696 else if(BId == Builtin::BImemmove) 10697 OperationType = 2; 10698 else if (IsCmp) 10699 OperationType = 3; 10700 } 10701 10702 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10703 PDiag(diag::warn_dyn_class_memaccess) 10704 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10705 << IsContained << ContainedRD << OperationType 10706 << Call->getCallee()->getSourceRange()); 10707 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10708 BId != Builtin::BImemset) 10709 DiagRuntimeBehavior( 10710 Dest->getExprLoc(), Dest, 10711 PDiag(diag::warn_arc_object_memaccess) 10712 << ArgIdx << FnName << PointeeTy 10713 << Call->getCallee()->getSourceRange()); 10714 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10715 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10716 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10717 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10718 PDiag(diag::warn_cstruct_memaccess) 10719 << ArgIdx << FnName << PointeeTy << 0); 10720 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10721 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10722 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10723 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10724 PDiag(diag::warn_cstruct_memaccess) 10725 << ArgIdx << FnName << PointeeTy << 1); 10726 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10727 } else { 10728 continue; 10729 } 10730 } else 10731 continue; 10732 10733 DiagRuntimeBehavior( 10734 Dest->getExprLoc(), Dest, 10735 PDiag(diag::note_bad_memaccess_silence) 10736 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10737 break; 10738 } 10739 } 10740 10741 // A little helper routine: ignore addition and subtraction of integer literals. 10742 // This intentionally does not ignore all integer constant expressions because 10743 // we don't want to remove sizeof(). 10744 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10745 Ex = Ex->IgnoreParenCasts(); 10746 10747 while (true) { 10748 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10749 if (!BO || !BO->isAdditiveOp()) 10750 break; 10751 10752 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10753 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10754 10755 if (isa<IntegerLiteral>(RHS)) 10756 Ex = LHS; 10757 else if (isa<IntegerLiteral>(LHS)) 10758 Ex = RHS; 10759 else 10760 break; 10761 } 10762 10763 return Ex; 10764 } 10765 10766 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10767 ASTContext &Context) { 10768 // Only handle constant-sized or VLAs, but not flexible members. 10769 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10770 // Only issue the FIXIT for arrays of size > 1. 10771 if (CAT->getSize().getSExtValue() <= 1) 10772 return false; 10773 } else if (!Ty->isVariableArrayType()) { 10774 return false; 10775 } 10776 return true; 10777 } 10778 10779 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10780 // be the size of the source, instead of the destination. 10781 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10782 IdentifierInfo *FnName) { 10783 10784 // Don't crash if the user has the wrong number of arguments 10785 unsigned NumArgs = Call->getNumArgs(); 10786 if ((NumArgs != 3) && (NumArgs != 4)) 10787 return; 10788 10789 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10790 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10791 const Expr *CompareWithSrc = nullptr; 10792 10793 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10794 Call->getBeginLoc(), Call->getRParenLoc())) 10795 return; 10796 10797 // Look for 'strlcpy(dst, x, sizeof(x))' 10798 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10799 CompareWithSrc = Ex; 10800 else { 10801 // Look for 'strlcpy(dst, x, strlen(x))' 10802 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10803 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10804 SizeCall->getNumArgs() == 1) 10805 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10806 } 10807 } 10808 10809 if (!CompareWithSrc) 10810 return; 10811 10812 // Determine if the argument to sizeof/strlen is equal to the source 10813 // argument. In principle there's all kinds of things you could do 10814 // here, for instance creating an == expression and evaluating it with 10815 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10816 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10817 if (!SrcArgDRE) 10818 return; 10819 10820 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10821 if (!CompareWithSrcDRE || 10822 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10823 return; 10824 10825 const Expr *OriginalSizeArg = Call->getArg(2); 10826 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10827 << OriginalSizeArg->getSourceRange() << FnName; 10828 10829 // Output a FIXIT hint if the destination is an array (rather than a 10830 // pointer to an array). This could be enhanced to handle some 10831 // pointers if we know the actual size, like if DstArg is 'array+2' 10832 // we could say 'sizeof(array)-2'. 10833 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10834 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10835 return; 10836 10837 SmallString<128> sizeString; 10838 llvm::raw_svector_ostream OS(sizeString); 10839 OS << "sizeof("; 10840 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10841 OS << ")"; 10842 10843 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10844 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10845 OS.str()); 10846 } 10847 10848 /// Check if two expressions refer to the same declaration. 10849 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10850 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10851 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10852 return D1->getDecl() == D2->getDecl(); 10853 return false; 10854 } 10855 10856 static const Expr *getStrlenExprArg(const Expr *E) { 10857 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10858 const FunctionDecl *FD = CE->getDirectCallee(); 10859 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10860 return nullptr; 10861 return CE->getArg(0)->IgnoreParenCasts(); 10862 } 10863 return nullptr; 10864 } 10865 10866 // Warn on anti-patterns as the 'size' argument to strncat. 10867 // The correct size argument should look like following: 10868 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10869 void Sema::CheckStrncatArguments(const CallExpr *CE, 10870 IdentifierInfo *FnName) { 10871 // Don't crash if the user has the wrong number of arguments. 10872 if (CE->getNumArgs() < 3) 10873 return; 10874 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10875 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10876 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10877 10878 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10879 CE->getRParenLoc())) 10880 return; 10881 10882 // Identify common expressions, which are wrongly used as the size argument 10883 // to strncat and may lead to buffer overflows. 10884 unsigned PatternType = 0; 10885 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10886 // - sizeof(dst) 10887 if (referToTheSameDecl(SizeOfArg, DstArg)) 10888 PatternType = 1; 10889 // - sizeof(src) 10890 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10891 PatternType = 2; 10892 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10893 if (BE->getOpcode() == BO_Sub) { 10894 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10895 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10896 // - sizeof(dst) - strlen(dst) 10897 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10898 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10899 PatternType = 1; 10900 // - sizeof(src) - (anything) 10901 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10902 PatternType = 2; 10903 } 10904 } 10905 10906 if (PatternType == 0) 10907 return; 10908 10909 // Generate the diagnostic. 10910 SourceLocation SL = LenArg->getBeginLoc(); 10911 SourceRange SR = LenArg->getSourceRange(); 10912 SourceManager &SM = getSourceManager(); 10913 10914 // If the function is defined as a builtin macro, do not show macro expansion. 10915 if (SM.isMacroArgExpansion(SL)) { 10916 SL = SM.getSpellingLoc(SL); 10917 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10918 SM.getSpellingLoc(SR.getEnd())); 10919 } 10920 10921 // Check if the destination is an array (rather than a pointer to an array). 10922 QualType DstTy = DstArg->getType(); 10923 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10924 Context); 10925 if (!isKnownSizeArray) { 10926 if (PatternType == 1) 10927 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10928 else 10929 Diag(SL, diag::warn_strncat_src_size) << SR; 10930 return; 10931 } 10932 10933 if (PatternType == 1) 10934 Diag(SL, diag::warn_strncat_large_size) << SR; 10935 else 10936 Diag(SL, diag::warn_strncat_src_size) << SR; 10937 10938 SmallString<128> sizeString; 10939 llvm::raw_svector_ostream OS(sizeString); 10940 OS << "sizeof("; 10941 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10942 OS << ") - "; 10943 OS << "strlen("; 10944 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10945 OS << ") - 1"; 10946 10947 Diag(SL, diag::note_strncat_wrong_size) 10948 << FixItHint::CreateReplacement(SR, OS.str()); 10949 } 10950 10951 namespace { 10952 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10953 const UnaryOperator *UnaryExpr, const Decl *D) { 10954 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10955 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10956 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10957 return; 10958 } 10959 } 10960 10961 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10962 const UnaryOperator *UnaryExpr) { 10963 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10964 const Decl *D = Lvalue->getDecl(); 10965 if (isa<DeclaratorDecl>(D)) 10966 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10967 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10968 } 10969 10970 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10971 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10972 Lvalue->getMemberDecl()); 10973 } 10974 10975 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10976 const UnaryOperator *UnaryExpr) { 10977 const auto *Lambda = dyn_cast<LambdaExpr>( 10978 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10979 if (!Lambda) 10980 return; 10981 10982 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10983 << CalleeName << 2 /*object: lambda expression*/; 10984 } 10985 10986 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10987 const DeclRefExpr *Lvalue) { 10988 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10989 if (Var == nullptr) 10990 return; 10991 10992 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10993 << CalleeName << 0 /*object: */ << Var; 10994 } 10995 10996 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10997 const CastExpr *Cast) { 10998 SmallString<128> SizeString; 10999 llvm::raw_svector_ostream OS(SizeString); 11000 11001 clang::CastKind Kind = Cast->getCastKind(); 11002 if (Kind == clang::CK_BitCast && 11003 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11004 return; 11005 if (Kind == clang::CK_IntegralToPointer && 11006 !isa<IntegerLiteral>( 11007 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11008 return; 11009 11010 switch (Cast->getCastKind()) { 11011 case clang::CK_BitCast: 11012 case clang::CK_IntegralToPointer: 11013 case clang::CK_FunctionToPointerDecay: 11014 OS << '\''; 11015 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11016 OS << '\''; 11017 break; 11018 default: 11019 return; 11020 } 11021 11022 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11023 << CalleeName << 0 /*object: */ << OS.str(); 11024 } 11025 } // namespace 11026 11027 /// Alerts the user that they are attempting to free a non-malloc'd object. 11028 void Sema::CheckFreeArguments(const CallExpr *E) { 11029 const std::string CalleeName = 11030 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11031 11032 { // Prefer something that doesn't involve a cast to make things simpler. 11033 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11034 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11035 switch (UnaryExpr->getOpcode()) { 11036 case UnaryOperator::Opcode::UO_AddrOf: 11037 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11038 case UnaryOperator::Opcode::UO_Plus: 11039 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11040 default: 11041 break; 11042 } 11043 11044 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11045 if (Lvalue->getType()->isArrayType()) 11046 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11047 11048 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11049 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11050 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11051 return; 11052 } 11053 11054 if (isa<BlockExpr>(Arg)) { 11055 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11056 << CalleeName << 1 /*object: block*/; 11057 return; 11058 } 11059 } 11060 // Maybe the cast was important, check after the other cases. 11061 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11062 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11063 } 11064 11065 void 11066 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11067 SourceLocation ReturnLoc, 11068 bool isObjCMethod, 11069 const AttrVec *Attrs, 11070 const FunctionDecl *FD) { 11071 // Check if the return value is null but should not be. 11072 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11073 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11074 CheckNonNullExpr(*this, RetValExp)) 11075 Diag(ReturnLoc, diag::warn_null_ret) 11076 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11077 11078 // C++11 [basic.stc.dynamic.allocation]p4: 11079 // If an allocation function declared with a non-throwing 11080 // exception-specification fails to allocate storage, it shall return 11081 // a null pointer. Any other allocation function that fails to allocate 11082 // storage shall indicate failure only by throwing an exception [...] 11083 if (FD) { 11084 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11085 if (Op == OO_New || Op == OO_Array_New) { 11086 const FunctionProtoType *Proto 11087 = FD->getType()->castAs<FunctionProtoType>(); 11088 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11089 CheckNonNullExpr(*this, RetValExp)) 11090 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11091 << FD << getLangOpts().CPlusPlus11; 11092 } 11093 } 11094 11095 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11096 // here prevent the user from using a PPC MMA type as trailing return type. 11097 if (Context.getTargetInfo().getTriple().isPPC64()) 11098 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11099 } 11100 11101 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11102 11103 /// Check for comparisons of floating point operands using != and ==. 11104 /// Issue a warning if these are no self-comparisons, as they are not likely 11105 /// to do what the programmer intended. 11106 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11107 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11108 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11109 11110 // Special case: check for x == x (which is OK). 11111 // Do not emit warnings for such cases. 11112 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11113 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11114 if (DRL->getDecl() == DRR->getDecl()) 11115 return; 11116 11117 // Special case: check for comparisons against literals that can be exactly 11118 // represented by APFloat. In such cases, do not emit a warning. This 11119 // is a heuristic: often comparison against such literals are used to 11120 // detect if a value in a variable has not changed. This clearly can 11121 // lead to false negatives. 11122 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11123 if (FLL->isExact()) 11124 return; 11125 } else 11126 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11127 if (FLR->isExact()) 11128 return; 11129 11130 // Check for comparisons with builtin types. 11131 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11132 if (CL->getBuiltinCallee()) 11133 return; 11134 11135 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11136 if (CR->getBuiltinCallee()) 11137 return; 11138 11139 // Emit the diagnostic. 11140 Diag(Loc, diag::warn_floatingpoint_eq) 11141 << LHS->getSourceRange() << RHS->getSourceRange(); 11142 } 11143 11144 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11145 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11146 11147 namespace { 11148 11149 /// Structure recording the 'active' range of an integer-valued 11150 /// expression. 11151 struct IntRange { 11152 /// The number of bits active in the int. Note that this includes exactly one 11153 /// sign bit if !NonNegative. 11154 unsigned Width; 11155 11156 /// True if the int is known not to have negative values. If so, all leading 11157 /// bits before Width are known zero, otherwise they are known to be the 11158 /// same as the MSB within Width. 11159 bool NonNegative; 11160 11161 IntRange(unsigned Width, bool NonNegative) 11162 : Width(Width), NonNegative(NonNegative) {} 11163 11164 /// Number of bits excluding the sign bit. 11165 unsigned valueBits() const { 11166 return NonNegative ? Width : Width - 1; 11167 } 11168 11169 /// Returns the range of the bool type. 11170 static IntRange forBoolType() { 11171 return IntRange(1, true); 11172 } 11173 11174 /// Returns the range of an opaque value of the given integral type. 11175 static IntRange forValueOfType(ASTContext &C, QualType T) { 11176 return forValueOfCanonicalType(C, 11177 T->getCanonicalTypeInternal().getTypePtr()); 11178 } 11179 11180 /// Returns the range of an opaque value of a canonical integral type. 11181 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11182 assert(T->isCanonicalUnqualified()); 11183 11184 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11185 T = VT->getElementType().getTypePtr(); 11186 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11187 T = CT->getElementType().getTypePtr(); 11188 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11189 T = AT->getValueType().getTypePtr(); 11190 11191 if (!C.getLangOpts().CPlusPlus) { 11192 // For enum types in C code, use the underlying datatype. 11193 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11194 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11195 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11196 // For enum types in C++, use the known bit width of the enumerators. 11197 EnumDecl *Enum = ET->getDecl(); 11198 // In C++11, enums can have a fixed underlying type. Use this type to 11199 // compute the range. 11200 if (Enum->isFixed()) { 11201 return IntRange(C.getIntWidth(QualType(T, 0)), 11202 !ET->isSignedIntegerOrEnumerationType()); 11203 } 11204 11205 unsigned NumPositive = Enum->getNumPositiveBits(); 11206 unsigned NumNegative = Enum->getNumNegativeBits(); 11207 11208 if (NumNegative == 0) 11209 return IntRange(NumPositive, true/*NonNegative*/); 11210 else 11211 return IntRange(std::max(NumPositive + 1, NumNegative), 11212 false/*NonNegative*/); 11213 } 11214 11215 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11216 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11217 11218 const BuiltinType *BT = cast<BuiltinType>(T); 11219 assert(BT->isInteger()); 11220 11221 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11222 } 11223 11224 /// Returns the "target" range of a canonical integral type, i.e. 11225 /// the range of values expressible in the type. 11226 /// 11227 /// This matches forValueOfCanonicalType except that enums have the 11228 /// full range of their type, not the range of their enumerators. 11229 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11230 assert(T->isCanonicalUnqualified()); 11231 11232 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11233 T = VT->getElementType().getTypePtr(); 11234 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11235 T = CT->getElementType().getTypePtr(); 11236 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11237 T = AT->getValueType().getTypePtr(); 11238 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11239 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11240 11241 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11242 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11243 11244 const BuiltinType *BT = cast<BuiltinType>(T); 11245 assert(BT->isInteger()); 11246 11247 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11248 } 11249 11250 /// Returns the supremum of two ranges: i.e. their conservative merge. 11251 static IntRange join(IntRange L, IntRange R) { 11252 bool Unsigned = L.NonNegative && R.NonNegative; 11253 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11254 L.NonNegative && R.NonNegative); 11255 } 11256 11257 /// Return the range of a bitwise-AND of the two ranges. 11258 static IntRange bit_and(IntRange L, IntRange R) { 11259 unsigned Bits = std::max(L.Width, R.Width); 11260 bool NonNegative = false; 11261 if (L.NonNegative) { 11262 Bits = std::min(Bits, L.Width); 11263 NonNegative = true; 11264 } 11265 if (R.NonNegative) { 11266 Bits = std::min(Bits, R.Width); 11267 NonNegative = true; 11268 } 11269 return IntRange(Bits, NonNegative); 11270 } 11271 11272 /// Return the range of a sum of the two ranges. 11273 static IntRange sum(IntRange L, IntRange R) { 11274 bool Unsigned = L.NonNegative && R.NonNegative; 11275 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11276 Unsigned); 11277 } 11278 11279 /// Return the range of a difference of the two ranges. 11280 static IntRange difference(IntRange L, IntRange R) { 11281 // We need a 1-bit-wider range if: 11282 // 1) LHS can be negative: least value can be reduced. 11283 // 2) RHS can be negative: greatest value can be increased. 11284 bool CanWiden = !L.NonNegative || !R.NonNegative; 11285 bool Unsigned = L.NonNegative && R.Width == 0; 11286 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11287 !Unsigned, 11288 Unsigned); 11289 } 11290 11291 /// Return the range of a product of the two ranges. 11292 static IntRange product(IntRange L, IntRange R) { 11293 // If both LHS and RHS can be negative, we can form 11294 // -2^L * -2^R = 2^(L + R) 11295 // which requires L + R + 1 value bits to represent. 11296 bool CanWiden = !L.NonNegative && !R.NonNegative; 11297 bool Unsigned = L.NonNegative && R.NonNegative; 11298 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11299 Unsigned); 11300 } 11301 11302 /// Return the range of a remainder operation between the two ranges. 11303 static IntRange rem(IntRange L, IntRange R) { 11304 // The result of a remainder can't be larger than the result of 11305 // either side. The sign of the result is the sign of the LHS. 11306 bool Unsigned = L.NonNegative; 11307 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11308 Unsigned); 11309 } 11310 }; 11311 11312 } // namespace 11313 11314 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11315 unsigned MaxWidth) { 11316 if (value.isSigned() && value.isNegative()) 11317 return IntRange(value.getMinSignedBits(), false); 11318 11319 if (value.getBitWidth() > MaxWidth) 11320 value = value.trunc(MaxWidth); 11321 11322 // isNonNegative() just checks the sign bit without considering 11323 // signedness. 11324 return IntRange(value.getActiveBits(), true); 11325 } 11326 11327 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11328 unsigned MaxWidth) { 11329 if (result.isInt()) 11330 return GetValueRange(C, result.getInt(), MaxWidth); 11331 11332 if (result.isVector()) { 11333 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11334 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11335 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11336 R = IntRange::join(R, El); 11337 } 11338 return R; 11339 } 11340 11341 if (result.isComplexInt()) { 11342 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11343 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11344 return IntRange::join(R, I); 11345 } 11346 11347 // This can happen with lossless casts to intptr_t of "based" lvalues. 11348 // Assume it might use arbitrary bits. 11349 // FIXME: The only reason we need to pass the type in here is to get 11350 // the sign right on this one case. It would be nice if APValue 11351 // preserved this. 11352 assert(result.isLValue() || result.isAddrLabelDiff()); 11353 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11354 } 11355 11356 static QualType GetExprType(const Expr *E) { 11357 QualType Ty = E->getType(); 11358 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11359 Ty = AtomicRHS->getValueType(); 11360 return Ty; 11361 } 11362 11363 /// Pseudo-evaluate the given integer expression, estimating the 11364 /// range of values it might take. 11365 /// 11366 /// \param MaxWidth The width to which the value will be truncated. 11367 /// \param Approximate If \c true, return a likely range for the result: in 11368 /// particular, assume that arithmetic on narrower types doesn't leave 11369 /// those types. If \c false, return a range including all possible 11370 /// result values. 11371 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11372 bool InConstantContext, bool Approximate) { 11373 E = E->IgnoreParens(); 11374 11375 // Try a full evaluation first. 11376 Expr::EvalResult result; 11377 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11378 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11379 11380 // I think we only want to look through implicit casts here; if the 11381 // user has an explicit widening cast, we should treat the value as 11382 // being of the new, wider type. 11383 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11384 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11385 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11386 Approximate); 11387 11388 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11389 11390 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11391 CE->getCastKind() == CK_BooleanToSignedIntegral; 11392 11393 // Assume that non-integer casts can span the full range of the type. 11394 if (!isIntegerCast) 11395 return OutputTypeRange; 11396 11397 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11398 std::min(MaxWidth, OutputTypeRange.Width), 11399 InConstantContext, Approximate); 11400 11401 // Bail out if the subexpr's range is as wide as the cast type. 11402 if (SubRange.Width >= OutputTypeRange.Width) 11403 return OutputTypeRange; 11404 11405 // Otherwise, we take the smaller width, and we're non-negative if 11406 // either the output type or the subexpr is. 11407 return IntRange(SubRange.Width, 11408 SubRange.NonNegative || OutputTypeRange.NonNegative); 11409 } 11410 11411 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11412 // If we can fold the condition, just take that operand. 11413 bool CondResult; 11414 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11415 return GetExprRange(C, 11416 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11417 MaxWidth, InConstantContext, Approximate); 11418 11419 // Otherwise, conservatively merge. 11420 // GetExprRange requires an integer expression, but a throw expression 11421 // results in a void type. 11422 Expr *E = CO->getTrueExpr(); 11423 IntRange L = E->getType()->isVoidType() 11424 ? IntRange{0, true} 11425 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11426 E = CO->getFalseExpr(); 11427 IntRange R = E->getType()->isVoidType() 11428 ? IntRange{0, true} 11429 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11430 return IntRange::join(L, R); 11431 } 11432 11433 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11434 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11435 11436 switch (BO->getOpcode()) { 11437 case BO_Cmp: 11438 llvm_unreachable("builtin <=> should have class type"); 11439 11440 // Boolean-valued operations are single-bit and positive. 11441 case BO_LAnd: 11442 case BO_LOr: 11443 case BO_LT: 11444 case BO_GT: 11445 case BO_LE: 11446 case BO_GE: 11447 case BO_EQ: 11448 case BO_NE: 11449 return IntRange::forBoolType(); 11450 11451 // The type of the assignments is the type of the LHS, so the RHS 11452 // is not necessarily the same type. 11453 case BO_MulAssign: 11454 case BO_DivAssign: 11455 case BO_RemAssign: 11456 case BO_AddAssign: 11457 case BO_SubAssign: 11458 case BO_XorAssign: 11459 case BO_OrAssign: 11460 // TODO: bitfields? 11461 return IntRange::forValueOfType(C, GetExprType(E)); 11462 11463 // Simple assignments just pass through the RHS, which will have 11464 // been coerced to the LHS type. 11465 case BO_Assign: 11466 // TODO: bitfields? 11467 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11468 Approximate); 11469 11470 // Operations with opaque sources are black-listed. 11471 case BO_PtrMemD: 11472 case BO_PtrMemI: 11473 return IntRange::forValueOfType(C, GetExprType(E)); 11474 11475 // Bitwise-and uses the *infinum* of the two source ranges. 11476 case BO_And: 11477 case BO_AndAssign: 11478 Combine = IntRange::bit_and; 11479 break; 11480 11481 // Left shift gets black-listed based on a judgement call. 11482 case BO_Shl: 11483 // ...except that we want to treat '1 << (blah)' as logically 11484 // positive. It's an important idiom. 11485 if (IntegerLiteral *I 11486 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11487 if (I->getValue() == 1) { 11488 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11489 return IntRange(R.Width, /*NonNegative*/ true); 11490 } 11491 } 11492 LLVM_FALLTHROUGH; 11493 11494 case BO_ShlAssign: 11495 return IntRange::forValueOfType(C, GetExprType(E)); 11496 11497 // Right shift by a constant can narrow its left argument. 11498 case BO_Shr: 11499 case BO_ShrAssign: { 11500 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11501 Approximate); 11502 11503 // If the shift amount is a positive constant, drop the width by 11504 // that much. 11505 if (Optional<llvm::APSInt> shift = 11506 BO->getRHS()->getIntegerConstantExpr(C)) { 11507 if (shift->isNonNegative()) { 11508 unsigned zext = shift->getZExtValue(); 11509 if (zext >= L.Width) 11510 L.Width = (L.NonNegative ? 0 : 1); 11511 else 11512 L.Width -= zext; 11513 } 11514 } 11515 11516 return L; 11517 } 11518 11519 // Comma acts as its right operand. 11520 case BO_Comma: 11521 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11522 Approximate); 11523 11524 case BO_Add: 11525 if (!Approximate) 11526 Combine = IntRange::sum; 11527 break; 11528 11529 case BO_Sub: 11530 if (BO->getLHS()->getType()->isPointerType()) 11531 return IntRange::forValueOfType(C, GetExprType(E)); 11532 if (!Approximate) 11533 Combine = IntRange::difference; 11534 break; 11535 11536 case BO_Mul: 11537 if (!Approximate) 11538 Combine = IntRange::product; 11539 break; 11540 11541 // The width of a division result is mostly determined by the size 11542 // of the LHS. 11543 case BO_Div: { 11544 // Don't 'pre-truncate' the operands. 11545 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11546 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11547 Approximate); 11548 11549 // If the divisor is constant, use that. 11550 if (Optional<llvm::APSInt> divisor = 11551 BO->getRHS()->getIntegerConstantExpr(C)) { 11552 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11553 if (log2 >= L.Width) 11554 L.Width = (L.NonNegative ? 0 : 1); 11555 else 11556 L.Width = std::min(L.Width - log2, MaxWidth); 11557 return L; 11558 } 11559 11560 // Otherwise, just use the LHS's width. 11561 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11562 // could be -1. 11563 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11564 Approximate); 11565 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11566 } 11567 11568 case BO_Rem: 11569 Combine = IntRange::rem; 11570 break; 11571 11572 // The default behavior is okay for these. 11573 case BO_Xor: 11574 case BO_Or: 11575 break; 11576 } 11577 11578 // Combine the two ranges, but limit the result to the type in which we 11579 // performed the computation. 11580 QualType T = GetExprType(E); 11581 unsigned opWidth = C.getIntWidth(T); 11582 IntRange L = 11583 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11584 IntRange R = 11585 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11586 IntRange C = Combine(L, R); 11587 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11588 C.Width = std::min(C.Width, MaxWidth); 11589 return C; 11590 } 11591 11592 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11593 switch (UO->getOpcode()) { 11594 // Boolean-valued operations are white-listed. 11595 case UO_LNot: 11596 return IntRange::forBoolType(); 11597 11598 // Operations with opaque sources are black-listed. 11599 case UO_Deref: 11600 case UO_AddrOf: // should be impossible 11601 return IntRange::forValueOfType(C, GetExprType(E)); 11602 11603 default: 11604 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11605 Approximate); 11606 } 11607 } 11608 11609 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11610 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11611 Approximate); 11612 11613 if (const auto *BitField = E->getSourceBitField()) 11614 return IntRange(BitField->getBitWidthValue(C), 11615 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11616 11617 return IntRange::forValueOfType(C, GetExprType(E)); 11618 } 11619 11620 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11621 bool InConstantContext, bool Approximate) { 11622 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11623 Approximate); 11624 } 11625 11626 /// Checks whether the given value, which currently has the given 11627 /// source semantics, has the same value when coerced through the 11628 /// target semantics. 11629 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11630 const llvm::fltSemantics &Src, 11631 const llvm::fltSemantics &Tgt) { 11632 llvm::APFloat truncated = value; 11633 11634 bool ignored; 11635 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11636 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11637 11638 return truncated.bitwiseIsEqual(value); 11639 } 11640 11641 /// Checks whether the given value, which currently has the given 11642 /// source semantics, has the same value when coerced through the 11643 /// target semantics. 11644 /// 11645 /// The value might be a vector of floats (or a complex number). 11646 static bool IsSameFloatAfterCast(const APValue &value, 11647 const llvm::fltSemantics &Src, 11648 const llvm::fltSemantics &Tgt) { 11649 if (value.isFloat()) 11650 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11651 11652 if (value.isVector()) { 11653 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11654 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11655 return false; 11656 return true; 11657 } 11658 11659 assert(value.isComplexFloat()); 11660 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11661 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11662 } 11663 11664 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11665 bool IsListInit = false); 11666 11667 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11668 // Suppress cases where we are comparing against an enum constant. 11669 if (const DeclRefExpr *DR = 11670 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11671 if (isa<EnumConstantDecl>(DR->getDecl())) 11672 return true; 11673 11674 // Suppress cases where the value is expanded from a macro, unless that macro 11675 // is how a language represents a boolean literal. This is the case in both C 11676 // and Objective-C. 11677 SourceLocation BeginLoc = E->getBeginLoc(); 11678 if (BeginLoc.isMacroID()) { 11679 StringRef MacroName = Lexer::getImmediateMacroName( 11680 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11681 return MacroName != "YES" && MacroName != "NO" && 11682 MacroName != "true" && MacroName != "false"; 11683 } 11684 11685 return false; 11686 } 11687 11688 static bool isKnownToHaveUnsignedValue(Expr *E) { 11689 return E->getType()->isIntegerType() && 11690 (!E->getType()->isSignedIntegerType() || 11691 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11692 } 11693 11694 namespace { 11695 /// The promoted range of values of a type. In general this has the 11696 /// following structure: 11697 /// 11698 /// |-----------| . . . |-----------| 11699 /// ^ ^ ^ ^ 11700 /// Min HoleMin HoleMax Max 11701 /// 11702 /// ... where there is only a hole if a signed type is promoted to unsigned 11703 /// (in which case Min and Max are the smallest and largest representable 11704 /// values). 11705 struct PromotedRange { 11706 // Min, or HoleMax if there is a hole. 11707 llvm::APSInt PromotedMin; 11708 // Max, or HoleMin if there is a hole. 11709 llvm::APSInt PromotedMax; 11710 11711 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11712 if (R.Width == 0) 11713 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11714 else if (R.Width >= BitWidth && !Unsigned) { 11715 // Promotion made the type *narrower*. This happens when promoting 11716 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11717 // Treat all values of 'signed int' as being in range for now. 11718 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11719 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11720 } else { 11721 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11722 .extOrTrunc(BitWidth); 11723 PromotedMin.setIsUnsigned(Unsigned); 11724 11725 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11726 .extOrTrunc(BitWidth); 11727 PromotedMax.setIsUnsigned(Unsigned); 11728 } 11729 } 11730 11731 // Determine whether this range is contiguous (has no hole). 11732 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11733 11734 // Where a constant value is within the range. 11735 enum ComparisonResult { 11736 LT = 0x1, 11737 LE = 0x2, 11738 GT = 0x4, 11739 GE = 0x8, 11740 EQ = 0x10, 11741 NE = 0x20, 11742 InRangeFlag = 0x40, 11743 11744 Less = LE | LT | NE, 11745 Min = LE | InRangeFlag, 11746 InRange = InRangeFlag, 11747 Max = GE | InRangeFlag, 11748 Greater = GE | GT | NE, 11749 11750 OnlyValue = LE | GE | EQ | InRangeFlag, 11751 InHole = NE 11752 }; 11753 11754 ComparisonResult compare(const llvm::APSInt &Value) const { 11755 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11756 Value.isUnsigned() == PromotedMin.isUnsigned()); 11757 if (!isContiguous()) { 11758 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11759 if (Value.isMinValue()) return Min; 11760 if (Value.isMaxValue()) return Max; 11761 if (Value >= PromotedMin) return InRange; 11762 if (Value <= PromotedMax) return InRange; 11763 return InHole; 11764 } 11765 11766 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11767 case -1: return Less; 11768 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11769 case 1: 11770 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11771 case -1: return InRange; 11772 case 0: return Max; 11773 case 1: return Greater; 11774 } 11775 } 11776 11777 llvm_unreachable("impossible compare result"); 11778 } 11779 11780 static llvm::Optional<StringRef> 11781 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11782 if (Op == BO_Cmp) { 11783 ComparisonResult LTFlag = LT, GTFlag = GT; 11784 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11785 11786 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11787 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11788 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11789 return llvm::None; 11790 } 11791 11792 ComparisonResult TrueFlag, FalseFlag; 11793 if (Op == BO_EQ) { 11794 TrueFlag = EQ; 11795 FalseFlag = NE; 11796 } else if (Op == BO_NE) { 11797 TrueFlag = NE; 11798 FalseFlag = EQ; 11799 } else { 11800 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11801 TrueFlag = LT; 11802 FalseFlag = GE; 11803 } else { 11804 TrueFlag = GT; 11805 FalseFlag = LE; 11806 } 11807 if (Op == BO_GE || Op == BO_LE) 11808 std::swap(TrueFlag, FalseFlag); 11809 } 11810 if (R & TrueFlag) 11811 return StringRef("true"); 11812 if (R & FalseFlag) 11813 return StringRef("false"); 11814 return llvm::None; 11815 } 11816 }; 11817 } 11818 11819 static bool HasEnumType(Expr *E) { 11820 // Strip off implicit integral promotions. 11821 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11822 if (ICE->getCastKind() != CK_IntegralCast && 11823 ICE->getCastKind() != CK_NoOp) 11824 break; 11825 E = ICE->getSubExpr(); 11826 } 11827 11828 return E->getType()->isEnumeralType(); 11829 } 11830 11831 static int classifyConstantValue(Expr *Constant) { 11832 // The values of this enumeration are used in the diagnostics 11833 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11834 enum ConstantValueKind { 11835 Miscellaneous = 0, 11836 LiteralTrue, 11837 LiteralFalse 11838 }; 11839 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11840 return BL->getValue() ? ConstantValueKind::LiteralTrue 11841 : ConstantValueKind::LiteralFalse; 11842 return ConstantValueKind::Miscellaneous; 11843 } 11844 11845 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11846 Expr *Constant, Expr *Other, 11847 const llvm::APSInt &Value, 11848 bool RhsConstant) { 11849 if (S.inTemplateInstantiation()) 11850 return false; 11851 11852 Expr *OriginalOther = Other; 11853 11854 Constant = Constant->IgnoreParenImpCasts(); 11855 Other = Other->IgnoreParenImpCasts(); 11856 11857 // Suppress warnings on tautological comparisons between values of the same 11858 // enumeration type. There are only two ways we could warn on this: 11859 // - If the constant is outside the range of representable values of 11860 // the enumeration. In such a case, we should warn about the cast 11861 // to enumeration type, not about the comparison. 11862 // - If the constant is the maximum / minimum in-range value. For an 11863 // enumeratin type, such comparisons can be meaningful and useful. 11864 if (Constant->getType()->isEnumeralType() && 11865 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11866 return false; 11867 11868 IntRange OtherValueRange = GetExprRange( 11869 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11870 11871 QualType OtherT = Other->getType(); 11872 if (const auto *AT = OtherT->getAs<AtomicType>()) 11873 OtherT = AT->getValueType(); 11874 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11875 11876 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11877 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11878 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11879 S.NSAPIObj->isObjCBOOLType(OtherT) && 11880 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11881 11882 // Whether we're treating Other as being a bool because of the form of 11883 // expression despite it having another type (typically 'int' in C). 11884 bool OtherIsBooleanDespiteType = 11885 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11886 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11887 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11888 11889 // Check if all values in the range of possible values of this expression 11890 // lead to the same comparison outcome. 11891 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11892 Value.isUnsigned()); 11893 auto Cmp = OtherPromotedValueRange.compare(Value); 11894 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11895 if (!Result) 11896 return false; 11897 11898 // Also consider the range determined by the type alone. This allows us to 11899 // classify the warning under the proper diagnostic group. 11900 bool TautologicalTypeCompare = false; 11901 { 11902 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11903 Value.isUnsigned()); 11904 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11905 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11906 RhsConstant)) { 11907 TautologicalTypeCompare = true; 11908 Cmp = TypeCmp; 11909 Result = TypeResult; 11910 } 11911 } 11912 11913 // Don't warn if the non-constant operand actually always evaluates to the 11914 // same value. 11915 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11916 return false; 11917 11918 // Suppress the diagnostic for an in-range comparison if the constant comes 11919 // from a macro or enumerator. We don't want to diagnose 11920 // 11921 // some_long_value <= INT_MAX 11922 // 11923 // when sizeof(int) == sizeof(long). 11924 bool InRange = Cmp & PromotedRange::InRangeFlag; 11925 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11926 return false; 11927 11928 // A comparison of an unsigned bit-field against 0 is really a type problem, 11929 // even though at the type level the bit-field might promote to 'signed int'. 11930 if (Other->refersToBitField() && InRange && Value == 0 && 11931 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11932 TautologicalTypeCompare = true; 11933 11934 // If this is a comparison to an enum constant, include that 11935 // constant in the diagnostic. 11936 const EnumConstantDecl *ED = nullptr; 11937 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11938 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11939 11940 // Should be enough for uint128 (39 decimal digits) 11941 SmallString<64> PrettySourceValue; 11942 llvm::raw_svector_ostream OS(PrettySourceValue); 11943 if (ED) { 11944 OS << '\'' << *ED << "' (" << Value << ")"; 11945 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11946 Constant->IgnoreParenImpCasts())) { 11947 OS << (BL->getValue() ? "YES" : "NO"); 11948 } else { 11949 OS << Value; 11950 } 11951 11952 if (!TautologicalTypeCompare) { 11953 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11954 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11955 << E->getOpcodeStr() << OS.str() << *Result 11956 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11957 return true; 11958 } 11959 11960 if (IsObjCSignedCharBool) { 11961 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11962 S.PDiag(diag::warn_tautological_compare_objc_bool) 11963 << OS.str() << *Result); 11964 return true; 11965 } 11966 11967 // FIXME: We use a somewhat different formatting for the in-range cases and 11968 // cases involving boolean values for historical reasons. We should pick a 11969 // consistent way of presenting these diagnostics. 11970 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11971 11972 S.DiagRuntimeBehavior( 11973 E->getOperatorLoc(), E, 11974 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11975 : diag::warn_tautological_bool_compare) 11976 << OS.str() << classifyConstantValue(Constant) << OtherT 11977 << OtherIsBooleanDespiteType << *Result 11978 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11979 } else { 11980 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11981 unsigned Diag = 11982 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11983 ? (HasEnumType(OriginalOther) 11984 ? diag::warn_unsigned_enum_always_true_comparison 11985 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11986 : diag::warn_unsigned_always_true_comparison) 11987 : diag::warn_tautological_constant_compare; 11988 11989 S.Diag(E->getOperatorLoc(), Diag) 11990 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11991 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11992 } 11993 11994 return true; 11995 } 11996 11997 /// Analyze the operands of the given comparison. Implements the 11998 /// fallback case from AnalyzeComparison. 11999 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12000 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12001 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12002 } 12003 12004 /// Implements -Wsign-compare. 12005 /// 12006 /// \param E the binary operator to check for warnings 12007 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12008 // The type the comparison is being performed in. 12009 QualType T = E->getLHS()->getType(); 12010 12011 // Only analyze comparison operators where both sides have been converted to 12012 // the same type. 12013 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12014 return AnalyzeImpConvsInComparison(S, E); 12015 12016 // Don't analyze value-dependent comparisons directly. 12017 if (E->isValueDependent()) 12018 return AnalyzeImpConvsInComparison(S, E); 12019 12020 Expr *LHS = E->getLHS(); 12021 Expr *RHS = E->getRHS(); 12022 12023 if (T->isIntegralType(S.Context)) { 12024 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12025 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12026 12027 // We don't care about expressions whose result is a constant. 12028 if (RHSValue && LHSValue) 12029 return AnalyzeImpConvsInComparison(S, E); 12030 12031 // We only care about expressions where just one side is literal 12032 if ((bool)RHSValue ^ (bool)LHSValue) { 12033 // Is the constant on the RHS or LHS? 12034 const bool RhsConstant = (bool)RHSValue; 12035 Expr *Const = RhsConstant ? RHS : LHS; 12036 Expr *Other = RhsConstant ? LHS : RHS; 12037 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12038 12039 // Check whether an integer constant comparison results in a value 12040 // of 'true' or 'false'. 12041 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12042 return AnalyzeImpConvsInComparison(S, E); 12043 } 12044 } 12045 12046 if (!T->hasUnsignedIntegerRepresentation()) { 12047 // We don't do anything special if this isn't an unsigned integral 12048 // comparison: we're only interested in integral comparisons, and 12049 // signed comparisons only happen in cases we don't care to warn about. 12050 return AnalyzeImpConvsInComparison(S, E); 12051 } 12052 12053 LHS = LHS->IgnoreParenImpCasts(); 12054 RHS = RHS->IgnoreParenImpCasts(); 12055 12056 if (!S.getLangOpts().CPlusPlus) { 12057 // Avoid warning about comparison of integers with different signs when 12058 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12059 // the type of `E`. 12060 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12061 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12062 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12063 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12064 } 12065 12066 // Check to see if one of the (unmodified) operands is of different 12067 // signedness. 12068 Expr *signedOperand, *unsignedOperand; 12069 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12070 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12071 "unsigned comparison between two signed integer expressions?"); 12072 signedOperand = LHS; 12073 unsignedOperand = RHS; 12074 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12075 signedOperand = RHS; 12076 unsignedOperand = LHS; 12077 } else { 12078 return AnalyzeImpConvsInComparison(S, E); 12079 } 12080 12081 // Otherwise, calculate the effective range of the signed operand. 12082 IntRange signedRange = GetExprRange( 12083 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12084 12085 // Go ahead and analyze implicit conversions in the operands. Note 12086 // that we skip the implicit conversions on both sides. 12087 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12088 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12089 12090 // If the signed range is non-negative, -Wsign-compare won't fire. 12091 if (signedRange.NonNegative) 12092 return; 12093 12094 // For (in)equality comparisons, if the unsigned operand is a 12095 // constant which cannot collide with a overflowed signed operand, 12096 // then reinterpreting the signed operand as unsigned will not 12097 // change the result of the comparison. 12098 if (E->isEqualityOp()) { 12099 unsigned comparisonWidth = S.Context.getIntWidth(T); 12100 IntRange unsignedRange = 12101 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12102 /*Approximate*/ true); 12103 12104 // We should never be unable to prove that the unsigned operand is 12105 // non-negative. 12106 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12107 12108 if (unsignedRange.Width < comparisonWidth) 12109 return; 12110 } 12111 12112 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12113 S.PDiag(diag::warn_mixed_sign_comparison) 12114 << LHS->getType() << RHS->getType() 12115 << LHS->getSourceRange() << RHS->getSourceRange()); 12116 } 12117 12118 /// Analyzes an attempt to assign the given value to a bitfield. 12119 /// 12120 /// Returns true if there was something fishy about the attempt. 12121 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12122 SourceLocation InitLoc) { 12123 assert(Bitfield->isBitField()); 12124 if (Bitfield->isInvalidDecl()) 12125 return false; 12126 12127 // White-list bool bitfields. 12128 QualType BitfieldType = Bitfield->getType(); 12129 if (BitfieldType->isBooleanType()) 12130 return false; 12131 12132 if (BitfieldType->isEnumeralType()) { 12133 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12134 // If the underlying enum type was not explicitly specified as an unsigned 12135 // type and the enum contain only positive values, MSVC++ will cause an 12136 // inconsistency by storing this as a signed type. 12137 if (S.getLangOpts().CPlusPlus11 && 12138 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12139 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12140 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12141 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12142 << BitfieldEnumDecl; 12143 } 12144 } 12145 12146 if (Bitfield->getType()->isBooleanType()) 12147 return false; 12148 12149 // Ignore value- or type-dependent expressions. 12150 if (Bitfield->getBitWidth()->isValueDependent() || 12151 Bitfield->getBitWidth()->isTypeDependent() || 12152 Init->isValueDependent() || 12153 Init->isTypeDependent()) 12154 return false; 12155 12156 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12157 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12158 12159 Expr::EvalResult Result; 12160 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12161 Expr::SE_AllowSideEffects)) { 12162 // The RHS is not constant. If the RHS has an enum type, make sure the 12163 // bitfield is wide enough to hold all the values of the enum without 12164 // truncation. 12165 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12166 EnumDecl *ED = EnumTy->getDecl(); 12167 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12168 12169 // Enum types are implicitly signed on Windows, so check if there are any 12170 // negative enumerators to see if the enum was intended to be signed or 12171 // not. 12172 bool SignedEnum = ED->getNumNegativeBits() > 0; 12173 12174 // Check for surprising sign changes when assigning enum values to a 12175 // bitfield of different signedness. If the bitfield is signed and we 12176 // have exactly the right number of bits to store this unsigned enum, 12177 // suggest changing the enum to an unsigned type. This typically happens 12178 // on Windows where unfixed enums always use an underlying type of 'int'. 12179 unsigned DiagID = 0; 12180 if (SignedEnum && !SignedBitfield) { 12181 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12182 } else if (SignedBitfield && !SignedEnum && 12183 ED->getNumPositiveBits() == FieldWidth) { 12184 DiagID = diag::warn_signed_bitfield_enum_conversion; 12185 } 12186 12187 if (DiagID) { 12188 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12189 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12190 SourceRange TypeRange = 12191 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12192 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12193 << SignedEnum << TypeRange; 12194 } 12195 12196 // Compute the required bitwidth. If the enum has negative values, we need 12197 // one more bit than the normal number of positive bits to represent the 12198 // sign bit. 12199 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12200 ED->getNumNegativeBits()) 12201 : ED->getNumPositiveBits(); 12202 12203 // Check the bitwidth. 12204 if (BitsNeeded > FieldWidth) { 12205 Expr *WidthExpr = Bitfield->getBitWidth(); 12206 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12207 << Bitfield << ED; 12208 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12209 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12210 } 12211 } 12212 12213 return false; 12214 } 12215 12216 llvm::APSInt Value = Result.Val.getInt(); 12217 12218 unsigned OriginalWidth = Value.getBitWidth(); 12219 12220 if (!Value.isSigned() || Value.isNegative()) 12221 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12222 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12223 OriginalWidth = Value.getMinSignedBits(); 12224 12225 if (OriginalWidth <= FieldWidth) 12226 return false; 12227 12228 // Compute the value which the bitfield will contain. 12229 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12230 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12231 12232 // Check whether the stored value is equal to the original value. 12233 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12234 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12235 return false; 12236 12237 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12238 // therefore don't strictly fit into a signed bitfield of width 1. 12239 if (FieldWidth == 1 && Value == 1) 12240 return false; 12241 12242 std::string PrettyValue = toString(Value, 10); 12243 std::string PrettyTrunc = toString(TruncatedValue, 10); 12244 12245 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12246 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12247 << Init->getSourceRange(); 12248 12249 return true; 12250 } 12251 12252 /// Analyze the given simple or compound assignment for warning-worthy 12253 /// operations. 12254 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12255 // Just recurse on the LHS. 12256 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12257 12258 // We want to recurse on the RHS as normal unless we're assigning to 12259 // a bitfield. 12260 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12261 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12262 E->getOperatorLoc())) { 12263 // Recurse, ignoring any implicit conversions on the RHS. 12264 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12265 E->getOperatorLoc()); 12266 } 12267 } 12268 12269 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12270 12271 // Diagnose implicitly sequentially-consistent atomic assignment. 12272 if (E->getLHS()->getType()->isAtomicType()) 12273 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12274 } 12275 12276 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12277 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12278 SourceLocation CContext, unsigned diag, 12279 bool pruneControlFlow = false) { 12280 if (pruneControlFlow) { 12281 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12282 S.PDiag(diag) 12283 << SourceType << T << E->getSourceRange() 12284 << SourceRange(CContext)); 12285 return; 12286 } 12287 S.Diag(E->getExprLoc(), diag) 12288 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12289 } 12290 12291 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12292 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12293 SourceLocation CContext, 12294 unsigned diag, bool pruneControlFlow = false) { 12295 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12296 } 12297 12298 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12299 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12300 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12301 } 12302 12303 static void adornObjCBoolConversionDiagWithTernaryFixit( 12304 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12305 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12306 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12307 Ignored = OVE->getSourceExpr(); 12308 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12309 isa<BinaryOperator>(Ignored) || 12310 isa<CXXOperatorCallExpr>(Ignored); 12311 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12312 if (NeedsParens) 12313 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12314 << FixItHint::CreateInsertion(EndLoc, ")"); 12315 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12316 } 12317 12318 /// Diagnose an implicit cast from a floating point value to an integer value. 12319 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12320 SourceLocation CContext) { 12321 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12322 const bool PruneWarnings = S.inTemplateInstantiation(); 12323 12324 Expr *InnerE = E->IgnoreParenImpCasts(); 12325 // We also want to warn on, e.g., "int i = -1.234" 12326 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12327 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12328 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12329 12330 const bool IsLiteral = 12331 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12332 12333 llvm::APFloat Value(0.0); 12334 bool IsConstant = 12335 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12336 if (!IsConstant) { 12337 if (isObjCSignedCharBool(S, T)) { 12338 return adornObjCBoolConversionDiagWithTernaryFixit( 12339 S, E, 12340 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12341 << E->getType()); 12342 } 12343 12344 return DiagnoseImpCast(S, E, T, CContext, 12345 diag::warn_impcast_float_integer, PruneWarnings); 12346 } 12347 12348 bool isExact = false; 12349 12350 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12351 T->hasUnsignedIntegerRepresentation()); 12352 llvm::APFloat::opStatus Result = Value.convertToInteger( 12353 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12354 12355 // FIXME: Force the precision of the source value down so we don't print 12356 // digits which are usually useless (we don't really care here if we 12357 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12358 // would automatically print the shortest representation, but it's a bit 12359 // tricky to implement. 12360 SmallString<16> PrettySourceValue; 12361 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12362 precision = (precision * 59 + 195) / 196; 12363 Value.toString(PrettySourceValue, precision); 12364 12365 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12366 return adornObjCBoolConversionDiagWithTernaryFixit( 12367 S, E, 12368 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12369 << PrettySourceValue); 12370 } 12371 12372 if (Result == llvm::APFloat::opOK && isExact) { 12373 if (IsLiteral) return; 12374 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12375 PruneWarnings); 12376 } 12377 12378 // Conversion of a floating-point value to a non-bool integer where the 12379 // integral part cannot be represented by the integer type is undefined. 12380 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12381 return DiagnoseImpCast( 12382 S, E, T, CContext, 12383 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12384 : diag::warn_impcast_float_to_integer_out_of_range, 12385 PruneWarnings); 12386 12387 unsigned DiagID = 0; 12388 if (IsLiteral) { 12389 // Warn on floating point literal to integer. 12390 DiagID = diag::warn_impcast_literal_float_to_integer; 12391 } else if (IntegerValue == 0) { 12392 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12393 return DiagnoseImpCast(S, E, T, CContext, 12394 diag::warn_impcast_float_integer, PruneWarnings); 12395 } 12396 // Warn on non-zero to zero conversion. 12397 DiagID = diag::warn_impcast_float_to_integer_zero; 12398 } else { 12399 if (IntegerValue.isUnsigned()) { 12400 if (!IntegerValue.isMaxValue()) { 12401 return DiagnoseImpCast(S, E, T, CContext, 12402 diag::warn_impcast_float_integer, PruneWarnings); 12403 } 12404 } else { // IntegerValue.isSigned() 12405 if (!IntegerValue.isMaxSignedValue() && 12406 !IntegerValue.isMinSignedValue()) { 12407 return DiagnoseImpCast(S, E, T, CContext, 12408 diag::warn_impcast_float_integer, PruneWarnings); 12409 } 12410 } 12411 // Warn on evaluatable floating point expression to integer conversion. 12412 DiagID = diag::warn_impcast_float_to_integer; 12413 } 12414 12415 SmallString<16> PrettyTargetValue; 12416 if (IsBool) 12417 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12418 else 12419 IntegerValue.toString(PrettyTargetValue); 12420 12421 if (PruneWarnings) { 12422 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12423 S.PDiag(DiagID) 12424 << E->getType() << T.getUnqualifiedType() 12425 << PrettySourceValue << PrettyTargetValue 12426 << E->getSourceRange() << SourceRange(CContext)); 12427 } else { 12428 S.Diag(E->getExprLoc(), DiagID) 12429 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12430 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12431 } 12432 } 12433 12434 /// Analyze the given compound assignment for the possible losing of 12435 /// floating-point precision. 12436 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12437 assert(isa<CompoundAssignOperator>(E) && 12438 "Must be compound assignment operation"); 12439 // Recurse on the LHS and RHS in here 12440 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12441 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12442 12443 if (E->getLHS()->getType()->isAtomicType()) 12444 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12445 12446 // Now check the outermost expression 12447 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12448 const auto *RBT = cast<CompoundAssignOperator>(E) 12449 ->getComputationResultType() 12450 ->getAs<BuiltinType>(); 12451 12452 // The below checks assume source is floating point. 12453 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12454 12455 // If source is floating point but target is an integer. 12456 if (ResultBT->isInteger()) 12457 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12458 E->getExprLoc(), diag::warn_impcast_float_integer); 12459 12460 if (!ResultBT->isFloatingPoint()) 12461 return; 12462 12463 // If both source and target are floating points, warn about losing precision. 12464 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12465 QualType(ResultBT, 0), QualType(RBT, 0)); 12466 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12467 // warn about dropping FP rank. 12468 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12469 diag::warn_impcast_float_result_precision); 12470 } 12471 12472 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12473 IntRange Range) { 12474 if (!Range.Width) return "0"; 12475 12476 llvm::APSInt ValueInRange = Value; 12477 ValueInRange.setIsSigned(!Range.NonNegative); 12478 ValueInRange = ValueInRange.trunc(Range.Width); 12479 return toString(ValueInRange, 10); 12480 } 12481 12482 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12483 if (!isa<ImplicitCastExpr>(Ex)) 12484 return false; 12485 12486 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12487 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12488 const Type *Source = 12489 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12490 if (Target->isDependentType()) 12491 return false; 12492 12493 const BuiltinType *FloatCandidateBT = 12494 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12495 const Type *BoolCandidateType = ToBool ? Target : Source; 12496 12497 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12498 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12499 } 12500 12501 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12502 SourceLocation CC) { 12503 unsigned NumArgs = TheCall->getNumArgs(); 12504 for (unsigned i = 0; i < NumArgs; ++i) { 12505 Expr *CurrA = TheCall->getArg(i); 12506 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12507 continue; 12508 12509 bool IsSwapped = ((i > 0) && 12510 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12511 IsSwapped |= ((i < (NumArgs - 1)) && 12512 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12513 if (IsSwapped) { 12514 // Warn on this floating-point to bool conversion. 12515 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12516 CurrA->getType(), CC, 12517 diag::warn_impcast_floating_point_to_bool); 12518 } 12519 } 12520 } 12521 12522 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12523 SourceLocation CC) { 12524 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12525 E->getExprLoc())) 12526 return; 12527 12528 // Don't warn on functions which have return type nullptr_t. 12529 if (isa<CallExpr>(E)) 12530 return; 12531 12532 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12533 const Expr::NullPointerConstantKind NullKind = 12534 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12535 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12536 return; 12537 12538 // Return if target type is a safe conversion. 12539 if (T->isAnyPointerType() || T->isBlockPointerType() || 12540 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12541 return; 12542 12543 SourceLocation Loc = E->getSourceRange().getBegin(); 12544 12545 // Venture through the macro stacks to get to the source of macro arguments. 12546 // The new location is a better location than the complete location that was 12547 // passed in. 12548 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12549 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12550 12551 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12552 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12553 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12554 Loc, S.SourceMgr, S.getLangOpts()); 12555 if (MacroName == "NULL") 12556 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12557 } 12558 12559 // Only warn if the null and context location are in the same macro expansion. 12560 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12561 return; 12562 12563 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12564 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12565 << FixItHint::CreateReplacement(Loc, 12566 S.getFixItZeroLiteralForType(T, Loc)); 12567 } 12568 12569 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12570 ObjCArrayLiteral *ArrayLiteral); 12571 12572 static void 12573 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12574 ObjCDictionaryLiteral *DictionaryLiteral); 12575 12576 /// Check a single element within a collection literal against the 12577 /// target element type. 12578 static void checkObjCCollectionLiteralElement(Sema &S, 12579 QualType TargetElementType, 12580 Expr *Element, 12581 unsigned ElementKind) { 12582 // Skip a bitcast to 'id' or qualified 'id'. 12583 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12584 if (ICE->getCastKind() == CK_BitCast && 12585 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12586 Element = ICE->getSubExpr(); 12587 } 12588 12589 QualType ElementType = Element->getType(); 12590 ExprResult ElementResult(Element); 12591 if (ElementType->getAs<ObjCObjectPointerType>() && 12592 S.CheckSingleAssignmentConstraints(TargetElementType, 12593 ElementResult, 12594 false, false) 12595 != Sema::Compatible) { 12596 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12597 << ElementType << ElementKind << TargetElementType 12598 << Element->getSourceRange(); 12599 } 12600 12601 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12602 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12603 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12604 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12605 } 12606 12607 /// Check an Objective-C array literal being converted to the given 12608 /// target type. 12609 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12610 ObjCArrayLiteral *ArrayLiteral) { 12611 if (!S.NSArrayDecl) 12612 return; 12613 12614 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12615 if (!TargetObjCPtr) 12616 return; 12617 12618 if (TargetObjCPtr->isUnspecialized() || 12619 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12620 != S.NSArrayDecl->getCanonicalDecl()) 12621 return; 12622 12623 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12624 if (TypeArgs.size() != 1) 12625 return; 12626 12627 QualType TargetElementType = TypeArgs[0]; 12628 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12629 checkObjCCollectionLiteralElement(S, TargetElementType, 12630 ArrayLiteral->getElement(I), 12631 0); 12632 } 12633 } 12634 12635 /// Check an Objective-C dictionary literal being converted to the given 12636 /// target type. 12637 static void 12638 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12639 ObjCDictionaryLiteral *DictionaryLiteral) { 12640 if (!S.NSDictionaryDecl) 12641 return; 12642 12643 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12644 if (!TargetObjCPtr) 12645 return; 12646 12647 if (TargetObjCPtr->isUnspecialized() || 12648 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12649 != S.NSDictionaryDecl->getCanonicalDecl()) 12650 return; 12651 12652 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12653 if (TypeArgs.size() != 2) 12654 return; 12655 12656 QualType TargetKeyType = TypeArgs[0]; 12657 QualType TargetObjectType = TypeArgs[1]; 12658 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12659 auto Element = DictionaryLiteral->getKeyValueElement(I); 12660 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12661 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12662 } 12663 } 12664 12665 // Helper function to filter out cases for constant width constant conversion. 12666 // Don't warn on char array initialization or for non-decimal values. 12667 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12668 SourceLocation CC) { 12669 // If initializing from a constant, and the constant starts with '0', 12670 // then it is a binary, octal, or hexadecimal. Allow these constants 12671 // to fill all the bits, even if there is a sign change. 12672 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12673 const char FirstLiteralCharacter = 12674 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12675 if (FirstLiteralCharacter == '0') 12676 return false; 12677 } 12678 12679 // If the CC location points to a '{', and the type is char, then assume 12680 // assume it is an array initialization. 12681 if (CC.isValid() && T->isCharType()) { 12682 const char FirstContextCharacter = 12683 S.getSourceManager().getCharacterData(CC)[0]; 12684 if (FirstContextCharacter == '{') 12685 return false; 12686 } 12687 12688 return true; 12689 } 12690 12691 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12692 const auto *IL = dyn_cast<IntegerLiteral>(E); 12693 if (!IL) { 12694 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12695 if (UO->getOpcode() == UO_Minus) 12696 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12697 } 12698 } 12699 12700 return IL; 12701 } 12702 12703 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12704 E = E->IgnoreParenImpCasts(); 12705 SourceLocation ExprLoc = E->getExprLoc(); 12706 12707 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12708 BinaryOperator::Opcode Opc = BO->getOpcode(); 12709 Expr::EvalResult Result; 12710 // Do not diagnose unsigned shifts. 12711 if (Opc == BO_Shl) { 12712 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12713 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12714 if (LHS && LHS->getValue() == 0) 12715 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12716 else if (!E->isValueDependent() && LHS && RHS && 12717 RHS->getValue().isNonNegative() && 12718 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12719 S.Diag(ExprLoc, diag::warn_left_shift_always) 12720 << (Result.Val.getInt() != 0); 12721 else if (E->getType()->isSignedIntegerType()) 12722 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12723 } 12724 } 12725 12726 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12727 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12728 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12729 if (!LHS || !RHS) 12730 return; 12731 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12732 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12733 // Do not diagnose common idioms. 12734 return; 12735 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12736 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12737 } 12738 } 12739 12740 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12741 SourceLocation CC, 12742 bool *ICContext = nullptr, 12743 bool IsListInit = false) { 12744 if (E->isTypeDependent() || E->isValueDependent()) return; 12745 12746 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12747 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12748 if (Source == Target) return; 12749 if (Target->isDependentType()) return; 12750 12751 // If the conversion context location is invalid don't complain. We also 12752 // don't want to emit a warning if the issue occurs from the expansion of 12753 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12754 // delay this check as long as possible. Once we detect we are in that 12755 // scenario, we just return. 12756 if (CC.isInvalid()) 12757 return; 12758 12759 if (Source->isAtomicType()) 12760 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12761 12762 // Diagnose implicit casts to bool. 12763 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12764 if (isa<StringLiteral>(E)) 12765 // Warn on string literal to bool. Checks for string literals in logical 12766 // and expressions, for instance, assert(0 && "error here"), are 12767 // prevented by a check in AnalyzeImplicitConversions(). 12768 return DiagnoseImpCast(S, E, T, CC, 12769 diag::warn_impcast_string_literal_to_bool); 12770 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12771 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12772 // This covers the literal expressions that evaluate to Objective-C 12773 // objects. 12774 return DiagnoseImpCast(S, E, T, CC, 12775 diag::warn_impcast_objective_c_literal_to_bool); 12776 } 12777 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12778 // Warn on pointer to bool conversion that is always true. 12779 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12780 SourceRange(CC)); 12781 } 12782 } 12783 12784 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12785 // is a typedef for signed char (macOS), then that constant value has to be 1 12786 // or 0. 12787 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12788 Expr::EvalResult Result; 12789 if (E->EvaluateAsInt(Result, S.getASTContext(), 12790 Expr::SE_AllowSideEffects)) { 12791 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12792 adornObjCBoolConversionDiagWithTernaryFixit( 12793 S, E, 12794 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12795 << toString(Result.Val.getInt(), 10)); 12796 } 12797 return; 12798 } 12799 } 12800 12801 // Check implicit casts from Objective-C collection literals to specialized 12802 // collection types, e.g., NSArray<NSString *> *. 12803 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12804 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12805 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12806 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12807 12808 // Strip vector types. 12809 if (isa<VectorType>(Source)) { 12810 if (Target->isVLSTBuiltinType() && 12811 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12812 QualType(Source, 0)) || 12813 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12814 QualType(Source, 0)))) 12815 return; 12816 12817 if (!isa<VectorType>(Target)) { 12818 if (S.SourceMgr.isInSystemMacro(CC)) 12819 return; 12820 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12821 } 12822 12823 // If the vector cast is cast between two vectors of the same size, it is 12824 // a bitcast, not a conversion. 12825 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12826 return; 12827 12828 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12829 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12830 } 12831 if (auto VecTy = dyn_cast<VectorType>(Target)) 12832 Target = VecTy->getElementType().getTypePtr(); 12833 12834 // Strip complex types. 12835 if (isa<ComplexType>(Source)) { 12836 if (!isa<ComplexType>(Target)) { 12837 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12838 return; 12839 12840 return DiagnoseImpCast(S, E, T, CC, 12841 S.getLangOpts().CPlusPlus 12842 ? diag::err_impcast_complex_scalar 12843 : diag::warn_impcast_complex_scalar); 12844 } 12845 12846 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12847 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12848 } 12849 12850 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12851 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12852 12853 // If the source is floating point... 12854 if (SourceBT && SourceBT->isFloatingPoint()) { 12855 // ...and the target is floating point... 12856 if (TargetBT && TargetBT->isFloatingPoint()) { 12857 // ...then warn if we're dropping FP rank. 12858 12859 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12860 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12861 if (Order > 0) { 12862 // Don't warn about float constants that are precisely 12863 // representable in the target type. 12864 Expr::EvalResult result; 12865 if (E->EvaluateAsRValue(result, S.Context)) { 12866 // Value might be a float, a float vector, or a float complex. 12867 if (IsSameFloatAfterCast(result.Val, 12868 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12869 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12870 return; 12871 } 12872 12873 if (S.SourceMgr.isInSystemMacro(CC)) 12874 return; 12875 12876 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12877 } 12878 // ... or possibly if we're increasing rank, too 12879 else if (Order < 0) { 12880 if (S.SourceMgr.isInSystemMacro(CC)) 12881 return; 12882 12883 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12884 } 12885 return; 12886 } 12887 12888 // If the target is integral, always warn. 12889 if (TargetBT && TargetBT->isInteger()) { 12890 if (S.SourceMgr.isInSystemMacro(CC)) 12891 return; 12892 12893 DiagnoseFloatingImpCast(S, E, T, CC); 12894 } 12895 12896 // Detect the case where a call result is converted from floating-point to 12897 // to bool, and the final argument to the call is converted from bool, to 12898 // discover this typo: 12899 // 12900 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12901 // 12902 // FIXME: This is an incredibly special case; is there some more general 12903 // way to detect this class of misplaced-parentheses bug? 12904 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12905 // Check last argument of function call to see if it is an 12906 // implicit cast from a type matching the type the result 12907 // is being cast to. 12908 CallExpr *CEx = cast<CallExpr>(E); 12909 if (unsigned NumArgs = CEx->getNumArgs()) { 12910 Expr *LastA = CEx->getArg(NumArgs - 1); 12911 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12912 if (isa<ImplicitCastExpr>(LastA) && 12913 InnerE->getType()->isBooleanType()) { 12914 // Warn on this floating-point to bool conversion 12915 DiagnoseImpCast(S, E, T, CC, 12916 diag::warn_impcast_floating_point_to_bool); 12917 } 12918 } 12919 } 12920 return; 12921 } 12922 12923 // Valid casts involving fixed point types should be accounted for here. 12924 if (Source->isFixedPointType()) { 12925 if (Target->isUnsaturatedFixedPointType()) { 12926 Expr::EvalResult Result; 12927 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12928 S.isConstantEvaluated())) { 12929 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12930 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12931 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12932 if (Value > MaxVal || Value < MinVal) { 12933 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12934 S.PDiag(diag::warn_impcast_fixed_point_range) 12935 << Value.toString() << T 12936 << E->getSourceRange() 12937 << clang::SourceRange(CC)); 12938 return; 12939 } 12940 } 12941 } else if (Target->isIntegerType()) { 12942 Expr::EvalResult Result; 12943 if (!S.isConstantEvaluated() && 12944 E->EvaluateAsFixedPoint(Result, S.Context, 12945 Expr::SE_AllowSideEffects)) { 12946 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12947 12948 bool Overflowed; 12949 llvm::APSInt IntResult = FXResult.convertToInt( 12950 S.Context.getIntWidth(T), 12951 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12952 12953 if (Overflowed) { 12954 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12955 S.PDiag(diag::warn_impcast_fixed_point_range) 12956 << FXResult.toString() << T 12957 << E->getSourceRange() 12958 << clang::SourceRange(CC)); 12959 return; 12960 } 12961 } 12962 } 12963 } else if (Target->isUnsaturatedFixedPointType()) { 12964 if (Source->isIntegerType()) { 12965 Expr::EvalResult Result; 12966 if (!S.isConstantEvaluated() && 12967 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12968 llvm::APSInt Value = Result.Val.getInt(); 12969 12970 bool Overflowed; 12971 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12972 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12973 12974 if (Overflowed) { 12975 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12976 S.PDiag(diag::warn_impcast_fixed_point_range) 12977 << toString(Value, /*Radix=*/10) << T 12978 << E->getSourceRange() 12979 << clang::SourceRange(CC)); 12980 return; 12981 } 12982 } 12983 } 12984 } 12985 12986 // If we are casting an integer type to a floating point type without 12987 // initialization-list syntax, we might lose accuracy if the floating 12988 // point type has a narrower significand than the integer type. 12989 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12990 TargetBT->isFloatingType() && !IsListInit) { 12991 // Determine the number of precision bits in the source integer type. 12992 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12993 /*Approximate*/ true); 12994 unsigned int SourcePrecision = SourceRange.Width; 12995 12996 // Determine the number of precision bits in the 12997 // target floating point type. 12998 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12999 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13000 13001 if (SourcePrecision > 0 && TargetPrecision > 0 && 13002 SourcePrecision > TargetPrecision) { 13003 13004 if (Optional<llvm::APSInt> SourceInt = 13005 E->getIntegerConstantExpr(S.Context)) { 13006 // If the source integer is a constant, convert it to the target 13007 // floating point type. Issue a warning if the value changes 13008 // during the whole conversion. 13009 llvm::APFloat TargetFloatValue( 13010 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13011 llvm::APFloat::opStatus ConversionStatus = 13012 TargetFloatValue.convertFromAPInt( 13013 *SourceInt, SourceBT->isSignedInteger(), 13014 llvm::APFloat::rmNearestTiesToEven); 13015 13016 if (ConversionStatus != llvm::APFloat::opOK) { 13017 SmallString<32> PrettySourceValue; 13018 SourceInt->toString(PrettySourceValue, 10); 13019 SmallString<32> PrettyTargetValue; 13020 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13021 13022 S.DiagRuntimeBehavior( 13023 E->getExprLoc(), E, 13024 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13025 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13026 << E->getSourceRange() << clang::SourceRange(CC)); 13027 } 13028 } else { 13029 // Otherwise, the implicit conversion may lose precision. 13030 DiagnoseImpCast(S, E, T, CC, 13031 diag::warn_impcast_integer_float_precision); 13032 } 13033 } 13034 } 13035 13036 DiagnoseNullConversion(S, E, T, CC); 13037 13038 S.DiscardMisalignedMemberAddress(Target, E); 13039 13040 if (Target->isBooleanType()) 13041 DiagnoseIntInBoolContext(S, E); 13042 13043 if (!Source->isIntegerType() || !Target->isIntegerType()) 13044 return; 13045 13046 // TODO: remove this early return once the false positives for constant->bool 13047 // in templates, macros, etc, are reduced or removed. 13048 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13049 return; 13050 13051 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13052 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13053 return adornObjCBoolConversionDiagWithTernaryFixit( 13054 S, E, 13055 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13056 << E->getType()); 13057 } 13058 13059 IntRange SourceTypeRange = 13060 IntRange::forTargetOfCanonicalType(S.Context, Source); 13061 IntRange LikelySourceRange = 13062 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13063 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13064 13065 if (LikelySourceRange.Width > TargetRange.Width) { 13066 // If the source is a constant, use a default-on diagnostic. 13067 // TODO: this should happen for bitfield stores, too. 13068 Expr::EvalResult Result; 13069 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13070 S.isConstantEvaluated())) { 13071 llvm::APSInt Value(32); 13072 Value = Result.Val.getInt(); 13073 13074 if (S.SourceMgr.isInSystemMacro(CC)) 13075 return; 13076 13077 std::string PrettySourceValue = toString(Value, 10); 13078 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13079 13080 S.DiagRuntimeBehavior( 13081 E->getExprLoc(), E, 13082 S.PDiag(diag::warn_impcast_integer_precision_constant) 13083 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13084 << E->getSourceRange() << SourceRange(CC)); 13085 return; 13086 } 13087 13088 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13089 if (S.SourceMgr.isInSystemMacro(CC)) 13090 return; 13091 13092 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13093 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13094 /* pruneControlFlow */ true); 13095 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13096 } 13097 13098 if (TargetRange.Width > SourceTypeRange.Width) { 13099 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13100 if (UO->getOpcode() == UO_Minus) 13101 if (Source->isUnsignedIntegerType()) { 13102 if (Target->isUnsignedIntegerType()) 13103 return DiagnoseImpCast(S, E, T, CC, 13104 diag::warn_impcast_high_order_zero_bits); 13105 if (Target->isSignedIntegerType()) 13106 return DiagnoseImpCast(S, E, T, CC, 13107 diag::warn_impcast_nonnegative_result); 13108 } 13109 } 13110 13111 if (TargetRange.Width == LikelySourceRange.Width && 13112 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13113 Source->isSignedIntegerType()) { 13114 // Warn when doing a signed to signed conversion, warn if the positive 13115 // source value is exactly the width of the target type, which will 13116 // cause a negative value to be stored. 13117 13118 Expr::EvalResult Result; 13119 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13120 !S.SourceMgr.isInSystemMacro(CC)) { 13121 llvm::APSInt Value = Result.Val.getInt(); 13122 if (isSameWidthConstantConversion(S, E, T, CC)) { 13123 std::string PrettySourceValue = toString(Value, 10); 13124 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13125 13126 S.DiagRuntimeBehavior( 13127 E->getExprLoc(), E, 13128 S.PDiag(diag::warn_impcast_integer_precision_constant) 13129 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13130 << E->getSourceRange() << SourceRange(CC)); 13131 return; 13132 } 13133 } 13134 13135 // Fall through for non-constants to give a sign conversion warning. 13136 } 13137 13138 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13139 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13140 LikelySourceRange.Width == TargetRange.Width)) { 13141 if (S.SourceMgr.isInSystemMacro(CC)) 13142 return; 13143 13144 unsigned DiagID = diag::warn_impcast_integer_sign; 13145 13146 // Traditionally, gcc has warned about this under -Wsign-compare. 13147 // We also want to warn about it in -Wconversion. 13148 // So if -Wconversion is off, use a completely identical diagnostic 13149 // in the sign-compare group. 13150 // The conditional-checking code will 13151 if (ICContext) { 13152 DiagID = diag::warn_impcast_integer_sign_conditional; 13153 *ICContext = true; 13154 } 13155 13156 return DiagnoseImpCast(S, E, T, CC, DiagID); 13157 } 13158 13159 // Diagnose conversions between different enumeration types. 13160 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13161 // type, to give us better diagnostics. 13162 QualType SourceType = E->getType(); 13163 if (!S.getLangOpts().CPlusPlus) { 13164 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13165 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13166 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13167 SourceType = S.Context.getTypeDeclType(Enum); 13168 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13169 } 13170 } 13171 13172 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13173 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13174 if (SourceEnum->getDecl()->hasNameForLinkage() && 13175 TargetEnum->getDecl()->hasNameForLinkage() && 13176 SourceEnum != TargetEnum) { 13177 if (S.SourceMgr.isInSystemMacro(CC)) 13178 return; 13179 13180 return DiagnoseImpCast(S, E, SourceType, T, CC, 13181 diag::warn_impcast_different_enum_types); 13182 } 13183 } 13184 13185 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13186 SourceLocation CC, QualType T); 13187 13188 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13189 SourceLocation CC, bool &ICContext) { 13190 E = E->IgnoreParenImpCasts(); 13191 13192 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13193 return CheckConditionalOperator(S, CO, CC, T); 13194 13195 AnalyzeImplicitConversions(S, E, CC); 13196 if (E->getType() != T) 13197 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13198 } 13199 13200 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13201 SourceLocation CC, QualType T) { 13202 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13203 13204 Expr *TrueExpr = E->getTrueExpr(); 13205 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13206 TrueExpr = BCO->getCommon(); 13207 13208 bool Suspicious = false; 13209 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13210 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13211 13212 if (T->isBooleanType()) 13213 DiagnoseIntInBoolContext(S, E); 13214 13215 // If -Wconversion would have warned about either of the candidates 13216 // for a signedness conversion to the context type... 13217 if (!Suspicious) return; 13218 13219 // ...but it's currently ignored... 13220 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13221 return; 13222 13223 // ...then check whether it would have warned about either of the 13224 // candidates for a signedness conversion to the condition type. 13225 if (E->getType() == T) return; 13226 13227 Suspicious = false; 13228 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13229 E->getType(), CC, &Suspicious); 13230 if (!Suspicious) 13231 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13232 E->getType(), CC, &Suspicious); 13233 } 13234 13235 /// Check conversion of given expression to boolean. 13236 /// Input argument E is a logical expression. 13237 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13238 if (S.getLangOpts().Bool) 13239 return; 13240 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13241 return; 13242 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13243 } 13244 13245 namespace { 13246 struct AnalyzeImplicitConversionsWorkItem { 13247 Expr *E; 13248 SourceLocation CC; 13249 bool IsListInit; 13250 }; 13251 } 13252 13253 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13254 /// that should be visited are added to WorkList. 13255 static void AnalyzeImplicitConversions( 13256 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13257 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13258 Expr *OrigE = Item.E; 13259 SourceLocation CC = Item.CC; 13260 13261 QualType T = OrigE->getType(); 13262 Expr *E = OrigE->IgnoreParenImpCasts(); 13263 13264 // Propagate whether we are in a C++ list initialization expression. 13265 // If so, we do not issue warnings for implicit int-float conversion 13266 // precision loss, because C++11 narrowing already handles it. 13267 bool IsListInit = Item.IsListInit || 13268 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13269 13270 if (E->isTypeDependent() || E->isValueDependent()) 13271 return; 13272 13273 Expr *SourceExpr = E; 13274 // Examine, but don't traverse into the source expression of an 13275 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13276 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13277 // evaluate it in the context of checking the specific conversion to T though. 13278 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13279 if (auto *Src = OVE->getSourceExpr()) 13280 SourceExpr = Src; 13281 13282 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13283 if (UO->getOpcode() == UO_Not && 13284 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13285 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13286 << OrigE->getSourceRange() << T->isBooleanType() 13287 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13288 13289 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13290 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13291 BO->getLHS()->isKnownToHaveBooleanValue() && 13292 BO->getRHS()->isKnownToHaveBooleanValue() && 13293 BO->getLHS()->HasSideEffects(S.Context) && 13294 BO->getRHS()->HasSideEffects(S.Context)) { 13295 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13296 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13297 << FixItHint::CreateReplacement( 13298 BO->getOperatorLoc(), 13299 (BO->getOpcode() == BO_And ? "&&" : "||")); 13300 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13301 } 13302 13303 // For conditional operators, we analyze the arguments as if they 13304 // were being fed directly into the output. 13305 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13306 CheckConditionalOperator(S, CO, CC, T); 13307 return; 13308 } 13309 13310 // Check implicit argument conversions for function calls. 13311 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13312 CheckImplicitArgumentConversions(S, Call, CC); 13313 13314 // Go ahead and check any implicit conversions we might have skipped. 13315 // The non-canonical typecheck is just an optimization; 13316 // CheckImplicitConversion will filter out dead implicit conversions. 13317 if (SourceExpr->getType() != T) 13318 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13319 13320 // Now continue drilling into this expression. 13321 13322 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13323 // The bound subexpressions in a PseudoObjectExpr are not reachable 13324 // as transitive children. 13325 // FIXME: Use a more uniform representation for this. 13326 for (auto *SE : POE->semantics()) 13327 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13328 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13329 } 13330 13331 // Skip past explicit casts. 13332 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13333 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13334 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13335 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13336 WorkList.push_back({E, CC, IsListInit}); 13337 return; 13338 } 13339 13340 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13341 // Do a somewhat different check with comparison operators. 13342 if (BO->isComparisonOp()) 13343 return AnalyzeComparison(S, BO); 13344 13345 // And with simple assignments. 13346 if (BO->getOpcode() == BO_Assign) 13347 return AnalyzeAssignment(S, BO); 13348 // And with compound assignments. 13349 if (BO->isAssignmentOp()) 13350 return AnalyzeCompoundAssignment(S, BO); 13351 } 13352 13353 // These break the otherwise-useful invariant below. Fortunately, 13354 // we don't really need to recurse into them, because any internal 13355 // expressions should have been analyzed already when they were 13356 // built into statements. 13357 if (isa<StmtExpr>(E)) return; 13358 13359 // Don't descend into unevaluated contexts. 13360 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13361 13362 // Now just recurse over the expression's children. 13363 CC = E->getExprLoc(); 13364 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13365 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13366 for (Stmt *SubStmt : E->children()) { 13367 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13368 if (!ChildExpr) 13369 continue; 13370 13371 if (IsLogicalAndOperator && 13372 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13373 // Ignore checking string literals that are in logical and operators. 13374 // This is a common pattern for asserts. 13375 continue; 13376 WorkList.push_back({ChildExpr, CC, IsListInit}); 13377 } 13378 13379 if (BO && BO->isLogicalOp()) { 13380 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13381 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13382 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13383 13384 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13385 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13386 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13387 } 13388 13389 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13390 if (U->getOpcode() == UO_LNot) { 13391 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13392 } else if (U->getOpcode() != UO_AddrOf) { 13393 if (U->getSubExpr()->getType()->isAtomicType()) 13394 S.Diag(U->getSubExpr()->getBeginLoc(), 13395 diag::warn_atomic_implicit_seq_cst); 13396 } 13397 } 13398 } 13399 13400 /// AnalyzeImplicitConversions - Find and report any interesting 13401 /// implicit conversions in the given expression. There are a couple 13402 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13403 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13404 bool IsListInit/*= false*/) { 13405 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13406 WorkList.push_back({OrigE, CC, IsListInit}); 13407 while (!WorkList.empty()) 13408 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13409 } 13410 13411 /// Diagnose integer type and any valid implicit conversion to it. 13412 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13413 // Taking into account implicit conversions, 13414 // allow any integer. 13415 if (!E->getType()->isIntegerType()) { 13416 S.Diag(E->getBeginLoc(), 13417 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13418 return true; 13419 } 13420 // Potentially emit standard warnings for implicit conversions if enabled 13421 // using -Wconversion. 13422 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13423 return false; 13424 } 13425 13426 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13427 // Returns true when emitting a warning about taking the address of a reference. 13428 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13429 const PartialDiagnostic &PD) { 13430 E = E->IgnoreParenImpCasts(); 13431 13432 const FunctionDecl *FD = nullptr; 13433 13434 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13435 if (!DRE->getDecl()->getType()->isReferenceType()) 13436 return false; 13437 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13438 if (!M->getMemberDecl()->getType()->isReferenceType()) 13439 return false; 13440 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13441 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13442 return false; 13443 FD = Call->getDirectCallee(); 13444 } else { 13445 return false; 13446 } 13447 13448 SemaRef.Diag(E->getExprLoc(), PD); 13449 13450 // If possible, point to location of function. 13451 if (FD) { 13452 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13453 } 13454 13455 return true; 13456 } 13457 13458 // Returns true if the SourceLocation is expanded from any macro body. 13459 // Returns false if the SourceLocation is invalid, is from not in a macro 13460 // expansion, or is from expanded from a top-level macro argument. 13461 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13462 if (Loc.isInvalid()) 13463 return false; 13464 13465 while (Loc.isMacroID()) { 13466 if (SM.isMacroBodyExpansion(Loc)) 13467 return true; 13468 Loc = SM.getImmediateMacroCallerLoc(Loc); 13469 } 13470 13471 return false; 13472 } 13473 13474 /// Diagnose pointers that are always non-null. 13475 /// \param E the expression containing the pointer 13476 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13477 /// compared to a null pointer 13478 /// \param IsEqual True when the comparison is equal to a null pointer 13479 /// \param Range Extra SourceRange to highlight in the diagnostic 13480 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13481 Expr::NullPointerConstantKind NullKind, 13482 bool IsEqual, SourceRange Range) { 13483 if (!E) 13484 return; 13485 13486 // Don't warn inside macros. 13487 if (E->getExprLoc().isMacroID()) { 13488 const SourceManager &SM = getSourceManager(); 13489 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13490 IsInAnyMacroBody(SM, Range.getBegin())) 13491 return; 13492 } 13493 E = E->IgnoreImpCasts(); 13494 13495 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13496 13497 if (isa<CXXThisExpr>(E)) { 13498 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13499 : diag::warn_this_bool_conversion; 13500 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13501 return; 13502 } 13503 13504 bool IsAddressOf = false; 13505 13506 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13507 if (UO->getOpcode() != UO_AddrOf) 13508 return; 13509 IsAddressOf = true; 13510 E = UO->getSubExpr(); 13511 } 13512 13513 if (IsAddressOf) { 13514 unsigned DiagID = IsCompare 13515 ? diag::warn_address_of_reference_null_compare 13516 : diag::warn_address_of_reference_bool_conversion; 13517 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13518 << IsEqual; 13519 if (CheckForReference(*this, E, PD)) { 13520 return; 13521 } 13522 } 13523 13524 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13525 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13526 std::string Str; 13527 llvm::raw_string_ostream S(Str); 13528 E->printPretty(S, nullptr, getPrintingPolicy()); 13529 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13530 : diag::warn_cast_nonnull_to_bool; 13531 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13532 << E->getSourceRange() << Range << IsEqual; 13533 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13534 }; 13535 13536 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13537 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13538 if (auto *Callee = Call->getDirectCallee()) { 13539 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13540 ComplainAboutNonnullParamOrCall(A); 13541 return; 13542 } 13543 } 13544 } 13545 13546 // Expect to find a single Decl. Skip anything more complicated. 13547 ValueDecl *D = nullptr; 13548 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13549 D = R->getDecl(); 13550 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13551 D = M->getMemberDecl(); 13552 } 13553 13554 // Weak Decls can be null. 13555 if (!D || D->isWeak()) 13556 return; 13557 13558 // Check for parameter decl with nonnull attribute 13559 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13560 if (getCurFunction() && 13561 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13562 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13563 ComplainAboutNonnullParamOrCall(A); 13564 return; 13565 } 13566 13567 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13568 // Skip function template not specialized yet. 13569 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13570 return; 13571 auto ParamIter = llvm::find(FD->parameters(), PV); 13572 assert(ParamIter != FD->param_end()); 13573 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13574 13575 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13576 if (!NonNull->args_size()) { 13577 ComplainAboutNonnullParamOrCall(NonNull); 13578 return; 13579 } 13580 13581 for (const ParamIdx &ArgNo : NonNull->args()) { 13582 if (ArgNo.getASTIndex() == ParamNo) { 13583 ComplainAboutNonnullParamOrCall(NonNull); 13584 return; 13585 } 13586 } 13587 } 13588 } 13589 } 13590 } 13591 13592 QualType T = D->getType(); 13593 const bool IsArray = T->isArrayType(); 13594 const bool IsFunction = T->isFunctionType(); 13595 13596 // Address of function is used to silence the function warning. 13597 if (IsAddressOf && IsFunction) { 13598 return; 13599 } 13600 13601 // Found nothing. 13602 if (!IsAddressOf && !IsFunction && !IsArray) 13603 return; 13604 13605 // Pretty print the expression for the diagnostic. 13606 std::string Str; 13607 llvm::raw_string_ostream S(Str); 13608 E->printPretty(S, nullptr, getPrintingPolicy()); 13609 13610 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13611 : diag::warn_impcast_pointer_to_bool; 13612 enum { 13613 AddressOf, 13614 FunctionPointer, 13615 ArrayPointer 13616 } DiagType; 13617 if (IsAddressOf) 13618 DiagType = AddressOf; 13619 else if (IsFunction) 13620 DiagType = FunctionPointer; 13621 else if (IsArray) 13622 DiagType = ArrayPointer; 13623 else 13624 llvm_unreachable("Could not determine diagnostic."); 13625 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13626 << Range << IsEqual; 13627 13628 if (!IsFunction) 13629 return; 13630 13631 // Suggest '&' to silence the function warning. 13632 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13633 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13634 13635 // Check to see if '()' fixit should be emitted. 13636 QualType ReturnType; 13637 UnresolvedSet<4> NonTemplateOverloads; 13638 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13639 if (ReturnType.isNull()) 13640 return; 13641 13642 if (IsCompare) { 13643 // There are two cases here. If there is null constant, the only suggest 13644 // for a pointer return type. If the null is 0, then suggest if the return 13645 // type is a pointer or an integer type. 13646 if (!ReturnType->isPointerType()) { 13647 if (NullKind == Expr::NPCK_ZeroExpression || 13648 NullKind == Expr::NPCK_ZeroLiteral) { 13649 if (!ReturnType->isIntegerType()) 13650 return; 13651 } else { 13652 return; 13653 } 13654 } 13655 } else { // !IsCompare 13656 // For function to bool, only suggest if the function pointer has bool 13657 // return type. 13658 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13659 return; 13660 } 13661 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13662 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13663 } 13664 13665 /// Diagnoses "dangerous" implicit conversions within the given 13666 /// expression (which is a full expression). Implements -Wconversion 13667 /// and -Wsign-compare. 13668 /// 13669 /// \param CC the "context" location of the implicit conversion, i.e. 13670 /// the most location of the syntactic entity requiring the implicit 13671 /// conversion 13672 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13673 // Don't diagnose in unevaluated contexts. 13674 if (isUnevaluatedContext()) 13675 return; 13676 13677 // Don't diagnose for value- or type-dependent expressions. 13678 if (E->isTypeDependent() || E->isValueDependent()) 13679 return; 13680 13681 // Check for array bounds violations in cases where the check isn't triggered 13682 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13683 // ArraySubscriptExpr is on the RHS of a variable initialization. 13684 CheckArrayAccess(E); 13685 13686 // This is not the right CC for (e.g.) a variable initialization. 13687 AnalyzeImplicitConversions(*this, E, CC); 13688 } 13689 13690 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13691 /// Input argument E is a logical expression. 13692 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13693 ::CheckBoolLikeConversion(*this, E, CC); 13694 } 13695 13696 /// Diagnose when expression is an integer constant expression and its evaluation 13697 /// results in integer overflow 13698 void Sema::CheckForIntOverflow (Expr *E) { 13699 // Use a work list to deal with nested struct initializers. 13700 SmallVector<Expr *, 2> Exprs(1, E); 13701 13702 do { 13703 Expr *OriginalE = Exprs.pop_back_val(); 13704 Expr *E = OriginalE->IgnoreParenCasts(); 13705 13706 if (isa<BinaryOperator>(E)) { 13707 E->EvaluateForOverflow(Context); 13708 continue; 13709 } 13710 13711 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13712 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13713 else if (isa<ObjCBoxedExpr>(OriginalE)) 13714 E->EvaluateForOverflow(Context); 13715 else if (auto Call = dyn_cast<CallExpr>(E)) 13716 Exprs.append(Call->arg_begin(), Call->arg_end()); 13717 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13718 Exprs.append(Message->arg_begin(), Message->arg_end()); 13719 } while (!Exprs.empty()); 13720 } 13721 13722 namespace { 13723 13724 /// Visitor for expressions which looks for unsequenced operations on the 13725 /// same object. 13726 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13727 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13728 13729 /// A tree of sequenced regions within an expression. Two regions are 13730 /// unsequenced if one is an ancestor or a descendent of the other. When we 13731 /// finish processing an expression with sequencing, such as a comma 13732 /// expression, we fold its tree nodes into its parent, since they are 13733 /// unsequenced with respect to nodes we will visit later. 13734 class SequenceTree { 13735 struct Value { 13736 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13737 unsigned Parent : 31; 13738 unsigned Merged : 1; 13739 }; 13740 SmallVector<Value, 8> Values; 13741 13742 public: 13743 /// A region within an expression which may be sequenced with respect 13744 /// to some other region. 13745 class Seq { 13746 friend class SequenceTree; 13747 13748 unsigned Index; 13749 13750 explicit Seq(unsigned N) : Index(N) {} 13751 13752 public: 13753 Seq() : Index(0) {} 13754 }; 13755 13756 SequenceTree() { Values.push_back(Value(0)); } 13757 Seq root() const { return Seq(0); } 13758 13759 /// Create a new sequence of operations, which is an unsequenced 13760 /// subset of \p Parent. This sequence of operations is sequenced with 13761 /// respect to other children of \p Parent. 13762 Seq allocate(Seq Parent) { 13763 Values.push_back(Value(Parent.Index)); 13764 return Seq(Values.size() - 1); 13765 } 13766 13767 /// Merge a sequence of operations into its parent. 13768 void merge(Seq S) { 13769 Values[S.Index].Merged = true; 13770 } 13771 13772 /// Determine whether two operations are unsequenced. This operation 13773 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13774 /// should have been merged into its parent as appropriate. 13775 bool isUnsequenced(Seq Cur, Seq Old) { 13776 unsigned C = representative(Cur.Index); 13777 unsigned Target = representative(Old.Index); 13778 while (C >= Target) { 13779 if (C == Target) 13780 return true; 13781 C = Values[C].Parent; 13782 } 13783 return false; 13784 } 13785 13786 private: 13787 /// Pick a representative for a sequence. 13788 unsigned representative(unsigned K) { 13789 if (Values[K].Merged) 13790 // Perform path compression as we go. 13791 return Values[K].Parent = representative(Values[K].Parent); 13792 return K; 13793 } 13794 }; 13795 13796 /// An object for which we can track unsequenced uses. 13797 using Object = const NamedDecl *; 13798 13799 /// Different flavors of object usage which we track. We only track the 13800 /// least-sequenced usage of each kind. 13801 enum UsageKind { 13802 /// A read of an object. Multiple unsequenced reads are OK. 13803 UK_Use, 13804 13805 /// A modification of an object which is sequenced before the value 13806 /// computation of the expression, such as ++n in C++. 13807 UK_ModAsValue, 13808 13809 /// A modification of an object which is not sequenced before the value 13810 /// computation of the expression, such as n++. 13811 UK_ModAsSideEffect, 13812 13813 UK_Count = UK_ModAsSideEffect + 1 13814 }; 13815 13816 /// Bundle together a sequencing region and the expression corresponding 13817 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13818 struct Usage { 13819 const Expr *UsageExpr; 13820 SequenceTree::Seq Seq; 13821 13822 Usage() : UsageExpr(nullptr), Seq() {} 13823 }; 13824 13825 struct UsageInfo { 13826 Usage Uses[UK_Count]; 13827 13828 /// Have we issued a diagnostic for this object already? 13829 bool Diagnosed; 13830 13831 UsageInfo() : Uses(), Diagnosed(false) {} 13832 }; 13833 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13834 13835 Sema &SemaRef; 13836 13837 /// Sequenced regions within the expression. 13838 SequenceTree Tree; 13839 13840 /// Declaration modifications and references which we have seen. 13841 UsageInfoMap UsageMap; 13842 13843 /// The region we are currently within. 13844 SequenceTree::Seq Region; 13845 13846 /// Filled in with declarations which were modified as a side-effect 13847 /// (that is, post-increment operations). 13848 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13849 13850 /// Expressions to check later. We defer checking these to reduce 13851 /// stack usage. 13852 SmallVectorImpl<const Expr *> &WorkList; 13853 13854 /// RAII object wrapping the visitation of a sequenced subexpression of an 13855 /// expression. At the end of this process, the side-effects of the evaluation 13856 /// become sequenced with respect to the value computation of the result, so 13857 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13858 /// UK_ModAsValue. 13859 struct SequencedSubexpression { 13860 SequencedSubexpression(SequenceChecker &Self) 13861 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13862 Self.ModAsSideEffect = &ModAsSideEffect; 13863 } 13864 13865 ~SequencedSubexpression() { 13866 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13867 // Add a new usage with usage kind UK_ModAsValue, and then restore 13868 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13869 // the previous one was empty). 13870 UsageInfo &UI = Self.UsageMap[M.first]; 13871 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13872 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13873 SideEffectUsage = M.second; 13874 } 13875 Self.ModAsSideEffect = OldModAsSideEffect; 13876 } 13877 13878 SequenceChecker &Self; 13879 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13880 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13881 }; 13882 13883 /// RAII object wrapping the visitation of a subexpression which we might 13884 /// choose to evaluate as a constant. If any subexpression is evaluated and 13885 /// found to be non-constant, this allows us to suppress the evaluation of 13886 /// the outer expression. 13887 class EvaluationTracker { 13888 public: 13889 EvaluationTracker(SequenceChecker &Self) 13890 : Self(Self), Prev(Self.EvalTracker) { 13891 Self.EvalTracker = this; 13892 } 13893 13894 ~EvaluationTracker() { 13895 Self.EvalTracker = Prev; 13896 if (Prev) 13897 Prev->EvalOK &= EvalOK; 13898 } 13899 13900 bool evaluate(const Expr *E, bool &Result) { 13901 if (!EvalOK || E->isValueDependent()) 13902 return false; 13903 EvalOK = E->EvaluateAsBooleanCondition( 13904 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13905 return EvalOK; 13906 } 13907 13908 private: 13909 SequenceChecker &Self; 13910 EvaluationTracker *Prev; 13911 bool EvalOK = true; 13912 } *EvalTracker = nullptr; 13913 13914 /// Find the object which is produced by the specified expression, 13915 /// if any. 13916 Object getObject(const Expr *E, bool Mod) const { 13917 E = E->IgnoreParenCasts(); 13918 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13919 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13920 return getObject(UO->getSubExpr(), Mod); 13921 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13922 if (BO->getOpcode() == BO_Comma) 13923 return getObject(BO->getRHS(), Mod); 13924 if (Mod && BO->isAssignmentOp()) 13925 return getObject(BO->getLHS(), Mod); 13926 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13927 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13928 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13929 return ME->getMemberDecl(); 13930 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13931 // FIXME: If this is a reference, map through to its value. 13932 return DRE->getDecl(); 13933 return nullptr; 13934 } 13935 13936 /// Note that an object \p O was modified or used by an expression 13937 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13938 /// the object \p O as obtained via the \p UsageMap. 13939 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13940 // Get the old usage for the given object and usage kind. 13941 Usage &U = UI.Uses[UK]; 13942 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13943 // If we have a modification as side effect and are in a sequenced 13944 // subexpression, save the old Usage so that we can restore it later 13945 // in SequencedSubexpression::~SequencedSubexpression. 13946 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13947 ModAsSideEffect->push_back(std::make_pair(O, U)); 13948 // Then record the new usage with the current sequencing region. 13949 U.UsageExpr = UsageExpr; 13950 U.Seq = Region; 13951 } 13952 } 13953 13954 /// Check whether a modification or use of an object \p O in an expression 13955 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13956 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13957 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13958 /// usage and false we are checking for a mod-use unsequenced usage. 13959 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13960 UsageKind OtherKind, bool IsModMod) { 13961 if (UI.Diagnosed) 13962 return; 13963 13964 const Usage &U = UI.Uses[OtherKind]; 13965 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13966 return; 13967 13968 const Expr *Mod = U.UsageExpr; 13969 const Expr *ModOrUse = UsageExpr; 13970 if (OtherKind == UK_Use) 13971 std::swap(Mod, ModOrUse); 13972 13973 SemaRef.DiagRuntimeBehavior( 13974 Mod->getExprLoc(), {Mod, ModOrUse}, 13975 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13976 : diag::warn_unsequenced_mod_use) 13977 << O << SourceRange(ModOrUse->getExprLoc())); 13978 UI.Diagnosed = true; 13979 } 13980 13981 // A note on note{Pre, Post}{Use, Mod}: 13982 // 13983 // (It helps to follow the algorithm with an expression such as 13984 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13985 // operations before C++17 and both are well-defined in C++17). 13986 // 13987 // When visiting a node which uses/modify an object we first call notePreUse 13988 // or notePreMod before visiting its sub-expression(s). At this point the 13989 // children of the current node have not yet been visited and so the eventual 13990 // uses/modifications resulting from the children of the current node have not 13991 // been recorded yet. 13992 // 13993 // We then visit the children of the current node. After that notePostUse or 13994 // notePostMod is called. These will 1) detect an unsequenced modification 13995 // as side effect (as in "k++ + k") and 2) add a new usage with the 13996 // appropriate usage kind. 13997 // 13998 // We also have to be careful that some operation sequences modification as 13999 // side effect as well (for example: || or ,). To account for this we wrap 14000 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14001 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14002 // which record usages which are modifications as side effect, and then 14003 // downgrade them (or more accurately restore the previous usage which was a 14004 // modification as side effect) when exiting the scope of the sequenced 14005 // subexpression. 14006 14007 void notePreUse(Object O, const Expr *UseExpr) { 14008 UsageInfo &UI = UsageMap[O]; 14009 // Uses conflict with other modifications. 14010 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14011 } 14012 14013 void notePostUse(Object O, const Expr *UseExpr) { 14014 UsageInfo &UI = UsageMap[O]; 14015 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14016 /*IsModMod=*/false); 14017 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14018 } 14019 14020 void notePreMod(Object O, const Expr *ModExpr) { 14021 UsageInfo &UI = UsageMap[O]; 14022 // Modifications conflict with other modifications and with uses. 14023 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14024 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14025 } 14026 14027 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14028 UsageInfo &UI = UsageMap[O]; 14029 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14030 /*IsModMod=*/true); 14031 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14032 } 14033 14034 public: 14035 SequenceChecker(Sema &S, const Expr *E, 14036 SmallVectorImpl<const Expr *> &WorkList) 14037 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14038 Visit(E); 14039 // Silence a -Wunused-private-field since WorkList is now unused. 14040 // TODO: Evaluate if it can be used, and if not remove it. 14041 (void)this->WorkList; 14042 } 14043 14044 void VisitStmt(const Stmt *S) { 14045 // Skip all statements which aren't expressions for now. 14046 } 14047 14048 void VisitExpr(const Expr *E) { 14049 // By default, just recurse to evaluated subexpressions. 14050 Base::VisitStmt(E); 14051 } 14052 14053 void VisitCastExpr(const CastExpr *E) { 14054 Object O = Object(); 14055 if (E->getCastKind() == CK_LValueToRValue) 14056 O = getObject(E->getSubExpr(), false); 14057 14058 if (O) 14059 notePreUse(O, E); 14060 VisitExpr(E); 14061 if (O) 14062 notePostUse(O, E); 14063 } 14064 14065 void VisitSequencedExpressions(const Expr *SequencedBefore, 14066 const Expr *SequencedAfter) { 14067 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14068 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14069 SequenceTree::Seq OldRegion = Region; 14070 14071 { 14072 SequencedSubexpression SeqBefore(*this); 14073 Region = BeforeRegion; 14074 Visit(SequencedBefore); 14075 } 14076 14077 Region = AfterRegion; 14078 Visit(SequencedAfter); 14079 14080 Region = OldRegion; 14081 14082 Tree.merge(BeforeRegion); 14083 Tree.merge(AfterRegion); 14084 } 14085 14086 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14087 // C++17 [expr.sub]p1: 14088 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14089 // expression E1 is sequenced before the expression E2. 14090 if (SemaRef.getLangOpts().CPlusPlus17) 14091 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14092 else { 14093 Visit(ASE->getLHS()); 14094 Visit(ASE->getRHS()); 14095 } 14096 } 14097 14098 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14099 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14100 void VisitBinPtrMem(const BinaryOperator *BO) { 14101 // C++17 [expr.mptr.oper]p4: 14102 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14103 // the expression E1 is sequenced before the expression E2. 14104 if (SemaRef.getLangOpts().CPlusPlus17) 14105 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14106 else { 14107 Visit(BO->getLHS()); 14108 Visit(BO->getRHS()); 14109 } 14110 } 14111 14112 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14113 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14114 void VisitBinShlShr(const BinaryOperator *BO) { 14115 // C++17 [expr.shift]p4: 14116 // The expression E1 is sequenced before the expression E2. 14117 if (SemaRef.getLangOpts().CPlusPlus17) 14118 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14119 else { 14120 Visit(BO->getLHS()); 14121 Visit(BO->getRHS()); 14122 } 14123 } 14124 14125 void VisitBinComma(const BinaryOperator *BO) { 14126 // C++11 [expr.comma]p1: 14127 // Every value computation and side effect associated with the left 14128 // expression is sequenced before every value computation and side 14129 // effect associated with the right expression. 14130 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14131 } 14132 14133 void VisitBinAssign(const BinaryOperator *BO) { 14134 SequenceTree::Seq RHSRegion; 14135 SequenceTree::Seq LHSRegion; 14136 if (SemaRef.getLangOpts().CPlusPlus17) { 14137 RHSRegion = Tree.allocate(Region); 14138 LHSRegion = Tree.allocate(Region); 14139 } else { 14140 RHSRegion = Region; 14141 LHSRegion = Region; 14142 } 14143 SequenceTree::Seq OldRegion = Region; 14144 14145 // C++11 [expr.ass]p1: 14146 // [...] the assignment is sequenced after the value computation 14147 // of the right and left operands, [...] 14148 // 14149 // so check it before inspecting the operands and update the 14150 // map afterwards. 14151 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14152 if (O) 14153 notePreMod(O, BO); 14154 14155 if (SemaRef.getLangOpts().CPlusPlus17) { 14156 // C++17 [expr.ass]p1: 14157 // [...] The right operand is sequenced before the left operand. [...] 14158 { 14159 SequencedSubexpression SeqBefore(*this); 14160 Region = RHSRegion; 14161 Visit(BO->getRHS()); 14162 } 14163 14164 Region = LHSRegion; 14165 Visit(BO->getLHS()); 14166 14167 if (O && isa<CompoundAssignOperator>(BO)) 14168 notePostUse(O, BO); 14169 14170 } else { 14171 // C++11 does not specify any sequencing between the LHS and RHS. 14172 Region = LHSRegion; 14173 Visit(BO->getLHS()); 14174 14175 if (O && isa<CompoundAssignOperator>(BO)) 14176 notePostUse(O, BO); 14177 14178 Region = RHSRegion; 14179 Visit(BO->getRHS()); 14180 } 14181 14182 // C++11 [expr.ass]p1: 14183 // the assignment is sequenced [...] before the value computation of the 14184 // assignment expression. 14185 // C11 6.5.16/3 has no such rule. 14186 Region = OldRegion; 14187 if (O) 14188 notePostMod(O, BO, 14189 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14190 : UK_ModAsSideEffect); 14191 if (SemaRef.getLangOpts().CPlusPlus17) { 14192 Tree.merge(RHSRegion); 14193 Tree.merge(LHSRegion); 14194 } 14195 } 14196 14197 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14198 VisitBinAssign(CAO); 14199 } 14200 14201 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14202 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14203 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14204 Object O = getObject(UO->getSubExpr(), true); 14205 if (!O) 14206 return VisitExpr(UO); 14207 14208 notePreMod(O, UO); 14209 Visit(UO->getSubExpr()); 14210 // C++11 [expr.pre.incr]p1: 14211 // the expression ++x is equivalent to x+=1 14212 notePostMod(O, UO, 14213 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14214 : UK_ModAsSideEffect); 14215 } 14216 14217 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14218 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14219 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14220 Object O = getObject(UO->getSubExpr(), true); 14221 if (!O) 14222 return VisitExpr(UO); 14223 14224 notePreMod(O, UO); 14225 Visit(UO->getSubExpr()); 14226 notePostMod(O, UO, UK_ModAsSideEffect); 14227 } 14228 14229 void VisitBinLOr(const BinaryOperator *BO) { 14230 // C++11 [expr.log.or]p2: 14231 // If the second expression is evaluated, every value computation and 14232 // side effect associated with the first expression is sequenced before 14233 // every value computation and side effect associated with the 14234 // second expression. 14235 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14236 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14237 SequenceTree::Seq OldRegion = Region; 14238 14239 EvaluationTracker Eval(*this); 14240 { 14241 SequencedSubexpression Sequenced(*this); 14242 Region = LHSRegion; 14243 Visit(BO->getLHS()); 14244 } 14245 14246 // C++11 [expr.log.or]p1: 14247 // [...] the second operand is not evaluated if the first operand 14248 // evaluates to true. 14249 bool EvalResult = false; 14250 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14251 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14252 if (ShouldVisitRHS) { 14253 Region = RHSRegion; 14254 Visit(BO->getRHS()); 14255 } 14256 14257 Region = OldRegion; 14258 Tree.merge(LHSRegion); 14259 Tree.merge(RHSRegion); 14260 } 14261 14262 void VisitBinLAnd(const BinaryOperator *BO) { 14263 // C++11 [expr.log.and]p2: 14264 // If the second expression is evaluated, every value computation and 14265 // side effect associated with the first expression is sequenced before 14266 // every value computation and side effect associated with the 14267 // second expression. 14268 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14269 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14270 SequenceTree::Seq OldRegion = Region; 14271 14272 EvaluationTracker Eval(*this); 14273 { 14274 SequencedSubexpression Sequenced(*this); 14275 Region = LHSRegion; 14276 Visit(BO->getLHS()); 14277 } 14278 14279 // C++11 [expr.log.and]p1: 14280 // [...] the second operand is not evaluated if the first operand is false. 14281 bool EvalResult = false; 14282 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14283 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14284 if (ShouldVisitRHS) { 14285 Region = RHSRegion; 14286 Visit(BO->getRHS()); 14287 } 14288 14289 Region = OldRegion; 14290 Tree.merge(LHSRegion); 14291 Tree.merge(RHSRegion); 14292 } 14293 14294 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14295 // C++11 [expr.cond]p1: 14296 // [...] Every value computation and side effect associated with the first 14297 // expression is sequenced before every value computation and side effect 14298 // associated with the second or third expression. 14299 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14300 14301 // No sequencing is specified between the true and false expression. 14302 // However since exactly one of both is going to be evaluated we can 14303 // consider them to be sequenced. This is needed to avoid warning on 14304 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14305 // both the true and false expressions because we can't evaluate x. 14306 // This will still allow us to detect an expression like (pre C++17) 14307 // "(x ? y += 1 : y += 2) = y". 14308 // 14309 // We don't wrap the visitation of the true and false expression with 14310 // SequencedSubexpression because we don't want to downgrade modifications 14311 // as side effect in the true and false expressions after the visition 14312 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14313 // not warn between the two "y++", but we should warn between the "y++" 14314 // and the "y". 14315 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14316 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14317 SequenceTree::Seq OldRegion = Region; 14318 14319 EvaluationTracker Eval(*this); 14320 { 14321 SequencedSubexpression Sequenced(*this); 14322 Region = ConditionRegion; 14323 Visit(CO->getCond()); 14324 } 14325 14326 // C++11 [expr.cond]p1: 14327 // [...] The first expression is contextually converted to bool (Clause 4). 14328 // It is evaluated and if it is true, the result of the conditional 14329 // expression is the value of the second expression, otherwise that of the 14330 // third expression. Only one of the second and third expressions is 14331 // evaluated. [...] 14332 bool EvalResult = false; 14333 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14334 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14335 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14336 if (ShouldVisitTrueExpr) { 14337 Region = TrueRegion; 14338 Visit(CO->getTrueExpr()); 14339 } 14340 if (ShouldVisitFalseExpr) { 14341 Region = FalseRegion; 14342 Visit(CO->getFalseExpr()); 14343 } 14344 14345 Region = OldRegion; 14346 Tree.merge(ConditionRegion); 14347 Tree.merge(TrueRegion); 14348 Tree.merge(FalseRegion); 14349 } 14350 14351 void VisitCallExpr(const CallExpr *CE) { 14352 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14353 14354 if (CE->isUnevaluatedBuiltinCall(Context)) 14355 return; 14356 14357 // C++11 [intro.execution]p15: 14358 // When calling a function [...], every value computation and side effect 14359 // associated with any argument expression, or with the postfix expression 14360 // designating the called function, is sequenced before execution of every 14361 // expression or statement in the body of the function [and thus before 14362 // the value computation of its result]. 14363 SequencedSubexpression Sequenced(*this); 14364 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14365 // C++17 [expr.call]p5 14366 // The postfix-expression is sequenced before each expression in the 14367 // expression-list and any default argument. [...] 14368 SequenceTree::Seq CalleeRegion; 14369 SequenceTree::Seq OtherRegion; 14370 if (SemaRef.getLangOpts().CPlusPlus17) { 14371 CalleeRegion = Tree.allocate(Region); 14372 OtherRegion = Tree.allocate(Region); 14373 } else { 14374 CalleeRegion = Region; 14375 OtherRegion = Region; 14376 } 14377 SequenceTree::Seq OldRegion = Region; 14378 14379 // Visit the callee expression first. 14380 Region = CalleeRegion; 14381 if (SemaRef.getLangOpts().CPlusPlus17) { 14382 SequencedSubexpression Sequenced(*this); 14383 Visit(CE->getCallee()); 14384 } else { 14385 Visit(CE->getCallee()); 14386 } 14387 14388 // Then visit the argument expressions. 14389 Region = OtherRegion; 14390 for (const Expr *Argument : CE->arguments()) 14391 Visit(Argument); 14392 14393 Region = OldRegion; 14394 if (SemaRef.getLangOpts().CPlusPlus17) { 14395 Tree.merge(CalleeRegion); 14396 Tree.merge(OtherRegion); 14397 } 14398 }); 14399 } 14400 14401 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14402 // C++17 [over.match.oper]p2: 14403 // [...] the operator notation is first transformed to the equivalent 14404 // function-call notation as summarized in Table 12 (where @ denotes one 14405 // of the operators covered in the specified subclause). However, the 14406 // operands are sequenced in the order prescribed for the built-in 14407 // operator (Clause 8). 14408 // 14409 // From the above only overloaded binary operators and overloaded call 14410 // operators have sequencing rules in C++17 that we need to handle 14411 // separately. 14412 if (!SemaRef.getLangOpts().CPlusPlus17 || 14413 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14414 return VisitCallExpr(CXXOCE); 14415 14416 enum { 14417 NoSequencing, 14418 LHSBeforeRHS, 14419 RHSBeforeLHS, 14420 LHSBeforeRest 14421 } SequencingKind; 14422 switch (CXXOCE->getOperator()) { 14423 case OO_Equal: 14424 case OO_PlusEqual: 14425 case OO_MinusEqual: 14426 case OO_StarEqual: 14427 case OO_SlashEqual: 14428 case OO_PercentEqual: 14429 case OO_CaretEqual: 14430 case OO_AmpEqual: 14431 case OO_PipeEqual: 14432 case OO_LessLessEqual: 14433 case OO_GreaterGreaterEqual: 14434 SequencingKind = RHSBeforeLHS; 14435 break; 14436 14437 case OO_LessLess: 14438 case OO_GreaterGreater: 14439 case OO_AmpAmp: 14440 case OO_PipePipe: 14441 case OO_Comma: 14442 case OO_ArrowStar: 14443 case OO_Subscript: 14444 SequencingKind = LHSBeforeRHS; 14445 break; 14446 14447 case OO_Call: 14448 SequencingKind = LHSBeforeRest; 14449 break; 14450 14451 default: 14452 SequencingKind = NoSequencing; 14453 break; 14454 } 14455 14456 if (SequencingKind == NoSequencing) 14457 return VisitCallExpr(CXXOCE); 14458 14459 // This is a call, so all subexpressions are sequenced before the result. 14460 SequencedSubexpression Sequenced(*this); 14461 14462 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14463 assert(SemaRef.getLangOpts().CPlusPlus17 && 14464 "Should only get there with C++17 and above!"); 14465 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14466 "Should only get there with an overloaded binary operator" 14467 " or an overloaded call operator!"); 14468 14469 if (SequencingKind == LHSBeforeRest) { 14470 assert(CXXOCE->getOperator() == OO_Call && 14471 "We should only have an overloaded call operator here!"); 14472 14473 // This is very similar to VisitCallExpr, except that we only have the 14474 // C++17 case. The postfix-expression is the first argument of the 14475 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14476 // are in the following arguments. 14477 // 14478 // Note that we intentionally do not visit the callee expression since 14479 // it is just a decayed reference to a function. 14480 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14481 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14482 SequenceTree::Seq OldRegion = Region; 14483 14484 assert(CXXOCE->getNumArgs() >= 1 && 14485 "An overloaded call operator must have at least one argument" 14486 " for the postfix-expression!"); 14487 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14488 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14489 CXXOCE->getNumArgs() - 1); 14490 14491 // Visit the postfix-expression first. 14492 { 14493 Region = PostfixExprRegion; 14494 SequencedSubexpression Sequenced(*this); 14495 Visit(PostfixExpr); 14496 } 14497 14498 // Then visit the argument expressions. 14499 Region = ArgsRegion; 14500 for (const Expr *Arg : Args) 14501 Visit(Arg); 14502 14503 Region = OldRegion; 14504 Tree.merge(PostfixExprRegion); 14505 Tree.merge(ArgsRegion); 14506 } else { 14507 assert(CXXOCE->getNumArgs() == 2 && 14508 "Should only have two arguments here!"); 14509 assert((SequencingKind == LHSBeforeRHS || 14510 SequencingKind == RHSBeforeLHS) && 14511 "Unexpected sequencing kind!"); 14512 14513 // We do not visit the callee expression since it is just a decayed 14514 // reference to a function. 14515 const Expr *E1 = CXXOCE->getArg(0); 14516 const Expr *E2 = CXXOCE->getArg(1); 14517 if (SequencingKind == RHSBeforeLHS) 14518 std::swap(E1, E2); 14519 14520 return VisitSequencedExpressions(E1, E2); 14521 } 14522 }); 14523 } 14524 14525 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14526 // This is a call, so all subexpressions are sequenced before the result. 14527 SequencedSubexpression Sequenced(*this); 14528 14529 if (!CCE->isListInitialization()) 14530 return VisitExpr(CCE); 14531 14532 // In C++11, list initializations are sequenced. 14533 SmallVector<SequenceTree::Seq, 32> Elts; 14534 SequenceTree::Seq Parent = Region; 14535 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14536 E = CCE->arg_end(); 14537 I != E; ++I) { 14538 Region = Tree.allocate(Parent); 14539 Elts.push_back(Region); 14540 Visit(*I); 14541 } 14542 14543 // Forget that the initializers are sequenced. 14544 Region = Parent; 14545 for (unsigned I = 0; I < Elts.size(); ++I) 14546 Tree.merge(Elts[I]); 14547 } 14548 14549 void VisitInitListExpr(const InitListExpr *ILE) { 14550 if (!SemaRef.getLangOpts().CPlusPlus11) 14551 return VisitExpr(ILE); 14552 14553 // In C++11, list initializations are sequenced. 14554 SmallVector<SequenceTree::Seq, 32> Elts; 14555 SequenceTree::Seq Parent = Region; 14556 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14557 const Expr *E = ILE->getInit(I); 14558 if (!E) 14559 continue; 14560 Region = Tree.allocate(Parent); 14561 Elts.push_back(Region); 14562 Visit(E); 14563 } 14564 14565 // Forget that the initializers are sequenced. 14566 Region = Parent; 14567 for (unsigned I = 0; I < Elts.size(); ++I) 14568 Tree.merge(Elts[I]); 14569 } 14570 }; 14571 14572 } // namespace 14573 14574 void Sema::CheckUnsequencedOperations(const Expr *E) { 14575 SmallVector<const Expr *, 8> WorkList; 14576 WorkList.push_back(E); 14577 while (!WorkList.empty()) { 14578 const Expr *Item = WorkList.pop_back_val(); 14579 SequenceChecker(*this, Item, WorkList); 14580 } 14581 } 14582 14583 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14584 bool IsConstexpr) { 14585 llvm::SaveAndRestore<bool> ConstantContext( 14586 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14587 CheckImplicitConversions(E, CheckLoc); 14588 if (!E->isInstantiationDependent()) 14589 CheckUnsequencedOperations(E); 14590 if (!IsConstexpr && !E->isValueDependent()) 14591 CheckForIntOverflow(E); 14592 DiagnoseMisalignedMembers(); 14593 } 14594 14595 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14596 FieldDecl *BitField, 14597 Expr *Init) { 14598 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14599 } 14600 14601 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14602 SourceLocation Loc) { 14603 if (!PType->isVariablyModifiedType()) 14604 return; 14605 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14606 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14607 return; 14608 } 14609 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14610 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14611 return; 14612 } 14613 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14614 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14615 return; 14616 } 14617 14618 const ArrayType *AT = S.Context.getAsArrayType(PType); 14619 if (!AT) 14620 return; 14621 14622 if (AT->getSizeModifier() != ArrayType::Star) { 14623 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14624 return; 14625 } 14626 14627 S.Diag(Loc, diag::err_array_star_in_function_definition); 14628 } 14629 14630 /// CheckParmsForFunctionDef - Check that the parameters of the given 14631 /// function are appropriate for the definition of a function. This 14632 /// takes care of any checks that cannot be performed on the 14633 /// declaration itself, e.g., that the types of each of the function 14634 /// parameters are complete. 14635 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14636 bool CheckParameterNames) { 14637 bool HasInvalidParm = false; 14638 for (ParmVarDecl *Param : Parameters) { 14639 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14640 // function declarator that is part of a function definition of 14641 // that function shall not have incomplete type. 14642 // 14643 // This is also C++ [dcl.fct]p6. 14644 if (!Param->isInvalidDecl() && 14645 RequireCompleteType(Param->getLocation(), Param->getType(), 14646 diag::err_typecheck_decl_incomplete_type)) { 14647 Param->setInvalidDecl(); 14648 HasInvalidParm = true; 14649 } 14650 14651 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14652 // declaration of each parameter shall include an identifier. 14653 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14654 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14655 // Diagnose this as an extension in C17 and earlier. 14656 if (!getLangOpts().C2x) 14657 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14658 } 14659 14660 // C99 6.7.5.3p12: 14661 // If the function declarator is not part of a definition of that 14662 // function, parameters may have incomplete type and may use the [*] 14663 // notation in their sequences of declarator specifiers to specify 14664 // variable length array types. 14665 QualType PType = Param->getOriginalType(); 14666 // FIXME: This diagnostic should point the '[*]' if source-location 14667 // information is added for it. 14668 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14669 14670 // If the parameter is a c++ class type and it has to be destructed in the 14671 // callee function, declare the destructor so that it can be called by the 14672 // callee function. Do not perform any direct access check on the dtor here. 14673 if (!Param->isInvalidDecl()) { 14674 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14675 if (!ClassDecl->isInvalidDecl() && 14676 !ClassDecl->hasIrrelevantDestructor() && 14677 !ClassDecl->isDependentContext() && 14678 ClassDecl->isParamDestroyedInCallee()) { 14679 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14680 MarkFunctionReferenced(Param->getLocation(), Destructor); 14681 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14682 } 14683 } 14684 } 14685 14686 // Parameters with the pass_object_size attribute only need to be marked 14687 // constant at function definitions. Because we lack information about 14688 // whether we're on a declaration or definition when we're instantiating the 14689 // attribute, we need to check for constness here. 14690 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14691 if (!Param->getType().isConstQualified()) 14692 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14693 << Attr->getSpelling() << 1; 14694 14695 // Check for parameter names shadowing fields from the class. 14696 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14697 // The owning context for the parameter should be the function, but we 14698 // want to see if this function's declaration context is a record. 14699 DeclContext *DC = Param->getDeclContext(); 14700 if (DC && DC->isFunctionOrMethod()) { 14701 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14702 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14703 RD, /*DeclIsField*/ false); 14704 } 14705 } 14706 } 14707 14708 return HasInvalidParm; 14709 } 14710 14711 Optional<std::pair<CharUnits, CharUnits>> 14712 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14713 14714 /// Compute the alignment and offset of the base class object given the 14715 /// derived-to-base cast expression and the alignment and offset of the derived 14716 /// class object. 14717 static std::pair<CharUnits, CharUnits> 14718 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14719 CharUnits BaseAlignment, CharUnits Offset, 14720 ASTContext &Ctx) { 14721 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14722 ++PathI) { 14723 const CXXBaseSpecifier *Base = *PathI; 14724 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14725 if (Base->isVirtual()) { 14726 // The complete object may have a lower alignment than the non-virtual 14727 // alignment of the base, in which case the base may be misaligned. Choose 14728 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14729 // conservative lower bound of the complete object alignment. 14730 CharUnits NonVirtualAlignment = 14731 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14732 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14733 Offset = CharUnits::Zero(); 14734 } else { 14735 const ASTRecordLayout &RL = 14736 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14737 Offset += RL.getBaseClassOffset(BaseDecl); 14738 } 14739 DerivedType = Base->getType(); 14740 } 14741 14742 return std::make_pair(BaseAlignment, Offset); 14743 } 14744 14745 /// Compute the alignment and offset of a binary additive operator. 14746 static Optional<std::pair<CharUnits, CharUnits>> 14747 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14748 bool IsSub, ASTContext &Ctx) { 14749 QualType PointeeType = PtrE->getType()->getPointeeType(); 14750 14751 if (!PointeeType->isConstantSizeType()) 14752 return llvm::None; 14753 14754 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14755 14756 if (!P) 14757 return llvm::None; 14758 14759 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14760 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14761 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14762 if (IsSub) 14763 Offset = -Offset; 14764 return std::make_pair(P->first, P->second + Offset); 14765 } 14766 14767 // If the integer expression isn't a constant expression, compute the lower 14768 // bound of the alignment using the alignment and offset of the pointer 14769 // expression and the element size. 14770 return std::make_pair( 14771 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14772 CharUnits::Zero()); 14773 } 14774 14775 /// This helper function takes an lvalue expression and returns the alignment of 14776 /// a VarDecl and a constant offset from the VarDecl. 14777 Optional<std::pair<CharUnits, CharUnits>> 14778 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14779 E = E->IgnoreParens(); 14780 switch (E->getStmtClass()) { 14781 default: 14782 break; 14783 case Stmt::CStyleCastExprClass: 14784 case Stmt::CXXStaticCastExprClass: 14785 case Stmt::ImplicitCastExprClass: { 14786 auto *CE = cast<CastExpr>(E); 14787 const Expr *From = CE->getSubExpr(); 14788 switch (CE->getCastKind()) { 14789 default: 14790 break; 14791 case CK_NoOp: 14792 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14793 case CK_UncheckedDerivedToBase: 14794 case CK_DerivedToBase: { 14795 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14796 if (!P) 14797 break; 14798 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14799 P->second, Ctx); 14800 } 14801 } 14802 break; 14803 } 14804 case Stmt::ArraySubscriptExprClass: { 14805 auto *ASE = cast<ArraySubscriptExpr>(E); 14806 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14807 false, Ctx); 14808 } 14809 case Stmt::DeclRefExprClass: { 14810 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14811 // FIXME: If VD is captured by copy or is an escaping __block variable, 14812 // use the alignment of VD's type. 14813 if (!VD->getType()->isReferenceType()) 14814 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14815 if (VD->hasInit()) 14816 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14817 } 14818 break; 14819 } 14820 case Stmt::MemberExprClass: { 14821 auto *ME = cast<MemberExpr>(E); 14822 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14823 if (!FD || FD->getType()->isReferenceType() || 14824 FD->getParent()->isInvalidDecl()) 14825 break; 14826 Optional<std::pair<CharUnits, CharUnits>> P; 14827 if (ME->isArrow()) 14828 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14829 else 14830 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14831 if (!P) 14832 break; 14833 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14834 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14835 return std::make_pair(P->first, 14836 P->second + CharUnits::fromQuantity(Offset)); 14837 } 14838 case Stmt::UnaryOperatorClass: { 14839 auto *UO = cast<UnaryOperator>(E); 14840 switch (UO->getOpcode()) { 14841 default: 14842 break; 14843 case UO_Deref: 14844 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14845 } 14846 break; 14847 } 14848 case Stmt::BinaryOperatorClass: { 14849 auto *BO = cast<BinaryOperator>(E); 14850 auto Opcode = BO->getOpcode(); 14851 switch (Opcode) { 14852 default: 14853 break; 14854 case BO_Comma: 14855 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14856 } 14857 break; 14858 } 14859 } 14860 return llvm::None; 14861 } 14862 14863 /// This helper function takes a pointer expression and returns the alignment of 14864 /// a VarDecl and a constant offset from the VarDecl. 14865 Optional<std::pair<CharUnits, CharUnits>> 14866 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14867 E = E->IgnoreParens(); 14868 switch (E->getStmtClass()) { 14869 default: 14870 break; 14871 case Stmt::CStyleCastExprClass: 14872 case Stmt::CXXStaticCastExprClass: 14873 case Stmt::ImplicitCastExprClass: { 14874 auto *CE = cast<CastExpr>(E); 14875 const Expr *From = CE->getSubExpr(); 14876 switch (CE->getCastKind()) { 14877 default: 14878 break; 14879 case CK_NoOp: 14880 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14881 case CK_ArrayToPointerDecay: 14882 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14883 case CK_UncheckedDerivedToBase: 14884 case CK_DerivedToBase: { 14885 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14886 if (!P) 14887 break; 14888 return getDerivedToBaseAlignmentAndOffset( 14889 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14890 } 14891 } 14892 break; 14893 } 14894 case Stmt::CXXThisExprClass: { 14895 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14896 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14897 return std::make_pair(Alignment, CharUnits::Zero()); 14898 } 14899 case Stmt::UnaryOperatorClass: { 14900 auto *UO = cast<UnaryOperator>(E); 14901 if (UO->getOpcode() == UO_AddrOf) 14902 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14903 break; 14904 } 14905 case Stmt::BinaryOperatorClass: { 14906 auto *BO = cast<BinaryOperator>(E); 14907 auto Opcode = BO->getOpcode(); 14908 switch (Opcode) { 14909 default: 14910 break; 14911 case BO_Add: 14912 case BO_Sub: { 14913 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14914 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14915 std::swap(LHS, RHS); 14916 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14917 Ctx); 14918 } 14919 case BO_Comma: 14920 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14921 } 14922 break; 14923 } 14924 } 14925 return llvm::None; 14926 } 14927 14928 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14929 // See if we can compute the alignment of a VarDecl and an offset from it. 14930 Optional<std::pair<CharUnits, CharUnits>> P = 14931 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14932 14933 if (P) 14934 return P->first.alignmentAtOffset(P->second); 14935 14936 // If that failed, return the type's alignment. 14937 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14938 } 14939 14940 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14941 /// pointer cast increases the alignment requirements. 14942 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14943 // This is actually a lot of work to potentially be doing on every 14944 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14945 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14946 return; 14947 14948 // Ignore dependent types. 14949 if (T->isDependentType() || Op->getType()->isDependentType()) 14950 return; 14951 14952 // Require that the destination be a pointer type. 14953 const PointerType *DestPtr = T->getAs<PointerType>(); 14954 if (!DestPtr) return; 14955 14956 // If the destination has alignment 1, we're done. 14957 QualType DestPointee = DestPtr->getPointeeType(); 14958 if (DestPointee->isIncompleteType()) return; 14959 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14960 if (DestAlign.isOne()) return; 14961 14962 // Require that the source be a pointer type. 14963 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14964 if (!SrcPtr) return; 14965 QualType SrcPointee = SrcPtr->getPointeeType(); 14966 14967 // Explicitly allow casts from cv void*. We already implicitly 14968 // allowed casts to cv void*, since they have alignment 1. 14969 // Also allow casts involving incomplete types, which implicitly 14970 // includes 'void'. 14971 if (SrcPointee->isIncompleteType()) return; 14972 14973 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14974 14975 if (SrcAlign >= DestAlign) return; 14976 14977 Diag(TRange.getBegin(), diag::warn_cast_align) 14978 << Op->getType() << T 14979 << static_cast<unsigned>(SrcAlign.getQuantity()) 14980 << static_cast<unsigned>(DestAlign.getQuantity()) 14981 << TRange << Op->getSourceRange(); 14982 } 14983 14984 /// Check whether this array fits the idiom of a size-one tail padded 14985 /// array member of a struct. 14986 /// 14987 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14988 /// commonly used to emulate flexible arrays in C89 code. 14989 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14990 const NamedDecl *ND) { 14991 if (Size != 1 || !ND) return false; 14992 14993 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14994 if (!FD) return false; 14995 14996 // Don't consider sizes resulting from macro expansions or template argument 14997 // substitution to form C89 tail-padded arrays. 14998 14999 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15000 while (TInfo) { 15001 TypeLoc TL = TInfo->getTypeLoc(); 15002 // Look through typedefs. 15003 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15004 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15005 TInfo = TDL->getTypeSourceInfo(); 15006 continue; 15007 } 15008 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15009 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15010 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15011 return false; 15012 } 15013 break; 15014 } 15015 15016 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15017 if (!RD) return false; 15018 if (RD->isUnion()) return false; 15019 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15020 if (!CRD->isStandardLayout()) return false; 15021 } 15022 15023 // See if this is the last field decl in the record. 15024 const Decl *D = FD; 15025 while ((D = D->getNextDeclInContext())) 15026 if (isa<FieldDecl>(D)) 15027 return false; 15028 return true; 15029 } 15030 15031 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15032 const ArraySubscriptExpr *ASE, 15033 bool AllowOnePastEnd, bool IndexNegated) { 15034 // Already diagnosed by the constant evaluator. 15035 if (isConstantEvaluated()) 15036 return; 15037 15038 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15039 if (IndexExpr->isValueDependent()) 15040 return; 15041 15042 const Type *EffectiveType = 15043 BaseExpr->getType()->getPointeeOrArrayElementType(); 15044 BaseExpr = BaseExpr->IgnoreParenCasts(); 15045 const ConstantArrayType *ArrayTy = 15046 Context.getAsConstantArrayType(BaseExpr->getType()); 15047 15048 const Type *BaseType = 15049 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15050 bool IsUnboundedArray = (BaseType == nullptr); 15051 if (EffectiveType->isDependentType() || 15052 (!IsUnboundedArray && BaseType->isDependentType())) 15053 return; 15054 15055 Expr::EvalResult Result; 15056 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15057 return; 15058 15059 llvm::APSInt index = Result.Val.getInt(); 15060 if (IndexNegated) { 15061 index.setIsUnsigned(false); 15062 index = -index; 15063 } 15064 15065 const NamedDecl *ND = nullptr; 15066 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15067 ND = DRE->getDecl(); 15068 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15069 ND = ME->getMemberDecl(); 15070 15071 if (IsUnboundedArray) { 15072 if (index.isUnsigned() || !index.isNegative()) { 15073 const auto &ASTC = getASTContext(); 15074 unsigned AddrBits = 15075 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15076 EffectiveType->getCanonicalTypeInternal())); 15077 if (index.getBitWidth() < AddrBits) 15078 index = index.zext(AddrBits); 15079 Optional<CharUnits> ElemCharUnits = 15080 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15081 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15082 // pointer) bounds-checking isn't meaningful. 15083 if (!ElemCharUnits) 15084 return; 15085 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15086 // If index has more active bits than address space, we already know 15087 // we have a bounds violation to warn about. Otherwise, compute 15088 // address of (index + 1)th element, and warn about bounds violation 15089 // only if that address exceeds address space. 15090 if (index.getActiveBits() <= AddrBits) { 15091 bool Overflow; 15092 llvm::APInt Product(index); 15093 Product += 1; 15094 Product = Product.umul_ov(ElemBytes, Overflow); 15095 if (!Overflow && Product.getActiveBits() <= AddrBits) 15096 return; 15097 } 15098 15099 // Need to compute max possible elements in address space, since that 15100 // is included in diag message. 15101 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15102 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15103 MaxElems += 1; 15104 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15105 MaxElems = MaxElems.udiv(ElemBytes); 15106 15107 unsigned DiagID = 15108 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15109 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15110 15111 // Diag message shows element size in bits and in "bytes" (platform- 15112 // dependent CharUnits) 15113 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15114 PDiag(DiagID) 15115 << toString(index, 10, true) << AddrBits 15116 << (unsigned)ASTC.toBits(*ElemCharUnits) 15117 << toString(ElemBytes, 10, false) 15118 << toString(MaxElems, 10, false) 15119 << (unsigned)MaxElems.getLimitedValue(~0U) 15120 << IndexExpr->getSourceRange()); 15121 15122 if (!ND) { 15123 // Try harder to find a NamedDecl to point at in the note. 15124 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15125 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15126 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15127 ND = DRE->getDecl(); 15128 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15129 ND = ME->getMemberDecl(); 15130 } 15131 15132 if (ND) 15133 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15134 PDiag(diag::note_array_declared_here) << ND); 15135 } 15136 return; 15137 } 15138 15139 if (index.isUnsigned() || !index.isNegative()) { 15140 // It is possible that the type of the base expression after 15141 // IgnoreParenCasts is incomplete, even though the type of the base 15142 // expression before IgnoreParenCasts is complete (see PR39746 for an 15143 // example). In this case we have no information about whether the array 15144 // access exceeds the array bounds. However we can still diagnose an array 15145 // access which precedes the array bounds. 15146 if (BaseType->isIncompleteType()) 15147 return; 15148 15149 llvm::APInt size = ArrayTy->getSize(); 15150 if (!size.isStrictlyPositive()) 15151 return; 15152 15153 if (BaseType != EffectiveType) { 15154 // Make sure we're comparing apples to apples when comparing index to size 15155 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15156 uint64_t array_typesize = Context.getTypeSize(BaseType); 15157 // Handle ptrarith_typesize being zero, such as when casting to void* 15158 if (!ptrarith_typesize) ptrarith_typesize = 1; 15159 if (ptrarith_typesize != array_typesize) { 15160 // There's a cast to a different size type involved 15161 uint64_t ratio = array_typesize / ptrarith_typesize; 15162 // TODO: Be smarter about handling cases where array_typesize is not a 15163 // multiple of ptrarith_typesize 15164 if (ptrarith_typesize * ratio == array_typesize) 15165 size *= llvm::APInt(size.getBitWidth(), ratio); 15166 } 15167 } 15168 15169 if (size.getBitWidth() > index.getBitWidth()) 15170 index = index.zext(size.getBitWidth()); 15171 else if (size.getBitWidth() < index.getBitWidth()) 15172 size = size.zext(index.getBitWidth()); 15173 15174 // For array subscripting the index must be less than size, but for pointer 15175 // arithmetic also allow the index (offset) to be equal to size since 15176 // computing the next address after the end of the array is legal and 15177 // commonly done e.g. in C++ iterators and range-based for loops. 15178 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15179 return; 15180 15181 // Also don't warn for arrays of size 1 which are members of some 15182 // structure. These are often used to approximate flexible arrays in C89 15183 // code. 15184 if (IsTailPaddedMemberArray(*this, size, ND)) 15185 return; 15186 15187 // Suppress the warning if the subscript expression (as identified by the 15188 // ']' location) and the index expression are both from macro expansions 15189 // within a system header. 15190 if (ASE) { 15191 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15192 ASE->getRBracketLoc()); 15193 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15194 SourceLocation IndexLoc = 15195 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15196 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15197 return; 15198 } 15199 } 15200 15201 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15202 : diag::warn_ptr_arith_exceeds_bounds; 15203 15204 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15205 PDiag(DiagID) << toString(index, 10, true) 15206 << toString(size, 10, true) 15207 << (unsigned)size.getLimitedValue(~0U) 15208 << IndexExpr->getSourceRange()); 15209 } else { 15210 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15211 if (!ASE) { 15212 DiagID = diag::warn_ptr_arith_precedes_bounds; 15213 if (index.isNegative()) index = -index; 15214 } 15215 15216 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15217 PDiag(DiagID) << toString(index, 10, true) 15218 << IndexExpr->getSourceRange()); 15219 } 15220 15221 if (!ND) { 15222 // Try harder to find a NamedDecl to point at in the note. 15223 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15224 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15225 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15226 ND = DRE->getDecl(); 15227 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15228 ND = ME->getMemberDecl(); 15229 } 15230 15231 if (ND) 15232 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15233 PDiag(diag::note_array_declared_here) << ND); 15234 } 15235 15236 void Sema::CheckArrayAccess(const Expr *expr) { 15237 int AllowOnePastEnd = 0; 15238 while (expr) { 15239 expr = expr->IgnoreParenImpCasts(); 15240 switch (expr->getStmtClass()) { 15241 case Stmt::ArraySubscriptExprClass: { 15242 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15243 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15244 AllowOnePastEnd > 0); 15245 expr = ASE->getBase(); 15246 break; 15247 } 15248 case Stmt::MemberExprClass: { 15249 expr = cast<MemberExpr>(expr)->getBase(); 15250 break; 15251 } 15252 case Stmt::OMPArraySectionExprClass: { 15253 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15254 if (ASE->getLowerBound()) 15255 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15256 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15257 return; 15258 } 15259 case Stmt::UnaryOperatorClass: { 15260 // Only unwrap the * and & unary operators 15261 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15262 expr = UO->getSubExpr(); 15263 switch (UO->getOpcode()) { 15264 case UO_AddrOf: 15265 AllowOnePastEnd++; 15266 break; 15267 case UO_Deref: 15268 AllowOnePastEnd--; 15269 break; 15270 default: 15271 return; 15272 } 15273 break; 15274 } 15275 case Stmt::ConditionalOperatorClass: { 15276 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15277 if (const Expr *lhs = cond->getLHS()) 15278 CheckArrayAccess(lhs); 15279 if (const Expr *rhs = cond->getRHS()) 15280 CheckArrayAccess(rhs); 15281 return; 15282 } 15283 case Stmt::CXXOperatorCallExprClass: { 15284 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15285 for (const auto *Arg : OCE->arguments()) 15286 CheckArrayAccess(Arg); 15287 return; 15288 } 15289 default: 15290 return; 15291 } 15292 } 15293 } 15294 15295 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15296 15297 namespace { 15298 15299 struct RetainCycleOwner { 15300 VarDecl *Variable = nullptr; 15301 SourceRange Range; 15302 SourceLocation Loc; 15303 bool Indirect = false; 15304 15305 RetainCycleOwner() = default; 15306 15307 void setLocsFrom(Expr *e) { 15308 Loc = e->getExprLoc(); 15309 Range = e->getSourceRange(); 15310 } 15311 }; 15312 15313 } // namespace 15314 15315 /// Consider whether capturing the given variable can possibly lead to 15316 /// a retain cycle. 15317 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15318 // In ARC, it's captured strongly iff the variable has __strong 15319 // lifetime. In MRR, it's captured strongly if the variable is 15320 // __block and has an appropriate type. 15321 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15322 return false; 15323 15324 owner.Variable = var; 15325 if (ref) 15326 owner.setLocsFrom(ref); 15327 return true; 15328 } 15329 15330 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15331 while (true) { 15332 e = e->IgnoreParens(); 15333 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15334 switch (cast->getCastKind()) { 15335 case CK_BitCast: 15336 case CK_LValueBitCast: 15337 case CK_LValueToRValue: 15338 case CK_ARCReclaimReturnedObject: 15339 e = cast->getSubExpr(); 15340 continue; 15341 15342 default: 15343 return false; 15344 } 15345 } 15346 15347 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15348 ObjCIvarDecl *ivar = ref->getDecl(); 15349 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15350 return false; 15351 15352 // Try to find a retain cycle in the base. 15353 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15354 return false; 15355 15356 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15357 owner.Indirect = true; 15358 return true; 15359 } 15360 15361 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15362 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15363 if (!var) return false; 15364 return considerVariable(var, ref, owner); 15365 } 15366 15367 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15368 if (member->isArrow()) return false; 15369 15370 // Don't count this as an indirect ownership. 15371 e = member->getBase(); 15372 continue; 15373 } 15374 15375 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15376 // Only pay attention to pseudo-objects on property references. 15377 ObjCPropertyRefExpr *pre 15378 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15379 ->IgnoreParens()); 15380 if (!pre) return false; 15381 if (pre->isImplicitProperty()) return false; 15382 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15383 if (!property->isRetaining() && 15384 !(property->getPropertyIvarDecl() && 15385 property->getPropertyIvarDecl()->getType() 15386 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15387 return false; 15388 15389 owner.Indirect = true; 15390 if (pre->isSuperReceiver()) { 15391 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15392 if (!owner.Variable) 15393 return false; 15394 owner.Loc = pre->getLocation(); 15395 owner.Range = pre->getSourceRange(); 15396 return true; 15397 } 15398 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15399 ->getSourceExpr()); 15400 continue; 15401 } 15402 15403 // Array ivars? 15404 15405 return false; 15406 } 15407 } 15408 15409 namespace { 15410 15411 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15412 ASTContext &Context; 15413 VarDecl *Variable; 15414 Expr *Capturer = nullptr; 15415 bool VarWillBeReased = false; 15416 15417 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15418 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15419 Context(Context), Variable(variable) {} 15420 15421 void VisitDeclRefExpr(DeclRefExpr *ref) { 15422 if (ref->getDecl() == Variable && !Capturer) 15423 Capturer = ref; 15424 } 15425 15426 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15427 if (Capturer) return; 15428 Visit(ref->getBase()); 15429 if (Capturer && ref->isFreeIvar()) 15430 Capturer = ref; 15431 } 15432 15433 void VisitBlockExpr(BlockExpr *block) { 15434 // Look inside nested blocks 15435 if (block->getBlockDecl()->capturesVariable(Variable)) 15436 Visit(block->getBlockDecl()->getBody()); 15437 } 15438 15439 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15440 if (Capturer) return; 15441 if (OVE->getSourceExpr()) 15442 Visit(OVE->getSourceExpr()); 15443 } 15444 15445 void VisitBinaryOperator(BinaryOperator *BinOp) { 15446 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15447 return; 15448 Expr *LHS = BinOp->getLHS(); 15449 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15450 if (DRE->getDecl() != Variable) 15451 return; 15452 if (Expr *RHS = BinOp->getRHS()) { 15453 RHS = RHS->IgnoreParenCasts(); 15454 Optional<llvm::APSInt> Value; 15455 VarWillBeReased = 15456 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15457 *Value == 0); 15458 } 15459 } 15460 } 15461 }; 15462 15463 } // namespace 15464 15465 /// Check whether the given argument is a block which captures a 15466 /// variable. 15467 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15468 assert(owner.Variable && owner.Loc.isValid()); 15469 15470 e = e->IgnoreParenCasts(); 15471 15472 // Look through [^{...} copy] and Block_copy(^{...}). 15473 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15474 Selector Cmd = ME->getSelector(); 15475 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15476 e = ME->getInstanceReceiver(); 15477 if (!e) 15478 return nullptr; 15479 e = e->IgnoreParenCasts(); 15480 } 15481 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15482 if (CE->getNumArgs() == 1) { 15483 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15484 if (Fn) { 15485 const IdentifierInfo *FnI = Fn->getIdentifier(); 15486 if (FnI && FnI->isStr("_Block_copy")) { 15487 e = CE->getArg(0)->IgnoreParenCasts(); 15488 } 15489 } 15490 } 15491 } 15492 15493 BlockExpr *block = dyn_cast<BlockExpr>(e); 15494 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15495 return nullptr; 15496 15497 FindCaptureVisitor visitor(S.Context, owner.Variable); 15498 visitor.Visit(block->getBlockDecl()->getBody()); 15499 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15500 } 15501 15502 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15503 RetainCycleOwner &owner) { 15504 assert(capturer); 15505 assert(owner.Variable && owner.Loc.isValid()); 15506 15507 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15508 << owner.Variable << capturer->getSourceRange(); 15509 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15510 << owner.Indirect << owner.Range; 15511 } 15512 15513 /// Check for a keyword selector that starts with the word 'add' or 15514 /// 'set'. 15515 static bool isSetterLikeSelector(Selector sel) { 15516 if (sel.isUnarySelector()) return false; 15517 15518 StringRef str = sel.getNameForSlot(0); 15519 while (!str.empty() && str.front() == '_') str = str.substr(1); 15520 if (str.startswith("set")) 15521 str = str.substr(3); 15522 else if (str.startswith("add")) { 15523 // Specially allow 'addOperationWithBlock:'. 15524 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15525 return false; 15526 str = str.substr(3); 15527 } 15528 else 15529 return false; 15530 15531 if (str.empty()) return true; 15532 return !isLowercase(str.front()); 15533 } 15534 15535 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15536 ObjCMessageExpr *Message) { 15537 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15538 Message->getReceiverInterface(), 15539 NSAPI::ClassId_NSMutableArray); 15540 if (!IsMutableArray) { 15541 return None; 15542 } 15543 15544 Selector Sel = Message->getSelector(); 15545 15546 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15547 S.NSAPIObj->getNSArrayMethodKind(Sel); 15548 if (!MKOpt) { 15549 return None; 15550 } 15551 15552 NSAPI::NSArrayMethodKind MK = *MKOpt; 15553 15554 switch (MK) { 15555 case NSAPI::NSMutableArr_addObject: 15556 case NSAPI::NSMutableArr_insertObjectAtIndex: 15557 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15558 return 0; 15559 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15560 return 1; 15561 15562 default: 15563 return None; 15564 } 15565 15566 return None; 15567 } 15568 15569 static 15570 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15571 ObjCMessageExpr *Message) { 15572 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15573 Message->getReceiverInterface(), 15574 NSAPI::ClassId_NSMutableDictionary); 15575 if (!IsMutableDictionary) { 15576 return None; 15577 } 15578 15579 Selector Sel = Message->getSelector(); 15580 15581 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15582 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15583 if (!MKOpt) { 15584 return None; 15585 } 15586 15587 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15588 15589 switch (MK) { 15590 case NSAPI::NSMutableDict_setObjectForKey: 15591 case NSAPI::NSMutableDict_setValueForKey: 15592 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15593 return 0; 15594 15595 default: 15596 return None; 15597 } 15598 15599 return None; 15600 } 15601 15602 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15603 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15604 Message->getReceiverInterface(), 15605 NSAPI::ClassId_NSMutableSet); 15606 15607 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15608 Message->getReceiverInterface(), 15609 NSAPI::ClassId_NSMutableOrderedSet); 15610 if (!IsMutableSet && !IsMutableOrderedSet) { 15611 return None; 15612 } 15613 15614 Selector Sel = Message->getSelector(); 15615 15616 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15617 if (!MKOpt) { 15618 return None; 15619 } 15620 15621 NSAPI::NSSetMethodKind MK = *MKOpt; 15622 15623 switch (MK) { 15624 case NSAPI::NSMutableSet_addObject: 15625 case NSAPI::NSOrderedSet_setObjectAtIndex: 15626 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15627 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15628 return 0; 15629 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15630 return 1; 15631 } 15632 15633 return None; 15634 } 15635 15636 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15637 if (!Message->isInstanceMessage()) { 15638 return; 15639 } 15640 15641 Optional<int> ArgOpt; 15642 15643 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15644 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15645 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15646 return; 15647 } 15648 15649 int ArgIndex = *ArgOpt; 15650 15651 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15652 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15653 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15654 } 15655 15656 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15657 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15658 if (ArgRE->isObjCSelfExpr()) { 15659 Diag(Message->getSourceRange().getBegin(), 15660 diag::warn_objc_circular_container) 15661 << ArgRE->getDecl() << StringRef("'super'"); 15662 } 15663 } 15664 } else { 15665 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15666 15667 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15668 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15669 } 15670 15671 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15672 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15673 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15674 ValueDecl *Decl = ReceiverRE->getDecl(); 15675 Diag(Message->getSourceRange().getBegin(), 15676 diag::warn_objc_circular_container) 15677 << Decl << Decl; 15678 if (!ArgRE->isObjCSelfExpr()) { 15679 Diag(Decl->getLocation(), 15680 diag::note_objc_circular_container_declared_here) 15681 << Decl; 15682 } 15683 } 15684 } 15685 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15686 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15687 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15688 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15689 Diag(Message->getSourceRange().getBegin(), 15690 diag::warn_objc_circular_container) 15691 << Decl << Decl; 15692 Diag(Decl->getLocation(), 15693 diag::note_objc_circular_container_declared_here) 15694 << Decl; 15695 } 15696 } 15697 } 15698 } 15699 } 15700 15701 /// Check a message send to see if it's likely to cause a retain cycle. 15702 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15703 // Only check instance methods whose selector looks like a setter. 15704 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15705 return; 15706 15707 // Try to find a variable that the receiver is strongly owned by. 15708 RetainCycleOwner owner; 15709 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15710 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15711 return; 15712 } else { 15713 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15714 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15715 owner.Loc = msg->getSuperLoc(); 15716 owner.Range = msg->getSuperLoc(); 15717 } 15718 15719 // Check whether the receiver is captured by any of the arguments. 15720 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15721 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15722 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15723 // noescape blocks should not be retained by the method. 15724 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15725 continue; 15726 return diagnoseRetainCycle(*this, capturer, owner); 15727 } 15728 } 15729 } 15730 15731 /// Check a property assign to see if it's likely to cause a retain cycle. 15732 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15733 RetainCycleOwner owner; 15734 if (!findRetainCycleOwner(*this, receiver, owner)) 15735 return; 15736 15737 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15738 diagnoseRetainCycle(*this, capturer, owner); 15739 } 15740 15741 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15742 RetainCycleOwner Owner; 15743 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15744 return; 15745 15746 // Because we don't have an expression for the variable, we have to set the 15747 // location explicitly here. 15748 Owner.Loc = Var->getLocation(); 15749 Owner.Range = Var->getSourceRange(); 15750 15751 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15752 diagnoseRetainCycle(*this, Capturer, Owner); 15753 } 15754 15755 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15756 Expr *RHS, bool isProperty) { 15757 // Check if RHS is an Objective-C object literal, which also can get 15758 // immediately zapped in a weak reference. Note that we explicitly 15759 // allow ObjCStringLiterals, since those are designed to never really die. 15760 RHS = RHS->IgnoreParenImpCasts(); 15761 15762 // This enum needs to match with the 'select' in 15763 // warn_objc_arc_literal_assign (off-by-1). 15764 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15765 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15766 return false; 15767 15768 S.Diag(Loc, diag::warn_arc_literal_assign) 15769 << (unsigned) Kind 15770 << (isProperty ? 0 : 1) 15771 << RHS->getSourceRange(); 15772 15773 return true; 15774 } 15775 15776 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15777 Qualifiers::ObjCLifetime LT, 15778 Expr *RHS, bool isProperty) { 15779 // Strip off any implicit cast added to get to the one ARC-specific. 15780 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15781 if (cast->getCastKind() == CK_ARCConsumeObject) { 15782 S.Diag(Loc, diag::warn_arc_retained_assign) 15783 << (LT == Qualifiers::OCL_ExplicitNone) 15784 << (isProperty ? 0 : 1) 15785 << RHS->getSourceRange(); 15786 return true; 15787 } 15788 RHS = cast->getSubExpr(); 15789 } 15790 15791 if (LT == Qualifiers::OCL_Weak && 15792 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15793 return true; 15794 15795 return false; 15796 } 15797 15798 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15799 QualType LHS, Expr *RHS) { 15800 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15801 15802 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15803 return false; 15804 15805 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15806 return true; 15807 15808 return false; 15809 } 15810 15811 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15812 Expr *LHS, Expr *RHS) { 15813 QualType LHSType; 15814 // PropertyRef on LHS type need be directly obtained from 15815 // its declaration as it has a PseudoType. 15816 ObjCPropertyRefExpr *PRE 15817 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15818 if (PRE && !PRE->isImplicitProperty()) { 15819 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15820 if (PD) 15821 LHSType = PD->getType(); 15822 } 15823 15824 if (LHSType.isNull()) 15825 LHSType = LHS->getType(); 15826 15827 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15828 15829 if (LT == Qualifiers::OCL_Weak) { 15830 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15831 getCurFunction()->markSafeWeakUse(LHS); 15832 } 15833 15834 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15835 return; 15836 15837 // FIXME. Check for other life times. 15838 if (LT != Qualifiers::OCL_None) 15839 return; 15840 15841 if (PRE) { 15842 if (PRE->isImplicitProperty()) 15843 return; 15844 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15845 if (!PD) 15846 return; 15847 15848 unsigned Attributes = PD->getPropertyAttributes(); 15849 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15850 // when 'assign' attribute was not explicitly specified 15851 // by user, ignore it and rely on property type itself 15852 // for lifetime info. 15853 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15854 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15855 LHSType->isObjCRetainableType()) 15856 return; 15857 15858 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15859 if (cast->getCastKind() == CK_ARCConsumeObject) { 15860 Diag(Loc, diag::warn_arc_retained_property_assign) 15861 << RHS->getSourceRange(); 15862 return; 15863 } 15864 RHS = cast->getSubExpr(); 15865 } 15866 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15867 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15868 return; 15869 } 15870 } 15871 } 15872 15873 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15874 15875 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15876 SourceLocation StmtLoc, 15877 const NullStmt *Body) { 15878 // Do not warn if the body is a macro that expands to nothing, e.g: 15879 // 15880 // #define CALL(x) 15881 // if (condition) 15882 // CALL(0); 15883 if (Body->hasLeadingEmptyMacro()) 15884 return false; 15885 15886 // Get line numbers of statement and body. 15887 bool StmtLineInvalid; 15888 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15889 &StmtLineInvalid); 15890 if (StmtLineInvalid) 15891 return false; 15892 15893 bool BodyLineInvalid; 15894 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15895 &BodyLineInvalid); 15896 if (BodyLineInvalid) 15897 return false; 15898 15899 // Warn if null statement and body are on the same line. 15900 if (StmtLine != BodyLine) 15901 return false; 15902 15903 return true; 15904 } 15905 15906 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15907 const Stmt *Body, 15908 unsigned DiagID) { 15909 // Since this is a syntactic check, don't emit diagnostic for template 15910 // instantiations, this just adds noise. 15911 if (CurrentInstantiationScope) 15912 return; 15913 15914 // The body should be a null statement. 15915 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15916 if (!NBody) 15917 return; 15918 15919 // Do the usual checks. 15920 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15921 return; 15922 15923 Diag(NBody->getSemiLoc(), DiagID); 15924 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15925 } 15926 15927 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15928 const Stmt *PossibleBody) { 15929 assert(!CurrentInstantiationScope); // Ensured by caller 15930 15931 SourceLocation StmtLoc; 15932 const Stmt *Body; 15933 unsigned DiagID; 15934 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15935 StmtLoc = FS->getRParenLoc(); 15936 Body = FS->getBody(); 15937 DiagID = diag::warn_empty_for_body; 15938 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15939 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15940 Body = WS->getBody(); 15941 DiagID = diag::warn_empty_while_body; 15942 } else 15943 return; // Neither `for' nor `while'. 15944 15945 // The body should be a null statement. 15946 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15947 if (!NBody) 15948 return; 15949 15950 // Skip expensive checks if diagnostic is disabled. 15951 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15952 return; 15953 15954 // Do the usual checks. 15955 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15956 return; 15957 15958 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15959 // noise level low, emit diagnostics only if for/while is followed by a 15960 // CompoundStmt, e.g.: 15961 // for (int i = 0; i < n; i++); 15962 // { 15963 // a(i); 15964 // } 15965 // or if for/while is followed by a statement with more indentation 15966 // than for/while itself: 15967 // for (int i = 0; i < n; i++); 15968 // a(i); 15969 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15970 if (!ProbableTypo) { 15971 bool BodyColInvalid; 15972 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15973 PossibleBody->getBeginLoc(), &BodyColInvalid); 15974 if (BodyColInvalid) 15975 return; 15976 15977 bool StmtColInvalid; 15978 unsigned StmtCol = 15979 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15980 if (StmtColInvalid) 15981 return; 15982 15983 if (BodyCol > StmtCol) 15984 ProbableTypo = true; 15985 } 15986 15987 if (ProbableTypo) { 15988 Diag(NBody->getSemiLoc(), DiagID); 15989 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15990 } 15991 } 15992 15993 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15994 15995 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15996 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15997 SourceLocation OpLoc) { 15998 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15999 return; 16000 16001 if (inTemplateInstantiation()) 16002 return; 16003 16004 // Strip parens and casts away. 16005 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16006 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16007 16008 // Check for a call expression 16009 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16010 if (!CE || CE->getNumArgs() != 1) 16011 return; 16012 16013 // Check for a call to std::move 16014 if (!CE->isCallToStdMove()) 16015 return; 16016 16017 // Get argument from std::move 16018 RHSExpr = CE->getArg(0); 16019 16020 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16021 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16022 16023 // Two DeclRefExpr's, check that the decls are the same. 16024 if (LHSDeclRef && RHSDeclRef) { 16025 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16026 return; 16027 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16028 RHSDeclRef->getDecl()->getCanonicalDecl()) 16029 return; 16030 16031 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16032 << LHSExpr->getSourceRange() 16033 << RHSExpr->getSourceRange(); 16034 return; 16035 } 16036 16037 // Member variables require a different approach to check for self moves. 16038 // MemberExpr's are the same if every nested MemberExpr refers to the same 16039 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16040 // the base Expr's are CXXThisExpr's. 16041 const Expr *LHSBase = LHSExpr; 16042 const Expr *RHSBase = RHSExpr; 16043 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16044 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16045 if (!LHSME || !RHSME) 16046 return; 16047 16048 while (LHSME && RHSME) { 16049 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16050 RHSME->getMemberDecl()->getCanonicalDecl()) 16051 return; 16052 16053 LHSBase = LHSME->getBase(); 16054 RHSBase = RHSME->getBase(); 16055 LHSME = dyn_cast<MemberExpr>(LHSBase); 16056 RHSME = dyn_cast<MemberExpr>(RHSBase); 16057 } 16058 16059 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16060 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16061 if (LHSDeclRef && RHSDeclRef) { 16062 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16063 return; 16064 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16065 RHSDeclRef->getDecl()->getCanonicalDecl()) 16066 return; 16067 16068 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16069 << LHSExpr->getSourceRange() 16070 << RHSExpr->getSourceRange(); 16071 return; 16072 } 16073 16074 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16075 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16076 << LHSExpr->getSourceRange() 16077 << RHSExpr->getSourceRange(); 16078 } 16079 16080 //===--- Layout compatibility ----------------------------------------------// 16081 16082 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16083 16084 /// Check if two enumeration types are layout-compatible. 16085 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16086 // C++11 [dcl.enum] p8: 16087 // Two enumeration types are layout-compatible if they have the same 16088 // underlying type. 16089 return ED1->isComplete() && ED2->isComplete() && 16090 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16091 } 16092 16093 /// Check if two fields are layout-compatible. 16094 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16095 FieldDecl *Field2) { 16096 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16097 return false; 16098 16099 if (Field1->isBitField() != Field2->isBitField()) 16100 return false; 16101 16102 if (Field1->isBitField()) { 16103 // Make sure that the bit-fields are the same length. 16104 unsigned Bits1 = Field1->getBitWidthValue(C); 16105 unsigned Bits2 = Field2->getBitWidthValue(C); 16106 16107 if (Bits1 != Bits2) 16108 return false; 16109 } 16110 16111 return true; 16112 } 16113 16114 /// Check if two standard-layout structs are layout-compatible. 16115 /// (C++11 [class.mem] p17) 16116 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16117 RecordDecl *RD2) { 16118 // If both records are C++ classes, check that base classes match. 16119 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16120 // If one of records is a CXXRecordDecl we are in C++ mode, 16121 // thus the other one is a CXXRecordDecl, too. 16122 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16123 // Check number of base classes. 16124 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16125 return false; 16126 16127 // Check the base classes. 16128 for (CXXRecordDecl::base_class_const_iterator 16129 Base1 = D1CXX->bases_begin(), 16130 BaseEnd1 = D1CXX->bases_end(), 16131 Base2 = D2CXX->bases_begin(); 16132 Base1 != BaseEnd1; 16133 ++Base1, ++Base2) { 16134 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16135 return false; 16136 } 16137 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16138 // If only RD2 is a C++ class, it should have zero base classes. 16139 if (D2CXX->getNumBases() > 0) 16140 return false; 16141 } 16142 16143 // Check the fields. 16144 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16145 Field2End = RD2->field_end(), 16146 Field1 = RD1->field_begin(), 16147 Field1End = RD1->field_end(); 16148 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16149 if (!isLayoutCompatible(C, *Field1, *Field2)) 16150 return false; 16151 } 16152 if (Field1 != Field1End || Field2 != Field2End) 16153 return false; 16154 16155 return true; 16156 } 16157 16158 /// Check if two standard-layout unions are layout-compatible. 16159 /// (C++11 [class.mem] p18) 16160 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16161 RecordDecl *RD2) { 16162 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16163 for (auto *Field2 : RD2->fields()) 16164 UnmatchedFields.insert(Field2); 16165 16166 for (auto *Field1 : RD1->fields()) { 16167 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16168 I = UnmatchedFields.begin(), 16169 E = UnmatchedFields.end(); 16170 16171 for ( ; I != E; ++I) { 16172 if (isLayoutCompatible(C, Field1, *I)) { 16173 bool Result = UnmatchedFields.erase(*I); 16174 (void) Result; 16175 assert(Result); 16176 break; 16177 } 16178 } 16179 if (I == E) 16180 return false; 16181 } 16182 16183 return UnmatchedFields.empty(); 16184 } 16185 16186 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16187 RecordDecl *RD2) { 16188 if (RD1->isUnion() != RD2->isUnion()) 16189 return false; 16190 16191 if (RD1->isUnion()) 16192 return isLayoutCompatibleUnion(C, RD1, RD2); 16193 else 16194 return isLayoutCompatibleStruct(C, RD1, RD2); 16195 } 16196 16197 /// Check if two types are layout-compatible in C++11 sense. 16198 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16199 if (T1.isNull() || T2.isNull()) 16200 return false; 16201 16202 // C++11 [basic.types] p11: 16203 // If two types T1 and T2 are the same type, then T1 and T2 are 16204 // layout-compatible types. 16205 if (C.hasSameType(T1, T2)) 16206 return true; 16207 16208 T1 = T1.getCanonicalType().getUnqualifiedType(); 16209 T2 = T2.getCanonicalType().getUnqualifiedType(); 16210 16211 const Type::TypeClass TC1 = T1->getTypeClass(); 16212 const Type::TypeClass TC2 = T2->getTypeClass(); 16213 16214 if (TC1 != TC2) 16215 return false; 16216 16217 if (TC1 == Type::Enum) { 16218 return isLayoutCompatible(C, 16219 cast<EnumType>(T1)->getDecl(), 16220 cast<EnumType>(T2)->getDecl()); 16221 } else if (TC1 == Type::Record) { 16222 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16223 return false; 16224 16225 return isLayoutCompatible(C, 16226 cast<RecordType>(T1)->getDecl(), 16227 cast<RecordType>(T2)->getDecl()); 16228 } 16229 16230 return false; 16231 } 16232 16233 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16234 16235 /// Given a type tag expression find the type tag itself. 16236 /// 16237 /// \param TypeExpr Type tag expression, as it appears in user's code. 16238 /// 16239 /// \param VD Declaration of an identifier that appears in a type tag. 16240 /// 16241 /// \param MagicValue Type tag magic value. 16242 /// 16243 /// \param isConstantEvaluated whether the evalaution should be performed in 16244 16245 /// constant context. 16246 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16247 const ValueDecl **VD, uint64_t *MagicValue, 16248 bool isConstantEvaluated) { 16249 while(true) { 16250 if (!TypeExpr) 16251 return false; 16252 16253 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16254 16255 switch (TypeExpr->getStmtClass()) { 16256 case Stmt::UnaryOperatorClass: { 16257 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16258 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16259 TypeExpr = UO->getSubExpr(); 16260 continue; 16261 } 16262 return false; 16263 } 16264 16265 case Stmt::DeclRefExprClass: { 16266 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16267 *VD = DRE->getDecl(); 16268 return true; 16269 } 16270 16271 case Stmt::IntegerLiteralClass: { 16272 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16273 llvm::APInt MagicValueAPInt = IL->getValue(); 16274 if (MagicValueAPInt.getActiveBits() <= 64) { 16275 *MagicValue = MagicValueAPInt.getZExtValue(); 16276 return true; 16277 } else 16278 return false; 16279 } 16280 16281 case Stmt::BinaryConditionalOperatorClass: 16282 case Stmt::ConditionalOperatorClass: { 16283 const AbstractConditionalOperator *ACO = 16284 cast<AbstractConditionalOperator>(TypeExpr); 16285 bool Result; 16286 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16287 isConstantEvaluated)) { 16288 if (Result) 16289 TypeExpr = ACO->getTrueExpr(); 16290 else 16291 TypeExpr = ACO->getFalseExpr(); 16292 continue; 16293 } 16294 return false; 16295 } 16296 16297 case Stmt::BinaryOperatorClass: { 16298 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16299 if (BO->getOpcode() == BO_Comma) { 16300 TypeExpr = BO->getRHS(); 16301 continue; 16302 } 16303 return false; 16304 } 16305 16306 default: 16307 return false; 16308 } 16309 } 16310 } 16311 16312 /// Retrieve the C type corresponding to type tag TypeExpr. 16313 /// 16314 /// \param TypeExpr Expression that specifies a type tag. 16315 /// 16316 /// \param MagicValues Registered magic values. 16317 /// 16318 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16319 /// kind. 16320 /// 16321 /// \param TypeInfo Information about the corresponding C type. 16322 /// 16323 /// \param isConstantEvaluated whether the evalaution should be performed in 16324 /// constant context. 16325 /// 16326 /// \returns true if the corresponding C type was found. 16327 static bool GetMatchingCType( 16328 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16329 const ASTContext &Ctx, 16330 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16331 *MagicValues, 16332 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16333 bool isConstantEvaluated) { 16334 FoundWrongKind = false; 16335 16336 // Variable declaration that has type_tag_for_datatype attribute. 16337 const ValueDecl *VD = nullptr; 16338 16339 uint64_t MagicValue; 16340 16341 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16342 return false; 16343 16344 if (VD) { 16345 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16346 if (I->getArgumentKind() != ArgumentKind) { 16347 FoundWrongKind = true; 16348 return false; 16349 } 16350 TypeInfo.Type = I->getMatchingCType(); 16351 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16352 TypeInfo.MustBeNull = I->getMustBeNull(); 16353 return true; 16354 } 16355 return false; 16356 } 16357 16358 if (!MagicValues) 16359 return false; 16360 16361 llvm::DenseMap<Sema::TypeTagMagicValue, 16362 Sema::TypeTagData>::const_iterator I = 16363 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16364 if (I == MagicValues->end()) 16365 return false; 16366 16367 TypeInfo = I->second; 16368 return true; 16369 } 16370 16371 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16372 uint64_t MagicValue, QualType Type, 16373 bool LayoutCompatible, 16374 bool MustBeNull) { 16375 if (!TypeTagForDatatypeMagicValues) 16376 TypeTagForDatatypeMagicValues.reset( 16377 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16378 16379 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16380 (*TypeTagForDatatypeMagicValues)[Magic] = 16381 TypeTagData(Type, LayoutCompatible, MustBeNull); 16382 } 16383 16384 static bool IsSameCharType(QualType T1, QualType T2) { 16385 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16386 if (!BT1) 16387 return false; 16388 16389 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16390 if (!BT2) 16391 return false; 16392 16393 BuiltinType::Kind T1Kind = BT1->getKind(); 16394 BuiltinType::Kind T2Kind = BT2->getKind(); 16395 16396 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16397 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16398 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16399 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16400 } 16401 16402 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16403 const ArrayRef<const Expr *> ExprArgs, 16404 SourceLocation CallSiteLoc) { 16405 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16406 bool IsPointerAttr = Attr->getIsPointer(); 16407 16408 // Retrieve the argument representing the 'type_tag'. 16409 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16410 if (TypeTagIdxAST >= ExprArgs.size()) { 16411 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16412 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16413 return; 16414 } 16415 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16416 bool FoundWrongKind; 16417 TypeTagData TypeInfo; 16418 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16419 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16420 TypeInfo, isConstantEvaluated())) { 16421 if (FoundWrongKind) 16422 Diag(TypeTagExpr->getExprLoc(), 16423 diag::warn_type_tag_for_datatype_wrong_kind) 16424 << TypeTagExpr->getSourceRange(); 16425 return; 16426 } 16427 16428 // Retrieve the argument representing the 'arg_idx'. 16429 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16430 if (ArgumentIdxAST >= ExprArgs.size()) { 16431 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16432 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16433 return; 16434 } 16435 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16436 if (IsPointerAttr) { 16437 // Skip implicit cast of pointer to `void *' (as a function argument). 16438 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16439 if (ICE->getType()->isVoidPointerType() && 16440 ICE->getCastKind() == CK_BitCast) 16441 ArgumentExpr = ICE->getSubExpr(); 16442 } 16443 QualType ArgumentType = ArgumentExpr->getType(); 16444 16445 // Passing a `void*' pointer shouldn't trigger a warning. 16446 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16447 return; 16448 16449 if (TypeInfo.MustBeNull) { 16450 // Type tag with matching void type requires a null pointer. 16451 if (!ArgumentExpr->isNullPointerConstant(Context, 16452 Expr::NPC_ValueDependentIsNotNull)) { 16453 Diag(ArgumentExpr->getExprLoc(), 16454 diag::warn_type_safety_null_pointer_required) 16455 << ArgumentKind->getName() 16456 << ArgumentExpr->getSourceRange() 16457 << TypeTagExpr->getSourceRange(); 16458 } 16459 return; 16460 } 16461 16462 QualType RequiredType = TypeInfo.Type; 16463 if (IsPointerAttr) 16464 RequiredType = Context.getPointerType(RequiredType); 16465 16466 bool mismatch = false; 16467 if (!TypeInfo.LayoutCompatible) { 16468 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16469 16470 // C++11 [basic.fundamental] p1: 16471 // Plain char, signed char, and unsigned char are three distinct types. 16472 // 16473 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16474 // char' depending on the current char signedness mode. 16475 if (mismatch) 16476 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16477 RequiredType->getPointeeType())) || 16478 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16479 mismatch = false; 16480 } else 16481 if (IsPointerAttr) 16482 mismatch = !isLayoutCompatible(Context, 16483 ArgumentType->getPointeeType(), 16484 RequiredType->getPointeeType()); 16485 else 16486 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16487 16488 if (mismatch) 16489 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16490 << ArgumentType << ArgumentKind 16491 << TypeInfo.LayoutCompatible << RequiredType 16492 << ArgumentExpr->getSourceRange() 16493 << TypeTagExpr->getSourceRange(); 16494 } 16495 16496 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16497 CharUnits Alignment) { 16498 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16499 } 16500 16501 void Sema::DiagnoseMisalignedMembers() { 16502 for (MisalignedMember &m : MisalignedMembers) { 16503 const NamedDecl *ND = m.RD; 16504 if (ND->getName().empty()) { 16505 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16506 ND = TD; 16507 } 16508 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16509 << m.MD << ND << m.E->getSourceRange(); 16510 } 16511 MisalignedMembers.clear(); 16512 } 16513 16514 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16515 E = E->IgnoreParens(); 16516 if (!T->isPointerType() && !T->isIntegerType()) 16517 return; 16518 if (isa<UnaryOperator>(E) && 16519 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16520 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16521 if (isa<MemberExpr>(Op)) { 16522 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16523 if (MA != MisalignedMembers.end() && 16524 (T->isIntegerType() || 16525 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16526 Context.getTypeAlignInChars( 16527 T->getPointeeType()) <= MA->Alignment)))) 16528 MisalignedMembers.erase(MA); 16529 } 16530 } 16531 } 16532 16533 void Sema::RefersToMemberWithReducedAlignment( 16534 Expr *E, 16535 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16536 Action) { 16537 const auto *ME = dyn_cast<MemberExpr>(E); 16538 if (!ME) 16539 return; 16540 16541 // No need to check expressions with an __unaligned-qualified type. 16542 if (E->getType().getQualifiers().hasUnaligned()) 16543 return; 16544 16545 // For a chain of MemberExpr like "a.b.c.d" this list 16546 // will keep FieldDecl's like [d, c, b]. 16547 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16548 const MemberExpr *TopME = nullptr; 16549 bool AnyIsPacked = false; 16550 do { 16551 QualType BaseType = ME->getBase()->getType(); 16552 if (BaseType->isDependentType()) 16553 return; 16554 if (ME->isArrow()) 16555 BaseType = BaseType->getPointeeType(); 16556 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16557 if (RD->isInvalidDecl()) 16558 return; 16559 16560 ValueDecl *MD = ME->getMemberDecl(); 16561 auto *FD = dyn_cast<FieldDecl>(MD); 16562 // We do not care about non-data members. 16563 if (!FD || FD->isInvalidDecl()) 16564 return; 16565 16566 AnyIsPacked = 16567 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16568 ReverseMemberChain.push_back(FD); 16569 16570 TopME = ME; 16571 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16572 } while (ME); 16573 assert(TopME && "We did not compute a topmost MemberExpr!"); 16574 16575 // Not the scope of this diagnostic. 16576 if (!AnyIsPacked) 16577 return; 16578 16579 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16580 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16581 // TODO: The innermost base of the member expression may be too complicated. 16582 // For now, just disregard these cases. This is left for future 16583 // improvement. 16584 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16585 return; 16586 16587 // Alignment expected by the whole expression. 16588 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16589 16590 // No need to do anything else with this case. 16591 if (ExpectedAlignment.isOne()) 16592 return; 16593 16594 // Synthesize offset of the whole access. 16595 CharUnits Offset; 16596 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16597 I++) { 16598 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16599 } 16600 16601 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16602 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16603 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16604 16605 // The base expression of the innermost MemberExpr may give 16606 // stronger guarantees than the class containing the member. 16607 if (DRE && !TopME->isArrow()) { 16608 const ValueDecl *VD = DRE->getDecl(); 16609 if (!VD->getType()->isReferenceType()) 16610 CompleteObjectAlignment = 16611 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16612 } 16613 16614 // Check if the synthesized offset fulfills the alignment. 16615 if (Offset % ExpectedAlignment != 0 || 16616 // It may fulfill the offset it but the effective alignment may still be 16617 // lower than the expected expression alignment. 16618 CompleteObjectAlignment < ExpectedAlignment) { 16619 // If this happens, we want to determine a sensible culprit of this. 16620 // Intuitively, watching the chain of member expressions from right to 16621 // left, we start with the required alignment (as required by the field 16622 // type) but some packed attribute in that chain has reduced the alignment. 16623 // It may happen that another packed structure increases it again. But if 16624 // we are here such increase has not been enough. So pointing the first 16625 // FieldDecl that either is packed or else its RecordDecl is, 16626 // seems reasonable. 16627 FieldDecl *FD = nullptr; 16628 CharUnits Alignment; 16629 for (FieldDecl *FDI : ReverseMemberChain) { 16630 if (FDI->hasAttr<PackedAttr>() || 16631 FDI->getParent()->hasAttr<PackedAttr>()) { 16632 FD = FDI; 16633 Alignment = std::min( 16634 Context.getTypeAlignInChars(FD->getType()), 16635 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16636 break; 16637 } 16638 } 16639 assert(FD && "We did not find a packed FieldDecl!"); 16640 Action(E, FD->getParent(), FD, Alignment); 16641 } 16642 } 16643 16644 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16645 using namespace std::placeholders; 16646 16647 RefersToMemberWithReducedAlignment( 16648 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16649 _2, _3, _4)); 16650 } 16651 16652 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16653 ExprResult CallResult) { 16654 if (checkArgCount(*this, TheCall, 1)) 16655 return ExprError(); 16656 16657 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16658 if (MatrixArg.isInvalid()) 16659 return MatrixArg; 16660 Expr *Matrix = MatrixArg.get(); 16661 16662 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16663 if (!MType) { 16664 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16665 return ExprError(); 16666 } 16667 16668 // Create returned matrix type by swapping rows and columns of the argument 16669 // matrix type. 16670 QualType ResultType = Context.getConstantMatrixType( 16671 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16672 16673 // Change the return type to the type of the returned matrix. 16674 TheCall->setType(ResultType); 16675 16676 // Update call argument to use the possibly converted matrix argument. 16677 TheCall->setArg(0, Matrix); 16678 return CallResult; 16679 } 16680 16681 // Get and verify the matrix dimensions. 16682 static llvm::Optional<unsigned> 16683 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16684 SourceLocation ErrorPos; 16685 Optional<llvm::APSInt> Value = 16686 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16687 if (!Value) { 16688 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16689 << Name; 16690 return {}; 16691 } 16692 uint64_t Dim = Value->getZExtValue(); 16693 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16694 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16695 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16696 return {}; 16697 } 16698 return Dim; 16699 } 16700 16701 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16702 ExprResult CallResult) { 16703 if (!getLangOpts().MatrixTypes) { 16704 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16705 return ExprError(); 16706 } 16707 16708 if (checkArgCount(*this, TheCall, 4)) 16709 return ExprError(); 16710 16711 unsigned PtrArgIdx = 0; 16712 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16713 Expr *RowsExpr = TheCall->getArg(1); 16714 Expr *ColumnsExpr = TheCall->getArg(2); 16715 Expr *StrideExpr = TheCall->getArg(3); 16716 16717 bool ArgError = false; 16718 16719 // Check pointer argument. 16720 { 16721 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16722 if (PtrConv.isInvalid()) 16723 return PtrConv; 16724 PtrExpr = PtrConv.get(); 16725 TheCall->setArg(0, PtrExpr); 16726 if (PtrExpr->isTypeDependent()) { 16727 TheCall->setType(Context.DependentTy); 16728 return TheCall; 16729 } 16730 } 16731 16732 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16733 QualType ElementTy; 16734 if (!PtrTy) { 16735 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16736 << PtrArgIdx + 1; 16737 ArgError = true; 16738 } else { 16739 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16740 16741 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16742 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16743 << PtrArgIdx + 1; 16744 ArgError = true; 16745 } 16746 } 16747 16748 // Apply default Lvalue conversions and convert the expression to size_t. 16749 auto ApplyArgumentConversions = [this](Expr *E) { 16750 ExprResult Conv = DefaultLvalueConversion(E); 16751 if (Conv.isInvalid()) 16752 return Conv; 16753 16754 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16755 }; 16756 16757 // Apply conversion to row and column expressions. 16758 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16759 if (!RowsConv.isInvalid()) { 16760 RowsExpr = RowsConv.get(); 16761 TheCall->setArg(1, RowsExpr); 16762 } else 16763 RowsExpr = nullptr; 16764 16765 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16766 if (!ColumnsConv.isInvalid()) { 16767 ColumnsExpr = ColumnsConv.get(); 16768 TheCall->setArg(2, ColumnsExpr); 16769 } else 16770 ColumnsExpr = nullptr; 16771 16772 // If any any part of the result matrix type is still pending, just use 16773 // Context.DependentTy, until all parts are resolved. 16774 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16775 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16776 TheCall->setType(Context.DependentTy); 16777 return CallResult; 16778 } 16779 16780 // Check row and column dimensions. 16781 llvm::Optional<unsigned> MaybeRows; 16782 if (RowsExpr) 16783 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16784 16785 llvm::Optional<unsigned> MaybeColumns; 16786 if (ColumnsExpr) 16787 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16788 16789 // Check stride argument. 16790 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16791 if (StrideConv.isInvalid()) 16792 return ExprError(); 16793 StrideExpr = StrideConv.get(); 16794 TheCall->setArg(3, StrideExpr); 16795 16796 if (MaybeRows) { 16797 if (Optional<llvm::APSInt> Value = 16798 StrideExpr->getIntegerConstantExpr(Context)) { 16799 uint64_t Stride = Value->getZExtValue(); 16800 if (Stride < *MaybeRows) { 16801 Diag(StrideExpr->getBeginLoc(), 16802 diag::err_builtin_matrix_stride_too_small); 16803 ArgError = true; 16804 } 16805 } 16806 } 16807 16808 if (ArgError || !MaybeRows || !MaybeColumns) 16809 return ExprError(); 16810 16811 TheCall->setType( 16812 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16813 return CallResult; 16814 } 16815 16816 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16817 ExprResult CallResult) { 16818 if (checkArgCount(*this, TheCall, 3)) 16819 return ExprError(); 16820 16821 unsigned PtrArgIdx = 1; 16822 Expr *MatrixExpr = TheCall->getArg(0); 16823 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16824 Expr *StrideExpr = TheCall->getArg(2); 16825 16826 bool ArgError = false; 16827 16828 { 16829 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16830 if (MatrixConv.isInvalid()) 16831 return MatrixConv; 16832 MatrixExpr = MatrixConv.get(); 16833 TheCall->setArg(0, MatrixExpr); 16834 } 16835 if (MatrixExpr->isTypeDependent()) { 16836 TheCall->setType(Context.DependentTy); 16837 return TheCall; 16838 } 16839 16840 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16841 if (!MatrixTy) { 16842 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16843 ArgError = true; 16844 } 16845 16846 { 16847 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16848 if (PtrConv.isInvalid()) 16849 return PtrConv; 16850 PtrExpr = PtrConv.get(); 16851 TheCall->setArg(1, PtrExpr); 16852 if (PtrExpr->isTypeDependent()) { 16853 TheCall->setType(Context.DependentTy); 16854 return TheCall; 16855 } 16856 } 16857 16858 // Check pointer argument. 16859 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16860 if (!PtrTy) { 16861 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16862 << PtrArgIdx + 1; 16863 ArgError = true; 16864 } else { 16865 QualType ElementTy = PtrTy->getPointeeType(); 16866 if (ElementTy.isConstQualified()) { 16867 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16868 ArgError = true; 16869 } 16870 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16871 if (MatrixTy && 16872 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16873 Diag(PtrExpr->getBeginLoc(), 16874 diag::err_builtin_matrix_pointer_arg_mismatch) 16875 << ElementTy << MatrixTy->getElementType(); 16876 ArgError = true; 16877 } 16878 } 16879 16880 // Apply default Lvalue conversions and convert the stride expression to 16881 // size_t. 16882 { 16883 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16884 if (StrideConv.isInvalid()) 16885 return StrideConv; 16886 16887 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16888 if (StrideConv.isInvalid()) 16889 return StrideConv; 16890 StrideExpr = StrideConv.get(); 16891 TheCall->setArg(2, StrideExpr); 16892 } 16893 16894 // Check stride argument. 16895 if (MatrixTy) { 16896 if (Optional<llvm::APSInt> Value = 16897 StrideExpr->getIntegerConstantExpr(Context)) { 16898 uint64_t Stride = Value->getZExtValue(); 16899 if (Stride < MatrixTy->getNumRows()) { 16900 Diag(StrideExpr->getBeginLoc(), 16901 diag::err_builtin_matrix_stride_too_small); 16902 ArgError = true; 16903 } 16904 } 16905 } 16906 16907 if (ArgError) 16908 return ExprError(); 16909 16910 return CallResult; 16911 } 16912 16913 /// \brief Enforce the bounds of a TCB 16914 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16915 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16916 /// and enforce_tcb_leaf attributes. 16917 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16918 const FunctionDecl *Callee) { 16919 const FunctionDecl *Caller = getCurFunctionDecl(); 16920 16921 // Calls to builtins are not enforced. 16922 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16923 Callee->getBuiltinID() != 0) 16924 return; 16925 16926 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16927 // all TCBs the callee is a part of. 16928 llvm::StringSet<> CalleeTCBs; 16929 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16930 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16931 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16932 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16933 16934 // Go through the TCBs the caller is a part of and emit warnings if Caller 16935 // is in a TCB that the Callee is not. 16936 for_each( 16937 Caller->specific_attrs<EnforceTCBAttr>(), 16938 [&](const auto *A) { 16939 StringRef CallerTCB = A->getTCBName(); 16940 if (CalleeTCBs.count(CallerTCB) == 0) { 16941 this->Diag(TheCall->getExprLoc(), 16942 diag::warn_tcb_enforcement_violation) << Callee 16943 << CallerTCB; 16944 } 16945 }); 16946 } 16947