1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 592 /// __builtin_*_chk function, then use the object size argument specified in the 593 /// source. Otherwise, infer the object size using __builtin_object_size. 594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 595 CallExpr *TheCall) { 596 // FIXME: There are some more useful checks we could be doing here: 597 // - Evaluate strlen of strcpy arguments, use as object size. 598 599 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 600 isConstantEvaluated()) 601 return; 602 603 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 604 if (!BuiltinID) 605 return; 606 607 const TargetInfo &TI = getASTContext().getTargetInfo(); 608 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 609 610 unsigned DiagID = 0; 611 bool IsChkVariant = false; 612 Optional<llvm::APSInt> UsedSize; 613 unsigned SizeIndex, ObjectIndex; 614 switch (BuiltinID) { 615 default: 616 return; 617 case Builtin::BIsprintf: 618 case Builtin::BI__builtin___sprintf_chk: { 619 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 620 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 621 622 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 623 624 if (!Format->isAscii() && !Format->isUTF8()) 625 return; 626 627 StringRef FormatStrRef = Format->getString(); 628 EstimateSizeFormatHandler H(FormatStrRef); 629 const char *FormatBytes = FormatStrRef.data(); 630 const ConstantArrayType *T = 631 Context.getAsConstantArrayType(Format->getType()); 632 assert(T && "String literal not of constant array type!"); 633 size_t TypeSize = T->getSize().getZExtValue(); 634 635 // In case there's a null byte somewhere. 636 size_t StrLen = 637 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 638 if (!analyze_format_string::ParsePrintfString( 639 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 640 Context.getTargetInfo(), false)) { 641 DiagID = diag::warn_fortify_source_format_overflow; 642 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 643 .extOrTrunc(SizeTypeWidth); 644 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 645 IsChkVariant = true; 646 ObjectIndex = 2; 647 } else { 648 IsChkVariant = false; 649 ObjectIndex = 0; 650 } 651 break; 652 } 653 } 654 return; 655 } 656 case Builtin::BI__builtin___memcpy_chk: 657 case Builtin::BI__builtin___memmove_chk: 658 case Builtin::BI__builtin___memset_chk: 659 case Builtin::BI__builtin___strlcat_chk: 660 case Builtin::BI__builtin___strlcpy_chk: 661 case Builtin::BI__builtin___strncat_chk: 662 case Builtin::BI__builtin___strncpy_chk: 663 case Builtin::BI__builtin___stpncpy_chk: 664 case Builtin::BI__builtin___memccpy_chk: 665 case Builtin::BI__builtin___mempcpy_chk: { 666 DiagID = diag::warn_builtin_chk_overflow; 667 IsChkVariant = true; 668 SizeIndex = TheCall->getNumArgs() - 2; 669 ObjectIndex = TheCall->getNumArgs() - 1; 670 break; 671 } 672 673 case Builtin::BI__builtin___snprintf_chk: 674 case Builtin::BI__builtin___vsnprintf_chk: { 675 DiagID = diag::warn_builtin_chk_overflow; 676 IsChkVariant = true; 677 SizeIndex = 1; 678 ObjectIndex = 3; 679 break; 680 } 681 682 case Builtin::BIstrncat: 683 case Builtin::BI__builtin_strncat: 684 case Builtin::BIstrncpy: 685 case Builtin::BI__builtin_strncpy: 686 case Builtin::BIstpncpy: 687 case Builtin::BI__builtin_stpncpy: { 688 // Whether these functions overflow depends on the runtime strlen of the 689 // string, not just the buffer size, so emitting the "always overflow" 690 // diagnostic isn't quite right. We should still diagnose passing a buffer 691 // size larger than the destination buffer though; this is a runtime abort 692 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 693 DiagID = diag::warn_fortify_source_size_mismatch; 694 SizeIndex = TheCall->getNumArgs() - 1; 695 ObjectIndex = 0; 696 break; 697 } 698 699 case Builtin::BImemcpy: 700 case Builtin::BI__builtin_memcpy: 701 case Builtin::BImemmove: 702 case Builtin::BI__builtin_memmove: 703 case Builtin::BImemset: 704 case Builtin::BI__builtin_memset: 705 case Builtin::BImempcpy: 706 case Builtin::BI__builtin_mempcpy: { 707 DiagID = diag::warn_fortify_source_overflow; 708 SizeIndex = TheCall->getNumArgs() - 1; 709 ObjectIndex = 0; 710 break; 711 } 712 case Builtin::BIsnprintf: 713 case Builtin::BI__builtin_snprintf: 714 case Builtin::BIvsnprintf: 715 case Builtin::BI__builtin_vsnprintf: { 716 DiagID = diag::warn_fortify_source_size_mismatch; 717 SizeIndex = 1; 718 ObjectIndex = 0; 719 break; 720 } 721 } 722 723 llvm::APSInt ObjectSize; 724 // For __builtin___*_chk, the object size is explicitly provided by the caller 725 // (usually using __builtin_object_size). Use that value to check this call. 726 if (IsChkVariant) { 727 Expr::EvalResult Result; 728 Expr *SizeArg = TheCall->getArg(ObjectIndex); 729 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 730 return; 731 ObjectSize = Result.Val.getInt(); 732 733 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 734 } else { 735 // If the parameter has a pass_object_size attribute, then we should use its 736 // (potentially) more strict checking mode. Otherwise, conservatively assume 737 // type 0. 738 int BOSType = 0; 739 if (const auto *POS = 740 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 741 BOSType = POS->getType(); 742 743 Expr *ObjArg = TheCall->getArg(ObjectIndex); 744 uint64_t Result; 745 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 746 return; 747 // Get the object size in the target's size_t width. 748 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 749 } 750 751 // Evaluate the number of bytes of the object that this call will use. 752 if (!UsedSize) { 753 Expr::EvalResult Result; 754 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 755 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 756 return; 757 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 758 } 759 760 if (UsedSize.getValue().ule(ObjectSize)) 761 return; 762 763 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 764 // Skim off the details of whichever builtin was called to produce a better 765 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 766 if (IsChkVariant) { 767 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 768 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 769 } else if (FunctionName.startswith("__builtin_")) { 770 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 771 } 772 773 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 774 PDiag(DiagID) 775 << FunctionName << toString(ObjectSize, /*Radix=*/10) 776 << toString(UsedSize.getValue(), /*Radix=*/10)); 777 } 778 779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 780 Scope::ScopeFlags NeededScopeFlags, 781 unsigned DiagID) { 782 // Scopes aren't available during instantiation. Fortunately, builtin 783 // functions cannot be template args so they cannot be formed through template 784 // instantiation. Therefore checking once during the parse is sufficient. 785 if (SemaRef.inTemplateInstantiation()) 786 return false; 787 788 Scope *S = SemaRef.getCurScope(); 789 while (S && !S->isSEHExceptScope()) 790 S = S->getParent(); 791 if (!S || !(S->getFlags() & NeededScopeFlags)) { 792 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 793 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 794 << DRE->getDecl()->getIdentifier(); 795 return true; 796 } 797 798 return false; 799 } 800 801 static inline bool isBlockPointer(Expr *Arg) { 802 return Arg->getType()->isBlockPointerType(); 803 } 804 805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 806 /// void*, which is a requirement of device side enqueue. 807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 808 const BlockPointerType *BPT = 809 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 810 ArrayRef<QualType> Params = 811 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 812 unsigned ArgCounter = 0; 813 bool IllegalParams = false; 814 // Iterate through the block parameters until either one is found that is not 815 // a local void*, or the block is valid. 816 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 817 I != E; ++I, ++ArgCounter) { 818 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 819 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 820 LangAS::opencl_local) { 821 // Get the location of the error. If a block literal has been passed 822 // (BlockExpr) then we can point straight to the offending argument, 823 // else we just point to the variable reference. 824 SourceLocation ErrorLoc; 825 if (isa<BlockExpr>(BlockArg)) { 826 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 827 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 828 } else if (isa<DeclRefExpr>(BlockArg)) { 829 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 830 } 831 S.Diag(ErrorLoc, 832 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 833 IllegalParams = true; 834 } 835 } 836 837 return IllegalParams; 838 } 839 840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 841 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 843 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 844 return true; 845 } 846 return false; 847 } 848 849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 850 if (checkArgCount(S, TheCall, 2)) 851 return true; 852 853 if (checkOpenCLSubgroupExt(S, TheCall)) 854 return true; 855 856 // First argument is an ndrange_t type. 857 Expr *NDRangeArg = TheCall->getArg(0); 858 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 859 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 860 << TheCall->getDirectCallee() << "'ndrange_t'"; 861 return true; 862 } 863 864 Expr *BlockArg = TheCall->getArg(1); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 874 /// get_kernel_work_group_size 875 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 877 if (checkArgCount(S, TheCall, 1)) 878 return true; 879 880 Expr *BlockArg = TheCall->getArg(0); 881 if (!isBlockPointer(BlockArg)) { 882 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 883 << TheCall->getDirectCallee() << "block"; 884 return true; 885 } 886 return checkOpenCLBlockArgs(S, BlockArg); 887 } 888 889 /// Diagnose integer type and any valid implicit conversion to it. 890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 891 const QualType &IntType); 892 893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 894 unsigned Start, unsigned End) { 895 bool IllegalParams = false; 896 for (unsigned I = Start; I <= End; ++I) 897 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 898 S.Context.getSizeType()); 899 return IllegalParams; 900 } 901 902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 903 /// 'local void*' parameter of passed block. 904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 905 Expr *BlockArg, 906 unsigned NumNonVarArgs) { 907 const BlockPointerType *BPT = 908 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 909 unsigned NumBlockParams = 910 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 911 unsigned TotalNumArgs = TheCall->getNumArgs(); 912 913 // For each argument passed to the block, a corresponding uint needs to 914 // be passed to describe the size of the local memory. 915 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 916 S.Diag(TheCall->getBeginLoc(), 917 diag::err_opencl_enqueue_kernel_local_size_args); 918 return true; 919 } 920 921 // Check that the sizes of the local memory are specified by integers. 922 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 923 TotalNumArgs - 1); 924 } 925 926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 927 /// overload formats specified in Table 6.13.17.1. 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// void (^block)(void)) 932 /// int enqueue_kernel(queue_t queue, 933 /// kernel_enqueue_flags_t flags, 934 /// const ndrange_t ndrange, 935 /// uint num_events_in_wait_list, 936 /// clk_event_t *event_wait_list, 937 /// clk_event_t *event_ret, 938 /// void (^block)(void)) 939 /// int enqueue_kernel(queue_t queue, 940 /// kernel_enqueue_flags_t flags, 941 /// const ndrange_t ndrange, 942 /// void (^block)(local void*, ...), 943 /// uint size0, ...) 944 /// int enqueue_kernel(queue_t queue, 945 /// kernel_enqueue_flags_t flags, 946 /// const ndrange_t ndrange, 947 /// uint num_events_in_wait_list, 948 /// clk_event_t *event_wait_list, 949 /// clk_event_t *event_ret, 950 /// void (^block)(local void*, ...), 951 /// uint size0, ...) 952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 953 unsigned NumArgs = TheCall->getNumArgs(); 954 955 if (NumArgs < 4) { 956 S.Diag(TheCall->getBeginLoc(), 957 diag::err_typecheck_call_too_few_args_at_least) 958 << 0 << 4 << NumArgs; 959 return true; 960 } 961 962 Expr *Arg0 = TheCall->getArg(0); 963 Expr *Arg1 = TheCall->getArg(1); 964 Expr *Arg2 = TheCall->getArg(2); 965 Expr *Arg3 = TheCall->getArg(3); 966 967 // First argument always needs to be a queue_t type. 968 if (!Arg0->getType()->isQueueT()) { 969 S.Diag(TheCall->getArg(0)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 972 return true; 973 } 974 975 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 976 if (!Arg1->getType()->isIntegerType()) { 977 S.Diag(TheCall->getArg(1)->getBeginLoc(), 978 diag::err_opencl_builtin_expected_type) 979 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 980 return true; 981 } 982 983 // Third argument is always an ndrange_t type. 984 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 985 S.Diag(TheCall->getArg(2)->getBeginLoc(), 986 diag::err_opencl_builtin_expected_type) 987 << TheCall->getDirectCallee() << "'ndrange_t'"; 988 return true; 989 } 990 991 // With four arguments, there is only one form that the function could be 992 // called in: no events and no variable arguments. 993 if (NumArgs == 4) { 994 // check that the last argument is the right block type. 995 if (!isBlockPointer(Arg3)) { 996 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 997 << TheCall->getDirectCallee() << "block"; 998 return true; 999 } 1000 // we have a block type, check the prototype 1001 const BlockPointerType *BPT = 1002 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1003 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1004 S.Diag(Arg3->getBeginLoc(), 1005 diag::err_opencl_enqueue_kernel_blocks_no_args); 1006 return true; 1007 } 1008 return false; 1009 } 1010 // we can have block + varargs. 1011 if (isBlockPointer(Arg3)) 1012 return (checkOpenCLBlockArgs(S, Arg3) || 1013 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1014 // last two cases with either exactly 7 args or 7 args and varargs. 1015 if (NumArgs >= 7) { 1016 // check common block argument. 1017 Expr *Arg6 = TheCall->getArg(6); 1018 if (!isBlockPointer(Arg6)) { 1019 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1020 << TheCall->getDirectCallee() << "block"; 1021 return true; 1022 } 1023 if (checkOpenCLBlockArgs(S, Arg6)) 1024 return true; 1025 1026 // Forth argument has to be any integer type. 1027 if (!Arg3->getType()->isIntegerType()) { 1028 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1029 diag::err_opencl_builtin_expected_type) 1030 << TheCall->getDirectCallee() << "integer"; 1031 return true; 1032 } 1033 // check remaining common arguments. 1034 Expr *Arg4 = TheCall->getArg(4); 1035 Expr *Arg5 = TheCall->getArg(5); 1036 1037 // Fifth argument is always passed as a pointer to clk_event_t. 1038 if (!Arg4->isNullPointerConstant(S.Context, 1039 Expr::NPC_ValueDependentIsNotNull) && 1040 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1041 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1042 diag::err_opencl_builtin_expected_type) 1043 << TheCall->getDirectCallee() 1044 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1045 return true; 1046 } 1047 1048 // Sixth argument is always passed as a pointer to clk_event_t. 1049 if (!Arg5->isNullPointerConstant(S.Context, 1050 Expr::NPC_ValueDependentIsNotNull) && 1051 !(Arg5->getType()->isPointerType() && 1052 Arg5->getType()->getPointeeType()->isClkEventT())) { 1053 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1054 diag::err_opencl_builtin_expected_type) 1055 << TheCall->getDirectCallee() 1056 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1057 return true; 1058 } 1059 1060 if (NumArgs == 7) 1061 return false; 1062 1063 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1064 } 1065 1066 // None of the specific case has been detected, give generic error 1067 S.Diag(TheCall->getBeginLoc(), 1068 diag::err_opencl_enqueue_kernel_incorrect_args); 1069 return true; 1070 } 1071 1072 /// Returns OpenCL access qual. 1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1074 return D->getAttr<OpenCLAccessAttr>(); 1075 } 1076 1077 /// Returns true if pipe element type is different from the pointer. 1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1079 const Expr *Arg0 = Call->getArg(0); 1080 // First argument type should always be pipe. 1081 if (!Arg0->getType()->isPipeType()) { 1082 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1083 << Call->getDirectCallee() << Arg0->getSourceRange(); 1084 return true; 1085 } 1086 OpenCLAccessAttr *AccessQual = 1087 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1088 // Validates the access qualifier is compatible with the call. 1089 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1090 // read_only and write_only, and assumed to be read_only if no qualifier is 1091 // specified. 1092 switch (Call->getDirectCallee()->getBuiltinID()) { 1093 case Builtin::BIread_pipe: 1094 case Builtin::BIreserve_read_pipe: 1095 case Builtin::BIcommit_read_pipe: 1096 case Builtin::BIwork_group_reserve_read_pipe: 1097 case Builtin::BIsub_group_reserve_read_pipe: 1098 case Builtin::BIwork_group_commit_read_pipe: 1099 case Builtin::BIsub_group_commit_read_pipe: 1100 if (!(!AccessQual || AccessQual->isReadOnly())) { 1101 S.Diag(Arg0->getBeginLoc(), 1102 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1103 << "read_only" << Arg0->getSourceRange(); 1104 return true; 1105 } 1106 break; 1107 case Builtin::BIwrite_pipe: 1108 case Builtin::BIreserve_write_pipe: 1109 case Builtin::BIcommit_write_pipe: 1110 case Builtin::BIwork_group_reserve_write_pipe: 1111 case Builtin::BIsub_group_reserve_write_pipe: 1112 case Builtin::BIwork_group_commit_write_pipe: 1113 case Builtin::BIsub_group_commit_write_pipe: 1114 if (!(AccessQual && AccessQual->isWriteOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "write_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 default: 1122 break; 1123 } 1124 return false; 1125 } 1126 1127 /// Returns true if pipe element type is different from the pointer. 1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1129 const Expr *Arg0 = Call->getArg(0); 1130 const Expr *ArgIdx = Call->getArg(Idx); 1131 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1132 const QualType EltTy = PipeTy->getElementType(); 1133 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1134 // The Idx argument should be a pointer and the type of the pointer and 1135 // the type of pipe element should also be the same. 1136 if (!ArgTy || 1137 !S.Context.hasSameType( 1138 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1139 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1140 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1141 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1142 return true; 1143 } 1144 return false; 1145 } 1146 1147 // Performs semantic analysis for the read/write_pipe call. 1148 // \param S Reference to the semantic analyzer. 1149 // \param Call A pointer to the builtin call. 1150 // \return True if a semantic error has been found, false otherwise. 1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1152 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1153 // functions have two forms. 1154 switch (Call->getNumArgs()) { 1155 case 2: 1156 if (checkOpenCLPipeArg(S, Call)) 1157 return true; 1158 // The call with 2 arguments should be 1159 // read/write_pipe(pipe T, T*). 1160 // Check packet type T. 1161 if (checkOpenCLPipePacketType(S, Call, 1)) 1162 return true; 1163 break; 1164 1165 case 4: { 1166 if (checkOpenCLPipeArg(S, Call)) 1167 return true; 1168 // The call with 4 arguments should be 1169 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1170 // Check reserve_id_t. 1171 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1172 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1173 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1174 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1175 return true; 1176 } 1177 1178 // Check the index. 1179 const Expr *Arg2 = Call->getArg(2); 1180 if (!Arg2->getType()->isIntegerType() && 1181 !Arg2->getType()->isUnsignedIntegerType()) { 1182 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1183 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1184 << Arg2->getType() << Arg2->getSourceRange(); 1185 return true; 1186 } 1187 1188 // Check packet type T. 1189 if (checkOpenCLPipePacketType(S, Call, 3)) 1190 return true; 1191 } break; 1192 default: 1193 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1194 << Call->getDirectCallee() << Call->getSourceRange(); 1195 return true; 1196 } 1197 1198 return false; 1199 } 1200 1201 // Performs a semantic analysis on the {work_group_/sub_group_ 1202 // /_}reserve_{read/write}_pipe 1203 // \param S Reference to the semantic analyzer. 1204 // \param Call The call to the builtin function to be analyzed. 1205 // \return True if a semantic error was found, false otherwise. 1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1207 if (checkArgCount(S, Call, 2)) 1208 return true; 1209 1210 if (checkOpenCLPipeArg(S, Call)) 1211 return true; 1212 1213 // Check the reserve size. 1214 if (!Call->getArg(1)->getType()->isIntegerType() && 1215 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1216 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1217 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1218 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1219 return true; 1220 } 1221 1222 // Since return type of reserve_read/write_pipe built-in function is 1223 // reserve_id_t, which is not defined in the builtin def file , we used int 1224 // as return type and need to override the return type of these functions. 1225 Call->setType(S.Context.OCLReserveIDTy); 1226 1227 return false; 1228 } 1229 1230 // Performs a semantic analysis on {work_group_/sub_group_ 1231 // /_}commit_{read/write}_pipe 1232 // \param S Reference to the semantic analyzer. 1233 // \param Call The call to the builtin function to be analyzed. 1234 // \return True if a semantic error was found, false otherwise. 1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1236 if (checkArgCount(S, Call, 2)) 1237 return true; 1238 1239 if (checkOpenCLPipeArg(S, Call)) 1240 return true; 1241 1242 // Check reserve_id_t. 1243 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1244 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1245 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1246 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1247 return true; 1248 } 1249 1250 return false; 1251 } 1252 1253 // Performs a semantic analysis on the call to built-in Pipe 1254 // Query Functions. 1255 // \param S Reference to the semantic analyzer. 1256 // \param Call The call to the builtin function to be analyzed. 1257 // \return True if a semantic error was found, false otherwise. 1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1259 if (checkArgCount(S, Call, 1)) 1260 return true; 1261 1262 if (!Call->getArg(0)->getType()->isPipeType()) { 1263 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1264 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1265 return true; 1266 } 1267 1268 return false; 1269 } 1270 1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1272 // Performs semantic analysis for the to_global/local/private call. 1273 // \param S Reference to the semantic analyzer. 1274 // \param BuiltinID ID of the builtin function. 1275 // \param Call A pointer to the builtin call. 1276 // \return True if a semantic error has been found, false otherwise. 1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1278 CallExpr *Call) { 1279 if (checkArgCount(S, Call, 1)) 1280 return true; 1281 1282 auto RT = Call->getArg(0)->getType(); 1283 if (!RT->isPointerType() || RT->getPointeeType() 1284 .getAddressSpace() == LangAS::opencl_constant) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1287 return true; 1288 } 1289 1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1291 S.Diag(Call->getArg(0)->getBeginLoc(), 1292 diag::warn_opencl_generic_address_space_arg) 1293 << Call->getDirectCallee()->getNameInfo().getAsString() 1294 << Call->getArg(0)->getSourceRange(); 1295 } 1296 1297 RT = RT->getPointeeType(); 1298 auto Qual = RT.getQualifiers(); 1299 switch (BuiltinID) { 1300 case Builtin::BIto_global: 1301 Qual.setAddressSpace(LangAS::opencl_global); 1302 break; 1303 case Builtin::BIto_local: 1304 Qual.setAddressSpace(LangAS::opencl_local); 1305 break; 1306 case Builtin::BIto_private: 1307 Qual.setAddressSpace(LangAS::opencl_private); 1308 break; 1309 default: 1310 llvm_unreachable("Invalid builtin function"); 1311 } 1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1313 RT.getUnqualifiedType(), Qual))); 1314 1315 return false; 1316 } 1317 1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1319 if (checkArgCount(S, TheCall, 1)) 1320 return ExprError(); 1321 1322 // Compute __builtin_launder's parameter type from the argument. 1323 // The parameter type is: 1324 // * The type of the argument if it's not an array or function type, 1325 // Otherwise, 1326 // * The decayed argument type. 1327 QualType ParamTy = [&]() { 1328 QualType ArgTy = TheCall->getArg(0)->getType(); 1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1330 return S.Context.getPointerType(Ty->getElementType()); 1331 if (ArgTy->isFunctionType()) { 1332 return S.Context.getPointerType(ArgTy); 1333 } 1334 return ArgTy; 1335 }(); 1336 1337 TheCall->setType(ParamTy); 1338 1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1340 if (!ParamTy->isPointerType()) 1341 return 0; 1342 if (ParamTy->isFunctionPointerType()) 1343 return 1; 1344 if (ParamTy->isVoidPointerType()) 1345 return 2; 1346 return llvm::Optional<unsigned>{}; 1347 }(); 1348 if (DiagSelect.hasValue()) { 1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1350 << DiagSelect.getValue() << TheCall->getSourceRange(); 1351 return ExprError(); 1352 } 1353 1354 // We either have an incomplete class type, or we have a class template 1355 // whose instantiation has not been forced. Example: 1356 // 1357 // template <class T> struct Foo { T value; }; 1358 // Foo<int> *p = nullptr; 1359 // auto *d = __builtin_launder(p); 1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1361 diag::err_incomplete_type)) 1362 return ExprError(); 1363 1364 assert(ParamTy->getPointeeType()->isObjectType() && 1365 "Unhandled non-object pointer case"); 1366 1367 InitializedEntity Entity = 1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1369 ExprResult Arg = 1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1371 if (Arg.isInvalid()) 1372 return ExprError(); 1373 TheCall->setArg(0, Arg.get()); 1374 1375 return TheCall; 1376 } 1377 1378 // Emit an error and return true if the current architecture is not in the list 1379 // of supported architectures. 1380 static bool 1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1383 llvm::Triple::ArchType CurArch = 1384 S.getASTContext().getTargetInfo().getTriple().getArch(); 1385 if (llvm::is_contained(SupportedArchs, CurArch)) 1386 return false; 1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1388 << TheCall->getSourceRange(); 1389 return true; 1390 } 1391 1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1393 SourceLocation CallSiteLoc); 1394 1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1396 CallExpr *TheCall) { 1397 switch (TI.getTriple().getArch()) { 1398 default: 1399 // Some builtins don't require additional checking, so just consider these 1400 // acceptable. 1401 return false; 1402 case llvm::Triple::arm: 1403 case llvm::Triple::armeb: 1404 case llvm::Triple::thumb: 1405 case llvm::Triple::thumbeb: 1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1407 case llvm::Triple::aarch64: 1408 case llvm::Triple::aarch64_32: 1409 case llvm::Triple::aarch64_be: 1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1411 case llvm::Triple::bpfeb: 1412 case llvm::Triple::bpfel: 1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::hexagon: 1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1416 case llvm::Triple::mips: 1417 case llvm::Triple::mipsel: 1418 case llvm::Triple::mips64: 1419 case llvm::Triple::mips64el: 1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::systemz: 1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1423 case llvm::Triple::x86: 1424 case llvm::Triple::x86_64: 1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1426 case llvm::Triple::ppc: 1427 case llvm::Triple::ppcle: 1428 case llvm::Triple::ppc64: 1429 case llvm::Triple::ppc64le: 1430 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1431 case llvm::Triple::amdgcn: 1432 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1433 case llvm::Triple::riscv32: 1434 case llvm::Triple::riscv64: 1435 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1436 } 1437 } 1438 1439 ExprResult 1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1441 CallExpr *TheCall) { 1442 ExprResult TheCallResult(TheCall); 1443 1444 // Find out if any arguments are required to be integer constant expressions. 1445 unsigned ICEArguments = 0; 1446 ASTContext::GetBuiltinTypeError Error; 1447 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1448 if (Error != ASTContext::GE_None) 1449 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1450 1451 // If any arguments are required to be ICE's, check and diagnose. 1452 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1453 // Skip arguments not required to be ICE's. 1454 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1455 1456 llvm::APSInt Result; 1457 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1458 return true; 1459 ICEArguments &= ~(1 << ArgNo); 1460 } 1461 1462 switch (BuiltinID) { 1463 case Builtin::BI__builtin___CFStringMakeConstantString: 1464 assert(TheCall->getNumArgs() == 1 && 1465 "Wrong # arguments to builtin CFStringMakeConstantString"); 1466 if (CheckObjCString(TheCall->getArg(0))) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_ms_va_start: 1470 case Builtin::BI__builtin_stdarg_start: 1471 case Builtin::BI__builtin_va_start: 1472 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BI__va_start: { 1476 switch (Context.getTargetInfo().getTriple().getArch()) { 1477 case llvm::Triple::aarch64: 1478 case llvm::Triple::arm: 1479 case llvm::Triple::thumb: 1480 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1481 return ExprError(); 1482 break; 1483 default: 1484 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1485 return ExprError(); 1486 break; 1487 } 1488 break; 1489 } 1490 1491 // The acquire, release, and no fence variants are ARM and AArch64 only. 1492 case Builtin::BI_interlockedbittestandset_acq: 1493 case Builtin::BI_interlockedbittestandset_rel: 1494 case Builtin::BI_interlockedbittestandset_nf: 1495 case Builtin::BI_interlockedbittestandreset_acq: 1496 case Builtin::BI_interlockedbittestandreset_rel: 1497 case Builtin::BI_interlockedbittestandreset_nf: 1498 if (CheckBuiltinTargetSupport( 1499 *this, BuiltinID, TheCall, 1500 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1501 return ExprError(); 1502 break; 1503 1504 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1505 case Builtin::BI_bittest64: 1506 case Builtin::BI_bittestandcomplement64: 1507 case Builtin::BI_bittestandreset64: 1508 case Builtin::BI_bittestandset64: 1509 case Builtin::BI_interlockedbittestandreset64: 1510 case Builtin::BI_interlockedbittestandset64: 1511 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1512 {llvm::Triple::x86_64, llvm::Triple::arm, 1513 llvm::Triple::thumb, llvm::Triple::aarch64})) 1514 return ExprError(); 1515 break; 1516 1517 case Builtin::BI__builtin_isgreater: 1518 case Builtin::BI__builtin_isgreaterequal: 1519 case Builtin::BI__builtin_isless: 1520 case Builtin::BI__builtin_islessequal: 1521 case Builtin::BI__builtin_islessgreater: 1522 case Builtin::BI__builtin_isunordered: 1523 if (SemaBuiltinUnorderedCompare(TheCall)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__builtin_fpclassify: 1527 if (SemaBuiltinFPClassification(TheCall, 6)) 1528 return ExprError(); 1529 break; 1530 case Builtin::BI__builtin_isfinite: 1531 case Builtin::BI__builtin_isinf: 1532 case Builtin::BI__builtin_isinf_sign: 1533 case Builtin::BI__builtin_isnan: 1534 case Builtin::BI__builtin_isnormal: 1535 case Builtin::BI__builtin_signbit: 1536 case Builtin::BI__builtin_signbitf: 1537 case Builtin::BI__builtin_signbitl: 1538 if (SemaBuiltinFPClassification(TheCall, 1)) 1539 return ExprError(); 1540 break; 1541 case Builtin::BI__builtin_shufflevector: 1542 return SemaBuiltinShuffleVector(TheCall); 1543 // TheCall will be freed by the smart pointer here, but that's fine, since 1544 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1545 case Builtin::BI__builtin_prefetch: 1546 if (SemaBuiltinPrefetch(TheCall)) 1547 return ExprError(); 1548 break; 1549 case Builtin::BI__builtin_alloca_with_align: 1550 if (SemaBuiltinAllocaWithAlign(TheCall)) 1551 return ExprError(); 1552 LLVM_FALLTHROUGH; 1553 case Builtin::BI__builtin_alloca: 1554 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1555 << TheCall->getDirectCallee(); 1556 break; 1557 case Builtin::BI__arithmetic_fence: 1558 if (SemaBuiltinArithmeticFence(TheCall)) 1559 return ExprError(); 1560 break; 1561 case Builtin::BI__assume: 1562 case Builtin::BI__builtin_assume: 1563 if (SemaBuiltinAssume(TheCall)) 1564 return ExprError(); 1565 break; 1566 case Builtin::BI__builtin_assume_aligned: 1567 if (SemaBuiltinAssumeAligned(TheCall)) 1568 return ExprError(); 1569 break; 1570 case Builtin::BI__builtin_dynamic_object_size: 1571 case Builtin::BI__builtin_object_size: 1572 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__builtin_longjmp: 1576 if (SemaBuiltinLongjmp(TheCall)) 1577 return ExprError(); 1578 break; 1579 case Builtin::BI__builtin_setjmp: 1580 if (SemaBuiltinSetjmp(TheCall)) 1581 return ExprError(); 1582 break; 1583 case Builtin::BI__builtin_classify_type: 1584 if (checkArgCount(*this, TheCall, 1)) return true; 1585 TheCall->setType(Context.IntTy); 1586 break; 1587 case Builtin::BI__builtin_complex: 1588 if (SemaBuiltinComplex(TheCall)) 1589 return ExprError(); 1590 break; 1591 case Builtin::BI__builtin_constant_p: { 1592 if (checkArgCount(*this, TheCall, 1)) return true; 1593 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1594 if (Arg.isInvalid()) return true; 1595 TheCall->setArg(0, Arg.get()); 1596 TheCall->setType(Context.IntTy); 1597 break; 1598 } 1599 case Builtin::BI__builtin_launder: 1600 return SemaBuiltinLaunder(*this, TheCall); 1601 case Builtin::BI__sync_fetch_and_add: 1602 case Builtin::BI__sync_fetch_and_add_1: 1603 case Builtin::BI__sync_fetch_and_add_2: 1604 case Builtin::BI__sync_fetch_and_add_4: 1605 case Builtin::BI__sync_fetch_and_add_8: 1606 case Builtin::BI__sync_fetch_and_add_16: 1607 case Builtin::BI__sync_fetch_and_sub: 1608 case Builtin::BI__sync_fetch_and_sub_1: 1609 case Builtin::BI__sync_fetch_and_sub_2: 1610 case Builtin::BI__sync_fetch_and_sub_4: 1611 case Builtin::BI__sync_fetch_and_sub_8: 1612 case Builtin::BI__sync_fetch_and_sub_16: 1613 case Builtin::BI__sync_fetch_and_or: 1614 case Builtin::BI__sync_fetch_and_or_1: 1615 case Builtin::BI__sync_fetch_and_or_2: 1616 case Builtin::BI__sync_fetch_and_or_4: 1617 case Builtin::BI__sync_fetch_and_or_8: 1618 case Builtin::BI__sync_fetch_and_or_16: 1619 case Builtin::BI__sync_fetch_and_and: 1620 case Builtin::BI__sync_fetch_and_and_1: 1621 case Builtin::BI__sync_fetch_and_and_2: 1622 case Builtin::BI__sync_fetch_and_and_4: 1623 case Builtin::BI__sync_fetch_and_and_8: 1624 case Builtin::BI__sync_fetch_and_and_16: 1625 case Builtin::BI__sync_fetch_and_xor: 1626 case Builtin::BI__sync_fetch_and_xor_1: 1627 case Builtin::BI__sync_fetch_and_xor_2: 1628 case Builtin::BI__sync_fetch_and_xor_4: 1629 case Builtin::BI__sync_fetch_and_xor_8: 1630 case Builtin::BI__sync_fetch_and_xor_16: 1631 case Builtin::BI__sync_fetch_and_nand: 1632 case Builtin::BI__sync_fetch_and_nand_1: 1633 case Builtin::BI__sync_fetch_and_nand_2: 1634 case Builtin::BI__sync_fetch_and_nand_4: 1635 case Builtin::BI__sync_fetch_and_nand_8: 1636 case Builtin::BI__sync_fetch_and_nand_16: 1637 case Builtin::BI__sync_add_and_fetch: 1638 case Builtin::BI__sync_add_and_fetch_1: 1639 case Builtin::BI__sync_add_and_fetch_2: 1640 case Builtin::BI__sync_add_and_fetch_4: 1641 case Builtin::BI__sync_add_and_fetch_8: 1642 case Builtin::BI__sync_add_and_fetch_16: 1643 case Builtin::BI__sync_sub_and_fetch: 1644 case Builtin::BI__sync_sub_and_fetch_1: 1645 case Builtin::BI__sync_sub_and_fetch_2: 1646 case Builtin::BI__sync_sub_and_fetch_4: 1647 case Builtin::BI__sync_sub_and_fetch_8: 1648 case Builtin::BI__sync_sub_and_fetch_16: 1649 case Builtin::BI__sync_and_and_fetch: 1650 case Builtin::BI__sync_and_and_fetch_1: 1651 case Builtin::BI__sync_and_and_fetch_2: 1652 case Builtin::BI__sync_and_and_fetch_4: 1653 case Builtin::BI__sync_and_and_fetch_8: 1654 case Builtin::BI__sync_and_and_fetch_16: 1655 case Builtin::BI__sync_or_and_fetch: 1656 case Builtin::BI__sync_or_and_fetch_1: 1657 case Builtin::BI__sync_or_and_fetch_2: 1658 case Builtin::BI__sync_or_and_fetch_4: 1659 case Builtin::BI__sync_or_and_fetch_8: 1660 case Builtin::BI__sync_or_and_fetch_16: 1661 case Builtin::BI__sync_xor_and_fetch: 1662 case Builtin::BI__sync_xor_and_fetch_1: 1663 case Builtin::BI__sync_xor_and_fetch_2: 1664 case Builtin::BI__sync_xor_and_fetch_4: 1665 case Builtin::BI__sync_xor_and_fetch_8: 1666 case Builtin::BI__sync_xor_and_fetch_16: 1667 case Builtin::BI__sync_nand_and_fetch: 1668 case Builtin::BI__sync_nand_and_fetch_1: 1669 case Builtin::BI__sync_nand_and_fetch_2: 1670 case Builtin::BI__sync_nand_and_fetch_4: 1671 case Builtin::BI__sync_nand_and_fetch_8: 1672 case Builtin::BI__sync_nand_and_fetch_16: 1673 case Builtin::BI__sync_val_compare_and_swap: 1674 case Builtin::BI__sync_val_compare_and_swap_1: 1675 case Builtin::BI__sync_val_compare_and_swap_2: 1676 case Builtin::BI__sync_val_compare_and_swap_4: 1677 case Builtin::BI__sync_val_compare_and_swap_8: 1678 case Builtin::BI__sync_val_compare_and_swap_16: 1679 case Builtin::BI__sync_bool_compare_and_swap: 1680 case Builtin::BI__sync_bool_compare_and_swap_1: 1681 case Builtin::BI__sync_bool_compare_and_swap_2: 1682 case Builtin::BI__sync_bool_compare_and_swap_4: 1683 case Builtin::BI__sync_bool_compare_and_swap_8: 1684 case Builtin::BI__sync_bool_compare_and_swap_16: 1685 case Builtin::BI__sync_lock_test_and_set: 1686 case Builtin::BI__sync_lock_test_and_set_1: 1687 case Builtin::BI__sync_lock_test_and_set_2: 1688 case Builtin::BI__sync_lock_test_and_set_4: 1689 case Builtin::BI__sync_lock_test_and_set_8: 1690 case Builtin::BI__sync_lock_test_and_set_16: 1691 case Builtin::BI__sync_lock_release: 1692 case Builtin::BI__sync_lock_release_1: 1693 case Builtin::BI__sync_lock_release_2: 1694 case Builtin::BI__sync_lock_release_4: 1695 case Builtin::BI__sync_lock_release_8: 1696 case Builtin::BI__sync_lock_release_16: 1697 case Builtin::BI__sync_swap: 1698 case Builtin::BI__sync_swap_1: 1699 case Builtin::BI__sync_swap_2: 1700 case Builtin::BI__sync_swap_4: 1701 case Builtin::BI__sync_swap_8: 1702 case Builtin::BI__sync_swap_16: 1703 return SemaBuiltinAtomicOverloaded(TheCallResult); 1704 case Builtin::BI__sync_synchronize: 1705 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1706 << TheCall->getCallee()->getSourceRange(); 1707 break; 1708 case Builtin::BI__builtin_nontemporal_load: 1709 case Builtin::BI__builtin_nontemporal_store: 1710 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1711 case Builtin::BI__builtin_memcpy_inline: { 1712 clang::Expr *SizeOp = TheCall->getArg(2); 1713 // We warn about copying to or from `nullptr` pointers when `size` is 1714 // greater than 0. When `size` is value dependent we cannot evaluate its 1715 // value so we bail out. 1716 if (SizeOp->isValueDependent()) 1717 break; 1718 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1719 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1720 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1721 } 1722 break; 1723 } 1724 #define BUILTIN(ID, TYPE, ATTRS) 1725 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1726 case Builtin::BI##ID: \ 1727 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1728 #include "clang/Basic/Builtins.def" 1729 case Builtin::BI__annotation: 1730 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1731 return ExprError(); 1732 break; 1733 case Builtin::BI__builtin_annotation: 1734 if (SemaBuiltinAnnotation(*this, TheCall)) 1735 return ExprError(); 1736 break; 1737 case Builtin::BI__builtin_addressof: 1738 if (SemaBuiltinAddressof(*this, TheCall)) 1739 return ExprError(); 1740 break; 1741 case Builtin::BI__builtin_is_aligned: 1742 case Builtin::BI__builtin_align_up: 1743 case Builtin::BI__builtin_align_down: 1744 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_add_overflow: 1748 case Builtin::BI__builtin_sub_overflow: 1749 case Builtin::BI__builtin_mul_overflow: 1750 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1751 return ExprError(); 1752 break; 1753 case Builtin::BI__builtin_operator_new: 1754 case Builtin::BI__builtin_operator_delete: { 1755 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1756 ExprResult Res = 1757 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1758 if (Res.isInvalid()) 1759 CorrectDelayedTyposInExpr(TheCallResult.get()); 1760 return Res; 1761 } 1762 case Builtin::BI__builtin_dump_struct: { 1763 // We first want to ensure we are called with 2 arguments 1764 if (checkArgCount(*this, TheCall, 2)) 1765 return ExprError(); 1766 // Ensure that the first argument is of type 'struct XX *' 1767 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1768 const QualType PtrArgType = PtrArg->getType(); 1769 if (!PtrArgType->isPointerType() || 1770 !PtrArgType->getPointeeType()->isRecordType()) { 1771 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1772 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1773 << "structure pointer"; 1774 return ExprError(); 1775 } 1776 1777 // Ensure that the second argument is of type 'FunctionType' 1778 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1779 const QualType FnPtrArgType = FnPtrArg->getType(); 1780 if (!FnPtrArgType->isPointerType()) { 1781 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1782 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1783 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1784 return ExprError(); 1785 } 1786 1787 const auto *FuncType = 1788 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1789 1790 if (!FuncType) { 1791 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1792 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1793 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1794 return ExprError(); 1795 } 1796 1797 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1798 if (!FT->getNumParams()) { 1799 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1800 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1801 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1802 return ExprError(); 1803 } 1804 QualType PT = FT->getParamType(0); 1805 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1806 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1807 !PT->getPointeeType().isConstQualified()) { 1808 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1809 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1810 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1811 return ExprError(); 1812 } 1813 } 1814 1815 TheCall->setType(Context.IntTy); 1816 break; 1817 } 1818 case Builtin::BI__builtin_expect_with_probability: { 1819 // We first want to ensure we are called with 3 arguments 1820 if (checkArgCount(*this, TheCall, 3)) 1821 return ExprError(); 1822 // then check probability is constant float in range [0.0, 1.0] 1823 const Expr *ProbArg = TheCall->getArg(2); 1824 SmallVector<PartialDiagnosticAt, 8> Notes; 1825 Expr::EvalResult Eval; 1826 Eval.Diag = &Notes; 1827 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1828 !Eval.Val.isFloat()) { 1829 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1830 << ProbArg->getSourceRange(); 1831 for (const PartialDiagnosticAt &PDiag : Notes) 1832 Diag(PDiag.first, PDiag.second); 1833 return ExprError(); 1834 } 1835 llvm::APFloat Probability = Eval.Val.getFloat(); 1836 bool LoseInfo = false; 1837 Probability.convert(llvm::APFloat::IEEEdouble(), 1838 llvm::RoundingMode::Dynamic, &LoseInfo); 1839 if (!(Probability >= llvm::APFloat(0.0) && 1840 Probability <= llvm::APFloat(1.0))) { 1841 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1842 << ProbArg->getSourceRange(); 1843 return ExprError(); 1844 } 1845 break; 1846 } 1847 case Builtin::BI__builtin_preserve_access_index: 1848 if (SemaBuiltinPreserveAI(*this, TheCall)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__builtin_call_with_static_chain: 1852 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1853 return ExprError(); 1854 break; 1855 case Builtin::BI__exception_code: 1856 case Builtin::BI_exception_code: 1857 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1858 diag::err_seh___except_block)) 1859 return ExprError(); 1860 break; 1861 case Builtin::BI__exception_info: 1862 case Builtin::BI_exception_info: 1863 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1864 diag::err_seh___except_filter)) 1865 return ExprError(); 1866 break; 1867 case Builtin::BI__GetExceptionInfo: 1868 if (checkArgCount(*this, TheCall, 1)) 1869 return ExprError(); 1870 1871 if (CheckCXXThrowOperand( 1872 TheCall->getBeginLoc(), 1873 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1874 TheCall)) 1875 return ExprError(); 1876 1877 TheCall->setType(Context.VoidPtrTy); 1878 break; 1879 // OpenCL v2.0, s6.13.16 - Pipe functions 1880 case Builtin::BIread_pipe: 1881 case Builtin::BIwrite_pipe: 1882 // Since those two functions are declared with var args, we need a semantic 1883 // check for the argument. 1884 if (SemaBuiltinRWPipe(*this, TheCall)) 1885 return ExprError(); 1886 break; 1887 case Builtin::BIreserve_read_pipe: 1888 case Builtin::BIreserve_write_pipe: 1889 case Builtin::BIwork_group_reserve_read_pipe: 1890 case Builtin::BIwork_group_reserve_write_pipe: 1891 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1892 return ExprError(); 1893 break; 1894 case Builtin::BIsub_group_reserve_read_pipe: 1895 case Builtin::BIsub_group_reserve_write_pipe: 1896 if (checkOpenCLSubgroupExt(*this, TheCall) || 1897 SemaBuiltinReserveRWPipe(*this, TheCall)) 1898 return ExprError(); 1899 break; 1900 case Builtin::BIcommit_read_pipe: 1901 case Builtin::BIcommit_write_pipe: 1902 case Builtin::BIwork_group_commit_read_pipe: 1903 case Builtin::BIwork_group_commit_write_pipe: 1904 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1905 return ExprError(); 1906 break; 1907 case Builtin::BIsub_group_commit_read_pipe: 1908 case Builtin::BIsub_group_commit_write_pipe: 1909 if (checkOpenCLSubgroupExt(*this, TheCall) || 1910 SemaBuiltinCommitRWPipe(*this, TheCall)) 1911 return ExprError(); 1912 break; 1913 case Builtin::BIget_pipe_num_packets: 1914 case Builtin::BIget_pipe_max_packets: 1915 if (SemaBuiltinPipePackets(*this, TheCall)) 1916 return ExprError(); 1917 break; 1918 case Builtin::BIto_global: 1919 case Builtin::BIto_local: 1920 case Builtin::BIto_private: 1921 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1922 return ExprError(); 1923 break; 1924 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1925 case Builtin::BIenqueue_kernel: 1926 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1927 return ExprError(); 1928 break; 1929 case Builtin::BIget_kernel_work_group_size: 1930 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1931 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1932 return ExprError(); 1933 break; 1934 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1935 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1936 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1937 return ExprError(); 1938 break; 1939 case Builtin::BI__builtin_os_log_format: 1940 Cleanup.setExprNeedsCleanups(true); 1941 LLVM_FALLTHROUGH; 1942 case Builtin::BI__builtin_os_log_format_buffer_size: 1943 if (SemaBuiltinOSLogFormat(TheCall)) 1944 return ExprError(); 1945 break; 1946 case Builtin::BI__builtin_frame_address: 1947 case Builtin::BI__builtin_return_address: { 1948 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1949 return ExprError(); 1950 1951 // -Wframe-address warning if non-zero passed to builtin 1952 // return/frame address. 1953 Expr::EvalResult Result; 1954 if (!TheCall->getArg(0)->isValueDependent() && 1955 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1956 Result.Val.getInt() != 0) 1957 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1958 << ((BuiltinID == Builtin::BI__builtin_return_address) 1959 ? "__builtin_return_address" 1960 : "__builtin_frame_address") 1961 << TheCall->getSourceRange(); 1962 break; 1963 } 1964 1965 case Builtin::BI__builtin_matrix_transpose: 1966 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1967 1968 case Builtin::BI__builtin_matrix_column_major_load: 1969 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1970 1971 case Builtin::BI__builtin_matrix_column_major_store: 1972 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1973 1974 case Builtin::BI__builtin_get_device_side_mangled_name: { 1975 auto Check = [](CallExpr *TheCall) { 1976 if (TheCall->getNumArgs() != 1) 1977 return false; 1978 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1979 if (!DRE) 1980 return false; 1981 auto *D = DRE->getDecl(); 1982 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1983 return false; 1984 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1985 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 1986 }; 1987 if (!Check(TheCall)) { 1988 Diag(TheCall->getBeginLoc(), 1989 diag::err_hip_invalid_args_builtin_mangled_name); 1990 return ExprError(); 1991 } 1992 } 1993 } 1994 1995 // Since the target specific builtins for each arch overlap, only check those 1996 // of the arch we are compiling for. 1997 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1998 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1999 assert(Context.getAuxTargetInfo() && 2000 "Aux Target Builtin, but not an aux target?"); 2001 2002 if (CheckTSBuiltinFunctionCall( 2003 *Context.getAuxTargetInfo(), 2004 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2005 return ExprError(); 2006 } else { 2007 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2008 TheCall)) 2009 return ExprError(); 2010 } 2011 } 2012 2013 return TheCallResult; 2014 } 2015 2016 // Get the valid immediate range for the specified NEON type code. 2017 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2018 NeonTypeFlags Type(t); 2019 int IsQuad = ForceQuad ? true : Type.isQuad(); 2020 switch (Type.getEltType()) { 2021 case NeonTypeFlags::Int8: 2022 case NeonTypeFlags::Poly8: 2023 return shift ? 7 : (8 << IsQuad) - 1; 2024 case NeonTypeFlags::Int16: 2025 case NeonTypeFlags::Poly16: 2026 return shift ? 15 : (4 << IsQuad) - 1; 2027 case NeonTypeFlags::Int32: 2028 return shift ? 31 : (2 << IsQuad) - 1; 2029 case NeonTypeFlags::Int64: 2030 case NeonTypeFlags::Poly64: 2031 return shift ? 63 : (1 << IsQuad) - 1; 2032 case NeonTypeFlags::Poly128: 2033 return shift ? 127 : (1 << IsQuad) - 1; 2034 case NeonTypeFlags::Float16: 2035 assert(!shift && "cannot shift float types!"); 2036 return (4 << IsQuad) - 1; 2037 case NeonTypeFlags::Float32: 2038 assert(!shift && "cannot shift float types!"); 2039 return (2 << IsQuad) - 1; 2040 case NeonTypeFlags::Float64: 2041 assert(!shift && "cannot shift float types!"); 2042 return (1 << IsQuad) - 1; 2043 case NeonTypeFlags::BFloat16: 2044 assert(!shift && "cannot shift float types!"); 2045 return (4 << IsQuad) - 1; 2046 } 2047 llvm_unreachable("Invalid NeonTypeFlag!"); 2048 } 2049 2050 /// getNeonEltType - Return the QualType corresponding to the elements of 2051 /// the vector type specified by the NeonTypeFlags. This is used to check 2052 /// the pointer arguments for Neon load/store intrinsics. 2053 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2054 bool IsPolyUnsigned, bool IsInt64Long) { 2055 switch (Flags.getEltType()) { 2056 case NeonTypeFlags::Int8: 2057 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2058 case NeonTypeFlags::Int16: 2059 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2060 case NeonTypeFlags::Int32: 2061 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2062 case NeonTypeFlags::Int64: 2063 if (IsInt64Long) 2064 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2065 else 2066 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2067 : Context.LongLongTy; 2068 case NeonTypeFlags::Poly8: 2069 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2070 case NeonTypeFlags::Poly16: 2071 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2072 case NeonTypeFlags::Poly64: 2073 if (IsInt64Long) 2074 return Context.UnsignedLongTy; 2075 else 2076 return Context.UnsignedLongLongTy; 2077 case NeonTypeFlags::Poly128: 2078 break; 2079 case NeonTypeFlags::Float16: 2080 return Context.HalfTy; 2081 case NeonTypeFlags::Float32: 2082 return Context.FloatTy; 2083 case NeonTypeFlags::Float64: 2084 return Context.DoubleTy; 2085 case NeonTypeFlags::BFloat16: 2086 return Context.BFloat16Ty; 2087 } 2088 llvm_unreachable("Invalid NeonTypeFlag!"); 2089 } 2090 2091 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2092 // Range check SVE intrinsics that take immediate values. 2093 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2094 2095 switch (BuiltinID) { 2096 default: 2097 return false; 2098 #define GET_SVE_IMMEDIATE_CHECK 2099 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2100 #undef GET_SVE_IMMEDIATE_CHECK 2101 } 2102 2103 // Perform all the immediate checks for this builtin call. 2104 bool HasError = false; 2105 for (auto &I : ImmChecks) { 2106 int ArgNum, CheckTy, ElementSizeInBits; 2107 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2108 2109 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2110 2111 // Function that checks whether the operand (ArgNum) is an immediate 2112 // that is one of the predefined values. 2113 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2114 int ErrDiag) -> bool { 2115 // We can't check the value of a dependent argument. 2116 Expr *Arg = TheCall->getArg(ArgNum); 2117 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2118 return false; 2119 2120 // Check constant-ness first. 2121 llvm::APSInt Imm; 2122 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2123 return true; 2124 2125 if (!CheckImm(Imm.getSExtValue())) 2126 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2127 return false; 2128 }; 2129 2130 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2131 case SVETypeFlags::ImmCheck0_31: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2133 HasError = true; 2134 break; 2135 case SVETypeFlags::ImmCheck0_13: 2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2137 HasError = true; 2138 break; 2139 case SVETypeFlags::ImmCheck1_16: 2140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2141 HasError = true; 2142 break; 2143 case SVETypeFlags::ImmCheck0_7: 2144 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2145 HasError = true; 2146 break; 2147 case SVETypeFlags::ImmCheckExtract: 2148 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2149 (2048 / ElementSizeInBits) - 1)) 2150 HasError = true; 2151 break; 2152 case SVETypeFlags::ImmCheckShiftRight: 2153 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2154 HasError = true; 2155 break; 2156 case SVETypeFlags::ImmCheckShiftRightNarrow: 2157 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2158 ElementSizeInBits / 2)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckShiftLeft: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 ElementSizeInBits - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckLaneIndex: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2168 (128 / (1 * ElementSizeInBits)) - 1)) 2169 HasError = true; 2170 break; 2171 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2172 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2173 (128 / (2 * ElementSizeInBits)) - 1)) 2174 HasError = true; 2175 break; 2176 case SVETypeFlags::ImmCheckLaneIndexDot: 2177 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2178 (128 / (4 * ElementSizeInBits)) - 1)) 2179 HasError = true; 2180 break; 2181 case SVETypeFlags::ImmCheckComplexRot90_270: 2182 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2183 diag::err_rotation_argument_to_cadd)) 2184 HasError = true; 2185 break; 2186 case SVETypeFlags::ImmCheckComplexRotAll90: 2187 if (CheckImmediateInSet( 2188 [](int64_t V) { 2189 return V == 0 || V == 90 || V == 180 || V == 270; 2190 }, 2191 diag::err_rotation_argument_to_cmla)) 2192 HasError = true; 2193 break; 2194 case SVETypeFlags::ImmCheck0_1: 2195 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2196 HasError = true; 2197 break; 2198 case SVETypeFlags::ImmCheck0_2: 2199 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2200 HasError = true; 2201 break; 2202 case SVETypeFlags::ImmCheck0_3: 2203 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2204 HasError = true; 2205 break; 2206 } 2207 } 2208 2209 return HasError; 2210 } 2211 2212 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2213 unsigned BuiltinID, CallExpr *TheCall) { 2214 llvm::APSInt Result; 2215 uint64_t mask = 0; 2216 unsigned TV = 0; 2217 int PtrArgNum = -1; 2218 bool HasConstPtr = false; 2219 switch (BuiltinID) { 2220 #define GET_NEON_OVERLOAD_CHECK 2221 #include "clang/Basic/arm_neon.inc" 2222 #include "clang/Basic/arm_fp16.inc" 2223 #undef GET_NEON_OVERLOAD_CHECK 2224 } 2225 2226 // For NEON intrinsics which are overloaded on vector element type, validate 2227 // the immediate which specifies which variant to emit. 2228 unsigned ImmArg = TheCall->getNumArgs()-1; 2229 if (mask) { 2230 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2231 return true; 2232 2233 TV = Result.getLimitedValue(64); 2234 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2235 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2236 << TheCall->getArg(ImmArg)->getSourceRange(); 2237 } 2238 2239 if (PtrArgNum >= 0) { 2240 // Check that pointer arguments have the specified type. 2241 Expr *Arg = TheCall->getArg(PtrArgNum); 2242 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2243 Arg = ICE->getSubExpr(); 2244 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2245 QualType RHSTy = RHS.get()->getType(); 2246 2247 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2248 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2249 Arch == llvm::Triple::aarch64_32 || 2250 Arch == llvm::Triple::aarch64_be; 2251 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2252 QualType EltTy = 2253 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2254 if (HasConstPtr) 2255 EltTy = EltTy.withConst(); 2256 QualType LHSTy = Context.getPointerType(EltTy); 2257 AssignConvertType ConvTy; 2258 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2259 if (RHS.isInvalid()) 2260 return true; 2261 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2262 RHS.get(), AA_Assigning)) 2263 return true; 2264 } 2265 2266 // For NEON intrinsics which take an immediate value as part of the 2267 // instruction, range check them here. 2268 unsigned i = 0, l = 0, u = 0; 2269 switch (BuiltinID) { 2270 default: 2271 return false; 2272 #define GET_NEON_IMMEDIATE_CHECK 2273 #include "clang/Basic/arm_neon.inc" 2274 #include "clang/Basic/arm_fp16.inc" 2275 #undef GET_NEON_IMMEDIATE_CHECK 2276 } 2277 2278 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2279 } 2280 2281 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2282 switch (BuiltinID) { 2283 default: 2284 return false; 2285 #include "clang/Basic/arm_mve_builtin_sema.inc" 2286 } 2287 } 2288 2289 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2290 CallExpr *TheCall) { 2291 bool Err = false; 2292 switch (BuiltinID) { 2293 default: 2294 return false; 2295 #include "clang/Basic/arm_cde_builtin_sema.inc" 2296 } 2297 2298 if (Err) 2299 return true; 2300 2301 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2302 } 2303 2304 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2305 const Expr *CoprocArg, bool WantCDE) { 2306 if (isConstantEvaluated()) 2307 return false; 2308 2309 // We can't check the value of a dependent argument. 2310 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2311 return false; 2312 2313 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2314 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2315 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2316 2317 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2318 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2319 2320 if (IsCDECoproc != WantCDE) 2321 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2322 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2323 2324 return false; 2325 } 2326 2327 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2328 unsigned MaxWidth) { 2329 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2330 BuiltinID == ARM::BI__builtin_arm_ldaex || 2331 BuiltinID == ARM::BI__builtin_arm_strex || 2332 BuiltinID == ARM::BI__builtin_arm_stlex || 2333 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2334 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2335 BuiltinID == AArch64::BI__builtin_arm_strex || 2336 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2337 "unexpected ARM builtin"); 2338 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2339 BuiltinID == ARM::BI__builtin_arm_ldaex || 2340 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2341 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2342 2343 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2344 2345 // Ensure that we have the proper number of arguments. 2346 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2347 return true; 2348 2349 // Inspect the pointer argument of the atomic builtin. This should always be 2350 // a pointer type, whose element is an integral scalar or pointer type. 2351 // Because it is a pointer type, we don't have to worry about any implicit 2352 // casts here. 2353 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2354 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2355 if (PointerArgRes.isInvalid()) 2356 return true; 2357 PointerArg = PointerArgRes.get(); 2358 2359 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2360 if (!pointerType) { 2361 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2362 << PointerArg->getType() << PointerArg->getSourceRange(); 2363 return true; 2364 } 2365 2366 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2367 // task is to insert the appropriate casts into the AST. First work out just 2368 // what the appropriate type is. 2369 QualType ValType = pointerType->getPointeeType(); 2370 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2371 if (IsLdrex) 2372 AddrType.addConst(); 2373 2374 // Issue a warning if the cast is dodgy. 2375 CastKind CastNeeded = CK_NoOp; 2376 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2377 CastNeeded = CK_BitCast; 2378 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2379 << PointerArg->getType() << Context.getPointerType(AddrType) 2380 << AA_Passing << PointerArg->getSourceRange(); 2381 } 2382 2383 // Finally, do the cast and replace the argument with the corrected version. 2384 AddrType = Context.getPointerType(AddrType); 2385 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2386 if (PointerArgRes.isInvalid()) 2387 return true; 2388 PointerArg = PointerArgRes.get(); 2389 2390 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2391 2392 // In general, we allow ints, floats and pointers to be loaded and stored. 2393 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2394 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2395 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2396 << PointerArg->getType() << PointerArg->getSourceRange(); 2397 return true; 2398 } 2399 2400 // But ARM doesn't have instructions to deal with 128-bit versions. 2401 if (Context.getTypeSize(ValType) > MaxWidth) { 2402 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2403 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2404 << PointerArg->getType() << PointerArg->getSourceRange(); 2405 return true; 2406 } 2407 2408 switch (ValType.getObjCLifetime()) { 2409 case Qualifiers::OCL_None: 2410 case Qualifiers::OCL_ExplicitNone: 2411 // okay 2412 break; 2413 2414 case Qualifiers::OCL_Weak: 2415 case Qualifiers::OCL_Strong: 2416 case Qualifiers::OCL_Autoreleasing: 2417 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2418 << ValType << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 if (IsLdrex) { 2423 TheCall->setType(ValType); 2424 return false; 2425 } 2426 2427 // Initialize the argument to be stored. 2428 ExprResult ValArg = TheCall->getArg(0); 2429 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2430 Context, ValType, /*consume*/ false); 2431 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2432 if (ValArg.isInvalid()) 2433 return true; 2434 TheCall->setArg(0, ValArg.get()); 2435 2436 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2437 // but the custom checker bypasses all default analysis. 2438 TheCall->setType(Context.IntTy); 2439 return false; 2440 } 2441 2442 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2443 CallExpr *TheCall) { 2444 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2445 BuiltinID == ARM::BI__builtin_arm_ldaex || 2446 BuiltinID == ARM::BI__builtin_arm_strex || 2447 BuiltinID == ARM::BI__builtin_arm_stlex) { 2448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2449 } 2450 2451 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2454 } 2455 2456 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2457 BuiltinID == ARM::BI__builtin_arm_wsr64) 2458 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2459 2460 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2461 BuiltinID == ARM::BI__builtin_arm_rsrp || 2462 BuiltinID == ARM::BI__builtin_arm_wsr || 2463 BuiltinID == ARM::BI__builtin_arm_wsrp) 2464 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2465 2466 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2467 return true; 2468 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2469 return true; 2470 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2471 return true; 2472 2473 // For intrinsics which take an immediate value as part of the instruction, 2474 // range check them here. 2475 // FIXME: VFP Intrinsics should error if VFP not present. 2476 switch (BuiltinID) { 2477 default: return false; 2478 case ARM::BI__builtin_arm_ssat: 2479 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2480 case ARM::BI__builtin_arm_usat: 2481 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2482 case ARM::BI__builtin_arm_ssat16: 2483 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2484 case ARM::BI__builtin_arm_usat16: 2485 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2486 case ARM::BI__builtin_arm_vcvtr_f: 2487 case ARM::BI__builtin_arm_vcvtr_d: 2488 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2489 case ARM::BI__builtin_arm_dmb: 2490 case ARM::BI__builtin_arm_dsb: 2491 case ARM::BI__builtin_arm_isb: 2492 case ARM::BI__builtin_arm_dbg: 2493 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2494 case ARM::BI__builtin_arm_cdp: 2495 case ARM::BI__builtin_arm_cdp2: 2496 case ARM::BI__builtin_arm_mcr: 2497 case ARM::BI__builtin_arm_mcr2: 2498 case ARM::BI__builtin_arm_mrc: 2499 case ARM::BI__builtin_arm_mrc2: 2500 case ARM::BI__builtin_arm_mcrr: 2501 case ARM::BI__builtin_arm_mcrr2: 2502 case ARM::BI__builtin_arm_mrrc: 2503 case ARM::BI__builtin_arm_mrrc2: 2504 case ARM::BI__builtin_arm_ldc: 2505 case ARM::BI__builtin_arm_ldcl: 2506 case ARM::BI__builtin_arm_ldc2: 2507 case ARM::BI__builtin_arm_ldc2l: 2508 case ARM::BI__builtin_arm_stc: 2509 case ARM::BI__builtin_arm_stcl: 2510 case ARM::BI__builtin_arm_stc2: 2511 case ARM::BI__builtin_arm_stc2l: 2512 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2513 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2514 /*WantCDE*/ false); 2515 } 2516 } 2517 2518 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2519 unsigned BuiltinID, 2520 CallExpr *TheCall) { 2521 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2522 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2523 BuiltinID == AArch64::BI__builtin_arm_strex || 2524 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2525 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2526 } 2527 2528 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2529 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2530 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2531 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2532 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2533 } 2534 2535 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2536 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2537 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2538 2539 // Memory Tagging Extensions (MTE) Intrinsics 2540 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2541 BuiltinID == AArch64::BI__builtin_arm_addg || 2542 BuiltinID == AArch64::BI__builtin_arm_gmi || 2543 BuiltinID == AArch64::BI__builtin_arm_ldg || 2544 BuiltinID == AArch64::BI__builtin_arm_stg || 2545 BuiltinID == AArch64::BI__builtin_arm_subp) { 2546 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2550 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2551 BuiltinID == AArch64::BI__builtin_arm_wsr || 2552 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2553 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2554 2555 // Only check the valid encoding range. Any constant in this range would be 2556 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2557 // an exception for incorrect registers. This matches MSVC behavior. 2558 if (BuiltinID == AArch64::BI_ReadStatusReg || 2559 BuiltinID == AArch64::BI_WriteStatusReg) 2560 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2561 2562 if (BuiltinID == AArch64::BI__getReg) 2563 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2564 2565 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2566 return true; 2567 2568 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2569 return true; 2570 2571 // For intrinsics which take an immediate value as part of the instruction, 2572 // range check them here. 2573 unsigned i = 0, l = 0, u = 0; 2574 switch (BuiltinID) { 2575 default: return false; 2576 case AArch64::BI__builtin_arm_dmb: 2577 case AArch64::BI__builtin_arm_dsb: 2578 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2579 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2580 } 2581 2582 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2583 } 2584 2585 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2586 if (Arg->getType()->getAsPlaceholderType()) 2587 return false; 2588 2589 // The first argument needs to be a record field access. 2590 // If it is an array element access, we delay decision 2591 // to BPF backend to check whether the access is a 2592 // field access or not. 2593 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2594 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2595 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2596 } 2597 2598 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2599 QualType VectorTy, QualType EltTy) { 2600 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2601 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2602 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2603 << Call->getSourceRange() << VectorEltTy << EltTy; 2604 return false; 2605 } 2606 return true; 2607 } 2608 2609 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2610 QualType ArgType = Arg->getType(); 2611 if (ArgType->getAsPlaceholderType()) 2612 return false; 2613 2614 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2615 // format: 2616 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2617 // 2. <type> var; 2618 // __builtin_preserve_type_info(var, flag); 2619 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2620 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2621 return false; 2622 2623 // Typedef type. 2624 if (ArgType->getAs<TypedefType>()) 2625 return true; 2626 2627 // Record type or Enum type. 2628 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2629 if (const auto *RT = Ty->getAs<RecordType>()) { 2630 if (!RT->getDecl()->getDeclName().isEmpty()) 2631 return true; 2632 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2633 if (!ET->getDecl()->getDeclName().isEmpty()) 2634 return true; 2635 } 2636 2637 return false; 2638 } 2639 2640 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2641 QualType ArgType = Arg->getType(); 2642 if (ArgType->getAsPlaceholderType()) 2643 return false; 2644 2645 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2646 // format: 2647 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2648 // flag); 2649 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2650 if (!UO) 2651 return false; 2652 2653 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2654 if (!CE) 2655 return false; 2656 if (CE->getCastKind() != CK_IntegralToPointer && 2657 CE->getCastKind() != CK_NullToPointer) 2658 return false; 2659 2660 // The integer must be from an EnumConstantDecl. 2661 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2662 if (!DR) 2663 return false; 2664 2665 const EnumConstantDecl *Enumerator = 2666 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2667 if (!Enumerator) 2668 return false; 2669 2670 // The type must be EnumType. 2671 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2672 const auto *ET = Ty->getAs<EnumType>(); 2673 if (!ET) 2674 return false; 2675 2676 // The enum value must be supported. 2677 for (auto *EDI : ET->getDecl()->enumerators()) { 2678 if (EDI == Enumerator) 2679 return true; 2680 } 2681 2682 return false; 2683 } 2684 2685 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2686 CallExpr *TheCall) { 2687 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2688 BuiltinID == BPF::BI__builtin_btf_type_id || 2689 BuiltinID == BPF::BI__builtin_preserve_type_info || 2690 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2691 "unexpected BPF builtin"); 2692 2693 if (checkArgCount(*this, TheCall, 2)) 2694 return true; 2695 2696 // The second argument needs to be a constant int 2697 Expr *Arg = TheCall->getArg(1); 2698 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2699 diag::kind kind; 2700 if (!Value) { 2701 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2702 kind = diag::err_preserve_field_info_not_const; 2703 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2704 kind = diag::err_btf_type_id_not_const; 2705 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2706 kind = diag::err_preserve_type_info_not_const; 2707 else 2708 kind = diag::err_preserve_enum_value_not_const; 2709 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2710 return true; 2711 } 2712 2713 // The first argument 2714 Arg = TheCall->getArg(0); 2715 bool InvalidArg = false; 2716 bool ReturnUnsignedInt = true; 2717 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2718 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2719 InvalidArg = true; 2720 kind = diag::err_preserve_field_info_not_field; 2721 } 2722 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2723 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2724 InvalidArg = true; 2725 kind = diag::err_preserve_type_info_invalid; 2726 } 2727 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2728 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2729 InvalidArg = true; 2730 kind = diag::err_preserve_enum_value_invalid; 2731 } 2732 ReturnUnsignedInt = false; 2733 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2734 ReturnUnsignedInt = false; 2735 } 2736 2737 if (InvalidArg) { 2738 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2739 return true; 2740 } 2741 2742 if (ReturnUnsignedInt) 2743 TheCall->setType(Context.UnsignedIntTy); 2744 else 2745 TheCall->setType(Context.UnsignedLongTy); 2746 return false; 2747 } 2748 2749 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2750 struct ArgInfo { 2751 uint8_t OpNum; 2752 bool IsSigned; 2753 uint8_t BitWidth; 2754 uint8_t Align; 2755 }; 2756 struct BuiltinInfo { 2757 unsigned BuiltinID; 2758 ArgInfo Infos[2]; 2759 }; 2760 2761 static BuiltinInfo Infos[] = { 2762 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2763 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2764 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2765 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2766 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2767 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2768 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2769 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2770 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2771 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2772 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2773 2774 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2785 2786 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2838 {{ 1, false, 6, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2846 {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2853 { 2, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2855 { 2, false, 6, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2857 { 3, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2859 { 3, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2876 {{ 2, false, 4, 0 }, 2877 { 3, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2879 {{ 2, false, 4, 0 }, 2880 { 3, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2882 {{ 2, false, 4, 0 }, 2883 { 3, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2885 {{ 2, false, 4, 0 }, 2886 { 3, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2898 { 2, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2900 { 2, false, 6, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2910 {{ 1, false, 4, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2913 {{ 1, false, 4, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2934 {{ 3, false, 1, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2939 {{ 3, false, 1, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2944 {{ 3, false, 1, 0 }} }, 2945 }; 2946 2947 // Use a dynamically initialized static to sort the table exactly once on 2948 // first run. 2949 static const bool SortOnce = 2950 (llvm::sort(Infos, 2951 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2952 return LHS.BuiltinID < RHS.BuiltinID; 2953 }), 2954 true); 2955 (void)SortOnce; 2956 2957 const BuiltinInfo *F = llvm::partition_point( 2958 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2959 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2960 return false; 2961 2962 bool Error = false; 2963 2964 for (const ArgInfo &A : F->Infos) { 2965 // Ignore empty ArgInfo elements. 2966 if (A.BitWidth == 0) 2967 continue; 2968 2969 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2970 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2971 if (!A.Align) { 2972 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2973 } else { 2974 unsigned M = 1 << A.Align; 2975 Min *= M; 2976 Max *= M; 2977 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2978 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2979 } 2980 } 2981 return Error; 2982 } 2983 2984 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2985 CallExpr *TheCall) { 2986 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2987 } 2988 2989 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2990 unsigned BuiltinID, CallExpr *TheCall) { 2991 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2992 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2993 } 2994 2995 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2996 CallExpr *TheCall) { 2997 2998 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2999 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3000 if (!TI.hasFeature("dsp")) 3001 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3002 } 3003 3004 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3005 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3006 if (!TI.hasFeature("dspr2")) 3007 return Diag(TheCall->getBeginLoc(), 3008 diag::err_mips_builtin_requires_dspr2); 3009 } 3010 3011 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3012 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3013 if (!TI.hasFeature("msa")) 3014 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3015 } 3016 3017 return false; 3018 } 3019 3020 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3021 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3022 // ordering for DSP is unspecified. MSA is ordered by the data format used 3023 // by the underlying instruction i.e., df/m, df/n and then by size. 3024 // 3025 // FIXME: The size tests here should instead be tablegen'd along with the 3026 // definitions from include/clang/Basic/BuiltinsMips.def. 3027 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3028 // be too. 3029 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3030 unsigned i = 0, l = 0, u = 0, m = 0; 3031 switch (BuiltinID) { 3032 default: return false; 3033 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3034 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3035 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3036 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3037 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3038 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3039 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3040 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3041 // df/m field. 3042 // These intrinsics take an unsigned 3 bit immediate. 3043 case Mips::BI__builtin_msa_bclri_b: 3044 case Mips::BI__builtin_msa_bnegi_b: 3045 case Mips::BI__builtin_msa_bseti_b: 3046 case Mips::BI__builtin_msa_sat_s_b: 3047 case Mips::BI__builtin_msa_sat_u_b: 3048 case Mips::BI__builtin_msa_slli_b: 3049 case Mips::BI__builtin_msa_srai_b: 3050 case Mips::BI__builtin_msa_srari_b: 3051 case Mips::BI__builtin_msa_srli_b: 3052 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3053 case Mips::BI__builtin_msa_binsli_b: 3054 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3055 // These intrinsics take an unsigned 4 bit immediate. 3056 case Mips::BI__builtin_msa_bclri_h: 3057 case Mips::BI__builtin_msa_bnegi_h: 3058 case Mips::BI__builtin_msa_bseti_h: 3059 case Mips::BI__builtin_msa_sat_s_h: 3060 case Mips::BI__builtin_msa_sat_u_h: 3061 case Mips::BI__builtin_msa_slli_h: 3062 case Mips::BI__builtin_msa_srai_h: 3063 case Mips::BI__builtin_msa_srari_h: 3064 case Mips::BI__builtin_msa_srli_h: 3065 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3066 case Mips::BI__builtin_msa_binsli_h: 3067 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3068 // These intrinsics take an unsigned 5 bit immediate. 3069 // The first block of intrinsics actually have an unsigned 5 bit field, 3070 // not a df/n field. 3071 case Mips::BI__builtin_msa_cfcmsa: 3072 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3073 case Mips::BI__builtin_msa_clei_u_b: 3074 case Mips::BI__builtin_msa_clei_u_h: 3075 case Mips::BI__builtin_msa_clei_u_w: 3076 case Mips::BI__builtin_msa_clei_u_d: 3077 case Mips::BI__builtin_msa_clti_u_b: 3078 case Mips::BI__builtin_msa_clti_u_h: 3079 case Mips::BI__builtin_msa_clti_u_w: 3080 case Mips::BI__builtin_msa_clti_u_d: 3081 case Mips::BI__builtin_msa_maxi_u_b: 3082 case Mips::BI__builtin_msa_maxi_u_h: 3083 case Mips::BI__builtin_msa_maxi_u_w: 3084 case Mips::BI__builtin_msa_maxi_u_d: 3085 case Mips::BI__builtin_msa_mini_u_b: 3086 case Mips::BI__builtin_msa_mini_u_h: 3087 case Mips::BI__builtin_msa_mini_u_w: 3088 case Mips::BI__builtin_msa_mini_u_d: 3089 case Mips::BI__builtin_msa_addvi_b: 3090 case Mips::BI__builtin_msa_addvi_h: 3091 case Mips::BI__builtin_msa_addvi_w: 3092 case Mips::BI__builtin_msa_addvi_d: 3093 case Mips::BI__builtin_msa_bclri_w: 3094 case Mips::BI__builtin_msa_bnegi_w: 3095 case Mips::BI__builtin_msa_bseti_w: 3096 case Mips::BI__builtin_msa_sat_s_w: 3097 case Mips::BI__builtin_msa_sat_u_w: 3098 case Mips::BI__builtin_msa_slli_w: 3099 case Mips::BI__builtin_msa_srai_w: 3100 case Mips::BI__builtin_msa_srari_w: 3101 case Mips::BI__builtin_msa_srli_w: 3102 case Mips::BI__builtin_msa_srlri_w: 3103 case Mips::BI__builtin_msa_subvi_b: 3104 case Mips::BI__builtin_msa_subvi_h: 3105 case Mips::BI__builtin_msa_subvi_w: 3106 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3107 case Mips::BI__builtin_msa_binsli_w: 3108 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3109 // These intrinsics take an unsigned 6 bit immediate. 3110 case Mips::BI__builtin_msa_bclri_d: 3111 case Mips::BI__builtin_msa_bnegi_d: 3112 case Mips::BI__builtin_msa_bseti_d: 3113 case Mips::BI__builtin_msa_sat_s_d: 3114 case Mips::BI__builtin_msa_sat_u_d: 3115 case Mips::BI__builtin_msa_slli_d: 3116 case Mips::BI__builtin_msa_srai_d: 3117 case Mips::BI__builtin_msa_srari_d: 3118 case Mips::BI__builtin_msa_srli_d: 3119 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3120 case Mips::BI__builtin_msa_binsli_d: 3121 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3122 // These intrinsics take a signed 5 bit immediate. 3123 case Mips::BI__builtin_msa_ceqi_b: 3124 case Mips::BI__builtin_msa_ceqi_h: 3125 case Mips::BI__builtin_msa_ceqi_w: 3126 case Mips::BI__builtin_msa_ceqi_d: 3127 case Mips::BI__builtin_msa_clti_s_b: 3128 case Mips::BI__builtin_msa_clti_s_h: 3129 case Mips::BI__builtin_msa_clti_s_w: 3130 case Mips::BI__builtin_msa_clti_s_d: 3131 case Mips::BI__builtin_msa_clei_s_b: 3132 case Mips::BI__builtin_msa_clei_s_h: 3133 case Mips::BI__builtin_msa_clei_s_w: 3134 case Mips::BI__builtin_msa_clei_s_d: 3135 case Mips::BI__builtin_msa_maxi_s_b: 3136 case Mips::BI__builtin_msa_maxi_s_h: 3137 case Mips::BI__builtin_msa_maxi_s_w: 3138 case Mips::BI__builtin_msa_maxi_s_d: 3139 case Mips::BI__builtin_msa_mini_s_b: 3140 case Mips::BI__builtin_msa_mini_s_h: 3141 case Mips::BI__builtin_msa_mini_s_w: 3142 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3143 // These intrinsics take an unsigned 8 bit immediate. 3144 case Mips::BI__builtin_msa_andi_b: 3145 case Mips::BI__builtin_msa_nori_b: 3146 case Mips::BI__builtin_msa_ori_b: 3147 case Mips::BI__builtin_msa_shf_b: 3148 case Mips::BI__builtin_msa_shf_h: 3149 case Mips::BI__builtin_msa_shf_w: 3150 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3151 case Mips::BI__builtin_msa_bseli_b: 3152 case Mips::BI__builtin_msa_bmnzi_b: 3153 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3154 // df/n format 3155 // These intrinsics take an unsigned 4 bit immediate. 3156 case Mips::BI__builtin_msa_copy_s_b: 3157 case Mips::BI__builtin_msa_copy_u_b: 3158 case Mips::BI__builtin_msa_insve_b: 3159 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3160 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3161 // These intrinsics take an unsigned 3 bit immediate. 3162 case Mips::BI__builtin_msa_copy_s_h: 3163 case Mips::BI__builtin_msa_copy_u_h: 3164 case Mips::BI__builtin_msa_insve_h: 3165 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3166 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3167 // These intrinsics take an unsigned 2 bit immediate. 3168 case Mips::BI__builtin_msa_copy_s_w: 3169 case Mips::BI__builtin_msa_copy_u_w: 3170 case Mips::BI__builtin_msa_insve_w: 3171 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3172 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3173 // These intrinsics take an unsigned 1 bit immediate. 3174 case Mips::BI__builtin_msa_copy_s_d: 3175 case Mips::BI__builtin_msa_copy_u_d: 3176 case Mips::BI__builtin_msa_insve_d: 3177 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3178 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3179 // Memory offsets and immediate loads. 3180 // These intrinsics take a signed 10 bit immediate. 3181 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3182 case Mips::BI__builtin_msa_ldi_h: 3183 case Mips::BI__builtin_msa_ldi_w: 3184 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3185 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3186 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3187 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3188 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3189 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3190 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3191 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3192 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3193 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3194 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3195 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3196 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3197 } 3198 3199 if (!m) 3200 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3201 3202 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3203 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3204 } 3205 3206 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3207 /// advancing the pointer over the consumed characters. The decoded type is 3208 /// returned. If the decoded type represents a constant integer with a 3209 /// constraint on its value then Mask is set to that value. The type descriptors 3210 /// used in Str are specific to PPC MMA builtins and are documented in the file 3211 /// defining the PPC builtins. 3212 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3213 unsigned &Mask) { 3214 bool RequireICE = false; 3215 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3216 switch (*Str++) { 3217 case 'V': 3218 return Context.getVectorType(Context.UnsignedCharTy, 16, 3219 VectorType::VectorKind::AltiVecVector); 3220 case 'i': { 3221 char *End; 3222 unsigned size = strtoul(Str, &End, 10); 3223 assert(End != Str && "Missing constant parameter constraint"); 3224 Str = End; 3225 Mask = size; 3226 return Context.IntTy; 3227 } 3228 case 'W': { 3229 char *End; 3230 unsigned size = strtoul(Str, &End, 10); 3231 assert(End != Str && "Missing PowerPC MMA type size"); 3232 Str = End; 3233 QualType Type; 3234 switch (size) { 3235 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3236 case size: Type = Context.Id##Ty; break; 3237 #include "clang/Basic/PPCTypes.def" 3238 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3239 } 3240 bool CheckVectorArgs = false; 3241 while (!CheckVectorArgs) { 3242 switch (*Str++) { 3243 case '*': 3244 Type = Context.getPointerType(Type); 3245 break; 3246 case 'C': 3247 Type = Type.withConst(); 3248 break; 3249 default: 3250 CheckVectorArgs = true; 3251 --Str; 3252 break; 3253 } 3254 } 3255 return Type; 3256 } 3257 default: 3258 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3259 } 3260 } 3261 3262 static bool isPPC_64Builtin(unsigned BuiltinID) { 3263 // These builtins only work on PPC 64bit targets. 3264 switch (BuiltinID) { 3265 case PPC::BI__builtin_divde: 3266 case PPC::BI__builtin_divdeu: 3267 case PPC::BI__builtin_bpermd: 3268 case PPC::BI__builtin_ppc_ldarx: 3269 case PPC::BI__builtin_ppc_stdcx: 3270 case PPC::BI__builtin_ppc_tdw: 3271 case PPC::BI__builtin_ppc_trapd: 3272 case PPC::BI__builtin_ppc_cmpeqb: 3273 case PPC::BI__builtin_ppc_setb: 3274 case PPC::BI__builtin_ppc_mulhd: 3275 case PPC::BI__builtin_ppc_mulhdu: 3276 case PPC::BI__builtin_ppc_maddhd: 3277 case PPC::BI__builtin_ppc_maddhdu: 3278 case PPC::BI__builtin_ppc_maddld: 3279 case PPC::BI__builtin_ppc_load8r: 3280 case PPC::BI__builtin_ppc_store8r: 3281 case PPC::BI__builtin_ppc_insert_exp: 3282 case PPC::BI__builtin_ppc_extract_sig: 3283 return true; 3284 } 3285 return false; 3286 } 3287 3288 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3289 StringRef FeatureToCheck, unsigned DiagID, 3290 StringRef DiagArg = "") { 3291 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3292 return false; 3293 3294 if (DiagArg.empty()) 3295 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3296 else 3297 S.Diag(TheCall->getBeginLoc(), DiagID) 3298 << DiagArg << TheCall->getSourceRange(); 3299 3300 return true; 3301 } 3302 3303 /// Returns true if the argument consists of one contiguous run of 1s with any 3304 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3305 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3306 /// since all 1s are not contiguous. 3307 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3308 llvm::APSInt Result; 3309 // We can't check the value of a dependent argument. 3310 Expr *Arg = TheCall->getArg(ArgNum); 3311 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3312 return false; 3313 3314 // Check constant-ness first. 3315 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3316 return true; 3317 3318 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3319 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3320 return false; 3321 3322 return Diag(TheCall->getBeginLoc(), 3323 diag::err_argument_not_contiguous_bit_field) 3324 << ArgNum << Arg->getSourceRange(); 3325 } 3326 3327 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3328 CallExpr *TheCall) { 3329 unsigned i = 0, l = 0, u = 0; 3330 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3331 llvm::APSInt Result; 3332 3333 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3334 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3335 << TheCall->getSourceRange(); 3336 3337 switch (BuiltinID) { 3338 default: return false; 3339 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3340 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3341 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3342 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3343 case PPC::BI__builtin_altivec_dss: 3344 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3345 case PPC::BI__builtin_tbegin: 3346 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3347 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3348 case PPC::BI__builtin_tabortwc: 3349 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3350 case PPC::BI__builtin_tabortwci: 3351 case PPC::BI__builtin_tabortdci: 3352 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3353 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3354 case PPC::BI__builtin_altivec_dst: 3355 case PPC::BI__builtin_altivec_dstt: 3356 case PPC::BI__builtin_altivec_dstst: 3357 case PPC::BI__builtin_altivec_dststt: 3358 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3359 case PPC::BI__builtin_vsx_xxpermdi: 3360 case PPC::BI__builtin_vsx_xxsldwi: 3361 return SemaBuiltinVSX(TheCall); 3362 case PPC::BI__builtin_divwe: 3363 case PPC::BI__builtin_divweu: 3364 case PPC::BI__builtin_divde: 3365 case PPC::BI__builtin_divdeu: 3366 return SemaFeatureCheck(*this, TheCall, "extdiv", 3367 diag::err_ppc_builtin_only_on_arch, "7"); 3368 case PPC::BI__builtin_bpermd: 3369 return SemaFeatureCheck(*this, TheCall, "bpermd", 3370 diag::err_ppc_builtin_only_on_arch, "7"); 3371 case PPC::BI__builtin_unpack_vector_int128: 3372 return SemaFeatureCheck(*this, TheCall, "vsx", 3373 diag::err_ppc_builtin_only_on_arch, "7") || 3374 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3375 case PPC::BI__builtin_pack_vector_int128: 3376 return SemaFeatureCheck(*this, TheCall, "vsx", 3377 diag::err_ppc_builtin_only_on_arch, "7"); 3378 case PPC::BI__builtin_altivec_vgnb: 3379 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3380 case PPC::BI__builtin_altivec_vec_replace_elt: 3381 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3382 QualType VecTy = TheCall->getArg(0)->getType(); 3383 QualType EltTy = TheCall->getArg(1)->getType(); 3384 unsigned Width = Context.getIntWidth(EltTy); 3385 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3386 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3387 } 3388 case PPC::BI__builtin_vsx_xxeval: 3389 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3390 case PPC::BI__builtin_altivec_vsldbi: 3391 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3392 case PPC::BI__builtin_altivec_vsrdbi: 3393 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3394 case PPC::BI__builtin_vsx_xxpermx: 3395 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3396 case PPC::BI__builtin_ppc_tw: 3397 case PPC::BI__builtin_ppc_tdw: 3398 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3399 case PPC::BI__builtin_ppc_cmpeqb: 3400 case PPC::BI__builtin_ppc_setb: 3401 case PPC::BI__builtin_ppc_maddhd: 3402 case PPC::BI__builtin_ppc_maddhdu: 3403 case PPC::BI__builtin_ppc_maddld: 3404 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3405 diag::err_ppc_builtin_only_on_arch, "9"); 3406 case PPC::BI__builtin_ppc_cmprb: 3407 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3408 diag::err_ppc_builtin_only_on_arch, "9") || 3409 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3410 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3411 // be a constant that represents a contiguous bit field. 3412 case PPC::BI__builtin_ppc_rlwnm: 3413 return SemaBuiltinConstantArg(TheCall, 1, Result) || 3414 SemaValueIsRunOfOnes(TheCall, 2); 3415 case PPC::BI__builtin_ppc_rlwimi: 3416 case PPC::BI__builtin_ppc_rldimi: 3417 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3418 SemaValueIsRunOfOnes(TheCall, 3); 3419 case PPC::BI__builtin_ppc_extract_exp: 3420 case PPC::BI__builtin_ppc_extract_sig: 3421 case PPC::BI__builtin_ppc_insert_exp: 3422 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3423 diag::err_ppc_builtin_only_on_arch, "9"); 3424 case PPC::BI__builtin_ppc_mtfsb0: 3425 case PPC::BI__builtin_ppc_mtfsb1: 3426 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3427 case PPC::BI__builtin_ppc_mtfsf: 3428 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3429 case PPC::BI__builtin_ppc_mtfsfi: 3430 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3431 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3432 case PPC::BI__builtin_ppc_alignx: 3433 return SemaBuiltinConstantArgPower2(TheCall, 0); 3434 case PPC::BI__builtin_ppc_rdlam: 3435 return SemaValueIsRunOfOnes(TheCall, 2); 3436 case PPC::BI__builtin_ppc_icbt: 3437 case PPC::BI__builtin_ppc_sthcx: 3438 case PPC::BI__builtin_ppc_stbcx: 3439 case PPC::BI__builtin_ppc_lharx: 3440 case PPC::BI__builtin_ppc_lbarx: 3441 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3442 diag::err_ppc_builtin_only_on_arch, "8"); 3443 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3444 case PPC::BI__builtin_##Name: \ 3445 return SemaBuiltinPPCMMACall(TheCall, Types); 3446 #include "clang/Basic/BuiltinsPPC.def" 3447 } 3448 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3449 } 3450 3451 // Check if the given type is a non-pointer PPC MMA type. This function is used 3452 // in Sema to prevent invalid uses of restricted PPC MMA types. 3453 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3454 if (Type->isPointerType() || Type->isArrayType()) 3455 return false; 3456 3457 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3458 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3459 if (false 3460 #include "clang/Basic/PPCTypes.def" 3461 ) { 3462 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3463 return true; 3464 } 3465 return false; 3466 } 3467 3468 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3469 CallExpr *TheCall) { 3470 // position of memory order and scope arguments in the builtin 3471 unsigned OrderIndex, ScopeIndex; 3472 switch (BuiltinID) { 3473 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3474 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3475 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3476 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3477 OrderIndex = 2; 3478 ScopeIndex = 3; 3479 break; 3480 case AMDGPU::BI__builtin_amdgcn_fence: 3481 OrderIndex = 0; 3482 ScopeIndex = 1; 3483 break; 3484 default: 3485 return false; 3486 } 3487 3488 ExprResult Arg = TheCall->getArg(OrderIndex); 3489 auto ArgExpr = Arg.get(); 3490 Expr::EvalResult ArgResult; 3491 3492 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3493 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3494 << ArgExpr->getType(); 3495 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3496 3497 // Check valididty of memory ordering as per C11 / C++11's memody model. 3498 // Only fence needs check. Atomic dec/inc allow all memory orders. 3499 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3500 return Diag(ArgExpr->getBeginLoc(), 3501 diag::warn_atomic_op_has_invalid_memory_order) 3502 << ArgExpr->getSourceRange(); 3503 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3504 case llvm::AtomicOrderingCABI::relaxed: 3505 case llvm::AtomicOrderingCABI::consume: 3506 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3507 return Diag(ArgExpr->getBeginLoc(), 3508 diag::warn_atomic_op_has_invalid_memory_order) 3509 << ArgExpr->getSourceRange(); 3510 break; 3511 case llvm::AtomicOrderingCABI::acquire: 3512 case llvm::AtomicOrderingCABI::release: 3513 case llvm::AtomicOrderingCABI::acq_rel: 3514 case llvm::AtomicOrderingCABI::seq_cst: 3515 break; 3516 } 3517 3518 Arg = TheCall->getArg(ScopeIndex); 3519 ArgExpr = Arg.get(); 3520 Expr::EvalResult ArgResult1; 3521 // Check that sync scope is a constant literal 3522 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3523 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3524 << ArgExpr->getType(); 3525 3526 return false; 3527 } 3528 3529 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3530 llvm::APSInt Result; 3531 3532 // We can't check the value of a dependent argument. 3533 Expr *Arg = TheCall->getArg(ArgNum); 3534 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3535 return false; 3536 3537 // Check constant-ness first. 3538 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3539 return true; 3540 3541 int64_t Val = Result.getSExtValue(); 3542 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3543 return false; 3544 3545 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3546 << Arg->getSourceRange(); 3547 } 3548 3549 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3550 unsigned BuiltinID, 3551 CallExpr *TheCall) { 3552 // CodeGenFunction can also detect this, but this gives a better error 3553 // message. 3554 bool FeatureMissing = false; 3555 SmallVector<StringRef> ReqFeatures; 3556 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3557 Features.split(ReqFeatures, ','); 3558 3559 // Check if each required feature is included 3560 for (StringRef F : ReqFeatures) { 3561 if (TI.hasFeature(F)) 3562 continue; 3563 3564 // If the feature is 64bit, alter the string so it will print better in 3565 // the diagnostic. 3566 if (F == "64bit") 3567 F = "RV64"; 3568 3569 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3570 F.consume_front("experimental-"); 3571 std::string FeatureStr = F.str(); 3572 FeatureStr[0] = std::toupper(FeatureStr[0]); 3573 3574 // Error message 3575 FeatureMissing = true; 3576 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3577 << TheCall->getSourceRange() << StringRef(FeatureStr); 3578 } 3579 3580 if (FeatureMissing) 3581 return true; 3582 3583 switch (BuiltinID) { 3584 case RISCV::BI__builtin_rvv_vsetvli: 3585 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3586 CheckRISCVLMUL(TheCall, 2); 3587 case RISCV::BI__builtin_rvv_vsetvlimax: 3588 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3589 CheckRISCVLMUL(TheCall, 1); 3590 case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1: 3591 case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1: 3592 case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1: 3593 case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1: 3594 case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1: 3595 case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1: 3596 case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1: 3597 case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1: 3598 case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1: 3599 case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1: 3600 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2: 3601 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2: 3602 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2: 3603 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2: 3604 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2: 3605 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2: 3606 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2: 3607 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2: 3608 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2: 3609 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2: 3610 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4: 3611 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4: 3612 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4: 3613 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4: 3614 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4: 3615 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4: 3616 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4: 3617 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4: 3618 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4: 3619 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4: 3620 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3621 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1: 3622 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1: 3623 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1: 3624 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1: 3625 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1: 3626 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1: 3627 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1: 3628 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1: 3629 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1: 3630 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1: 3631 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2: 3632 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2: 3633 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2: 3634 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2: 3635 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2: 3636 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2: 3637 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2: 3638 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2: 3639 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2: 3640 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2: 3641 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3642 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1: 3643 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1: 3644 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1: 3645 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1: 3646 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1: 3647 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1: 3648 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1: 3649 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1: 3650 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1: 3651 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1: 3652 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3653 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2: 3654 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2: 3655 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2: 3656 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2: 3657 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2: 3658 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2: 3659 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2: 3660 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2: 3661 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2: 3662 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2: 3663 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4: 3664 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4: 3665 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4: 3666 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4: 3667 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4: 3668 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4: 3669 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4: 3670 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4: 3671 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4: 3672 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4: 3673 case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8: 3674 case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8: 3675 case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8: 3676 case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8: 3677 case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8: 3678 case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8: 3679 case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8: 3680 case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8: 3681 case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8: 3682 case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8: 3683 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3684 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4: 3685 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4: 3686 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4: 3687 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4: 3688 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4: 3689 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4: 3690 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4: 3691 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4: 3692 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4: 3693 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4: 3694 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8: 3695 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8: 3696 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8: 3697 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8: 3698 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8: 3699 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8: 3700 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8: 3701 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8: 3702 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8: 3703 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8: 3704 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3705 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8: 3706 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8: 3707 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8: 3708 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8: 3709 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8: 3710 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8: 3711 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8: 3712 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8: 3713 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8: 3714 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8: 3715 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3716 } 3717 3718 return false; 3719 } 3720 3721 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3722 CallExpr *TheCall) { 3723 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3724 Expr *Arg = TheCall->getArg(0); 3725 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3726 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3727 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3728 << Arg->getSourceRange(); 3729 } 3730 3731 // For intrinsics which take an immediate value as part of the instruction, 3732 // range check them here. 3733 unsigned i = 0, l = 0, u = 0; 3734 switch (BuiltinID) { 3735 default: return false; 3736 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3737 case SystemZ::BI__builtin_s390_verimb: 3738 case SystemZ::BI__builtin_s390_verimh: 3739 case SystemZ::BI__builtin_s390_verimf: 3740 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3741 case SystemZ::BI__builtin_s390_vfaeb: 3742 case SystemZ::BI__builtin_s390_vfaeh: 3743 case SystemZ::BI__builtin_s390_vfaef: 3744 case SystemZ::BI__builtin_s390_vfaebs: 3745 case SystemZ::BI__builtin_s390_vfaehs: 3746 case SystemZ::BI__builtin_s390_vfaefs: 3747 case SystemZ::BI__builtin_s390_vfaezb: 3748 case SystemZ::BI__builtin_s390_vfaezh: 3749 case SystemZ::BI__builtin_s390_vfaezf: 3750 case SystemZ::BI__builtin_s390_vfaezbs: 3751 case SystemZ::BI__builtin_s390_vfaezhs: 3752 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3753 case SystemZ::BI__builtin_s390_vfisb: 3754 case SystemZ::BI__builtin_s390_vfidb: 3755 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3756 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3757 case SystemZ::BI__builtin_s390_vftcisb: 3758 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3759 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3760 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3761 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3762 case SystemZ::BI__builtin_s390_vstrcb: 3763 case SystemZ::BI__builtin_s390_vstrch: 3764 case SystemZ::BI__builtin_s390_vstrcf: 3765 case SystemZ::BI__builtin_s390_vstrczb: 3766 case SystemZ::BI__builtin_s390_vstrczh: 3767 case SystemZ::BI__builtin_s390_vstrczf: 3768 case SystemZ::BI__builtin_s390_vstrcbs: 3769 case SystemZ::BI__builtin_s390_vstrchs: 3770 case SystemZ::BI__builtin_s390_vstrcfs: 3771 case SystemZ::BI__builtin_s390_vstrczbs: 3772 case SystemZ::BI__builtin_s390_vstrczhs: 3773 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3774 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3775 case SystemZ::BI__builtin_s390_vfminsb: 3776 case SystemZ::BI__builtin_s390_vfmaxsb: 3777 case SystemZ::BI__builtin_s390_vfmindb: 3778 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3779 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3780 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3781 case SystemZ::BI__builtin_s390_vclfnhs: 3782 case SystemZ::BI__builtin_s390_vclfnls: 3783 case SystemZ::BI__builtin_s390_vcfn: 3784 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3785 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3786 } 3787 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3788 } 3789 3790 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3791 /// This checks that the target supports __builtin_cpu_supports and 3792 /// that the string argument is constant and valid. 3793 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3794 CallExpr *TheCall) { 3795 Expr *Arg = TheCall->getArg(0); 3796 3797 // Check if the argument is a string literal. 3798 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3799 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3800 << Arg->getSourceRange(); 3801 3802 // Check the contents of the string. 3803 StringRef Feature = 3804 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3805 if (!TI.validateCpuSupports(Feature)) 3806 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3807 << Arg->getSourceRange(); 3808 return false; 3809 } 3810 3811 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3812 /// This checks that the target supports __builtin_cpu_is and 3813 /// that the string argument is constant and valid. 3814 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3815 Expr *Arg = TheCall->getArg(0); 3816 3817 // Check if the argument is a string literal. 3818 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3819 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3820 << Arg->getSourceRange(); 3821 3822 // Check the contents of the string. 3823 StringRef Feature = 3824 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3825 if (!TI.validateCpuIs(Feature)) 3826 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3827 << Arg->getSourceRange(); 3828 return false; 3829 } 3830 3831 // Check if the rounding mode is legal. 3832 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3833 // Indicates if this instruction has rounding control or just SAE. 3834 bool HasRC = false; 3835 3836 unsigned ArgNum = 0; 3837 switch (BuiltinID) { 3838 default: 3839 return false; 3840 case X86::BI__builtin_ia32_vcvttsd2si32: 3841 case X86::BI__builtin_ia32_vcvttsd2si64: 3842 case X86::BI__builtin_ia32_vcvttsd2usi32: 3843 case X86::BI__builtin_ia32_vcvttsd2usi64: 3844 case X86::BI__builtin_ia32_vcvttss2si32: 3845 case X86::BI__builtin_ia32_vcvttss2si64: 3846 case X86::BI__builtin_ia32_vcvttss2usi32: 3847 case X86::BI__builtin_ia32_vcvttss2usi64: 3848 ArgNum = 1; 3849 break; 3850 case X86::BI__builtin_ia32_maxpd512: 3851 case X86::BI__builtin_ia32_maxps512: 3852 case X86::BI__builtin_ia32_minpd512: 3853 case X86::BI__builtin_ia32_minps512: 3854 ArgNum = 2; 3855 break; 3856 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3857 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3858 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3859 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3860 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3861 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3862 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3863 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3864 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3865 case X86::BI__builtin_ia32_exp2pd_mask: 3866 case X86::BI__builtin_ia32_exp2ps_mask: 3867 case X86::BI__builtin_ia32_getexppd512_mask: 3868 case X86::BI__builtin_ia32_getexpps512_mask: 3869 case X86::BI__builtin_ia32_rcp28pd_mask: 3870 case X86::BI__builtin_ia32_rcp28ps_mask: 3871 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3872 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3873 case X86::BI__builtin_ia32_vcomisd: 3874 case X86::BI__builtin_ia32_vcomiss: 3875 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3876 ArgNum = 3; 3877 break; 3878 case X86::BI__builtin_ia32_cmppd512_mask: 3879 case X86::BI__builtin_ia32_cmpps512_mask: 3880 case X86::BI__builtin_ia32_cmpsd_mask: 3881 case X86::BI__builtin_ia32_cmpss_mask: 3882 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3883 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3884 case X86::BI__builtin_ia32_getexpss128_round_mask: 3885 case X86::BI__builtin_ia32_getmantpd512_mask: 3886 case X86::BI__builtin_ia32_getmantps512_mask: 3887 case X86::BI__builtin_ia32_maxsd_round_mask: 3888 case X86::BI__builtin_ia32_maxss_round_mask: 3889 case X86::BI__builtin_ia32_minsd_round_mask: 3890 case X86::BI__builtin_ia32_minss_round_mask: 3891 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3892 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3893 case X86::BI__builtin_ia32_reducepd512_mask: 3894 case X86::BI__builtin_ia32_reduceps512_mask: 3895 case X86::BI__builtin_ia32_rndscalepd_mask: 3896 case X86::BI__builtin_ia32_rndscaleps_mask: 3897 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3898 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3899 ArgNum = 4; 3900 break; 3901 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3902 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3903 case X86::BI__builtin_ia32_fixupimmps512_mask: 3904 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3905 case X86::BI__builtin_ia32_fixupimmsd_mask: 3906 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3907 case X86::BI__builtin_ia32_fixupimmss_mask: 3908 case X86::BI__builtin_ia32_fixupimmss_maskz: 3909 case X86::BI__builtin_ia32_getmantsd_round_mask: 3910 case X86::BI__builtin_ia32_getmantss_round_mask: 3911 case X86::BI__builtin_ia32_rangepd512_mask: 3912 case X86::BI__builtin_ia32_rangeps512_mask: 3913 case X86::BI__builtin_ia32_rangesd128_round_mask: 3914 case X86::BI__builtin_ia32_rangess128_round_mask: 3915 case X86::BI__builtin_ia32_reducesd_mask: 3916 case X86::BI__builtin_ia32_reducess_mask: 3917 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3918 case X86::BI__builtin_ia32_rndscaless_round_mask: 3919 ArgNum = 5; 3920 break; 3921 case X86::BI__builtin_ia32_vcvtsd2si64: 3922 case X86::BI__builtin_ia32_vcvtsd2si32: 3923 case X86::BI__builtin_ia32_vcvtsd2usi32: 3924 case X86::BI__builtin_ia32_vcvtsd2usi64: 3925 case X86::BI__builtin_ia32_vcvtss2si32: 3926 case X86::BI__builtin_ia32_vcvtss2si64: 3927 case X86::BI__builtin_ia32_vcvtss2usi32: 3928 case X86::BI__builtin_ia32_vcvtss2usi64: 3929 case X86::BI__builtin_ia32_sqrtpd512: 3930 case X86::BI__builtin_ia32_sqrtps512: 3931 ArgNum = 1; 3932 HasRC = true; 3933 break; 3934 case X86::BI__builtin_ia32_addpd512: 3935 case X86::BI__builtin_ia32_addps512: 3936 case X86::BI__builtin_ia32_divpd512: 3937 case X86::BI__builtin_ia32_divps512: 3938 case X86::BI__builtin_ia32_mulpd512: 3939 case X86::BI__builtin_ia32_mulps512: 3940 case X86::BI__builtin_ia32_subpd512: 3941 case X86::BI__builtin_ia32_subps512: 3942 case X86::BI__builtin_ia32_cvtsi2sd64: 3943 case X86::BI__builtin_ia32_cvtsi2ss32: 3944 case X86::BI__builtin_ia32_cvtsi2ss64: 3945 case X86::BI__builtin_ia32_cvtusi2sd64: 3946 case X86::BI__builtin_ia32_cvtusi2ss32: 3947 case X86::BI__builtin_ia32_cvtusi2ss64: 3948 ArgNum = 2; 3949 HasRC = true; 3950 break; 3951 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3952 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3953 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3954 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3955 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3956 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3957 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3958 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3959 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3960 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3961 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3962 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3963 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3964 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3965 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3966 ArgNum = 3; 3967 HasRC = true; 3968 break; 3969 case X86::BI__builtin_ia32_addss_round_mask: 3970 case X86::BI__builtin_ia32_addsd_round_mask: 3971 case X86::BI__builtin_ia32_divss_round_mask: 3972 case X86::BI__builtin_ia32_divsd_round_mask: 3973 case X86::BI__builtin_ia32_mulss_round_mask: 3974 case X86::BI__builtin_ia32_mulsd_round_mask: 3975 case X86::BI__builtin_ia32_subss_round_mask: 3976 case X86::BI__builtin_ia32_subsd_round_mask: 3977 case X86::BI__builtin_ia32_scalefpd512_mask: 3978 case X86::BI__builtin_ia32_scalefps512_mask: 3979 case X86::BI__builtin_ia32_scalefsd_round_mask: 3980 case X86::BI__builtin_ia32_scalefss_round_mask: 3981 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3982 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3983 case X86::BI__builtin_ia32_sqrtss_round_mask: 3984 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3985 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3986 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3987 case X86::BI__builtin_ia32_vfmaddss3_mask: 3988 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3989 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3990 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3991 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3992 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3993 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3994 case X86::BI__builtin_ia32_vfmaddps512_mask: 3995 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3996 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3997 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3998 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3999 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4000 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4001 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4002 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4003 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4004 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4005 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4006 ArgNum = 4; 4007 HasRC = true; 4008 break; 4009 } 4010 4011 llvm::APSInt Result; 4012 4013 // We can't check the value of a dependent argument. 4014 Expr *Arg = TheCall->getArg(ArgNum); 4015 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4016 return false; 4017 4018 // Check constant-ness first. 4019 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4020 return true; 4021 4022 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4023 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4024 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4025 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4026 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4027 Result == 8/*ROUND_NO_EXC*/ || 4028 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4029 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4030 return false; 4031 4032 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4033 << Arg->getSourceRange(); 4034 } 4035 4036 // Check if the gather/scatter scale is legal. 4037 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4038 CallExpr *TheCall) { 4039 unsigned ArgNum = 0; 4040 switch (BuiltinID) { 4041 default: 4042 return false; 4043 case X86::BI__builtin_ia32_gatherpfdpd: 4044 case X86::BI__builtin_ia32_gatherpfdps: 4045 case X86::BI__builtin_ia32_gatherpfqpd: 4046 case X86::BI__builtin_ia32_gatherpfqps: 4047 case X86::BI__builtin_ia32_scatterpfdpd: 4048 case X86::BI__builtin_ia32_scatterpfdps: 4049 case X86::BI__builtin_ia32_scatterpfqpd: 4050 case X86::BI__builtin_ia32_scatterpfqps: 4051 ArgNum = 3; 4052 break; 4053 case X86::BI__builtin_ia32_gatherd_pd: 4054 case X86::BI__builtin_ia32_gatherd_pd256: 4055 case X86::BI__builtin_ia32_gatherq_pd: 4056 case X86::BI__builtin_ia32_gatherq_pd256: 4057 case X86::BI__builtin_ia32_gatherd_ps: 4058 case X86::BI__builtin_ia32_gatherd_ps256: 4059 case X86::BI__builtin_ia32_gatherq_ps: 4060 case X86::BI__builtin_ia32_gatherq_ps256: 4061 case X86::BI__builtin_ia32_gatherd_q: 4062 case X86::BI__builtin_ia32_gatherd_q256: 4063 case X86::BI__builtin_ia32_gatherq_q: 4064 case X86::BI__builtin_ia32_gatherq_q256: 4065 case X86::BI__builtin_ia32_gatherd_d: 4066 case X86::BI__builtin_ia32_gatherd_d256: 4067 case X86::BI__builtin_ia32_gatherq_d: 4068 case X86::BI__builtin_ia32_gatherq_d256: 4069 case X86::BI__builtin_ia32_gather3div2df: 4070 case X86::BI__builtin_ia32_gather3div2di: 4071 case X86::BI__builtin_ia32_gather3div4df: 4072 case X86::BI__builtin_ia32_gather3div4di: 4073 case X86::BI__builtin_ia32_gather3div4sf: 4074 case X86::BI__builtin_ia32_gather3div4si: 4075 case X86::BI__builtin_ia32_gather3div8sf: 4076 case X86::BI__builtin_ia32_gather3div8si: 4077 case X86::BI__builtin_ia32_gather3siv2df: 4078 case X86::BI__builtin_ia32_gather3siv2di: 4079 case X86::BI__builtin_ia32_gather3siv4df: 4080 case X86::BI__builtin_ia32_gather3siv4di: 4081 case X86::BI__builtin_ia32_gather3siv4sf: 4082 case X86::BI__builtin_ia32_gather3siv4si: 4083 case X86::BI__builtin_ia32_gather3siv8sf: 4084 case X86::BI__builtin_ia32_gather3siv8si: 4085 case X86::BI__builtin_ia32_gathersiv8df: 4086 case X86::BI__builtin_ia32_gathersiv16sf: 4087 case X86::BI__builtin_ia32_gatherdiv8df: 4088 case X86::BI__builtin_ia32_gatherdiv16sf: 4089 case X86::BI__builtin_ia32_gathersiv8di: 4090 case X86::BI__builtin_ia32_gathersiv16si: 4091 case X86::BI__builtin_ia32_gatherdiv8di: 4092 case X86::BI__builtin_ia32_gatherdiv16si: 4093 case X86::BI__builtin_ia32_scatterdiv2df: 4094 case X86::BI__builtin_ia32_scatterdiv2di: 4095 case X86::BI__builtin_ia32_scatterdiv4df: 4096 case X86::BI__builtin_ia32_scatterdiv4di: 4097 case X86::BI__builtin_ia32_scatterdiv4sf: 4098 case X86::BI__builtin_ia32_scatterdiv4si: 4099 case X86::BI__builtin_ia32_scatterdiv8sf: 4100 case X86::BI__builtin_ia32_scatterdiv8si: 4101 case X86::BI__builtin_ia32_scattersiv2df: 4102 case X86::BI__builtin_ia32_scattersiv2di: 4103 case X86::BI__builtin_ia32_scattersiv4df: 4104 case X86::BI__builtin_ia32_scattersiv4di: 4105 case X86::BI__builtin_ia32_scattersiv4sf: 4106 case X86::BI__builtin_ia32_scattersiv4si: 4107 case X86::BI__builtin_ia32_scattersiv8sf: 4108 case X86::BI__builtin_ia32_scattersiv8si: 4109 case X86::BI__builtin_ia32_scattersiv8df: 4110 case X86::BI__builtin_ia32_scattersiv16sf: 4111 case X86::BI__builtin_ia32_scatterdiv8df: 4112 case X86::BI__builtin_ia32_scatterdiv16sf: 4113 case X86::BI__builtin_ia32_scattersiv8di: 4114 case X86::BI__builtin_ia32_scattersiv16si: 4115 case X86::BI__builtin_ia32_scatterdiv8di: 4116 case X86::BI__builtin_ia32_scatterdiv16si: 4117 ArgNum = 4; 4118 break; 4119 } 4120 4121 llvm::APSInt Result; 4122 4123 // We can't check the value of a dependent argument. 4124 Expr *Arg = TheCall->getArg(ArgNum); 4125 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4126 return false; 4127 4128 // Check constant-ness first. 4129 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4130 return true; 4131 4132 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4133 return false; 4134 4135 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4136 << Arg->getSourceRange(); 4137 } 4138 4139 enum { TileRegLow = 0, TileRegHigh = 7 }; 4140 4141 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4142 ArrayRef<int> ArgNums) { 4143 for (int ArgNum : ArgNums) { 4144 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4145 return true; 4146 } 4147 return false; 4148 } 4149 4150 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4151 ArrayRef<int> ArgNums) { 4152 // Because the max number of tile register is TileRegHigh + 1, so here we use 4153 // each bit to represent the usage of them in bitset. 4154 std::bitset<TileRegHigh + 1> ArgValues; 4155 for (int ArgNum : ArgNums) { 4156 Expr *Arg = TheCall->getArg(ArgNum); 4157 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4158 continue; 4159 4160 llvm::APSInt Result; 4161 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4162 return true; 4163 int ArgExtValue = Result.getExtValue(); 4164 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4165 "Incorrect tile register num."); 4166 if (ArgValues.test(ArgExtValue)) 4167 return Diag(TheCall->getBeginLoc(), 4168 diag::err_x86_builtin_tile_arg_duplicate) 4169 << TheCall->getArg(ArgNum)->getSourceRange(); 4170 ArgValues.set(ArgExtValue); 4171 } 4172 return false; 4173 } 4174 4175 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4176 ArrayRef<int> ArgNums) { 4177 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4178 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4179 } 4180 4181 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4182 switch (BuiltinID) { 4183 default: 4184 return false; 4185 case X86::BI__builtin_ia32_tileloadd64: 4186 case X86::BI__builtin_ia32_tileloaddt164: 4187 case X86::BI__builtin_ia32_tilestored64: 4188 case X86::BI__builtin_ia32_tilezero: 4189 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4190 case X86::BI__builtin_ia32_tdpbssd: 4191 case X86::BI__builtin_ia32_tdpbsud: 4192 case X86::BI__builtin_ia32_tdpbusd: 4193 case X86::BI__builtin_ia32_tdpbuud: 4194 case X86::BI__builtin_ia32_tdpbf16ps: 4195 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4196 } 4197 } 4198 static bool isX86_32Builtin(unsigned BuiltinID) { 4199 // These builtins only work on x86-32 targets. 4200 switch (BuiltinID) { 4201 case X86::BI__builtin_ia32_readeflags_u32: 4202 case X86::BI__builtin_ia32_writeeflags_u32: 4203 return true; 4204 } 4205 4206 return false; 4207 } 4208 4209 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4210 CallExpr *TheCall) { 4211 if (BuiltinID == X86::BI__builtin_cpu_supports) 4212 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4213 4214 if (BuiltinID == X86::BI__builtin_cpu_is) 4215 return SemaBuiltinCpuIs(*this, TI, TheCall); 4216 4217 // Check for 32-bit only builtins on a 64-bit target. 4218 const llvm::Triple &TT = TI.getTriple(); 4219 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4220 return Diag(TheCall->getCallee()->getBeginLoc(), 4221 diag::err_32_bit_builtin_64_bit_tgt); 4222 4223 // If the intrinsic has rounding or SAE make sure its valid. 4224 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4225 return true; 4226 4227 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4228 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4229 return true; 4230 4231 // If the intrinsic has a tile arguments, make sure they are valid. 4232 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4233 return true; 4234 4235 // For intrinsics which take an immediate value as part of the instruction, 4236 // range check them here. 4237 int i = 0, l = 0, u = 0; 4238 switch (BuiltinID) { 4239 default: 4240 return false; 4241 case X86::BI__builtin_ia32_vec_ext_v2si: 4242 case X86::BI__builtin_ia32_vec_ext_v2di: 4243 case X86::BI__builtin_ia32_vextractf128_pd256: 4244 case X86::BI__builtin_ia32_vextractf128_ps256: 4245 case X86::BI__builtin_ia32_vextractf128_si256: 4246 case X86::BI__builtin_ia32_extract128i256: 4247 case X86::BI__builtin_ia32_extractf64x4_mask: 4248 case X86::BI__builtin_ia32_extracti64x4_mask: 4249 case X86::BI__builtin_ia32_extractf32x8_mask: 4250 case X86::BI__builtin_ia32_extracti32x8_mask: 4251 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4252 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4253 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4254 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4255 i = 1; l = 0; u = 1; 4256 break; 4257 case X86::BI__builtin_ia32_vec_set_v2di: 4258 case X86::BI__builtin_ia32_vinsertf128_pd256: 4259 case X86::BI__builtin_ia32_vinsertf128_ps256: 4260 case X86::BI__builtin_ia32_vinsertf128_si256: 4261 case X86::BI__builtin_ia32_insert128i256: 4262 case X86::BI__builtin_ia32_insertf32x8: 4263 case X86::BI__builtin_ia32_inserti32x8: 4264 case X86::BI__builtin_ia32_insertf64x4: 4265 case X86::BI__builtin_ia32_inserti64x4: 4266 case X86::BI__builtin_ia32_insertf64x2_256: 4267 case X86::BI__builtin_ia32_inserti64x2_256: 4268 case X86::BI__builtin_ia32_insertf32x4_256: 4269 case X86::BI__builtin_ia32_inserti32x4_256: 4270 i = 2; l = 0; u = 1; 4271 break; 4272 case X86::BI__builtin_ia32_vpermilpd: 4273 case X86::BI__builtin_ia32_vec_ext_v4hi: 4274 case X86::BI__builtin_ia32_vec_ext_v4si: 4275 case X86::BI__builtin_ia32_vec_ext_v4sf: 4276 case X86::BI__builtin_ia32_vec_ext_v4di: 4277 case X86::BI__builtin_ia32_extractf32x4_mask: 4278 case X86::BI__builtin_ia32_extracti32x4_mask: 4279 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4280 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4281 i = 1; l = 0; u = 3; 4282 break; 4283 case X86::BI_mm_prefetch: 4284 case X86::BI__builtin_ia32_vec_ext_v8hi: 4285 case X86::BI__builtin_ia32_vec_ext_v8si: 4286 i = 1; l = 0; u = 7; 4287 break; 4288 case X86::BI__builtin_ia32_sha1rnds4: 4289 case X86::BI__builtin_ia32_blendpd: 4290 case X86::BI__builtin_ia32_shufpd: 4291 case X86::BI__builtin_ia32_vec_set_v4hi: 4292 case X86::BI__builtin_ia32_vec_set_v4si: 4293 case X86::BI__builtin_ia32_vec_set_v4di: 4294 case X86::BI__builtin_ia32_shuf_f32x4_256: 4295 case X86::BI__builtin_ia32_shuf_f64x2_256: 4296 case X86::BI__builtin_ia32_shuf_i32x4_256: 4297 case X86::BI__builtin_ia32_shuf_i64x2_256: 4298 case X86::BI__builtin_ia32_insertf64x2_512: 4299 case X86::BI__builtin_ia32_inserti64x2_512: 4300 case X86::BI__builtin_ia32_insertf32x4: 4301 case X86::BI__builtin_ia32_inserti32x4: 4302 i = 2; l = 0; u = 3; 4303 break; 4304 case X86::BI__builtin_ia32_vpermil2pd: 4305 case X86::BI__builtin_ia32_vpermil2pd256: 4306 case X86::BI__builtin_ia32_vpermil2ps: 4307 case X86::BI__builtin_ia32_vpermil2ps256: 4308 i = 3; l = 0; u = 3; 4309 break; 4310 case X86::BI__builtin_ia32_cmpb128_mask: 4311 case X86::BI__builtin_ia32_cmpw128_mask: 4312 case X86::BI__builtin_ia32_cmpd128_mask: 4313 case X86::BI__builtin_ia32_cmpq128_mask: 4314 case X86::BI__builtin_ia32_cmpb256_mask: 4315 case X86::BI__builtin_ia32_cmpw256_mask: 4316 case X86::BI__builtin_ia32_cmpd256_mask: 4317 case X86::BI__builtin_ia32_cmpq256_mask: 4318 case X86::BI__builtin_ia32_cmpb512_mask: 4319 case X86::BI__builtin_ia32_cmpw512_mask: 4320 case X86::BI__builtin_ia32_cmpd512_mask: 4321 case X86::BI__builtin_ia32_cmpq512_mask: 4322 case X86::BI__builtin_ia32_ucmpb128_mask: 4323 case X86::BI__builtin_ia32_ucmpw128_mask: 4324 case X86::BI__builtin_ia32_ucmpd128_mask: 4325 case X86::BI__builtin_ia32_ucmpq128_mask: 4326 case X86::BI__builtin_ia32_ucmpb256_mask: 4327 case X86::BI__builtin_ia32_ucmpw256_mask: 4328 case X86::BI__builtin_ia32_ucmpd256_mask: 4329 case X86::BI__builtin_ia32_ucmpq256_mask: 4330 case X86::BI__builtin_ia32_ucmpb512_mask: 4331 case X86::BI__builtin_ia32_ucmpw512_mask: 4332 case X86::BI__builtin_ia32_ucmpd512_mask: 4333 case X86::BI__builtin_ia32_ucmpq512_mask: 4334 case X86::BI__builtin_ia32_vpcomub: 4335 case X86::BI__builtin_ia32_vpcomuw: 4336 case X86::BI__builtin_ia32_vpcomud: 4337 case X86::BI__builtin_ia32_vpcomuq: 4338 case X86::BI__builtin_ia32_vpcomb: 4339 case X86::BI__builtin_ia32_vpcomw: 4340 case X86::BI__builtin_ia32_vpcomd: 4341 case X86::BI__builtin_ia32_vpcomq: 4342 case X86::BI__builtin_ia32_vec_set_v8hi: 4343 case X86::BI__builtin_ia32_vec_set_v8si: 4344 i = 2; l = 0; u = 7; 4345 break; 4346 case X86::BI__builtin_ia32_vpermilpd256: 4347 case X86::BI__builtin_ia32_roundps: 4348 case X86::BI__builtin_ia32_roundpd: 4349 case X86::BI__builtin_ia32_roundps256: 4350 case X86::BI__builtin_ia32_roundpd256: 4351 case X86::BI__builtin_ia32_getmantpd128_mask: 4352 case X86::BI__builtin_ia32_getmantpd256_mask: 4353 case X86::BI__builtin_ia32_getmantps128_mask: 4354 case X86::BI__builtin_ia32_getmantps256_mask: 4355 case X86::BI__builtin_ia32_getmantpd512_mask: 4356 case X86::BI__builtin_ia32_getmantps512_mask: 4357 case X86::BI__builtin_ia32_vec_ext_v16qi: 4358 case X86::BI__builtin_ia32_vec_ext_v16hi: 4359 i = 1; l = 0; u = 15; 4360 break; 4361 case X86::BI__builtin_ia32_pblendd128: 4362 case X86::BI__builtin_ia32_blendps: 4363 case X86::BI__builtin_ia32_blendpd256: 4364 case X86::BI__builtin_ia32_shufpd256: 4365 case X86::BI__builtin_ia32_roundss: 4366 case X86::BI__builtin_ia32_roundsd: 4367 case X86::BI__builtin_ia32_rangepd128_mask: 4368 case X86::BI__builtin_ia32_rangepd256_mask: 4369 case X86::BI__builtin_ia32_rangepd512_mask: 4370 case X86::BI__builtin_ia32_rangeps128_mask: 4371 case X86::BI__builtin_ia32_rangeps256_mask: 4372 case X86::BI__builtin_ia32_rangeps512_mask: 4373 case X86::BI__builtin_ia32_getmantsd_round_mask: 4374 case X86::BI__builtin_ia32_getmantss_round_mask: 4375 case X86::BI__builtin_ia32_vec_set_v16qi: 4376 case X86::BI__builtin_ia32_vec_set_v16hi: 4377 i = 2; l = 0; u = 15; 4378 break; 4379 case X86::BI__builtin_ia32_vec_ext_v32qi: 4380 i = 1; l = 0; u = 31; 4381 break; 4382 case X86::BI__builtin_ia32_cmpps: 4383 case X86::BI__builtin_ia32_cmpss: 4384 case X86::BI__builtin_ia32_cmppd: 4385 case X86::BI__builtin_ia32_cmpsd: 4386 case X86::BI__builtin_ia32_cmpps256: 4387 case X86::BI__builtin_ia32_cmppd256: 4388 case X86::BI__builtin_ia32_cmpps128_mask: 4389 case X86::BI__builtin_ia32_cmppd128_mask: 4390 case X86::BI__builtin_ia32_cmpps256_mask: 4391 case X86::BI__builtin_ia32_cmppd256_mask: 4392 case X86::BI__builtin_ia32_cmpps512_mask: 4393 case X86::BI__builtin_ia32_cmppd512_mask: 4394 case X86::BI__builtin_ia32_cmpsd_mask: 4395 case X86::BI__builtin_ia32_cmpss_mask: 4396 case X86::BI__builtin_ia32_vec_set_v32qi: 4397 i = 2; l = 0; u = 31; 4398 break; 4399 case X86::BI__builtin_ia32_permdf256: 4400 case X86::BI__builtin_ia32_permdi256: 4401 case X86::BI__builtin_ia32_permdf512: 4402 case X86::BI__builtin_ia32_permdi512: 4403 case X86::BI__builtin_ia32_vpermilps: 4404 case X86::BI__builtin_ia32_vpermilps256: 4405 case X86::BI__builtin_ia32_vpermilpd512: 4406 case X86::BI__builtin_ia32_vpermilps512: 4407 case X86::BI__builtin_ia32_pshufd: 4408 case X86::BI__builtin_ia32_pshufd256: 4409 case X86::BI__builtin_ia32_pshufd512: 4410 case X86::BI__builtin_ia32_pshufhw: 4411 case X86::BI__builtin_ia32_pshufhw256: 4412 case X86::BI__builtin_ia32_pshufhw512: 4413 case X86::BI__builtin_ia32_pshuflw: 4414 case X86::BI__builtin_ia32_pshuflw256: 4415 case X86::BI__builtin_ia32_pshuflw512: 4416 case X86::BI__builtin_ia32_vcvtps2ph: 4417 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4418 case X86::BI__builtin_ia32_vcvtps2ph256: 4419 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4420 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4421 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4422 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4423 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4424 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4425 case X86::BI__builtin_ia32_rndscaleps_mask: 4426 case X86::BI__builtin_ia32_rndscalepd_mask: 4427 case X86::BI__builtin_ia32_reducepd128_mask: 4428 case X86::BI__builtin_ia32_reducepd256_mask: 4429 case X86::BI__builtin_ia32_reducepd512_mask: 4430 case X86::BI__builtin_ia32_reduceps128_mask: 4431 case X86::BI__builtin_ia32_reduceps256_mask: 4432 case X86::BI__builtin_ia32_reduceps512_mask: 4433 case X86::BI__builtin_ia32_prold512: 4434 case X86::BI__builtin_ia32_prolq512: 4435 case X86::BI__builtin_ia32_prold128: 4436 case X86::BI__builtin_ia32_prold256: 4437 case X86::BI__builtin_ia32_prolq128: 4438 case X86::BI__builtin_ia32_prolq256: 4439 case X86::BI__builtin_ia32_prord512: 4440 case X86::BI__builtin_ia32_prorq512: 4441 case X86::BI__builtin_ia32_prord128: 4442 case X86::BI__builtin_ia32_prord256: 4443 case X86::BI__builtin_ia32_prorq128: 4444 case X86::BI__builtin_ia32_prorq256: 4445 case X86::BI__builtin_ia32_fpclasspd128_mask: 4446 case X86::BI__builtin_ia32_fpclasspd256_mask: 4447 case X86::BI__builtin_ia32_fpclassps128_mask: 4448 case X86::BI__builtin_ia32_fpclassps256_mask: 4449 case X86::BI__builtin_ia32_fpclassps512_mask: 4450 case X86::BI__builtin_ia32_fpclasspd512_mask: 4451 case X86::BI__builtin_ia32_fpclasssd_mask: 4452 case X86::BI__builtin_ia32_fpclassss_mask: 4453 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4454 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4455 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4456 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4457 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4458 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4459 case X86::BI__builtin_ia32_kshiftliqi: 4460 case X86::BI__builtin_ia32_kshiftlihi: 4461 case X86::BI__builtin_ia32_kshiftlisi: 4462 case X86::BI__builtin_ia32_kshiftlidi: 4463 case X86::BI__builtin_ia32_kshiftriqi: 4464 case X86::BI__builtin_ia32_kshiftrihi: 4465 case X86::BI__builtin_ia32_kshiftrisi: 4466 case X86::BI__builtin_ia32_kshiftridi: 4467 i = 1; l = 0; u = 255; 4468 break; 4469 case X86::BI__builtin_ia32_vperm2f128_pd256: 4470 case X86::BI__builtin_ia32_vperm2f128_ps256: 4471 case X86::BI__builtin_ia32_vperm2f128_si256: 4472 case X86::BI__builtin_ia32_permti256: 4473 case X86::BI__builtin_ia32_pblendw128: 4474 case X86::BI__builtin_ia32_pblendw256: 4475 case X86::BI__builtin_ia32_blendps256: 4476 case X86::BI__builtin_ia32_pblendd256: 4477 case X86::BI__builtin_ia32_palignr128: 4478 case X86::BI__builtin_ia32_palignr256: 4479 case X86::BI__builtin_ia32_palignr512: 4480 case X86::BI__builtin_ia32_alignq512: 4481 case X86::BI__builtin_ia32_alignd512: 4482 case X86::BI__builtin_ia32_alignd128: 4483 case X86::BI__builtin_ia32_alignd256: 4484 case X86::BI__builtin_ia32_alignq128: 4485 case X86::BI__builtin_ia32_alignq256: 4486 case X86::BI__builtin_ia32_vcomisd: 4487 case X86::BI__builtin_ia32_vcomiss: 4488 case X86::BI__builtin_ia32_shuf_f32x4: 4489 case X86::BI__builtin_ia32_shuf_f64x2: 4490 case X86::BI__builtin_ia32_shuf_i32x4: 4491 case X86::BI__builtin_ia32_shuf_i64x2: 4492 case X86::BI__builtin_ia32_shufpd512: 4493 case X86::BI__builtin_ia32_shufps: 4494 case X86::BI__builtin_ia32_shufps256: 4495 case X86::BI__builtin_ia32_shufps512: 4496 case X86::BI__builtin_ia32_dbpsadbw128: 4497 case X86::BI__builtin_ia32_dbpsadbw256: 4498 case X86::BI__builtin_ia32_dbpsadbw512: 4499 case X86::BI__builtin_ia32_vpshldd128: 4500 case X86::BI__builtin_ia32_vpshldd256: 4501 case X86::BI__builtin_ia32_vpshldd512: 4502 case X86::BI__builtin_ia32_vpshldq128: 4503 case X86::BI__builtin_ia32_vpshldq256: 4504 case X86::BI__builtin_ia32_vpshldq512: 4505 case X86::BI__builtin_ia32_vpshldw128: 4506 case X86::BI__builtin_ia32_vpshldw256: 4507 case X86::BI__builtin_ia32_vpshldw512: 4508 case X86::BI__builtin_ia32_vpshrdd128: 4509 case X86::BI__builtin_ia32_vpshrdd256: 4510 case X86::BI__builtin_ia32_vpshrdd512: 4511 case X86::BI__builtin_ia32_vpshrdq128: 4512 case X86::BI__builtin_ia32_vpshrdq256: 4513 case X86::BI__builtin_ia32_vpshrdq512: 4514 case X86::BI__builtin_ia32_vpshrdw128: 4515 case X86::BI__builtin_ia32_vpshrdw256: 4516 case X86::BI__builtin_ia32_vpshrdw512: 4517 i = 2; l = 0; u = 255; 4518 break; 4519 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4520 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4521 case X86::BI__builtin_ia32_fixupimmps512_mask: 4522 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4523 case X86::BI__builtin_ia32_fixupimmsd_mask: 4524 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4525 case X86::BI__builtin_ia32_fixupimmss_mask: 4526 case X86::BI__builtin_ia32_fixupimmss_maskz: 4527 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4528 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4529 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4530 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4531 case X86::BI__builtin_ia32_fixupimmps128_mask: 4532 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4533 case X86::BI__builtin_ia32_fixupimmps256_mask: 4534 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4535 case X86::BI__builtin_ia32_pternlogd512_mask: 4536 case X86::BI__builtin_ia32_pternlogd512_maskz: 4537 case X86::BI__builtin_ia32_pternlogq512_mask: 4538 case X86::BI__builtin_ia32_pternlogq512_maskz: 4539 case X86::BI__builtin_ia32_pternlogd128_mask: 4540 case X86::BI__builtin_ia32_pternlogd128_maskz: 4541 case X86::BI__builtin_ia32_pternlogd256_mask: 4542 case X86::BI__builtin_ia32_pternlogd256_maskz: 4543 case X86::BI__builtin_ia32_pternlogq128_mask: 4544 case X86::BI__builtin_ia32_pternlogq128_maskz: 4545 case X86::BI__builtin_ia32_pternlogq256_mask: 4546 case X86::BI__builtin_ia32_pternlogq256_maskz: 4547 i = 3; l = 0; u = 255; 4548 break; 4549 case X86::BI__builtin_ia32_gatherpfdpd: 4550 case X86::BI__builtin_ia32_gatherpfdps: 4551 case X86::BI__builtin_ia32_gatherpfqpd: 4552 case X86::BI__builtin_ia32_gatherpfqps: 4553 case X86::BI__builtin_ia32_scatterpfdpd: 4554 case X86::BI__builtin_ia32_scatterpfdps: 4555 case X86::BI__builtin_ia32_scatterpfqpd: 4556 case X86::BI__builtin_ia32_scatterpfqps: 4557 i = 4; l = 2; u = 3; 4558 break; 4559 case X86::BI__builtin_ia32_reducesd_mask: 4560 case X86::BI__builtin_ia32_reducess_mask: 4561 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4562 case X86::BI__builtin_ia32_rndscaless_round_mask: 4563 i = 4; l = 0; u = 255; 4564 break; 4565 } 4566 4567 // Note that we don't force a hard error on the range check here, allowing 4568 // template-generated or macro-generated dead code to potentially have out-of- 4569 // range values. These need to code generate, but don't need to necessarily 4570 // make any sense. We use a warning that defaults to an error. 4571 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4572 } 4573 4574 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4575 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4576 /// Returns true when the format fits the function and the FormatStringInfo has 4577 /// been populated. 4578 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4579 FormatStringInfo *FSI) { 4580 FSI->HasVAListArg = Format->getFirstArg() == 0; 4581 FSI->FormatIdx = Format->getFormatIdx() - 1; 4582 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4583 4584 // The way the format attribute works in GCC, the implicit this argument 4585 // of member functions is counted. However, it doesn't appear in our own 4586 // lists, so decrement format_idx in that case. 4587 if (IsCXXMember) { 4588 if(FSI->FormatIdx == 0) 4589 return false; 4590 --FSI->FormatIdx; 4591 if (FSI->FirstDataArg != 0) 4592 --FSI->FirstDataArg; 4593 } 4594 return true; 4595 } 4596 4597 /// Checks if a the given expression evaluates to null. 4598 /// 4599 /// Returns true if the value evaluates to null. 4600 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4601 // If the expression has non-null type, it doesn't evaluate to null. 4602 if (auto nullability 4603 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4604 if (*nullability == NullabilityKind::NonNull) 4605 return false; 4606 } 4607 4608 // As a special case, transparent unions initialized with zero are 4609 // considered null for the purposes of the nonnull attribute. 4610 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4611 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4612 if (const CompoundLiteralExpr *CLE = 4613 dyn_cast<CompoundLiteralExpr>(Expr)) 4614 if (const InitListExpr *ILE = 4615 dyn_cast<InitListExpr>(CLE->getInitializer())) 4616 Expr = ILE->getInit(0); 4617 } 4618 4619 bool Result; 4620 return (!Expr->isValueDependent() && 4621 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4622 !Result); 4623 } 4624 4625 static void CheckNonNullArgument(Sema &S, 4626 const Expr *ArgExpr, 4627 SourceLocation CallSiteLoc) { 4628 if (CheckNonNullExpr(S, ArgExpr)) 4629 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4630 S.PDiag(diag::warn_null_arg) 4631 << ArgExpr->getSourceRange()); 4632 } 4633 4634 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4635 FormatStringInfo FSI; 4636 if ((GetFormatStringType(Format) == FST_NSString) && 4637 getFormatStringInfo(Format, false, &FSI)) { 4638 Idx = FSI.FormatIdx; 4639 return true; 4640 } 4641 return false; 4642 } 4643 4644 /// Diagnose use of %s directive in an NSString which is being passed 4645 /// as formatting string to formatting method. 4646 static void 4647 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4648 const NamedDecl *FDecl, 4649 Expr **Args, 4650 unsigned NumArgs) { 4651 unsigned Idx = 0; 4652 bool Format = false; 4653 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4654 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4655 Idx = 2; 4656 Format = true; 4657 } 4658 else 4659 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4660 if (S.GetFormatNSStringIdx(I, Idx)) { 4661 Format = true; 4662 break; 4663 } 4664 } 4665 if (!Format || NumArgs <= Idx) 4666 return; 4667 const Expr *FormatExpr = Args[Idx]; 4668 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4669 FormatExpr = CSCE->getSubExpr(); 4670 const StringLiteral *FormatString; 4671 if (const ObjCStringLiteral *OSL = 4672 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4673 FormatString = OSL->getString(); 4674 else 4675 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4676 if (!FormatString) 4677 return; 4678 if (S.FormatStringHasSArg(FormatString)) { 4679 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4680 << "%s" << 1 << 1; 4681 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4682 << FDecl->getDeclName(); 4683 } 4684 } 4685 4686 /// Determine whether the given type has a non-null nullability annotation. 4687 static bool isNonNullType(ASTContext &ctx, QualType type) { 4688 if (auto nullability = type->getNullability(ctx)) 4689 return *nullability == NullabilityKind::NonNull; 4690 4691 return false; 4692 } 4693 4694 static void CheckNonNullArguments(Sema &S, 4695 const NamedDecl *FDecl, 4696 const FunctionProtoType *Proto, 4697 ArrayRef<const Expr *> Args, 4698 SourceLocation CallSiteLoc) { 4699 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4700 4701 // Already checked by by constant evaluator. 4702 if (S.isConstantEvaluated()) 4703 return; 4704 // Check the attributes attached to the method/function itself. 4705 llvm::SmallBitVector NonNullArgs; 4706 if (FDecl) { 4707 // Handle the nonnull attribute on the function/method declaration itself. 4708 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4709 if (!NonNull->args_size()) { 4710 // Easy case: all pointer arguments are nonnull. 4711 for (const auto *Arg : Args) 4712 if (S.isValidPointerAttrType(Arg->getType())) 4713 CheckNonNullArgument(S, Arg, CallSiteLoc); 4714 return; 4715 } 4716 4717 for (const ParamIdx &Idx : NonNull->args()) { 4718 unsigned IdxAST = Idx.getASTIndex(); 4719 if (IdxAST >= Args.size()) 4720 continue; 4721 if (NonNullArgs.empty()) 4722 NonNullArgs.resize(Args.size()); 4723 NonNullArgs.set(IdxAST); 4724 } 4725 } 4726 } 4727 4728 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4729 // Handle the nonnull attribute on the parameters of the 4730 // function/method. 4731 ArrayRef<ParmVarDecl*> parms; 4732 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4733 parms = FD->parameters(); 4734 else 4735 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4736 4737 unsigned ParamIndex = 0; 4738 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4739 I != E; ++I, ++ParamIndex) { 4740 const ParmVarDecl *PVD = *I; 4741 if (PVD->hasAttr<NonNullAttr>() || 4742 isNonNullType(S.Context, PVD->getType())) { 4743 if (NonNullArgs.empty()) 4744 NonNullArgs.resize(Args.size()); 4745 4746 NonNullArgs.set(ParamIndex); 4747 } 4748 } 4749 } else { 4750 // If we have a non-function, non-method declaration but no 4751 // function prototype, try to dig out the function prototype. 4752 if (!Proto) { 4753 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4754 QualType type = VD->getType().getNonReferenceType(); 4755 if (auto pointerType = type->getAs<PointerType>()) 4756 type = pointerType->getPointeeType(); 4757 else if (auto blockType = type->getAs<BlockPointerType>()) 4758 type = blockType->getPointeeType(); 4759 // FIXME: data member pointers? 4760 4761 // Dig out the function prototype, if there is one. 4762 Proto = type->getAs<FunctionProtoType>(); 4763 } 4764 } 4765 4766 // Fill in non-null argument information from the nullability 4767 // information on the parameter types (if we have them). 4768 if (Proto) { 4769 unsigned Index = 0; 4770 for (auto paramType : Proto->getParamTypes()) { 4771 if (isNonNullType(S.Context, paramType)) { 4772 if (NonNullArgs.empty()) 4773 NonNullArgs.resize(Args.size()); 4774 4775 NonNullArgs.set(Index); 4776 } 4777 4778 ++Index; 4779 } 4780 } 4781 } 4782 4783 // Check for non-null arguments. 4784 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4785 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4786 if (NonNullArgs[ArgIndex]) 4787 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4788 } 4789 } 4790 4791 /// Warn if a pointer or reference argument passed to a function points to an 4792 /// object that is less aligned than the parameter. This can happen when 4793 /// creating a typedef with a lower alignment than the original type and then 4794 /// calling functions defined in terms of the original type. 4795 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4796 StringRef ParamName, QualType ArgTy, 4797 QualType ParamTy) { 4798 4799 // If a function accepts a pointer or reference type 4800 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4801 return; 4802 4803 // If the parameter is a pointer type, get the pointee type for the 4804 // argument too. If the parameter is a reference type, don't try to get 4805 // the pointee type for the argument. 4806 if (ParamTy->isPointerType()) 4807 ArgTy = ArgTy->getPointeeType(); 4808 4809 // Remove reference or pointer 4810 ParamTy = ParamTy->getPointeeType(); 4811 4812 // Find expected alignment, and the actual alignment of the passed object. 4813 // getTypeAlignInChars requires complete types 4814 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4815 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4816 ArgTy->isUndeducedType()) 4817 return; 4818 4819 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4820 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4821 4822 // If the argument is less aligned than the parameter, there is a 4823 // potential alignment issue. 4824 if (ArgAlign < ParamAlign) 4825 Diag(Loc, diag::warn_param_mismatched_alignment) 4826 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4827 << ParamName << FDecl; 4828 } 4829 4830 /// Handles the checks for format strings, non-POD arguments to vararg 4831 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4832 /// attributes. 4833 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4834 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4835 bool IsMemberFunction, SourceLocation Loc, 4836 SourceRange Range, VariadicCallType CallType) { 4837 // FIXME: We should check as much as we can in the template definition. 4838 if (CurContext->isDependentContext()) 4839 return; 4840 4841 // Printf and scanf checking. 4842 llvm::SmallBitVector CheckedVarArgs; 4843 if (FDecl) { 4844 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4845 // Only create vector if there are format attributes. 4846 CheckedVarArgs.resize(Args.size()); 4847 4848 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4849 CheckedVarArgs); 4850 } 4851 } 4852 4853 // Refuse POD arguments that weren't caught by the format string 4854 // checks above. 4855 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4856 if (CallType != VariadicDoesNotApply && 4857 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4858 unsigned NumParams = Proto ? Proto->getNumParams() 4859 : FDecl && isa<FunctionDecl>(FDecl) 4860 ? cast<FunctionDecl>(FDecl)->getNumParams() 4861 : FDecl && isa<ObjCMethodDecl>(FDecl) 4862 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4863 : 0; 4864 4865 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4866 // Args[ArgIdx] can be null in malformed code. 4867 if (const Expr *Arg = Args[ArgIdx]) { 4868 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4869 checkVariadicArgument(Arg, CallType); 4870 } 4871 } 4872 } 4873 4874 if (FDecl || Proto) { 4875 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4876 4877 // Type safety checking. 4878 if (FDecl) { 4879 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4880 CheckArgumentWithTypeTag(I, Args, Loc); 4881 } 4882 } 4883 4884 // Check that passed arguments match the alignment of original arguments. 4885 // Try to get the missing prototype from the declaration. 4886 if (!Proto && FDecl) { 4887 const auto *FT = FDecl->getFunctionType(); 4888 if (isa_and_nonnull<FunctionProtoType>(FT)) 4889 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4890 } 4891 if (Proto) { 4892 // For variadic functions, we may have more args than parameters. 4893 // For some K&R functions, we may have less args than parameters. 4894 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4895 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4896 // Args[ArgIdx] can be null in malformed code. 4897 if (const Expr *Arg = Args[ArgIdx]) { 4898 if (Arg->containsErrors()) 4899 continue; 4900 4901 QualType ParamTy = Proto->getParamType(ArgIdx); 4902 QualType ArgTy = Arg->getType(); 4903 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4904 ArgTy, ParamTy); 4905 } 4906 } 4907 } 4908 4909 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4910 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4911 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4912 if (!Arg->isValueDependent()) { 4913 Expr::EvalResult Align; 4914 if (Arg->EvaluateAsInt(Align, Context)) { 4915 const llvm::APSInt &I = Align.Val.getInt(); 4916 if (!I.isPowerOf2()) 4917 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4918 << Arg->getSourceRange(); 4919 4920 if (I > Sema::MaximumAlignment) 4921 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4922 << Arg->getSourceRange() << Sema::MaximumAlignment; 4923 } 4924 } 4925 } 4926 4927 if (FD) 4928 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4929 } 4930 4931 /// CheckConstructorCall - Check a constructor call for correctness and safety 4932 /// properties not enforced by the C type system. 4933 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4934 ArrayRef<const Expr *> Args, 4935 const FunctionProtoType *Proto, 4936 SourceLocation Loc) { 4937 VariadicCallType CallType = 4938 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4939 4940 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4941 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4942 Context.getPointerType(Ctor->getThisObjectType())); 4943 4944 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4945 Loc, SourceRange(), CallType); 4946 } 4947 4948 /// CheckFunctionCall - Check a direct function call for various correctness 4949 /// and safety properties not strictly enforced by the C type system. 4950 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4951 const FunctionProtoType *Proto) { 4952 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4953 isa<CXXMethodDecl>(FDecl); 4954 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4955 IsMemberOperatorCall; 4956 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4957 TheCall->getCallee()); 4958 Expr** Args = TheCall->getArgs(); 4959 unsigned NumArgs = TheCall->getNumArgs(); 4960 4961 Expr *ImplicitThis = nullptr; 4962 if (IsMemberOperatorCall) { 4963 // If this is a call to a member operator, hide the first argument 4964 // from checkCall. 4965 // FIXME: Our choice of AST representation here is less than ideal. 4966 ImplicitThis = Args[0]; 4967 ++Args; 4968 --NumArgs; 4969 } else if (IsMemberFunction) 4970 ImplicitThis = 4971 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4972 4973 if (ImplicitThis) { 4974 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4975 // used. 4976 QualType ThisType = ImplicitThis->getType(); 4977 if (!ThisType->isPointerType()) { 4978 assert(!ThisType->isReferenceType()); 4979 ThisType = Context.getPointerType(ThisType); 4980 } 4981 4982 QualType ThisTypeFromDecl = 4983 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 4984 4985 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 4986 ThisTypeFromDecl); 4987 } 4988 4989 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4990 IsMemberFunction, TheCall->getRParenLoc(), 4991 TheCall->getCallee()->getSourceRange(), CallType); 4992 4993 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4994 // None of the checks below are needed for functions that don't have 4995 // simple names (e.g., C++ conversion functions). 4996 if (!FnInfo) 4997 return false; 4998 4999 CheckTCBEnforcement(TheCall, FDecl); 5000 5001 CheckAbsoluteValueFunction(TheCall, FDecl); 5002 CheckMaxUnsignedZero(TheCall, FDecl); 5003 5004 if (getLangOpts().ObjC) 5005 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5006 5007 unsigned CMId = FDecl->getMemoryFunctionKind(); 5008 5009 // Handle memory setting and copying functions. 5010 switch (CMId) { 5011 case 0: 5012 return false; 5013 case Builtin::BIstrlcpy: // fallthrough 5014 case Builtin::BIstrlcat: 5015 CheckStrlcpycatArguments(TheCall, FnInfo); 5016 break; 5017 case Builtin::BIstrncat: 5018 CheckStrncatArguments(TheCall, FnInfo); 5019 break; 5020 case Builtin::BIfree: 5021 CheckFreeArguments(TheCall); 5022 break; 5023 default: 5024 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5025 } 5026 5027 return false; 5028 } 5029 5030 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5031 ArrayRef<const Expr *> Args) { 5032 VariadicCallType CallType = 5033 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5034 5035 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5036 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5037 CallType); 5038 5039 return false; 5040 } 5041 5042 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5043 const FunctionProtoType *Proto) { 5044 QualType Ty; 5045 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5046 Ty = V->getType().getNonReferenceType(); 5047 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5048 Ty = F->getType().getNonReferenceType(); 5049 else 5050 return false; 5051 5052 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5053 !Ty->isFunctionProtoType()) 5054 return false; 5055 5056 VariadicCallType CallType; 5057 if (!Proto || !Proto->isVariadic()) { 5058 CallType = VariadicDoesNotApply; 5059 } else if (Ty->isBlockPointerType()) { 5060 CallType = VariadicBlock; 5061 } else { // Ty->isFunctionPointerType() 5062 CallType = VariadicFunction; 5063 } 5064 5065 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5066 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5067 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5068 TheCall->getCallee()->getSourceRange(), CallType); 5069 5070 return false; 5071 } 5072 5073 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5074 /// such as function pointers returned from functions. 5075 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5076 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5077 TheCall->getCallee()); 5078 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5079 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5080 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5081 TheCall->getCallee()->getSourceRange(), CallType); 5082 5083 return false; 5084 } 5085 5086 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5087 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5088 return false; 5089 5090 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5091 switch (Op) { 5092 case AtomicExpr::AO__c11_atomic_init: 5093 case AtomicExpr::AO__opencl_atomic_init: 5094 llvm_unreachable("There is no ordering argument for an init"); 5095 5096 case AtomicExpr::AO__c11_atomic_load: 5097 case AtomicExpr::AO__opencl_atomic_load: 5098 case AtomicExpr::AO__atomic_load_n: 5099 case AtomicExpr::AO__atomic_load: 5100 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5101 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5102 5103 case AtomicExpr::AO__c11_atomic_store: 5104 case AtomicExpr::AO__opencl_atomic_store: 5105 case AtomicExpr::AO__atomic_store: 5106 case AtomicExpr::AO__atomic_store_n: 5107 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5108 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5109 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5110 5111 default: 5112 return true; 5113 } 5114 } 5115 5116 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5117 AtomicExpr::AtomicOp Op) { 5118 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5119 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5120 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5121 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5122 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5123 Op); 5124 } 5125 5126 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5127 SourceLocation RParenLoc, MultiExprArg Args, 5128 AtomicExpr::AtomicOp Op, 5129 AtomicArgumentOrder ArgOrder) { 5130 // All the non-OpenCL operations take one of the following forms. 5131 // The OpenCL operations take the __c11 forms with one extra argument for 5132 // synchronization scope. 5133 enum { 5134 // C __c11_atomic_init(A *, C) 5135 Init, 5136 5137 // C __c11_atomic_load(A *, int) 5138 Load, 5139 5140 // void __atomic_load(A *, CP, int) 5141 LoadCopy, 5142 5143 // void __atomic_store(A *, CP, int) 5144 Copy, 5145 5146 // C __c11_atomic_add(A *, M, int) 5147 Arithmetic, 5148 5149 // C __atomic_exchange_n(A *, CP, int) 5150 Xchg, 5151 5152 // void __atomic_exchange(A *, C *, CP, int) 5153 GNUXchg, 5154 5155 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5156 C11CmpXchg, 5157 5158 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5159 GNUCmpXchg 5160 } Form = Init; 5161 5162 const unsigned NumForm = GNUCmpXchg + 1; 5163 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5164 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5165 // where: 5166 // C is an appropriate type, 5167 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5168 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5169 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5170 // the int parameters are for orderings. 5171 5172 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5173 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5174 "need to update code for modified forms"); 5175 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5176 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5177 AtomicExpr::AO__atomic_load, 5178 "need to update code for modified C11 atomics"); 5179 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5180 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5181 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5182 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5183 IsOpenCL; 5184 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5185 Op == AtomicExpr::AO__atomic_store_n || 5186 Op == AtomicExpr::AO__atomic_exchange_n || 5187 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5188 bool IsAddSub = false; 5189 5190 switch (Op) { 5191 case AtomicExpr::AO__c11_atomic_init: 5192 case AtomicExpr::AO__opencl_atomic_init: 5193 Form = Init; 5194 break; 5195 5196 case AtomicExpr::AO__c11_atomic_load: 5197 case AtomicExpr::AO__opencl_atomic_load: 5198 case AtomicExpr::AO__atomic_load_n: 5199 Form = Load; 5200 break; 5201 5202 case AtomicExpr::AO__atomic_load: 5203 Form = LoadCopy; 5204 break; 5205 5206 case AtomicExpr::AO__c11_atomic_store: 5207 case AtomicExpr::AO__opencl_atomic_store: 5208 case AtomicExpr::AO__atomic_store: 5209 case AtomicExpr::AO__atomic_store_n: 5210 Form = Copy; 5211 break; 5212 5213 case AtomicExpr::AO__c11_atomic_fetch_add: 5214 case AtomicExpr::AO__c11_atomic_fetch_sub: 5215 case AtomicExpr::AO__opencl_atomic_fetch_add: 5216 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5217 case AtomicExpr::AO__atomic_fetch_add: 5218 case AtomicExpr::AO__atomic_fetch_sub: 5219 case AtomicExpr::AO__atomic_add_fetch: 5220 case AtomicExpr::AO__atomic_sub_fetch: 5221 IsAddSub = true; 5222 Form = Arithmetic; 5223 break; 5224 case AtomicExpr::AO__c11_atomic_fetch_and: 5225 case AtomicExpr::AO__c11_atomic_fetch_or: 5226 case AtomicExpr::AO__c11_atomic_fetch_xor: 5227 case AtomicExpr::AO__opencl_atomic_fetch_and: 5228 case AtomicExpr::AO__opencl_atomic_fetch_or: 5229 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5230 case AtomicExpr::AO__atomic_fetch_and: 5231 case AtomicExpr::AO__atomic_fetch_or: 5232 case AtomicExpr::AO__atomic_fetch_xor: 5233 case AtomicExpr::AO__atomic_fetch_nand: 5234 case AtomicExpr::AO__atomic_and_fetch: 5235 case AtomicExpr::AO__atomic_or_fetch: 5236 case AtomicExpr::AO__atomic_xor_fetch: 5237 case AtomicExpr::AO__atomic_nand_fetch: 5238 Form = Arithmetic; 5239 break; 5240 case AtomicExpr::AO__c11_atomic_fetch_min: 5241 case AtomicExpr::AO__c11_atomic_fetch_max: 5242 case AtomicExpr::AO__opencl_atomic_fetch_min: 5243 case AtomicExpr::AO__opencl_atomic_fetch_max: 5244 case AtomicExpr::AO__atomic_min_fetch: 5245 case AtomicExpr::AO__atomic_max_fetch: 5246 case AtomicExpr::AO__atomic_fetch_min: 5247 case AtomicExpr::AO__atomic_fetch_max: 5248 Form = Arithmetic; 5249 break; 5250 5251 case AtomicExpr::AO__c11_atomic_exchange: 5252 case AtomicExpr::AO__opencl_atomic_exchange: 5253 case AtomicExpr::AO__atomic_exchange_n: 5254 Form = Xchg; 5255 break; 5256 5257 case AtomicExpr::AO__atomic_exchange: 5258 Form = GNUXchg; 5259 break; 5260 5261 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5262 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5263 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5264 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5265 Form = C11CmpXchg; 5266 break; 5267 5268 case AtomicExpr::AO__atomic_compare_exchange: 5269 case AtomicExpr::AO__atomic_compare_exchange_n: 5270 Form = GNUCmpXchg; 5271 break; 5272 } 5273 5274 unsigned AdjustedNumArgs = NumArgs[Form]; 5275 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5276 ++AdjustedNumArgs; 5277 // Check we have the right number of arguments. 5278 if (Args.size() < AdjustedNumArgs) { 5279 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5280 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5281 << ExprRange; 5282 return ExprError(); 5283 } else if (Args.size() > AdjustedNumArgs) { 5284 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5285 diag::err_typecheck_call_too_many_args) 5286 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5287 << ExprRange; 5288 return ExprError(); 5289 } 5290 5291 // Inspect the first argument of the atomic operation. 5292 Expr *Ptr = Args[0]; 5293 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5294 if (ConvertedPtr.isInvalid()) 5295 return ExprError(); 5296 5297 Ptr = ConvertedPtr.get(); 5298 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5299 if (!pointerType) { 5300 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5301 << Ptr->getType() << Ptr->getSourceRange(); 5302 return ExprError(); 5303 } 5304 5305 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5306 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5307 QualType ValType = AtomTy; // 'C' 5308 if (IsC11) { 5309 if (!AtomTy->isAtomicType()) { 5310 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5311 << Ptr->getType() << Ptr->getSourceRange(); 5312 return ExprError(); 5313 } 5314 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5315 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5316 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5317 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5318 << Ptr->getSourceRange(); 5319 return ExprError(); 5320 } 5321 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5322 } else if (Form != Load && Form != LoadCopy) { 5323 if (ValType.isConstQualified()) { 5324 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5325 << Ptr->getType() << Ptr->getSourceRange(); 5326 return ExprError(); 5327 } 5328 } 5329 5330 // For an arithmetic operation, the implied arithmetic must be well-formed. 5331 if (Form == Arithmetic) { 5332 // gcc does not enforce these rules for GNU atomics, but we do so for 5333 // sanity. 5334 auto IsAllowedValueType = [&](QualType ValType) { 5335 if (ValType->isIntegerType()) 5336 return true; 5337 if (ValType->isPointerType()) 5338 return true; 5339 if (!ValType->isFloatingType()) 5340 return false; 5341 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5342 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5343 &Context.getTargetInfo().getLongDoubleFormat() == 5344 &llvm::APFloat::x87DoubleExtended()) 5345 return false; 5346 return true; 5347 }; 5348 if (IsAddSub && !IsAllowedValueType(ValType)) { 5349 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5350 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5351 return ExprError(); 5352 } 5353 if (!IsAddSub && !ValType->isIntegerType()) { 5354 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5355 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5356 return ExprError(); 5357 } 5358 if (IsC11 && ValType->isPointerType() && 5359 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5360 diag::err_incomplete_type)) { 5361 return ExprError(); 5362 } 5363 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5364 // For __atomic_*_n operations, the value type must be a scalar integral or 5365 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5366 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5367 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5368 return ExprError(); 5369 } 5370 5371 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5372 !AtomTy->isScalarType()) { 5373 // For GNU atomics, require a trivially-copyable type. This is not part of 5374 // the GNU atomics specification, but we enforce it for sanity. 5375 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5376 << Ptr->getType() << Ptr->getSourceRange(); 5377 return ExprError(); 5378 } 5379 5380 switch (ValType.getObjCLifetime()) { 5381 case Qualifiers::OCL_None: 5382 case Qualifiers::OCL_ExplicitNone: 5383 // okay 5384 break; 5385 5386 case Qualifiers::OCL_Weak: 5387 case Qualifiers::OCL_Strong: 5388 case Qualifiers::OCL_Autoreleasing: 5389 // FIXME: Can this happen? By this point, ValType should be known 5390 // to be trivially copyable. 5391 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5392 << ValType << Ptr->getSourceRange(); 5393 return ExprError(); 5394 } 5395 5396 // All atomic operations have an overload which takes a pointer to a volatile 5397 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5398 // into the result or the other operands. Similarly atomic_load takes a 5399 // pointer to a const 'A'. 5400 ValType.removeLocalVolatile(); 5401 ValType.removeLocalConst(); 5402 QualType ResultType = ValType; 5403 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5404 Form == Init) 5405 ResultType = Context.VoidTy; 5406 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5407 ResultType = Context.BoolTy; 5408 5409 // The type of a parameter passed 'by value'. In the GNU atomics, such 5410 // arguments are actually passed as pointers. 5411 QualType ByValType = ValType; // 'CP' 5412 bool IsPassedByAddress = false; 5413 if (!IsC11 && !IsN) { 5414 ByValType = Ptr->getType(); 5415 IsPassedByAddress = true; 5416 } 5417 5418 SmallVector<Expr *, 5> APIOrderedArgs; 5419 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5420 APIOrderedArgs.push_back(Args[0]); 5421 switch (Form) { 5422 case Init: 5423 case Load: 5424 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5425 break; 5426 case LoadCopy: 5427 case Copy: 5428 case Arithmetic: 5429 case Xchg: 5430 APIOrderedArgs.push_back(Args[2]); // Val1 5431 APIOrderedArgs.push_back(Args[1]); // Order 5432 break; 5433 case GNUXchg: 5434 APIOrderedArgs.push_back(Args[2]); // Val1 5435 APIOrderedArgs.push_back(Args[3]); // Val2 5436 APIOrderedArgs.push_back(Args[1]); // Order 5437 break; 5438 case C11CmpXchg: 5439 APIOrderedArgs.push_back(Args[2]); // Val1 5440 APIOrderedArgs.push_back(Args[4]); // Val2 5441 APIOrderedArgs.push_back(Args[1]); // Order 5442 APIOrderedArgs.push_back(Args[3]); // OrderFail 5443 break; 5444 case GNUCmpXchg: 5445 APIOrderedArgs.push_back(Args[2]); // Val1 5446 APIOrderedArgs.push_back(Args[4]); // Val2 5447 APIOrderedArgs.push_back(Args[5]); // Weak 5448 APIOrderedArgs.push_back(Args[1]); // Order 5449 APIOrderedArgs.push_back(Args[3]); // OrderFail 5450 break; 5451 } 5452 } else 5453 APIOrderedArgs.append(Args.begin(), Args.end()); 5454 5455 // The first argument's non-CV pointer type is used to deduce the type of 5456 // subsequent arguments, except for: 5457 // - weak flag (always converted to bool) 5458 // - memory order (always converted to int) 5459 // - scope (always converted to int) 5460 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5461 QualType Ty; 5462 if (i < NumVals[Form] + 1) { 5463 switch (i) { 5464 case 0: 5465 // The first argument is always a pointer. It has a fixed type. 5466 // It is always dereferenced, a nullptr is undefined. 5467 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5468 // Nothing else to do: we already know all we want about this pointer. 5469 continue; 5470 case 1: 5471 // The second argument is the non-atomic operand. For arithmetic, this 5472 // is always passed by value, and for a compare_exchange it is always 5473 // passed by address. For the rest, GNU uses by-address and C11 uses 5474 // by-value. 5475 assert(Form != Load); 5476 if (Form == Arithmetic && ValType->isPointerType()) 5477 Ty = Context.getPointerDiffType(); 5478 else if (Form == Init || Form == Arithmetic) 5479 Ty = ValType; 5480 else if (Form == Copy || Form == Xchg) { 5481 if (IsPassedByAddress) { 5482 // The value pointer is always dereferenced, a nullptr is undefined. 5483 CheckNonNullArgument(*this, APIOrderedArgs[i], 5484 ExprRange.getBegin()); 5485 } 5486 Ty = ByValType; 5487 } else { 5488 Expr *ValArg = APIOrderedArgs[i]; 5489 // The value pointer is always dereferenced, a nullptr is undefined. 5490 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5491 LangAS AS = LangAS::Default; 5492 // Keep address space of non-atomic pointer type. 5493 if (const PointerType *PtrTy = 5494 ValArg->getType()->getAs<PointerType>()) { 5495 AS = PtrTy->getPointeeType().getAddressSpace(); 5496 } 5497 Ty = Context.getPointerType( 5498 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5499 } 5500 break; 5501 case 2: 5502 // The third argument to compare_exchange / GNU exchange is the desired 5503 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5504 if (IsPassedByAddress) 5505 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5506 Ty = ByValType; 5507 break; 5508 case 3: 5509 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5510 Ty = Context.BoolTy; 5511 break; 5512 } 5513 } else { 5514 // The order(s) and scope are always converted to int. 5515 Ty = Context.IntTy; 5516 } 5517 5518 InitializedEntity Entity = 5519 InitializedEntity::InitializeParameter(Context, Ty, false); 5520 ExprResult Arg = APIOrderedArgs[i]; 5521 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5522 if (Arg.isInvalid()) 5523 return true; 5524 APIOrderedArgs[i] = Arg.get(); 5525 } 5526 5527 // Permute the arguments into a 'consistent' order. 5528 SmallVector<Expr*, 5> SubExprs; 5529 SubExprs.push_back(Ptr); 5530 switch (Form) { 5531 case Init: 5532 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5533 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5534 break; 5535 case Load: 5536 SubExprs.push_back(APIOrderedArgs[1]); // Order 5537 break; 5538 case LoadCopy: 5539 case Copy: 5540 case Arithmetic: 5541 case Xchg: 5542 SubExprs.push_back(APIOrderedArgs[2]); // Order 5543 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5544 break; 5545 case GNUXchg: 5546 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5547 SubExprs.push_back(APIOrderedArgs[3]); // Order 5548 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5549 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5550 break; 5551 case C11CmpXchg: 5552 SubExprs.push_back(APIOrderedArgs[3]); // Order 5553 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5554 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5555 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5556 break; 5557 case GNUCmpXchg: 5558 SubExprs.push_back(APIOrderedArgs[4]); // Order 5559 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5560 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5561 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5562 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5563 break; 5564 } 5565 5566 if (SubExprs.size() >= 2 && Form != Init) { 5567 if (Optional<llvm::APSInt> Result = 5568 SubExprs[1]->getIntegerConstantExpr(Context)) 5569 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5570 Diag(SubExprs[1]->getBeginLoc(), 5571 diag::warn_atomic_op_has_invalid_memory_order) 5572 << SubExprs[1]->getSourceRange(); 5573 } 5574 5575 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5576 auto *Scope = Args[Args.size() - 1]; 5577 if (Optional<llvm::APSInt> Result = 5578 Scope->getIntegerConstantExpr(Context)) { 5579 if (!ScopeModel->isValid(Result->getZExtValue())) 5580 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5581 << Scope->getSourceRange(); 5582 } 5583 SubExprs.push_back(Scope); 5584 } 5585 5586 AtomicExpr *AE = new (Context) 5587 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5588 5589 if ((Op == AtomicExpr::AO__c11_atomic_load || 5590 Op == AtomicExpr::AO__c11_atomic_store || 5591 Op == AtomicExpr::AO__opencl_atomic_load || 5592 Op == AtomicExpr::AO__opencl_atomic_store ) && 5593 Context.AtomicUsesUnsupportedLibcall(AE)) 5594 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5595 << ((Op == AtomicExpr::AO__c11_atomic_load || 5596 Op == AtomicExpr::AO__opencl_atomic_load) 5597 ? 0 5598 : 1); 5599 5600 if (ValType->isExtIntType()) { 5601 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5602 return ExprError(); 5603 } 5604 5605 return AE; 5606 } 5607 5608 /// checkBuiltinArgument - Given a call to a builtin function, perform 5609 /// normal type-checking on the given argument, updating the call in 5610 /// place. This is useful when a builtin function requires custom 5611 /// type-checking for some of its arguments but not necessarily all of 5612 /// them. 5613 /// 5614 /// Returns true on error. 5615 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5616 FunctionDecl *Fn = E->getDirectCallee(); 5617 assert(Fn && "builtin call without direct callee!"); 5618 5619 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5620 InitializedEntity Entity = 5621 InitializedEntity::InitializeParameter(S.Context, Param); 5622 5623 ExprResult Arg = E->getArg(0); 5624 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5625 if (Arg.isInvalid()) 5626 return true; 5627 5628 E->setArg(ArgIndex, Arg.get()); 5629 return false; 5630 } 5631 5632 /// We have a call to a function like __sync_fetch_and_add, which is an 5633 /// overloaded function based on the pointer type of its first argument. 5634 /// The main BuildCallExpr routines have already promoted the types of 5635 /// arguments because all of these calls are prototyped as void(...). 5636 /// 5637 /// This function goes through and does final semantic checking for these 5638 /// builtins, as well as generating any warnings. 5639 ExprResult 5640 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5641 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5642 Expr *Callee = TheCall->getCallee(); 5643 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5644 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5645 5646 // Ensure that we have at least one argument to do type inference from. 5647 if (TheCall->getNumArgs() < 1) { 5648 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5649 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5650 return ExprError(); 5651 } 5652 5653 // Inspect the first argument of the atomic builtin. This should always be 5654 // a pointer type, whose element is an integral scalar or pointer type. 5655 // Because it is a pointer type, we don't have to worry about any implicit 5656 // casts here. 5657 // FIXME: We don't allow floating point scalars as input. 5658 Expr *FirstArg = TheCall->getArg(0); 5659 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5660 if (FirstArgResult.isInvalid()) 5661 return ExprError(); 5662 FirstArg = FirstArgResult.get(); 5663 TheCall->setArg(0, FirstArg); 5664 5665 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5666 if (!pointerType) { 5667 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5668 << FirstArg->getType() << FirstArg->getSourceRange(); 5669 return ExprError(); 5670 } 5671 5672 QualType ValType = pointerType->getPointeeType(); 5673 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5674 !ValType->isBlockPointerType()) { 5675 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5676 << FirstArg->getType() << FirstArg->getSourceRange(); 5677 return ExprError(); 5678 } 5679 5680 if (ValType.isConstQualified()) { 5681 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5682 << FirstArg->getType() << FirstArg->getSourceRange(); 5683 return ExprError(); 5684 } 5685 5686 switch (ValType.getObjCLifetime()) { 5687 case Qualifiers::OCL_None: 5688 case Qualifiers::OCL_ExplicitNone: 5689 // okay 5690 break; 5691 5692 case Qualifiers::OCL_Weak: 5693 case Qualifiers::OCL_Strong: 5694 case Qualifiers::OCL_Autoreleasing: 5695 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5696 << ValType << FirstArg->getSourceRange(); 5697 return ExprError(); 5698 } 5699 5700 // Strip any qualifiers off ValType. 5701 ValType = ValType.getUnqualifiedType(); 5702 5703 // The majority of builtins return a value, but a few have special return 5704 // types, so allow them to override appropriately below. 5705 QualType ResultType = ValType; 5706 5707 // We need to figure out which concrete builtin this maps onto. For example, 5708 // __sync_fetch_and_add with a 2 byte object turns into 5709 // __sync_fetch_and_add_2. 5710 #define BUILTIN_ROW(x) \ 5711 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5712 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5713 5714 static const unsigned BuiltinIndices[][5] = { 5715 BUILTIN_ROW(__sync_fetch_and_add), 5716 BUILTIN_ROW(__sync_fetch_and_sub), 5717 BUILTIN_ROW(__sync_fetch_and_or), 5718 BUILTIN_ROW(__sync_fetch_and_and), 5719 BUILTIN_ROW(__sync_fetch_and_xor), 5720 BUILTIN_ROW(__sync_fetch_and_nand), 5721 5722 BUILTIN_ROW(__sync_add_and_fetch), 5723 BUILTIN_ROW(__sync_sub_and_fetch), 5724 BUILTIN_ROW(__sync_and_and_fetch), 5725 BUILTIN_ROW(__sync_or_and_fetch), 5726 BUILTIN_ROW(__sync_xor_and_fetch), 5727 BUILTIN_ROW(__sync_nand_and_fetch), 5728 5729 BUILTIN_ROW(__sync_val_compare_and_swap), 5730 BUILTIN_ROW(__sync_bool_compare_and_swap), 5731 BUILTIN_ROW(__sync_lock_test_and_set), 5732 BUILTIN_ROW(__sync_lock_release), 5733 BUILTIN_ROW(__sync_swap) 5734 }; 5735 #undef BUILTIN_ROW 5736 5737 // Determine the index of the size. 5738 unsigned SizeIndex; 5739 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5740 case 1: SizeIndex = 0; break; 5741 case 2: SizeIndex = 1; break; 5742 case 4: SizeIndex = 2; break; 5743 case 8: SizeIndex = 3; break; 5744 case 16: SizeIndex = 4; break; 5745 default: 5746 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5747 << FirstArg->getType() << FirstArg->getSourceRange(); 5748 return ExprError(); 5749 } 5750 5751 // Each of these builtins has one pointer argument, followed by some number of 5752 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5753 // that we ignore. Find out which row of BuiltinIndices to read from as well 5754 // as the number of fixed args. 5755 unsigned BuiltinID = FDecl->getBuiltinID(); 5756 unsigned BuiltinIndex, NumFixed = 1; 5757 bool WarnAboutSemanticsChange = false; 5758 switch (BuiltinID) { 5759 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5760 case Builtin::BI__sync_fetch_and_add: 5761 case Builtin::BI__sync_fetch_and_add_1: 5762 case Builtin::BI__sync_fetch_and_add_2: 5763 case Builtin::BI__sync_fetch_and_add_4: 5764 case Builtin::BI__sync_fetch_and_add_8: 5765 case Builtin::BI__sync_fetch_and_add_16: 5766 BuiltinIndex = 0; 5767 break; 5768 5769 case Builtin::BI__sync_fetch_and_sub: 5770 case Builtin::BI__sync_fetch_and_sub_1: 5771 case Builtin::BI__sync_fetch_and_sub_2: 5772 case Builtin::BI__sync_fetch_and_sub_4: 5773 case Builtin::BI__sync_fetch_and_sub_8: 5774 case Builtin::BI__sync_fetch_and_sub_16: 5775 BuiltinIndex = 1; 5776 break; 5777 5778 case Builtin::BI__sync_fetch_and_or: 5779 case Builtin::BI__sync_fetch_and_or_1: 5780 case Builtin::BI__sync_fetch_and_or_2: 5781 case Builtin::BI__sync_fetch_and_or_4: 5782 case Builtin::BI__sync_fetch_and_or_8: 5783 case Builtin::BI__sync_fetch_and_or_16: 5784 BuiltinIndex = 2; 5785 break; 5786 5787 case Builtin::BI__sync_fetch_and_and: 5788 case Builtin::BI__sync_fetch_and_and_1: 5789 case Builtin::BI__sync_fetch_and_and_2: 5790 case Builtin::BI__sync_fetch_and_and_4: 5791 case Builtin::BI__sync_fetch_and_and_8: 5792 case Builtin::BI__sync_fetch_and_and_16: 5793 BuiltinIndex = 3; 5794 break; 5795 5796 case Builtin::BI__sync_fetch_and_xor: 5797 case Builtin::BI__sync_fetch_and_xor_1: 5798 case Builtin::BI__sync_fetch_and_xor_2: 5799 case Builtin::BI__sync_fetch_and_xor_4: 5800 case Builtin::BI__sync_fetch_and_xor_8: 5801 case Builtin::BI__sync_fetch_and_xor_16: 5802 BuiltinIndex = 4; 5803 break; 5804 5805 case Builtin::BI__sync_fetch_and_nand: 5806 case Builtin::BI__sync_fetch_and_nand_1: 5807 case Builtin::BI__sync_fetch_and_nand_2: 5808 case Builtin::BI__sync_fetch_and_nand_4: 5809 case Builtin::BI__sync_fetch_and_nand_8: 5810 case Builtin::BI__sync_fetch_and_nand_16: 5811 BuiltinIndex = 5; 5812 WarnAboutSemanticsChange = true; 5813 break; 5814 5815 case Builtin::BI__sync_add_and_fetch: 5816 case Builtin::BI__sync_add_and_fetch_1: 5817 case Builtin::BI__sync_add_and_fetch_2: 5818 case Builtin::BI__sync_add_and_fetch_4: 5819 case Builtin::BI__sync_add_and_fetch_8: 5820 case Builtin::BI__sync_add_and_fetch_16: 5821 BuiltinIndex = 6; 5822 break; 5823 5824 case Builtin::BI__sync_sub_and_fetch: 5825 case Builtin::BI__sync_sub_and_fetch_1: 5826 case Builtin::BI__sync_sub_and_fetch_2: 5827 case Builtin::BI__sync_sub_and_fetch_4: 5828 case Builtin::BI__sync_sub_and_fetch_8: 5829 case Builtin::BI__sync_sub_and_fetch_16: 5830 BuiltinIndex = 7; 5831 break; 5832 5833 case Builtin::BI__sync_and_and_fetch: 5834 case Builtin::BI__sync_and_and_fetch_1: 5835 case Builtin::BI__sync_and_and_fetch_2: 5836 case Builtin::BI__sync_and_and_fetch_4: 5837 case Builtin::BI__sync_and_and_fetch_8: 5838 case Builtin::BI__sync_and_and_fetch_16: 5839 BuiltinIndex = 8; 5840 break; 5841 5842 case Builtin::BI__sync_or_and_fetch: 5843 case Builtin::BI__sync_or_and_fetch_1: 5844 case Builtin::BI__sync_or_and_fetch_2: 5845 case Builtin::BI__sync_or_and_fetch_4: 5846 case Builtin::BI__sync_or_and_fetch_8: 5847 case Builtin::BI__sync_or_and_fetch_16: 5848 BuiltinIndex = 9; 5849 break; 5850 5851 case Builtin::BI__sync_xor_and_fetch: 5852 case Builtin::BI__sync_xor_and_fetch_1: 5853 case Builtin::BI__sync_xor_and_fetch_2: 5854 case Builtin::BI__sync_xor_and_fetch_4: 5855 case Builtin::BI__sync_xor_and_fetch_8: 5856 case Builtin::BI__sync_xor_and_fetch_16: 5857 BuiltinIndex = 10; 5858 break; 5859 5860 case Builtin::BI__sync_nand_and_fetch: 5861 case Builtin::BI__sync_nand_and_fetch_1: 5862 case Builtin::BI__sync_nand_and_fetch_2: 5863 case Builtin::BI__sync_nand_and_fetch_4: 5864 case Builtin::BI__sync_nand_and_fetch_8: 5865 case Builtin::BI__sync_nand_and_fetch_16: 5866 BuiltinIndex = 11; 5867 WarnAboutSemanticsChange = true; 5868 break; 5869 5870 case Builtin::BI__sync_val_compare_and_swap: 5871 case Builtin::BI__sync_val_compare_and_swap_1: 5872 case Builtin::BI__sync_val_compare_and_swap_2: 5873 case Builtin::BI__sync_val_compare_and_swap_4: 5874 case Builtin::BI__sync_val_compare_and_swap_8: 5875 case Builtin::BI__sync_val_compare_and_swap_16: 5876 BuiltinIndex = 12; 5877 NumFixed = 2; 5878 break; 5879 5880 case Builtin::BI__sync_bool_compare_and_swap: 5881 case Builtin::BI__sync_bool_compare_and_swap_1: 5882 case Builtin::BI__sync_bool_compare_and_swap_2: 5883 case Builtin::BI__sync_bool_compare_and_swap_4: 5884 case Builtin::BI__sync_bool_compare_and_swap_8: 5885 case Builtin::BI__sync_bool_compare_and_swap_16: 5886 BuiltinIndex = 13; 5887 NumFixed = 2; 5888 ResultType = Context.BoolTy; 5889 break; 5890 5891 case Builtin::BI__sync_lock_test_and_set: 5892 case Builtin::BI__sync_lock_test_and_set_1: 5893 case Builtin::BI__sync_lock_test_and_set_2: 5894 case Builtin::BI__sync_lock_test_and_set_4: 5895 case Builtin::BI__sync_lock_test_and_set_8: 5896 case Builtin::BI__sync_lock_test_and_set_16: 5897 BuiltinIndex = 14; 5898 break; 5899 5900 case Builtin::BI__sync_lock_release: 5901 case Builtin::BI__sync_lock_release_1: 5902 case Builtin::BI__sync_lock_release_2: 5903 case Builtin::BI__sync_lock_release_4: 5904 case Builtin::BI__sync_lock_release_8: 5905 case Builtin::BI__sync_lock_release_16: 5906 BuiltinIndex = 15; 5907 NumFixed = 0; 5908 ResultType = Context.VoidTy; 5909 break; 5910 5911 case Builtin::BI__sync_swap: 5912 case Builtin::BI__sync_swap_1: 5913 case Builtin::BI__sync_swap_2: 5914 case Builtin::BI__sync_swap_4: 5915 case Builtin::BI__sync_swap_8: 5916 case Builtin::BI__sync_swap_16: 5917 BuiltinIndex = 16; 5918 break; 5919 } 5920 5921 // Now that we know how many fixed arguments we expect, first check that we 5922 // have at least that many. 5923 if (TheCall->getNumArgs() < 1+NumFixed) { 5924 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5925 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5926 << Callee->getSourceRange(); 5927 return ExprError(); 5928 } 5929 5930 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5931 << Callee->getSourceRange(); 5932 5933 if (WarnAboutSemanticsChange) { 5934 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5935 << Callee->getSourceRange(); 5936 } 5937 5938 // Get the decl for the concrete builtin from this, we can tell what the 5939 // concrete integer type we should convert to is. 5940 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5941 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5942 FunctionDecl *NewBuiltinDecl; 5943 if (NewBuiltinID == BuiltinID) 5944 NewBuiltinDecl = FDecl; 5945 else { 5946 // Perform builtin lookup to avoid redeclaring it. 5947 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5948 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5949 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5950 assert(Res.getFoundDecl()); 5951 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5952 if (!NewBuiltinDecl) 5953 return ExprError(); 5954 } 5955 5956 // The first argument --- the pointer --- has a fixed type; we 5957 // deduce the types of the rest of the arguments accordingly. Walk 5958 // the remaining arguments, converting them to the deduced value type. 5959 for (unsigned i = 0; i != NumFixed; ++i) { 5960 ExprResult Arg = TheCall->getArg(i+1); 5961 5962 // GCC does an implicit conversion to the pointer or integer ValType. This 5963 // can fail in some cases (1i -> int**), check for this error case now. 5964 // Initialize the argument. 5965 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5966 ValType, /*consume*/ false); 5967 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5968 if (Arg.isInvalid()) 5969 return ExprError(); 5970 5971 // Okay, we have something that *can* be converted to the right type. Check 5972 // to see if there is a potentially weird extension going on here. This can 5973 // happen when you do an atomic operation on something like an char* and 5974 // pass in 42. The 42 gets converted to char. This is even more strange 5975 // for things like 45.123 -> char, etc. 5976 // FIXME: Do this check. 5977 TheCall->setArg(i+1, Arg.get()); 5978 } 5979 5980 // Create a new DeclRefExpr to refer to the new decl. 5981 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5982 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5983 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5984 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5985 5986 // Set the callee in the CallExpr. 5987 // FIXME: This loses syntactic information. 5988 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5989 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5990 CK_BuiltinFnToFnPtr); 5991 TheCall->setCallee(PromotedCall.get()); 5992 5993 // Change the result type of the call to match the original value type. This 5994 // is arbitrary, but the codegen for these builtins ins design to handle it 5995 // gracefully. 5996 TheCall->setType(ResultType); 5997 5998 // Prohibit use of _ExtInt with atomic builtins. 5999 // The arguments would have already been converted to the first argument's 6000 // type, so only need to check the first argument. 6001 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6002 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6003 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6004 return ExprError(); 6005 } 6006 6007 return TheCallResult; 6008 } 6009 6010 /// SemaBuiltinNontemporalOverloaded - We have a call to 6011 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6012 /// overloaded function based on the pointer type of its last argument. 6013 /// 6014 /// This function goes through and does final semantic checking for these 6015 /// builtins. 6016 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6017 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6018 DeclRefExpr *DRE = 6019 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6020 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6021 unsigned BuiltinID = FDecl->getBuiltinID(); 6022 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6023 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6024 "Unexpected nontemporal load/store builtin!"); 6025 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6026 unsigned numArgs = isStore ? 2 : 1; 6027 6028 // Ensure that we have the proper number of arguments. 6029 if (checkArgCount(*this, TheCall, numArgs)) 6030 return ExprError(); 6031 6032 // Inspect the last argument of the nontemporal builtin. This should always 6033 // be a pointer type, from which we imply the type of the memory access. 6034 // Because it is a pointer type, we don't have to worry about any implicit 6035 // casts here. 6036 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6037 ExprResult PointerArgResult = 6038 DefaultFunctionArrayLvalueConversion(PointerArg); 6039 6040 if (PointerArgResult.isInvalid()) 6041 return ExprError(); 6042 PointerArg = PointerArgResult.get(); 6043 TheCall->setArg(numArgs - 1, PointerArg); 6044 6045 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6046 if (!pointerType) { 6047 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6048 << PointerArg->getType() << PointerArg->getSourceRange(); 6049 return ExprError(); 6050 } 6051 6052 QualType ValType = pointerType->getPointeeType(); 6053 6054 // Strip any qualifiers off ValType. 6055 ValType = ValType.getUnqualifiedType(); 6056 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6057 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6058 !ValType->isVectorType()) { 6059 Diag(DRE->getBeginLoc(), 6060 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6061 << PointerArg->getType() << PointerArg->getSourceRange(); 6062 return ExprError(); 6063 } 6064 6065 if (!isStore) { 6066 TheCall->setType(ValType); 6067 return TheCallResult; 6068 } 6069 6070 ExprResult ValArg = TheCall->getArg(0); 6071 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6072 Context, ValType, /*consume*/ false); 6073 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6074 if (ValArg.isInvalid()) 6075 return ExprError(); 6076 6077 TheCall->setArg(0, ValArg.get()); 6078 TheCall->setType(Context.VoidTy); 6079 return TheCallResult; 6080 } 6081 6082 /// CheckObjCString - Checks that the argument to the builtin 6083 /// CFString constructor is correct 6084 /// Note: It might also make sense to do the UTF-16 conversion here (would 6085 /// simplify the backend). 6086 bool Sema::CheckObjCString(Expr *Arg) { 6087 Arg = Arg->IgnoreParenCasts(); 6088 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6089 6090 if (!Literal || !Literal->isAscii()) { 6091 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6092 << Arg->getSourceRange(); 6093 return true; 6094 } 6095 6096 if (Literal->containsNonAsciiOrNull()) { 6097 StringRef String = Literal->getString(); 6098 unsigned NumBytes = String.size(); 6099 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6100 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6101 llvm::UTF16 *ToPtr = &ToBuf[0]; 6102 6103 llvm::ConversionResult Result = 6104 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6105 ToPtr + NumBytes, llvm::strictConversion); 6106 // Check for conversion failure. 6107 if (Result != llvm::conversionOK) 6108 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6109 << Arg->getSourceRange(); 6110 } 6111 return false; 6112 } 6113 6114 /// CheckObjCString - Checks that the format string argument to the os_log() 6115 /// and os_trace() functions is correct, and converts it to const char *. 6116 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6117 Arg = Arg->IgnoreParenCasts(); 6118 auto *Literal = dyn_cast<StringLiteral>(Arg); 6119 if (!Literal) { 6120 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6121 Literal = ObjcLiteral->getString(); 6122 } 6123 } 6124 6125 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6126 return ExprError( 6127 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6128 << Arg->getSourceRange()); 6129 } 6130 6131 ExprResult Result(Literal); 6132 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6133 InitializedEntity Entity = 6134 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6135 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6136 return Result; 6137 } 6138 6139 /// Check that the user is calling the appropriate va_start builtin for the 6140 /// target and calling convention. 6141 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6142 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6143 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6144 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6145 TT.getArch() == llvm::Triple::aarch64_32); 6146 bool IsWindows = TT.isOSWindows(); 6147 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6148 if (IsX64 || IsAArch64) { 6149 CallingConv CC = CC_C; 6150 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6151 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6152 if (IsMSVAStart) { 6153 // Don't allow this in System V ABI functions. 6154 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6155 return S.Diag(Fn->getBeginLoc(), 6156 diag::err_ms_va_start_used_in_sysv_function); 6157 } else { 6158 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6159 // On x64 Windows, don't allow this in System V ABI functions. 6160 // (Yes, that means there's no corresponding way to support variadic 6161 // System V ABI functions on Windows.) 6162 if ((IsWindows && CC == CC_X86_64SysV) || 6163 (!IsWindows && CC == CC_Win64)) 6164 return S.Diag(Fn->getBeginLoc(), 6165 diag::err_va_start_used_in_wrong_abi_function) 6166 << !IsWindows; 6167 } 6168 return false; 6169 } 6170 6171 if (IsMSVAStart) 6172 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6173 return false; 6174 } 6175 6176 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6177 ParmVarDecl **LastParam = nullptr) { 6178 // Determine whether the current function, block, or obj-c method is variadic 6179 // and get its parameter list. 6180 bool IsVariadic = false; 6181 ArrayRef<ParmVarDecl *> Params; 6182 DeclContext *Caller = S.CurContext; 6183 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6184 IsVariadic = Block->isVariadic(); 6185 Params = Block->parameters(); 6186 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6187 IsVariadic = FD->isVariadic(); 6188 Params = FD->parameters(); 6189 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6190 IsVariadic = MD->isVariadic(); 6191 // FIXME: This isn't correct for methods (results in bogus warning). 6192 Params = MD->parameters(); 6193 } else if (isa<CapturedDecl>(Caller)) { 6194 // We don't support va_start in a CapturedDecl. 6195 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6196 return true; 6197 } else { 6198 // This must be some other declcontext that parses exprs. 6199 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6200 return true; 6201 } 6202 6203 if (!IsVariadic) { 6204 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6205 return true; 6206 } 6207 6208 if (LastParam) 6209 *LastParam = Params.empty() ? nullptr : Params.back(); 6210 6211 return false; 6212 } 6213 6214 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6215 /// for validity. Emit an error and return true on failure; return false 6216 /// on success. 6217 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6218 Expr *Fn = TheCall->getCallee(); 6219 6220 if (checkVAStartABI(*this, BuiltinID, Fn)) 6221 return true; 6222 6223 if (checkArgCount(*this, TheCall, 2)) 6224 return true; 6225 6226 // Type-check the first argument normally. 6227 if (checkBuiltinArgument(*this, TheCall, 0)) 6228 return true; 6229 6230 // Check that the current function is variadic, and get its last parameter. 6231 ParmVarDecl *LastParam; 6232 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6233 return true; 6234 6235 // Verify that the second argument to the builtin is the last argument of the 6236 // current function or method. 6237 bool SecondArgIsLastNamedArgument = false; 6238 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6239 6240 // These are valid if SecondArgIsLastNamedArgument is false after the next 6241 // block. 6242 QualType Type; 6243 SourceLocation ParamLoc; 6244 bool IsCRegister = false; 6245 6246 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6247 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6248 SecondArgIsLastNamedArgument = PV == LastParam; 6249 6250 Type = PV->getType(); 6251 ParamLoc = PV->getLocation(); 6252 IsCRegister = 6253 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6254 } 6255 } 6256 6257 if (!SecondArgIsLastNamedArgument) 6258 Diag(TheCall->getArg(1)->getBeginLoc(), 6259 diag::warn_second_arg_of_va_start_not_last_named_param); 6260 else if (IsCRegister || Type->isReferenceType() || 6261 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6262 // Promotable integers are UB, but enumerations need a bit of 6263 // extra checking to see what their promotable type actually is. 6264 if (!Type->isPromotableIntegerType()) 6265 return false; 6266 if (!Type->isEnumeralType()) 6267 return true; 6268 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6269 return !(ED && 6270 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6271 }()) { 6272 unsigned Reason = 0; 6273 if (Type->isReferenceType()) Reason = 1; 6274 else if (IsCRegister) Reason = 2; 6275 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6276 Diag(ParamLoc, diag::note_parameter_type) << Type; 6277 } 6278 6279 TheCall->setType(Context.VoidTy); 6280 return false; 6281 } 6282 6283 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6284 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6285 // const char *named_addr); 6286 6287 Expr *Func = Call->getCallee(); 6288 6289 if (Call->getNumArgs() < 3) 6290 return Diag(Call->getEndLoc(), 6291 diag::err_typecheck_call_too_few_args_at_least) 6292 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6293 6294 // Type-check the first argument normally. 6295 if (checkBuiltinArgument(*this, Call, 0)) 6296 return true; 6297 6298 // Check that the current function is variadic. 6299 if (checkVAStartIsInVariadicFunction(*this, Func)) 6300 return true; 6301 6302 // __va_start on Windows does not validate the parameter qualifiers 6303 6304 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6305 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6306 6307 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6308 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6309 6310 const QualType &ConstCharPtrTy = 6311 Context.getPointerType(Context.CharTy.withConst()); 6312 if (!Arg1Ty->isPointerType() || 6313 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 6314 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6315 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6316 << 0 /* qualifier difference */ 6317 << 3 /* parameter mismatch */ 6318 << 2 << Arg1->getType() << ConstCharPtrTy; 6319 6320 const QualType SizeTy = Context.getSizeType(); 6321 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6322 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6323 << Arg2->getType() << SizeTy << 1 /* different class */ 6324 << 0 /* qualifier difference */ 6325 << 3 /* parameter mismatch */ 6326 << 3 << Arg2->getType() << SizeTy; 6327 6328 return false; 6329 } 6330 6331 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6332 /// friends. This is declared to take (...), so we have to check everything. 6333 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6334 if (checkArgCount(*this, TheCall, 2)) 6335 return true; 6336 6337 ExprResult OrigArg0 = TheCall->getArg(0); 6338 ExprResult OrigArg1 = TheCall->getArg(1); 6339 6340 // Do standard promotions between the two arguments, returning their common 6341 // type. 6342 QualType Res = UsualArithmeticConversions( 6343 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6344 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6345 return true; 6346 6347 // Make sure any conversions are pushed back into the call; this is 6348 // type safe since unordered compare builtins are declared as "_Bool 6349 // foo(...)". 6350 TheCall->setArg(0, OrigArg0.get()); 6351 TheCall->setArg(1, OrigArg1.get()); 6352 6353 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6354 return false; 6355 6356 // If the common type isn't a real floating type, then the arguments were 6357 // invalid for this operation. 6358 if (Res.isNull() || !Res->isRealFloatingType()) 6359 return Diag(OrigArg0.get()->getBeginLoc(), 6360 diag::err_typecheck_call_invalid_ordered_compare) 6361 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6362 << SourceRange(OrigArg0.get()->getBeginLoc(), 6363 OrigArg1.get()->getEndLoc()); 6364 6365 return false; 6366 } 6367 6368 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6369 /// __builtin_isnan and friends. This is declared to take (...), so we have 6370 /// to check everything. We expect the last argument to be a floating point 6371 /// value. 6372 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6373 if (checkArgCount(*this, TheCall, NumArgs)) 6374 return true; 6375 6376 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6377 // on all preceding parameters just being int. Try all of those. 6378 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6379 Expr *Arg = TheCall->getArg(i); 6380 6381 if (Arg->isTypeDependent()) 6382 return false; 6383 6384 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6385 6386 if (Res.isInvalid()) 6387 return true; 6388 TheCall->setArg(i, Res.get()); 6389 } 6390 6391 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6392 6393 if (OrigArg->isTypeDependent()) 6394 return false; 6395 6396 // Usual Unary Conversions will convert half to float, which we want for 6397 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6398 // type how it is, but do normal L->Rvalue conversions. 6399 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6400 OrigArg = UsualUnaryConversions(OrigArg).get(); 6401 else 6402 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6403 TheCall->setArg(NumArgs - 1, OrigArg); 6404 6405 // This operation requires a non-_Complex floating-point number. 6406 if (!OrigArg->getType()->isRealFloatingType()) 6407 return Diag(OrigArg->getBeginLoc(), 6408 diag::err_typecheck_call_invalid_unary_fp) 6409 << OrigArg->getType() << OrigArg->getSourceRange(); 6410 6411 return false; 6412 } 6413 6414 /// Perform semantic analysis for a call to __builtin_complex. 6415 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6416 if (checkArgCount(*this, TheCall, 2)) 6417 return true; 6418 6419 bool Dependent = false; 6420 for (unsigned I = 0; I != 2; ++I) { 6421 Expr *Arg = TheCall->getArg(I); 6422 QualType T = Arg->getType(); 6423 if (T->isDependentType()) { 6424 Dependent = true; 6425 continue; 6426 } 6427 6428 // Despite supporting _Complex int, GCC requires a real floating point type 6429 // for the operands of __builtin_complex. 6430 if (!T->isRealFloatingType()) { 6431 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6432 << Arg->getType() << Arg->getSourceRange(); 6433 } 6434 6435 ExprResult Converted = DefaultLvalueConversion(Arg); 6436 if (Converted.isInvalid()) 6437 return true; 6438 TheCall->setArg(I, Converted.get()); 6439 } 6440 6441 if (Dependent) { 6442 TheCall->setType(Context.DependentTy); 6443 return false; 6444 } 6445 6446 Expr *Real = TheCall->getArg(0); 6447 Expr *Imag = TheCall->getArg(1); 6448 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6449 return Diag(Real->getBeginLoc(), 6450 diag::err_typecheck_call_different_arg_types) 6451 << Real->getType() << Imag->getType() 6452 << Real->getSourceRange() << Imag->getSourceRange(); 6453 } 6454 6455 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6456 // don't allow this builtin to form those types either. 6457 // FIXME: Should we allow these types? 6458 if (Real->getType()->isFloat16Type()) 6459 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6460 << "_Float16"; 6461 if (Real->getType()->isHalfType()) 6462 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6463 << "half"; 6464 6465 TheCall->setType(Context.getComplexType(Real->getType())); 6466 return false; 6467 } 6468 6469 // Customized Sema Checking for VSX builtins that have the following signature: 6470 // vector [...] builtinName(vector [...], vector [...], const int); 6471 // Which takes the same type of vectors (any legal vector type) for the first 6472 // two arguments and takes compile time constant for the third argument. 6473 // Example builtins are : 6474 // vector double vec_xxpermdi(vector double, vector double, int); 6475 // vector short vec_xxsldwi(vector short, vector short, int); 6476 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6477 unsigned ExpectedNumArgs = 3; 6478 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6479 return true; 6480 6481 // Check the third argument is a compile time constant 6482 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6483 return Diag(TheCall->getBeginLoc(), 6484 diag::err_vsx_builtin_nonconstant_argument) 6485 << 3 /* argument index */ << TheCall->getDirectCallee() 6486 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6487 TheCall->getArg(2)->getEndLoc()); 6488 6489 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6490 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6491 6492 // Check the type of argument 1 and argument 2 are vectors. 6493 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6494 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6495 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6496 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6497 << TheCall->getDirectCallee() 6498 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6499 TheCall->getArg(1)->getEndLoc()); 6500 } 6501 6502 // Check the first two arguments are the same type. 6503 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6504 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6505 << TheCall->getDirectCallee() 6506 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6507 TheCall->getArg(1)->getEndLoc()); 6508 } 6509 6510 // When default clang type checking is turned off and the customized type 6511 // checking is used, the returning type of the function must be explicitly 6512 // set. Otherwise it is _Bool by default. 6513 TheCall->setType(Arg1Ty); 6514 6515 return false; 6516 } 6517 6518 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6519 // This is declared to take (...), so we have to check everything. 6520 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6521 if (TheCall->getNumArgs() < 2) 6522 return ExprError(Diag(TheCall->getEndLoc(), 6523 diag::err_typecheck_call_too_few_args_at_least) 6524 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6525 << TheCall->getSourceRange()); 6526 6527 // Determine which of the following types of shufflevector we're checking: 6528 // 1) unary, vector mask: (lhs, mask) 6529 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6530 QualType resType = TheCall->getArg(0)->getType(); 6531 unsigned numElements = 0; 6532 6533 if (!TheCall->getArg(0)->isTypeDependent() && 6534 !TheCall->getArg(1)->isTypeDependent()) { 6535 QualType LHSType = TheCall->getArg(0)->getType(); 6536 QualType RHSType = TheCall->getArg(1)->getType(); 6537 6538 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6539 return ExprError( 6540 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6541 << TheCall->getDirectCallee() 6542 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6543 TheCall->getArg(1)->getEndLoc())); 6544 6545 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6546 unsigned numResElements = TheCall->getNumArgs() - 2; 6547 6548 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6549 // with mask. If so, verify that RHS is an integer vector type with the 6550 // same number of elts as lhs. 6551 if (TheCall->getNumArgs() == 2) { 6552 if (!RHSType->hasIntegerRepresentation() || 6553 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6554 return ExprError(Diag(TheCall->getBeginLoc(), 6555 diag::err_vec_builtin_incompatible_vector) 6556 << TheCall->getDirectCallee() 6557 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6558 TheCall->getArg(1)->getEndLoc())); 6559 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6560 return ExprError(Diag(TheCall->getBeginLoc(), 6561 diag::err_vec_builtin_incompatible_vector) 6562 << TheCall->getDirectCallee() 6563 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6564 TheCall->getArg(1)->getEndLoc())); 6565 } else if (numElements != numResElements) { 6566 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6567 resType = Context.getVectorType(eltType, numResElements, 6568 VectorType::GenericVector); 6569 } 6570 } 6571 6572 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6573 if (TheCall->getArg(i)->isTypeDependent() || 6574 TheCall->getArg(i)->isValueDependent()) 6575 continue; 6576 6577 Optional<llvm::APSInt> Result; 6578 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6579 return ExprError(Diag(TheCall->getBeginLoc(), 6580 diag::err_shufflevector_nonconstant_argument) 6581 << TheCall->getArg(i)->getSourceRange()); 6582 6583 // Allow -1 which will be translated to undef in the IR. 6584 if (Result->isSigned() && Result->isAllOnesValue()) 6585 continue; 6586 6587 if (Result->getActiveBits() > 64 || 6588 Result->getZExtValue() >= numElements * 2) 6589 return ExprError(Diag(TheCall->getBeginLoc(), 6590 diag::err_shufflevector_argument_too_large) 6591 << TheCall->getArg(i)->getSourceRange()); 6592 } 6593 6594 SmallVector<Expr*, 32> exprs; 6595 6596 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6597 exprs.push_back(TheCall->getArg(i)); 6598 TheCall->setArg(i, nullptr); 6599 } 6600 6601 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6602 TheCall->getCallee()->getBeginLoc(), 6603 TheCall->getRParenLoc()); 6604 } 6605 6606 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6607 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6608 SourceLocation BuiltinLoc, 6609 SourceLocation RParenLoc) { 6610 ExprValueKind VK = VK_PRValue; 6611 ExprObjectKind OK = OK_Ordinary; 6612 QualType DstTy = TInfo->getType(); 6613 QualType SrcTy = E->getType(); 6614 6615 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6616 return ExprError(Diag(BuiltinLoc, 6617 diag::err_convertvector_non_vector) 6618 << E->getSourceRange()); 6619 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6620 return ExprError(Diag(BuiltinLoc, 6621 diag::err_convertvector_non_vector_type)); 6622 6623 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6624 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6625 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6626 if (SrcElts != DstElts) 6627 return ExprError(Diag(BuiltinLoc, 6628 diag::err_convertvector_incompatible_vector) 6629 << E->getSourceRange()); 6630 } 6631 6632 return new (Context) 6633 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6634 } 6635 6636 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6637 // This is declared to take (const void*, ...) and can take two 6638 // optional constant int args. 6639 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6640 unsigned NumArgs = TheCall->getNumArgs(); 6641 6642 if (NumArgs > 3) 6643 return Diag(TheCall->getEndLoc(), 6644 diag::err_typecheck_call_too_many_args_at_most) 6645 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6646 6647 // Argument 0 is checked for us and the remaining arguments must be 6648 // constant integers. 6649 for (unsigned i = 1; i != NumArgs; ++i) 6650 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6651 return true; 6652 6653 return false; 6654 } 6655 6656 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6657 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6658 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6659 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6660 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6661 if (checkArgCount(*this, TheCall, 1)) 6662 return true; 6663 Expr *Arg = TheCall->getArg(0); 6664 if (Arg->isInstantiationDependent()) 6665 return false; 6666 6667 QualType ArgTy = Arg->getType(); 6668 if (!ArgTy->hasFloatingRepresentation()) 6669 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6670 << ArgTy; 6671 if (Arg->isLValue()) { 6672 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6673 TheCall->setArg(0, FirstArg.get()); 6674 } 6675 TheCall->setType(TheCall->getArg(0)->getType()); 6676 return false; 6677 } 6678 6679 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6680 // __assume does not evaluate its arguments, and should warn if its argument 6681 // has side effects. 6682 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6683 Expr *Arg = TheCall->getArg(0); 6684 if (Arg->isInstantiationDependent()) return false; 6685 6686 if (Arg->HasSideEffects(Context)) 6687 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6688 << Arg->getSourceRange() 6689 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6690 6691 return false; 6692 } 6693 6694 /// Handle __builtin_alloca_with_align. This is declared 6695 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6696 /// than 8. 6697 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6698 // The alignment must be a constant integer. 6699 Expr *Arg = TheCall->getArg(1); 6700 6701 // We can't check the value of a dependent argument. 6702 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6703 if (const auto *UE = 6704 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6705 if (UE->getKind() == UETT_AlignOf || 6706 UE->getKind() == UETT_PreferredAlignOf) 6707 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6708 << Arg->getSourceRange(); 6709 6710 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6711 6712 if (!Result.isPowerOf2()) 6713 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6714 << Arg->getSourceRange(); 6715 6716 if (Result < Context.getCharWidth()) 6717 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6718 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6719 6720 if (Result > std::numeric_limits<int32_t>::max()) 6721 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6722 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6723 } 6724 6725 return false; 6726 } 6727 6728 /// Handle __builtin_assume_aligned. This is declared 6729 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6730 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6731 unsigned NumArgs = TheCall->getNumArgs(); 6732 6733 if (NumArgs > 3) 6734 return Diag(TheCall->getEndLoc(), 6735 diag::err_typecheck_call_too_many_args_at_most) 6736 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6737 6738 // The alignment must be a constant integer. 6739 Expr *Arg = TheCall->getArg(1); 6740 6741 // We can't check the value of a dependent argument. 6742 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6743 llvm::APSInt Result; 6744 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6745 return true; 6746 6747 if (!Result.isPowerOf2()) 6748 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6749 << Arg->getSourceRange(); 6750 6751 if (Result > Sema::MaximumAlignment) 6752 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6753 << Arg->getSourceRange() << Sema::MaximumAlignment; 6754 } 6755 6756 if (NumArgs > 2) { 6757 ExprResult Arg(TheCall->getArg(2)); 6758 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6759 Context.getSizeType(), false); 6760 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6761 if (Arg.isInvalid()) return true; 6762 TheCall->setArg(2, Arg.get()); 6763 } 6764 6765 return false; 6766 } 6767 6768 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6769 unsigned BuiltinID = 6770 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6771 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6772 6773 unsigned NumArgs = TheCall->getNumArgs(); 6774 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6775 if (NumArgs < NumRequiredArgs) { 6776 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6777 << 0 /* function call */ << NumRequiredArgs << NumArgs 6778 << TheCall->getSourceRange(); 6779 } 6780 if (NumArgs >= NumRequiredArgs + 0x100) { 6781 return Diag(TheCall->getEndLoc(), 6782 diag::err_typecheck_call_too_many_args_at_most) 6783 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6784 << TheCall->getSourceRange(); 6785 } 6786 unsigned i = 0; 6787 6788 // For formatting call, check buffer arg. 6789 if (!IsSizeCall) { 6790 ExprResult Arg(TheCall->getArg(i)); 6791 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6792 Context, Context.VoidPtrTy, false); 6793 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6794 if (Arg.isInvalid()) 6795 return true; 6796 TheCall->setArg(i, Arg.get()); 6797 i++; 6798 } 6799 6800 // Check string literal arg. 6801 unsigned FormatIdx = i; 6802 { 6803 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6804 if (Arg.isInvalid()) 6805 return true; 6806 TheCall->setArg(i, Arg.get()); 6807 i++; 6808 } 6809 6810 // Make sure variadic args are scalar. 6811 unsigned FirstDataArg = i; 6812 while (i < NumArgs) { 6813 ExprResult Arg = DefaultVariadicArgumentPromotion( 6814 TheCall->getArg(i), VariadicFunction, nullptr); 6815 if (Arg.isInvalid()) 6816 return true; 6817 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6818 if (ArgSize.getQuantity() >= 0x100) { 6819 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6820 << i << (int)ArgSize.getQuantity() << 0xff 6821 << TheCall->getSourceRange(); 6822 } 6823 TheCall->setArg(i, Arg.get()); 6824 i++; 6825 } 6826 6827 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6828 // call to avoid duplicate diagnostics. 6829 if (!IsSizeCall) { 6830 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6831 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6832 bool Success = CheckFormatArguments( 6833 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6834 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6835 CheckedVarArgs); 6836 if (!Success) 6837 return true; 6838 } 6839 6840 if (IsSizeCall) { 6841 TheCall->setType(Context.getSizeType()); 6842 } else { 6843 TheCall->setType(Context.VoidPtrTy); 6844 } 6845 return false; 6846 } 6847 6848 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6849 /// TheCall is a constant expression. 6850 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6851 llvm::APSInt &Result) { 6852 Expr *Arg = TheCall->getArg(ArgNum); 6853 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6854 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6855 6856 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6857 6858 Optional<llvm::APSInt> R; 6859 if (!(R = Arg->getIntegerConstantExpr(Context))) 6860 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6861 << FDecl->getDeclName() << Arg->getSourceRange(); 6862 Result = *R; 6863 return false; 6864 } 6865 6866 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6867 /// TheCall is a constant expression in the range [Low, High]. 6868 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6869 int Low, int High, bool RangeIsError) { 6870 if (isConstantEvaluated()) 6871 return false; 6872 llvm::APSInt Result; 6873 6874 // We can't check the value of a dependent argument. 6875 Expr *Arg = TheCall->getArg(ArgNum); 6876 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6877 return false; 6878 6879 // Check constant-ness first. 6880 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6881 return true; 6882 6883 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6884 if (RangeIsError) 6885 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6886 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 6887 else 6888 // Defer the warning until we know if the code will be emitted so that 6889 // dead code can ignore this. 6890 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6891 PDiag(diag::warn_argument_invalid_range) 6892 << toString(Result, 10) << Low << High 6893 << Arg->getSourceRange()); 6894 } 6895 6896 return false; 6897 } 6898 6899 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6900 /// TheCall is a constant expression is a multiple of Num.. 6901 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6902 unsigned Num) { 6903 llvm::APSInt Result; 6904 6905 // We can't check the value of a dependent argument. 6906 Expr *Arg = TheCall->getArg(ArgNum); 6907 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6908 return false; 6909 6910 // Check constant-ness first. 6911 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6912 return true; 6913 6914 if (Result.getSExtValue() % Num != 0) 6915 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6916 << Num << Arg->getSourceRange(); 6917 6918 return false; 6919 } 6920 6921 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6922 /// constant expression representing a power of 2. 6923 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6924 llvm::APSInt Result; 6925 6926 // We can't check the value of a dependent argument. 6927 Expr *Arg = TheCall->getArg(ArgNum); 6928 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6929 return false; 6930 6931 // Check constant-ness first. 6932 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6933 return true; 6934 6935 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6936 // and only if x is a power of 2. 6937 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6938 return false; 6939 6940 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6941 << Arg->getSourceRange(); 6942 } 6943 6944 static bool IsShiftedByte(llvm::APSInt Value) { 6945 if (Value.isNegative()) 6946 return false; 6947 6948 // Check if it's a shifted byte, by shifting it down 6949 while (true) { 6950 // If the value fits in the bottom byte, the check passes. 6951 if (Value < 0x100) 6952 return true; 6953 6954 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6955 // fails. 6956 if ((Value & 0xFF) != 0) 6957 return false; 6958 6959 // If the bottom 8 bits are all 0, but something above that is nonzero, 6960 // then shifting the value right by 8 bits won't affect whether it's a 6961 // shifted byte or not. So do that, and go round again. 6962 Value >>= 8; 6963 } 6964 } 6965 6966 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6967 /// a constant expression representing an arbitrary byte value shifted left by 6968 /// a multiple of 8 bits. 6969 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6970 unsigned ArgBits) { 6971 llvm::APSInt Result; 6972 6973 // We can't check the value of a dependent argument. 6974 Expr *Arg = TheCall->getArg(ArgNum); 6975 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6976 return false; 6977 6978 // Check constant-ness first. 6979 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6980 return true; 6981 6982 // Truncate to the given size. 6983 Result = Result.getLoBits(ArgBits); 6984 Result.setIsUnsigned(true); 6985 6986 if (IsShiftedByte(Result)) 6987 return false; 6988 6989 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6990 << Arg->getSourceRange(); 6991 } 6992 6993 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6994 /// TheCall is a constant expression representing either a shifted byte value, 6995 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6996 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6997 /// Arm MVE intrinsics. 6998 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6999 int ArgNum, 7000 unsigned ArgBits) { 7001 llvm::APSInt Result; 7002 7003 // We can't check the value of a dependent argument. 7004 Expr *Arg = TheCall->getArg(ArgNum); 7005 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7006 return false; 7007 7008 // Check constant-ness first. 7009 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7010 return true; 7011 7012 // Truncate to the given size. 7013 Result = Result.getLoBits(ArgBits); 7014 Result.setIsUnsigned(true); 7015 7016 // Check to see if it's in either of the required forms. 7017 if (IsShiftedByte(Result) || 7018 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7019 return false; 7020 7021 return Diag(TheCall->getBeginLoc(), 7022 diag::err_argument_not_shifted_byte_or_xxff) 7023 << Arg->getSourceRange(); 7024 } 7025 7026 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7027 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7028 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7029 if (checkArgCount(*this, TheCall, 2)) 7030 return true; 7031 Expr *Arg0 = TheCall->getArg(0); 7032 Expr *Arg1 = TheCall->getArg(1); 7033 7034 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7035 if (FirstArg.isInvalid()) 7036 return true; 7037 QualType FirstArgType = FirstArg.get()->getType(); 7038 if (!FirstArgType->isAnyPointerType()) 7039 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7040 << "first" << FirstArgType << Arg0->getSourceRange(); 7041 TheCall->setArg(0, FirstArg.get()); 7042 7043 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7044 if (SecArg.isInvalid()) 7045 return true; 7046 QualType SecArgType = SecArg.get()->getType(); 7047 if (!SecArgType->isIntegerType()) 7048 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7049 << "second" << SecArgType << Arg1->getSourceRange(); 7050 7051 // Derive the return type from the pointer argument. 7052 TheCall->setType(FirstArgType); 7053 return false; 7054 } 7055 7056 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7057 if (checkArgCount(*this, TheCall, 2)) 7058 return true; 7059 7060 Expr *Arg0 = TheCall->getArg(0); 7061 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7062 if (FirstArg.isInvalid()) 7063 return true; 7064 QualType FirstArgType = FirstArg.get()->getType(); 7065 if (!FirstArgType->isAnyPointerType()) 7066 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7067 << "first" << FirstArgType << Arg0->getSourceRange(); 7068 TheCall->setArg(0, FirstArg.get()); 7069 7070 // Derive the return type from the pointer argument. 7071 TheCall->setType(FirstArgType); 7072 7073 // Second arg must be an constant in range [0,15] 7074 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7075 } 7076 7077 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7078 if (checkArgCount(*this, TheCall, 2)) 7079 return true; 7080 Expr *Arg0 = TheCall->getArg(0); 7081 Expr *Arg1 = TheCall->getArg(1); 7082 7083 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7084 if (FirstArg.isInvalid()) 7085 return true; 7086 QualType FirstArgType = FirstArg.get()->getType(); 7087 if (!FirstArgType->isAnyPointerType()) 7088 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7089 << "first" << FirstArgType << Arg0->getSourceRange(); 7090 7091 QualType SecArgType = Arg1->getType(); 7092 if (!SecArgType->isIntegerType()) 7093 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7094 << "second" << SecArgType << Arg1->getSourceRange(); 7095 TheCall->setType(Context.IntTy); 7096 return false; 7097 } 7098 7099 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7100 BuiltinID == AArch64::BI__builtin_arm_stg) { 7101 if (checkArgCount(*this, TheCall, 1)) 7102 return true; 7103 Expr *Arg0 = TheCall->getArg(0); 7104 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7105 if (FirstArg.isInvalid()) 7106 return true; 7107 7108 QualType FirstArgType = FirstArg.get()->getType(); 7109 if (!FirstArgType->isAnyPointerType()) 7110 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7111 << "first" << FirstArgType << Arg0->getSourceRange(); 7112 TheCall->setArg(0, FirstArg.get()); 7113 7114 // Derive the return type from the pointer argument. 7115 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7116 TheCall->setType(FirstArgType); 7117 return false; 7118 } 7119 7120 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7121 Expr *ArgA = TheCall->getArg(0); 7122 Expr *ArgB = TheCall->getArg(1); 7123 7124 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7125 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7126 7127 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7128 return true; 7129 7130 QualType ArgTypeA = ArgExprA.get()->getType(); 7131 QualType ArgTypeB = ArgExprB.get()->getType(); 7132 7133 auto isNull = [&] (Expr *E) -> bool { 7134 return E->isNullPointerConstant( 7135 Context, Expr::NPC_ValueDependentIsNotNull); }; 7136 7137 // argument should be either a pointer or null 7138 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7139 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7140 << "first" << ArgTypeA << ArgA->getSourceRange(); 7141 7142 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7143 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7144 << "second" << ArgTypeB << ArgB->getSourceRange(); 7145 7146 // Ensure Pointee types are compatible 7147 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7148 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7149 QualType pointeeA = ArgTypeA->getPointeeType(); 7150 QualType pointeeB = ArgTypeB->getPointeeType(); 7151 if (!Context.typesAreCompatible( 7152 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7153 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7154 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7155 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7156 << ArgB->getSourceRange(); 7157 } 7158 } 7159 7160 // at least one argument should be pointer type 7161 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7162 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7163 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7164 7165 if (isNull(ArgA)) // adopt type of the other pointer 7166 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7167 7168 if (isNull(ArgB)) 7169 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7170 7171 TheCall->setArg(0, ArgExprA.get()); 7172 TheCall->setArg(1, ArgExprB.get()); 7173 TheCall->setType(Context.LongLongTy); 7174 return false; 7175 } 7176 assert(false && "Unhandled ARM MTE intrinsic"); 7177 return true; 7178 } 7179 7180 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7181 /// TheCall is an ARM/AArch64 special register string literal. 7182 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7183 int ArgNum, unsigned ExpectedFieldNum, 7184 bool AllowName) { 7185 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7186 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7187 BuiltinID == ARM::BI__builtin_arm_rsr || 7188 BuiltinID == ARM::BI__builtin_arm_rsrp || 7189 BuiltinID == ARM::BI__builtin_arm_wsr || 7190 BuiltinID == ARM::BI__builtin_arm_wsrp; 7191 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7192 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7193 BuiltinID == AArch64::BI__builtin_arm_rsr || 7194 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7195 BuiltinID == AArch64::BI__builtin_arm_wsr || 7196 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7197 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7198 7199 // We can't check the value of a dependent argument. 7200 Expr *Arg = TheCall->getArg(ArgNum); 7201 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7202 return false; 7203 7204 // Check if the argument is a string literal. 7205 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7206 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7207 << Arg->getSourceRange(); 7208 7209 // Check the type of special register given. 7210 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7211 SmallVector<StringRef, 6> Fields; 7212 Reg.split(Fields, ":"); 7213 7214 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7215 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7216 << Arg->getSourceRange(); 7217 7218 // If the string is the name of a register then we cannot check that it is 7219 // valid here but if the string is of one the forms described in ACLE then we 7220 // can check that the supplied fields are integers and within the valid 7221 // ranges. 7222 if (Fields.size() > 1) { 7223 bool FiveFields = Fields.size() == 5; 7224 7225 bool ValidString = true; 7226 if (IsARMBuiltin) { 7227 ValidString &= Fields[0].startswith_insensitive("cp") || 7228 Fields[0].startswith_insensitive("p"); 7229 if (ValidString) 7230 Fields[0] = Fields[0].drop_front( 7231 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7232 7233 ValidString &= Fields[2].startswith_insensitive("c"); 7234 if (ValidString) 7235 Fields[2] = Fields[2].drop_front(1); 7236 7237 if (FiveFields) { 7238 ValidString &= Fields[3].startswith_insensitive("c"); 7239 if (ValidString) 7240 Fields[3] = Fields[3].drop_front(1); 7241 } 7242 } 7243 7244 SmallVector<int, 5> Ranges; 7245 if (FiveFields) 7246 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7247 else 7248 Ranges.append({15, 7, 15}); 7249 7250 for (unsigned i=0; i<Fields.size(); ++i) { 7251 int IntField; 7252 ValidString &= !Fields[i].getAsInteger(10, IntField); 7253 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7254 } 7255 7256 if (!ValidString) 7257 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7258 << Arg->getSourceRange(); 7259 } else if (IsAArch64Builtin && Fields.size() == 1) { 7260 // If the register name is one of those that appear in the condition below 7261 // and the special register builtin being used is one of the write builtins, 7262 // then we require that the argument provided for writing to the register 7263 // is an integer constant expression. This is because it will be lowered to 7264 // an MSR (immediate) instruction, so we need to know the immediate at 7265 // compile time. 7266 if (TheCall->getNumArgs() != 2) 7267 return false; 7268 7269 std::string RegLower = Reg.lower(); 7270 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7271 RegLower != "pan" && RegLower != "uao") 7272 return false; 7273 7274 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7275 } 7276 7277 return false; 7278 } 7279 7280 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7281 /// Emit an error and return true on failure; return false on success. 7282 /// TypeStr is a string containing the type descriptor of the value returned by 7283 /// the builtin and the descriptors of the expected type of the arguments. 7284 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 7285 7286 assert((TypeStr[0] != '\0') && 7287 "Invalid types in PPC MMA builtin declaration"); 7288 7289 unsigned Mask = 0; 7290 unsigned ArgNum = 0; 7291 7292 // The first type in TypeStr is the type of the value returned by the 7293 // builtin. So we first read that type and change the type of TheCall. 7294 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7295 TheCall->setType(type); 7296 7297 while (*TypeStr != '\0') { 7298 Mask = 0; 7299 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7300 if (ArgNum >= TheCall->getNumArgs()) { 7301 ArgNum++; 7302 break; 7303 } 7304 7305 Expr *Arg = TheCall->getArg(ArgNum); 7306 QualType ArgType = Arg->getType(); 7307 7308 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7309 (!ExpectedType->isVoidPointerType() && 7310 ArgType.getCanonicalType() != ExpectedType)) 7311 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7312 << ArgType << ExpectedType << 1 << 0 << 0; 7313 7314 // If the value of the Mask is not 0, we have a constraint in the size of 7315 // the integer argument so here we ensure the argument is a constant that 7316 // is in the valid range. 7317 if (Mask != 0 && 7318 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7319 return true; 7320 7321 ArgNum++; 7322 } 7323 7324 // In case we exited early from the previous loop, there are other types to 7325 // read from TypeStr. So we need to read them all to ensure we have the right 7326 // number of arguments in TheCall and if it is not the case, to display a 7327 // better error message. 7328 while (*TypeStr != '\0') { 7329 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7330 ArgNum++; 7331 } 7332 if (checkArgCount(*this, TheCall, ArgNum)) 7333 return true; 7334 7335 return false; 7336 } 7337 7338 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7339 /// This checks that the target supports __builtin_longjmp and 7340 /// that val is a constant 1. 7341 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7342 if (!Context.getTargetInfo().hasSjLjLowering()) 7343 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7344 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7345 7346 Expr *Arg = TheCall->getArg(1); 7347 llvm::APSInt Result; 7348 7349 // TODO: This is less than ideal. Overload this to take a value. 7350 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7351 return true; 7352 7353 if (Result != 1) 7354 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7355 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7356 7357 return false; 7358 } 7359 7360 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7361 /// This checks that the target supports __builtin_setjmp. 7362 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7363 if (!Context.getTargetInfo().hasSjLjLowering()) 7364 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7365 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7366 return false; 7367 } 7368 7369 namespace { 7370 7371 class UncoveredArgHandler { 7372 enum { Unknown = -1, AllCovered = -2 }; 7373 7374 signed FirstUncoveredArg = Unknown; 7375 SmallVector<const Expr *, 4> DiagnosticExprs; 7376 7377 public: 7378 UncoveredArgHandler() = default; 7379 7380 bool hasUncoveredArg() const { 7381 return (FirstUncoveredArg >= 0); 7382 } 7383 7384 unsigned getUncoveredArg() const { 7385 assert(hasUncoveredArg() && "no uncovered argument"); 7386 return FirstUncoveredArg; 7387 } 7388 7389 void setAllCovered() { 7390 // A string has been found with all arguments covered, so clear out 7391 // the diagnostics. 7392 DiagnosticExprs.clear(); 7393 FirstUncoveredArg = AllCovered; 7394 } 7395 7396 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7397 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7398 7399 // Don't update if a previous string covers all arguments. 7400 if (FirstUncoveredArg == AllCovered) 7401 return; 7402 7403 // UncoveredArgHandler tracks the highest uncovered argument index 7404 // and with it all the strings that match this index. 7405 if (NewFirstUncoveredArg == FirstUncoveredArg) 7406 DiagnosticExprs.push_back(StrExpr); 7407 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7408 DiagnosticExprs.clear(); 7409 DiagnosticExprs.push_back(StrExpr); 7410 FirstUncoveredArg = NewFirstUncoveredArg; 7411 } 7412 } 7413 7414 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7415 }; 7416 7417 enum StringLiteralCheckType { 7418 SLCT_NotALiteral, 7419 SLCT_UncheckedLiteral, 7420 SLCT_CheckedLiteral 7421 }; 7422 7423 } // namespace 7424 7425 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7426 BinaryOperatorKind BinOpKind, 7427 bool AddendIsRight) { 7428 unsigned BitWidth = Offset.getBitWidth(); 7429 unsigned AddendBitWidth = Addend.getBitWidth(); 7430 // There might be negative interim results. 7431 if (Addend.isUnsigned()) { 7432 Addend = Addend.zext(++AddendBitWidth); 7433 Addend.setIsSigned(true); 7434 } 7435 // Adjust the bit width of the APSInts. 7436 if (AddendBitWidth > BitWidth) { 7437 Offset = Offset.sext(AddendBitWidth); 7438 BitWidth = AddendBitWidth; 7439 } else if (BitWidth > AddendBitWidth) { 7440 Addend = Addend.sext(BitWidth); 7441 } 7442 7443 bool Ov = false; 7444 llvm::APSInt ResOffset = Offset; 7445 if (BinOpKind == BO_Add) 7446 ResOffset = Offset.sadd_ov(Addend, Ov); 7447 else { 7448 assert(AddendIsRight && BinOpKind == BO_Sub && 7449 "operator must be add or sub with addend on the right"); 7450 ResOffset = Offset.ssub_ov(Addend, Ov); 7451 } 7452 7453 // We add an offset to a pointer here so we should support an offset as big as 7454 // possible. 7455 if (Ov) { 7456 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7457 "index (intermediate) result too big"); 7458 Offset = Offset.sext(2 * BitWidth); 7459 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7460 return; 7461 } 7462 7463 Offset = ResOffset; 7464 } 7465 7466 namespace { 7467 7468 // This is a wrapper class around StringLiteral to support offsetted string 7469 // literals as format strings. It takes the offset into account when returning 7470 // the string and its length or the source locations to display notes correctly. 7471 class FormatStringLiteral { 7472 const StringLiteral *FExpr; 7473 int64_t Offset; 7474 7475 public: 7476 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7477 : FExpr(fexpr), Offset(Offset) {} 7478 7479 StringRef getString() const { 7480 return FExpr->getString().drop_front(Offset); 7481 } 7482 7483 unsigned getByteLength() const { 7484 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7485 } 7486 7487 unsigned getLength() const { return FExpr->getLength() - Offset; } 7488 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7489 7490 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7491 7492 QualType getType() const { return FExpr->getType(); } 7493 7494 bool isAscii() const { return FExpr->isAscii(); } 7495 bool isWide() const { return FExpr->isWide(); } 7496 bool isUTF8() const { return FExpr->isUTF8(); } 7497 bool isUTF16() const { return FExpr->isUTF16(); } 7498 bool isUTF32() const { return FExpr->isUTF32(); } 7499 bool isPascal() const { return FExpr->isPascal(); } 7500 7501 SourceLocation getLocationOfByte( 7502 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7503 const TargetInfo &Target, unsigned *StartToken = nullptr, 7504 unsigned *StartTokenByteOffset = nullptr) const { 7505 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7506 StartToken, StartTokenByteOffset); 7507 } 7508 7509 SourceLocation getBeginLoc() const LLVM_READONLY { 7510 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7511 } 7512 7513 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7514 }; 7515 7516 } // namespace 7517 7518 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7519 const Expr *OrigFormatExpr, 7520 ArrayRef<const Expr *> Args, 7521 bool HasVAListArg, unsigned format_idx, 7522 unsigned firstDataArg, 7523 Sema::FormatStringType Type, 7524 bool inFunctionCall, 7525 Sema::VariadicCallType CallType, 7526 llvm::SmallBitVector &CheckedVarArgs, 7527 UncoveredArgHandler &UncoveredArg, 7528 bool IgnoreStringsWithoutSpecifiers); 7529 7530 // Determine if an expression is a string literal or constant string. 7531 // If this function returns false on the arguments to a function expecting a 7532 // format string, we will usually need to emit a warning. 7533 // True string literals are then checked by CheckFormatString. 7534 static StringLiteralCheckType 7535 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7536 bool HasVAListArg, unsigned format_idx, 7537 unsigned firstDataArg, Sema::FormatStringType Type, 7538 Sema::VariadicCallType CallType, bool InFunctionCall, 7539 llvm::SmallBitVector &CheckedVarArgs, 7540 UncoveredArgHandler &UncoveredArg, 7541 llvm::APSInt Offset, 7542 bool IgnoreStringsWithoutSpecifiers = false) { 7543 if (S.isConstantEvaluated()) 7544 return SLCT_NotALiteral; 7545 tryAgain: 7546 assert(Offset.isSigned() && "invalid offset"); 7547 7548 if (E->isTypeDependent() || E->isValueDependent()) 7549 return SLCT_NotALiteral; 7550 7551 E = E->IgnoreParenCasts(); 7552 7553 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7554 // Technically -Wformat-nonliteral does not warn about this case. 7555 // The behavior of printf and friends in this case is implementation 7556 // dependent. Ideally if the format string cannot be null then 7557 // it should have a 'nonnull' attribute in the function prototype. 7558 return SLCT_UncheckedLiteral; 7559 7560 switch (E->getStmtClass()) { 7561 case Stmt::BinaryConditionalOperatorClass: 7562 case Stmt::ConditionalOperatorClass: { 7563 // The expression is a literal if both sub-expressions were, and it was 7564 // completely checked only if both sub-expressions were checked. 7565 const AbstractConditionalOperator *C = 7566 cast<AbstractConditionalOperator>(E); 7567 7568 // Determine whether it is necessary to check both sub-expressions, for 7569 // example, because the condition expression is a constant that can be 7570 // evaluated at compile time. 7571 bool CheckLeft = true, CheckRight = true; 7572 7573 bool Cond; 7574 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7575 S.isConstantEvaluated())) { 7576 if (Cond) 7577 CheckRight = false; 7578 else 7579 CheckLeft = false; 7580 } 7581 7582 // We need to maintain the offsets for the right and the left hand side 7583 // separately to check if every possible indexed expression is a valid 7584 // string literal. They might have different offsets for different string 7585 // literals in the end. 7586 StringLiteralCheckType Left; 7587 if (!CheckLeft) 7588 Left = SLCT_UncheckedLiteral; 7589 else { 7590 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7591 HasVAListArg, format_idx, firstDataArg, 7592 Type, CallType, InFunctionCall, 7593 CheckedVarArgs, UncoveredArg, Offset, 7594 IgnoreStringsWithoutSpecifiers); 7595 if (Left == SLCT_NotALiteral || !CheckRight) { 7596 return Left; 7597 } 7598 } 7599 7600 StringLiteralCheckType Right = checkFormatStringExpr( 7601 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7602 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7603 IgnoreStringsWithoutSpecifiers); 7604 7605 return (CheckLeft && Left < Right) ? Left : Right; 7606 } 7607 7608 case Stmt::ImplicitCastExprClass: 7609 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7610 goto tryAgain; 7611 7612 case Stmt::OpaqueValueExprClass: 7613 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7614 E = src; 7615 goto tryAgain; 7616 } 7617 return SLCT_NotALiteral; 7618 7619 case Stmt::PredefinedExprClass: 7620 // While __func__, etc., are technically not string literals, they 7621 // cannot contain format specifiers and thus are not a security 7622 // liability. 7623 return SLCT_UncheckedLiteral; 7624 7625 case Stmt::DeclRefExprClass: { 7626 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7627 7628 // As an exception, do not flag errors for variables binding to 7629 // const string literals. 7630 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7631 bool isConstant = false; 7632 QualType T = DR->getType(); 7633 7634 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7635 isConstant = AT->getElementType().isConstant(S.Context); 7636 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7637 isConstant = T.isConstant(S.Context) && 7638 PT->getPointeeType().isConstant(S.Context); 7639 } else if (T->isObjCObjectPointerType()) { 7640 // In ObjC, there is usually no "const ObjectPointer" type, 7641 // so don't check if the pointee type is constant. 7642 isConstant = T.isConstant(S.Context); 7643 } 7644 7645 if (isConstant) { 7646 if (const Expr *Init = VD->getAnyInitializer()) { 7647 // Look through initializers like const char c[] = { "foo" } 7648 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7649 if (InitList->isStringLiteralInit()) 7650 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7651 } 7652 return checkFormatStringExpr(S, Init, Args, 7653 HasVAListArg, format_idx, 7654 firstDataArg, Type, CallType, 7655 /*InFunctionCall*/ false, CheckedVarArgs, 7656 UncoveredArg, Offset); 7657 } 7658 } 7659 7660 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7661 // special check to see if the format string is a function parameter 7662 // of the function calling the printf function. If the function 7663 // has an attribute indicating it is a printf-like function, then we 7664 // should suppress warnings concerning non-literals being used in a call 7665 // to a vprintf function. For example: 7666 // 7667 // void 7668 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7669 // va_list ap; 7670 // va_start(ap, fmt); 7671 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7672 // ... 7673 // } 7674 if (HasVAListArg) { 7675 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7676 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7677 int PVIndex = PV->getFunctionScopeIndex() + 1; 7678 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7679 // adjust for implicit parameter 7680 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7681 if (MD->isInstance()) 7682 ++PVIndex; 7683 // We also check if the formats are compatible. 7684 // We can't pass a 'scanf' string to a 'printf' function. 7685 if (PVIndex == PVFormat->getFormatIdx() && 7686 Type == S.GetFormatStringType(PVFormat)) 7687 return SLCT_UncheckedLiteral; 7688 } 7689 } 7690 } 7691 } 7692 } 7693 7694 return SLCT_NotALiteral; 7695 } 7696 7697 case Stmt::CallExprClass: 7698 case Stmt::CXXMemberCallExprClass: { 7699 const CallExpr *CE = cast<CallExpr>(E); 7700 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7701 bool IsFirst = true; 7702 StringLiteralCheckType CommonResult; 7703 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7704 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7705 StringLiteralCheckType Result = checkFormatStringExpr( 7706 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7707 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7708 IgnoreStringsWithoutSpecifiers); 7709 if (IsFirst) { 7710 CommonResult = Result; 7711 IsFirst = false; 7712 } 7713 } 7714 if (!IsFirst) 7715 return CommonResult; 7716 7717 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7718 unsigned BuiltinID = FD->getBuiltinID(); 7719 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7720 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7721 const Expr *Arg = CE->getArg(0); 7722 return checkFormatStringExpr(S, Arg, Args, 7723 HasVAListArg, format_idx, 7724 firstDataArg, Type, CallType, 7725 InFunctionCall, CheckedVarArgs, 7726 UncoveredArg, Offset, 7727 IgnoreStringsWithoutSpecifiers); 7728 } 7729 } 7730 } 7731 7732 return SLCT_NotALiteral; 7733 } 7734 case Stmt::ObjCMessageExprClass: { 7735 const auto *ME = cast<ObjCMessageExpr>(E); 7736 if (const auto *MD = ME->getMethodDecl()) { 7737 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7738 // As a special case heuristic, if we're using the method -[NSBundle 7739 // localizedStringForKey:value:table:], ignore any key strings that lack 7740 // format specifiers. The idea is that if the key doesn't have any 7741 // format specifiers then its probably just a key to map to the 7742 // localized strings. If it does have format specifiers though, then its 7743 // likely that the text of the key is the format string in the 7744 // programmer's language, and should be checked. 7745 const ObjCInterfaceDecl *IFace; 7746 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7747 IFace->getIdentifier()->isStr("NSBundle") && 7748 MD->getSelector().isKeywordSelector( 7749 {"localizedStringForKey", "value", "table"})) { 7750 IgnoreStringsWithoutSpecifiers = true; 7751 } 7752 7753 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7754 return checkFormatStringExpr( 7755 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7756 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7757 IgnoreStringsWithoutSpecifiers); 7758 } 7759 } 7760 7761 return SLCT_NotALiteral; 7762 } 7763 case Stmt::ObjCStringLiteralClass: 7764 case Stmt::StringLiteralClass: { 7765 const StringLiteral *StrE = nullptr; 7766 7767 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7768 StrE = ObjCFExpr->getString(); 7769 else 7770 StrE = cast<StringLiteral>(E); 7771 7772 if (StrE) { 7773 if (Offset.isNegative() || Offset > StrE->getLength()) { 7774 // TODO: It would be better to have an explicit warning for out of 7775 // bounds literals. 7776 return SLCT_NotALiteral; 7777 } 7778 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7779 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7780 firstDataArg, Type, InFunctionCall, CallType, 7781 CheckedVarArgs, UncoveredArg, 7782 IgnoreStringsWithoutSpecifiers); 7783 return SLCT_CheckedLiteral; 7784 } 7785 7786 return SLCT_NotALiteral; 7787 } 7788 case Stmt::BinaryOperatorClass: { 7789 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7790 7791 // A string literal + an int offset is still a string literal. 7792 if (BinOp->isAdditiveOp()) { 7793 Expr::EvalResult LResult, RResult; 7794 7795 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7796 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7797 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7798 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7799 7800 if (LIsInt != RIsInt) { 7801 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7802 7803 if (LIsInt) { 7804 if (BinOpKind == BO_Add) { 7805 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7806 E = BinOp->getRHS(); 7807 goto tryAgain; 7808 } 7809 } else { 7810 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7811 E = BinOp->getLHS(); 7812 goto tryAgain; 7813 } 7814 } 7815 } 7816 7817 return SLCT_NotALiteral; 7818 } 7819 case Stmt::UnaryOperatorClass: { 7820 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7821 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7822 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7823 Expr::EvalResult IndexResult; 7824 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7825 Expr::SE_NoSideEffects, 7826 S.isConstantEvaluated())) { 7827 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7828 /*RHS is int*/ true); 7829 E = ASE->getBase(); 7830 goto tryAgain; 7831 } 7832 } 7833 7834 return SLCT_NotALiteral; 7835 } 7836 7837 default: 7838 return SLCT_NotALiteral; 7839 } 7840 } 7841 7842 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7843 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7844 .Case("scanf", FST_Scanf) 7845 .Cases("printf", "printf0", FST_Printf) 7846 .Cases("NSString", "CFString", FST_NSString) 7847 .Case("strftime", FST_Strftime) 7848 .Case("strfmon", FST_Strfmon) 7849 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7850 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7851 .Case("os_trace", FST_OSLog) 7852 .Case("os_log", FST_OSLog) 7853 .Default(FST_Unknown); 7854 } 7855 7856 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7857 /// functions) for correct use of format strings. 7858 /// Returns true if a format string has been fully checked. 7859 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7860 ArrayRef<const Expr *> Args, 7861 bool IsCXXMember, 7862 VariadicCallType CallType, 7863 SourceLocation Loc, SourceRange Range, 7864 llvm::SmallBitVector &CheckedVarArgs) { 7865 FormatStringInfo FSI; 7866 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7867 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7868 FSI.FirstDataArg, GetFormatStringType(Format), 7869 CallType, Loc, Range, CheckedVarArgs); 7870 return false; 7871 } 7872 7873 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7874 bool HasVAListArg, unsigned format_idx, 7875 unsigned firstDataArg, FormatStringType Type, 7876 VariadicCallType CallType, 7877 SourceLocation Loc, SourceRange Range, 7878 llvm::SmallBitVector &CheckedVarArgs) { 7879 // CHECK: printf/scanf-like function is called with no format string. 7880 if (format_idx >= Args.size()) { 7881 Diag(Loc, diag::warn_missing_format_string) << Range; 7882 return false; 7883 } 7884 7885 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7886 7887 // CHECK: format string is not a string literal. 7888 // 7889 // Dynamically generated format strings are difficult to 7890 // automatically vet at compile time. Requiring that format strings 7891 // are string literals: (1) permits the checking of format strings by 7892 // the compiler and thereby (2) can practically remove the source of 7893 // many format string exploits. 7894 7895 // Format string can be either ObjC string (e.g. @"%d") or 7896 // C string (e.g. "%d") 7897 // ObjC string uses the same format specifiers as C string, so we can use 7898 // the same format string checking logic for both ObjC and C strings. 7899 UncoveredArgHandler UncoveredArg; 7900 StringLiteralCheckType CT = 7901 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7902 format_idx, firstDataArg, Type, CallType, 7903 /*IsFunctionCall*/ true, CheckedVarArgs, 7904 UncoveredArg, 7905 /*no string offset*/ llvm::APSInt(64, false) = 0); 7906 7907 // Generate a diagnostic where an uncovered argument is detected. 7908 if (UncoveredArg.hasUncoveredArg()) { 7909 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7910 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7911 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7912 } 7913 7914 if (CT != SLCT_NotALiteral) 7915 // Literal format string found, check done! 7916 return CT == SLCT_CheckedLiteral; 7917 7918 // Strftime is particular as it always uses a single 'time' argument, 7919 // so it is safe to pass a non-literal string. 7920 if (Type == FST_Strftime) 7921 return false; 7922 7923 // Do not emit diag when the string param is a macro expansion and the 7924 // format is either NSString or CFString. This is a hack to prevent 7925 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7926 // which are usually used in place of NS and CF string literals. 7927 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7928 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7929 return false; 7930 7931 // If there are no arguments specified, warn with -Wformat-security, otherwise 7932 // warn only with -Wformat-nonliteral. 7933 if (Args.size() == firstDataArg) { 7934 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7935 << OrigFormatExpr->getSourceRange(); 7936 switch (Type) { 7937 default: 7938 break; 7939 case FST_Kprintf: 7940 case FST_FreeBSDKPrintf: 7941 case FST_Printf: 7942 Diag(FormatLoc, diag::note_format_security_fixit) 7943 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7944 break; 7945 case FST_NSString: 7946 Diag(FormatLoc, diag::note_format_security_fixit) 7947 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7948 break; 7949 } 7950 } else { 7951 Diag(FormatLoc, diag::warn_format_nonliteral) 7952 << OrigFormatExpr->getSourceRange(); 7953 } 7954 return false; 7955 } 7956 7957 namespace { 7958 7959 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7960 protected: 7961 Sema &S; 7962 const FormatStringLiteral *FExpr; 7963 const Expr *OrigFormatExpr; 7964 const Sema::FormatStringType FSType; 7965 const unsigned FirstDataArg; 7966 const unsigned NumDataArgs; 7967 const char *Beg; // Start of format string. 7968 const bool HasVAListArg; 7969 ArrayRef<const Expr *> Args; 7970 unsigned FormatIdx; 7971 llvm::SmallBitVector CoveredArgs; 7972 bool usesPositionalArgs = false; 7973 bool atFirstArg = true; 7974 bool inFunctionCall; 7975 Sema::VariadicCallType CallType; 7976 llvm::SmallBitVector &CheckedVarArgs; 7977 UncoveredArgHandler &UncoveredArg; 7978 7979 public: 7980 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7981 const Expr *origFormatExpr, 7982 const Sema::FormatStringType type, unsigned firstDataArg, 7983 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7984 ArrayRef<const Expr *> Args, unsigned formatIdx, 7985 bool inFunctionCall, Sema::VariadicCallType callType, 7986 llvm::SmallBitVector &CheckedVarArgs, 7987 UncoveredArgHandler &UncoveredArg) 7988 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7989 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7990 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7991 inFunctionCall(inFunctionCall), CallType(callType), 7992 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7993 CoveredArgs.resize(numDataArgs); 7994 CoveredArgs.reset(); 7995 } 7996 7997 void DoneProcessing(); 7998 7999 void HandleIncompleteSpecifier(const char *startSpecifier, 8000 unsigned specifierLen) override; 8001 8002 void HandleInvalidLengthModifier( 8003 const analyze_format_string::FormatSpecifier &FS, 8004 const analyze_format_string::ConversionSpecifier &CS, 8005 const char *startSpecifier, unsigned specifierLen, 8006 unsigned DiagID); 8007 8008 void HandleNonStandardLengthModifier( 8009 const analyze_format_string::FormatSpecifier &FS, 8010 const char *startSpecifier, unsigned specifierLen); 8011 8012 void HandleNonStandardConversionSpecifier( 8013 const analyze_format_string::ConversionSpecifier &CS, 8014 const char *startSpecifier, unsigned specifierLen); 8015 8016 void HandlePosition(const char *startPos, unsigned posLen) override; 8017 8018 void HandleInvalidPosition(const char *startSpecifier, 8019 unsigned specifierLen, 8020 analyze_format_string::PositionContext p) override; 8021 8022 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8023 8024 void HandleNullChar(const char *nullCharacter) override; 8025 8026 template <typename Range> 8027 static void 8028 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8029 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8030 bool IsStringLocation, Range StringRange, 8031 ArrayRef<FixItHint> Fixit = None); 8032 8033 protected: 8034 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8035 const char *startSpec, 8036 unsigned specifierLen, 8037 const char *csStart, unsigned csLen); 8038 8039 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8040 const char *startSpec, 8041 unsigned specifierLen); 8042 8043 SourceRange getFormatStringRange(); 8044 CharSourceRange getSpecifierRange(const char *startSpecifier, 8045 unsigned specifierLen); 8046 SourceLocation getLocationOfByte(const char *x); 8047 8048 const Expr *getDataArg(unsigned i) const; 8049 8050 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8051 const analyze_format_string::ConversionSpecifier &CS, 8052 const char *startSpecifier, unsigned specifierLen, 8053 unsigned argIndex); 8054 8055 template <typename Range> 8056 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8057 bool IsStringLocation, Range StringRange, 8058 ArrayRef<FixItHint> Fixit = None); 8059 }; 8060 8061 } // namespace 8062 8063 SourceRange CheckFormatHandler::getFormatStringRange() { 8064 return OrigFormatExpr->getSourceRange(); 8065 } 8066 8067 CharSourceRange CheckFormatHandler:: 8068 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8069 SourceLocation Start = getLocationOfByte(startSpecifier); 8070 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8071 8072 // Advance the end SourceLocation by one due to half-open ranges. 8073 End = End.getLocWithOffset(1); 8074 8075 return CharSourceRange::getCharRange(Start, End); 8076 } 8077 8078 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8079 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8080 S.getLangOpts(), S.Context.getTargetInfo()); 8081 } 8082 8083 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8084 unsigned specifierLen){ 8085 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8086 getLocationOfByte(startSpecifier), 8087 /*IsStringLocation*/true, 8088 getSpecifierRange(startSpecifier, specifierLen)); 8089 } 8090 8091 void CheckFormatHandler::HandleInvalidLengthModifier( 8092 const analyze_format_string::FormatSpecifier &FS, 8093 const analyze_format_string::ConversionSpecifier &CS, 8094 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8095 using namespace analyze_format_string; 8096 8097 const LengthModifier &LM = FS.getLengthModifier(); 8098 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8099 8100 // See if we know how to fix this length modifier. 8101 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8102 if (FixedLM) { 8103 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8104 getLocationOfByte(LM.getStart()), 8105 /*IsStringLocation*/true, 8106 getSpecifierRange(startSpecifier, specifierLen)); 8107 8108 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8109 << FixedLM->toString() 8110 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8111 8112 } else { 8113 FixItHint Hint; 8114 if (DiagID == diag::warn_format_nonsensical_length) 8115 Hint = FixItHint::CreateRemoval(LMRange); 8116 8117 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8118 getLocationOfByte(LM.getStart()), 8119 /*IsStringLocation*/true, 8120 getSpecifierRange(startSpecifier, specifierLen), 8121 Hint); 8122 } 8123 } 8124 8125 void CheckFormatHandler::HandleNonStandardLengthModifier( 8126 const analyze_format_string::FormatSpecifier &FS, 8127 const char *startSpecifier, unsigned specifierLen) { 8128 using namespace analyze_format_string; 8129 8130 const LengthModifier &LM = FS.getLengthModifier(); 8131 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8132 8133 // See if we know how to fix this length modifier. 8134 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8135 if (FixedLM) { 8136 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8137 << LM.toString() << 0, 8138 getLocationOfByte(LM.getStart()), 8139 /*IsStringLocation*/true, 8140 getSpecifierRange(startSpecifier, specifierLen)); 8141 8142 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8143 << FixedLM->toString() 8144 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8145 8146 } else { 8147 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8148 << LM.toString() << 0, 8149 getLocationOfByte(LM.getStart()), 8150 /*IsStringLocation*/true, 8151 getSpecifierRange(startSpecifier, specifierLen)); 8152 } 8153 } 8154 8155 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8156 const analyze_format_string::ConversionSpecifier &CS, 8157 const char *startSpecifier, unsigned specifierLen) { 8158 using namespace analyze_format_string; 8159 8160 // See if we know how to fix this conversion specifier. 8161 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8162 if (FixedCS) { 8163 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8164 << CS.toString() << /*conversion specifier*/1, 8165 getLocationOfByte(CS.getStart()), 8166 /*IsStringLocation*/true, 8167 getSpecifierRange(startSpecifier, specifierLen)); 8168 8169 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8170 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8171 << FixedCS->toString() 8172 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8173 } else { 8174 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8175 << CS.toString() << /*conversion specifier*/1, 8176 getLocationOfByte(CS.getStart()), 8177 /*IsStringLocation*/true, 8178 getSpecifierRange(startSpecifier, specifierLen)); 8179 } 8180 } 8181 8182 void CheckFormatHandler::HandlePosition(const char *startPos, 8183 unsigned posLen) { 8184 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8185 getLocationOfByte(startPos), 8186 /*IsStringLocation*/true, 8187 getSpecifierRange(startPos, posLen)); 8188 } 8189 8190 void 8191 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8192 analyze_format_string::PositionContext p) { 8193 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8194 << (unsigned) p, 8195 getLocationOfByte(startPos), /*IsStringLocation*/true, 8196 getSpecifierRange(startPos, posLen)); 8197 } 8198 8199 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8200 unsigned posLen) { 8201 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8202 getLocationOfByte(startPos), 8203 /*IsStringLocation*/true, 8204 getSpecifierRange(startPos, posLen)); 8205 } 8206 8207 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8208 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8209 // The presence of a null character is likely an error. 8210 EmitFormatDiagnostic( 8211 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8212 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8213 getFormatStringRange()); 8214 } 8215 } 8216 8217 // Note that this may return NULL if there was an error parsing or building 8218 // one of the argument expressions. 8219 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8220 return Args[FirstDataArg + i]; 8221 } 8222 8223 void CheckFormatHandler::DoneProcessing() { 8224 // Does the number of data arguments exceed the number of 8225 // format conversions in the format string? 8226 if (!HasVAListArg) { 8227 // Find any arguments that weren't covered. 8228 CoveredArgs.flip(); 8229 signed notCoveredArg = CoveredArgs.find_first(); 8230 if (notCoveredArg >= 0) { 8231 assert((unsigned)notCoveredArg < NumDataArgs); 8232 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8233 } else { 8234 UncoveredArg.setAllCovered(); 8235 } 8236 } 8237 } 8238 8239 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8240 const Expr *ArgExpr) { 8241 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8242 "Invalid state"); 8243 8244 if (!ArgExpr) 8245 return; 8246 8247 SourceLocation Loc = ArgExpr->getBeginLoc(); 8248 8249 if (S.getSourceManager().isInSystemMacro(Loc)) 8250 return; 8251 8252 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8253 for (auto E : DiagnosticExprs) 8254 PDiag << E->getSourceRange(); 8255 8256 CheckFormatHandler::EmitFormatDiagnostic( 8257 S, IsFunctionCall, DiagnosticExprs[0], 8258 PDiag, Loc, /*IsStringLocation*/false, 8259 DiagnosticExprs[0]->getSourceRange()); 8260 } 8261 8262 bool 8263 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8264 SourceLocation Loc, 8265 const char *startSpec, 8266 unsigned specifierLen, 8267 const char *csStart, 8268 unsigned csLen) { 8269 bool keepGoing = true; 8270 if (argIndex < NumDataArgs) { 8271 // Consider the argument coverered, even though the specifier doesn't 8272 // make sense. 8273 CoveredArgs.set(argIndex); 8274 } 8275 else { 8276 // If argIndex exceeds the number of data arguments we 8277 // don't issue a warning because that is just a cascade of warnings (and 8278 // they may have intended '%%' anyway). We don't want to continue processing 8279 // the format string after this point, however, as we will like just get 8280 // gibberish when trying to match arguments. 8281 keepGoing = false; 8282 } 8283 8284 StringRef Specifier(csStart, csLen); 8285 8286 // If the specifier in non-printable, it could be the first byte of a UTF-8 8287 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8288 // hex value. 8289 std::string CodePointStr; 8290 if (!llvm::sys::locale::isPrint(*csStart)) { 8291 llvm::UTF32 CodePoint; 8292 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8293 const llvm::UTF8 *E = 8294 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8295 llvm::ConversionResult Result = 8296 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8297 8298 if (Result != llvm::conversionOK) { 8299 unsigned char FirstChar = *csStart; 8300 CodePoint = (llvm::UTF32)FirstChar; 8301 } 8302 8303 llvm::raw_string_ostream OS(CodePointStr); 8304 if (CodePoint < 256) 8305 OS << "\\x" << llvm::format("%02x", CodePoint); 8306 else if (CodePoint <= 0xFFFF) 8307 OS << "\\u" << llvm::format("%04x", CodePoint); 8308 else 8309 OS << "\\U" << llvm::format("%08x", CodePoint); 8310 OS.flush(); 8311 Specifier = CodePointStr; 8312 } 8313 8314 EmitFormatDiagnostic( 8315 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8316 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8317 8318 return keepGoing; 8319 } 8320 8321 void 8322 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8323 const char *startSpec, 8324 unsigned specifierLen) { 8325 EmitFormatDiagnostic( 8326 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8327 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8328 } 8329 8330 bool 8331 CheckFormatHandler::CheckNumArgs( 8332 const analyze_format_string::FormatSpecifier &FS, 8333 const analyze_format_string::ConversionSpecifier &CS, 8334 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8335 8336 if (argIndex >= NumDataArgs) { 8337 PartialDiagnostic PDiag = FS.usesPositionalArg() 8338 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8339 << (argIndex+1) << NumDataArgs) 8340 : S.PDiag(diag::warn_printf_insufficient_data_args); 8341 EmitFormatDiagnostic( 8342 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8343 getSpecifierRange(startSpecifier, specifierLen)); 8344 8345 // Since more arguments than conversion tokens are given, by extension 8346 // all arguments are covered, so mark this as so. 8347 UncoveredArg.setAllCovered(); 8348 return false; 8349 } 8350 return true; 8351 } 8352 8353 template<typename Range> 8354 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8355 SourceLocation Loc, 8356 bool IsStringLocation, 8357 Range StringRange, 8358 ArrayRef<FixItHint> FixIt) { 8359 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8360 Loc, IsStringLocation, StringRange, FixIt); 8361 } 8362 8363 /// If the format string is not within the function call, emit a note 8364 /// so that the function call and string are in diagnostic messages. 8365 /// 8366 /// \param InFunctionCall if true, the format string is within the function 8367 /// call and only one diagnostic message will be produced. Otherwise, an 8368 /// extra note will be emitted pointing to location of the format string. 8369 /// 8370 /// \param ArgumentExpr the expression that is passed as the format string 8371 /// argument in the function call. Used for getting locations when two 8372 /// diagnostics are emitted. 8373 /// 8374 /// \param PDiag the callee should already have provided any strings for the 8375 /// diagnostic message. This function only adds locations and fixits 8376 /// to diagnostics. 8377 /// 8378 /// \param Loc primary location for diagnostic. If two diagnostics are 8379 /// required, one will be at Loc and a new SourceLocation will be created for 8380 /// the other one. 8381 /// 8382 /// \param IsStringLocation if true, Loc points to the format string should be 8383 /// used for the note. Otherwise, Loc points to the argument list and will 8384 /// be used with PDiag. 8385 /// 8386 /// \param StringRange some or all of the string to highlight. This is 8387 /// templated so it can accept either a CharSourceRange or a SourceRange. 8388 /// 8389 /// \param FixIt optional fix it hint for the format string. 8390 template <typename Range> 8391 void CheckFormatHandler::EmitFormatDiagnostic( 8392 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8393 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8394 Range StringRange, ArrayRef<FixItHint> FixIt) { 8395 if (InFunctionCall) { 8396 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8397 D << StringRange; 8398 D << FixIt; 8399 } else { 8400 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8401 << ArgumentExpr->getSourceRange(); 8402 8403 const Sema::SemaDiagnosticBuilder &Note = 8404 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8405 diag::note_format_string_defined); 8406 8407 Note << StringRange; 8408 Note << FixIt; 8409 } 8410 } 8411 8412 //===--- CHECK: Printf format string checking ------------------------------===// 8413 8414 namespace { 8415 8416 class CheckPrintfHandler : public CheckFormatHandler { 8417 public: 8418 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8419 const Expr *origFormatExpr, 8420 const Sema::FormatStringType type, unsigned firstDataArg, 8421 unsigned numDataArgs, bool isObjC, const char *beg, 8422 bool hasVAListArg, ArrayRef<const Expr *> Args, 8423 unsigned formatIdx, bool inFunctionCall, 8424 Sema::VariadicCallType CallType, 8425 llvm::SmallBitVector &CheckedVarArgs, 8426 UncoveredArgHandler &UncoveredArg) 8427 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8428 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8429 inFunctionCall, CallType, CheckedVarArgs, 8430 UncoveredArg) {} 8431 8432 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8433 8434 /// Returns true if '%@' specifiers are allowed in the format string. 8435 bool allowsObjCArg() const { 8436 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8437 FSType == Sema::FST_OSTrace; 8438 } 8439 8440 bool HandleInvalidPrintfConversionSpecifier( 8441 const analyze_printf::PrintfSpecifier &FS, 8442 const char *startSpecifier, 8443 unsigned specifierLen) override; 8444 8445 void handleInvalidMaskType(StringRef MaskType) override; 8446 8447 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8448 const char *startSpecifier, 8449 unsigned specifierLen) override; 8450 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8451 const char *StartSpecifier, 8452 unsigned SpecifierLen, 8453 const Expr *E); 8454 8455 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8456 const char *startSpecifier, unsigned specifierLen); 8457 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8458 const analyze_printf::OptionalAmount &Amt, 8459 unsigned type, 8460 const char *startSpecifier, unsigned specifierLen); 8461 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8462 const analyze_printf::OptionalFlag &flag, 8463 const char *startSpecifier, unsigned specifierLen); 8464 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8465 const analyze_printf::OptionalFlag &ignoredFlag, 8466 const analyze_printf::OptionalFlag &flag, 8467 const char *startSpecifier, unsigned specifierLen); 8468 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8469 const Expr *E); 8470 8471 void HandleEmptyObjCModifierFlag(const char *startFlag, 8472 unsigned flagLen) override; 8473 8474 void HandleInvalidObjCModifierFlag(const char *startFlag, 8475 unsigned flagLen) override; 8476 8477 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8478 const char *flagsEnd, 8479 const char *conversionPosition) 8480 override; 8481 }; 8482 8483 } // namespace 8484 8485 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8486 const analyze_printf::PrintfSpecifier &FS, 8487 const char *startSpecifier, 8488 unsigned specifierLen) { 8489 const analyze_printf::PrintfConversionSpecifier &CS = 8490 FS.getConversionSpecifier(); 8491 8492 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8493 getLocationOfByte(CS.getStart()), 8494 startSpecifier, specifierLen, 8495 CS.getStart(), CS.getLength()); 8496 } 8497 8498 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8499 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8500 } 8501 8502 bool CheckPrintfHandler::HandleAmount( 8503 const analyze_format_string::OptionalAmount &Amt, 8504 unsigned k, const char *startSpecifier, 8505 unsigned specifierLen) { 8506 if (Amt.hasDataArgument()) { 8507 if (!HasVAListArg) { 8508 unsigned argIndex = Amt.getArgIndex(); 8509 if (argIndex >= NumDataArgs) { 8510 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8511 << k, 8512 getLocationOfByte(Amt.getStart()), 8513 /*IsStringLocation*/true, 8514 getSpecifierRange(startSpecifier, specifierLen)); 8515 // Don't do any more checking. We will just emit 8516 // spurious errors. 8517 return false; 8518 } 8519 8520 // Type check the data argument. It should be an 'int'. 8521 // Although not in conformance with C99, we also allow the argument to be 8522 // an 'unsigned int' as that is a reasonably safe case. GCC also 8523 // doesn't emit a warning for that case. 8524 CoveredArgs.set(argIndex); 8525 const Expr *Arg = getDataArg(argIndex); 8526 if (!Arg) 8527 return false; 8528 8529 QualType T = Arg->getType(); 8530 8531 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8532 assert(AT.isValid()); 8533 8534 if (!AT.matchesType(S.Context, T)) { 8535 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8536 << k << AT.getRepresentativeTypeName(S.Context) 8537 << T << Arg->getSourceRange(), 8538 getLocationOfByte(Amt.getStart()), 8539 /*IsStringLocation*/true, 8540 getSpecifierRange(startSpecifier, specifierLen)); 8541 // Don't do any more checking. We will just emit 8542 // spurious errors. 8543 return false; 8544 } 8545 } 8546 } 8547 return true; 8548 } 8549 8550 void CheckPrintfHandler::HandleInvalidAmount( 8551 const analyze_printf::PrintfSpecifier &FS, 8552 const analyze_printf::OptionalAmount &Amt, 8553 unsigned type, 8554 const char *startSpecifier, 8555 unsigned specifierLen) { 8556 const analyze_printf::PrintfConversionSpecifier &CS = 8557 FS.getConversionSpecifier(); 8558 8559 FixItHint fixit = 8560 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8561 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8562 Amt.getConstantLength())) 8563 : FixItHint(); 8564 8565 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8566 << type << CS.toString(), 8567 getLocationOfByte(Amt.getStart()), 8568 /*IsStringLocation*/true, 8569 getSpecifierRange(startSpecifier, specifierLen), 8570 fixit); 8571 } 8572 8573 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8574 const analyze_printf::OptionalFlag &flag, 8575 const char *startSpecifier, 8576 unsigned specifierLen) { 8577 // Warn about pointless flag with a fixit removal. 8578 const analyze_printf::PrintfConversionSpecifier &CS = 8579 FS.getConversionSpecifier(); 8580 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8581 << flag.toString() << CS.toString(), 8582 getLocationOfByte(flag.getPosition()), 8583 /*IsStringLocation*/true, 8584 getSpecifierRange(startSpecifier, specifierLen), 8585 FixItHint::CreateRemoval( 8586 getSpecifierRange(flag.getPosition(), 1))); 8587 } 8588 8589 void CheckPrintfHandler::HandleIgnoredFlag( 8590 const analyze_printf::PrintfSpecifier &FS, 8591 const analyze_printf::OptionalFlag &ignoredFlag, 8592 const analyze_printf::OptionalFlag &flag, 8593 const char *startSpecifier, 8594 unsigned specifierLen) { 8595 // Warn about ignored flag with a fixit removal. 8596 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8597 << ignoredFlag.toString() << flag.toString(), 8598 getLocationOfByte(ignoredFlag.getPosition()), 8599 /*IsStringLocation*/true, 8600 getSpecifierRange(startSpecifier, specifierLen), 8601 FixItHint::CreateRemoval( 8602 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8603 } 8604 8605 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8606 unsigned flagLen) { 8607 // Warn about an empty flag. 8608 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8609 getLocationOfByte(startFlag), 8610 /*IsStringLocation*/true, 8611 getSpecifierRange(startFlag, flagLen)); 8612 } 8613 8614 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8615 unsigned flagLen) { 8616 // Warn about an invalid flag. 8617 auto Range = getSpecifierRange(startFlag, flagLen); 8618 StringRef flag(startFlag, flagLen); 8619 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8620 getLocationOfByte(startFlag), 8621 /*IsStringLocation*/true, 8622 Range, FixItHint::CreateRemoval(Range)); 8623 } 8624 8625 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8626 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8627 // Warn about using '[...]' without a '@' conversion. 8628 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8629 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8630 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8631 getLocationOfByte(conversionPosition), 8632 /*IsStringLocation*/true, 8633 Range, FixItHint::CreateRemoval(Range)); 8634 } 8635 8636 // Determines if the specified is a C++ class or struct containing 8637 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8638 // "c_str()"). 8639 template<typename MemberKind> 8640 static llvm::SmallPtrSet<MemberKind*, 1> 8641 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8642 const RecordType *RT = Ty->getAs<RecordType>(); 8643 llvm::SmallPtrSet<MemberKind*, 1> Results; 8644 8645 if (!RT) 8646 return Results; 8647 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8648 if (!RD || !RD->getDefinition()) 8649 return Results; 8650 8651 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8652 Sema::LookupMemberName); 8653 R.suppressDiagnostics(); 8654 8655 // We just need to include all members of the right kind turned up by the 8656 // filter, at this point. 8657 if (S.LookupQualifiedName(R, RT->getDecl())) 8658 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8659 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8660 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8661 Results.insert(FK); 8662 } 8663 return Results; 8664 } 8665 8666 /// Check if we could call '.c_str()' on an object. 8667 /// 8668 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8669 /// allow the call, or if it would be ambiguous). 8670 bool Sema::hasCStrMethod(const Expr *E) { 8671 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8672 8673 MethodSet Results = 8674 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8675 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8676 MI != ME; ++MI) 8677 if ((*MI)->getMinRequiredArguments() == 0) 8678 return true; 8679 return false; 8680 } 8681 8682 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8683 // better diagnostic if so. AT is assumed to be valid. 8684 // Returns true when a c_str() conversion method is found. 8685 bool CheckPrintfHandler::checkForCStrMembers( 8686 const analyze_printf::ArgType &AT, const Expr *E) { 8687 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8688 8689 MethodSet Results = 8690 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8691 8692 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8693 MI != ME; ++MI) { 8694 const CXXMethodDecl *Method = *MI; 8695 if (Method->getMinRequiredArguments() == 0 && 8696 AT.matchesType(S.Context, Method->getReturnType())) { 8697 // FIXME: Suggest parens if the expression needs them. 8698 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8699 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8700 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8701 return true; 8702 } 8703 } 8704 8705 return false; 8706 } 8707 8708 bool 8709 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8710 &FS, 8711 const char *startSpecifier, 8712 unsigned specifierLen) { 8713 using namespace analyze_format_string; 8714 using namespace analyze_printf; 8715 8716 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8717 8718 if (FS.consumesDataArgument()) { 8719 if (atFirstArg) { 8720 atFirstArg = false; 8721 usesPositionalArgs = FS.usesPositionalArg(); 8722 } 8723 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8724 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8725 startSpecifier, specifierLen); 8726 return false; 8727 } 8728 } 8729 8730 // First check if the field width, precision, and conversion specifier 8731 // have matching data arguments. 8732 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8733 startSpecifier, specifierLen)) { 8734 return false; 8735 } 8736 8737 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8738 startSpecifier, specifierLen)) { 8739 return false; 8740 } 8741 8742 if (!CS.consumesDataArgument()) { 8743 // FIXME: Technically specifying a precision or field width here 8744 // makes no sense. Worth issuing a warning at some point. 8745 return true; 8746 } 8747 8748 // Consume the argument. 8749 unsigned argIndex = FS.getArgIndex(); 8750 if (argIndex < NumDataArgs) { 8751 // The check to see if the argIndex is valid will come later. 8752 // We set the bit here because we may exit early from this 8753 // function if we encounter some other error. 8754 CoveredArgs.set(argIndex); 8755 } 8756 8757 // FreeBSD kernel extensions. 8758 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8759 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8760 // We need at least two arguments. 8761 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8762 return false; 8763 8764 // Claim the second argument. 8765 CoveredArgs.set(argIndex + 1); 8766 8767 // Type check the first argument (int for %b, pointer for %D) 8768 const Expr *Ex = getDataArg(argIndex); 8769 const analyze_printf::ArgType &AT = 8770 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8771 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8772 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8773 EmitFormatDiagnostic( 8774 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8775 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8776 << false << Ex->getSourceRange(), 8777 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8778 getSpecifierRange(startSpecifier, specifierLen)); 8779 8780 // Type check the second argument (char * for both %b and %D) 8781 Ex = getDataArg(argIndex + 1); 8782 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8783 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8784 EmitFormatDiagnostic( 8785 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8786 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8787 << false << Ex->getSourceRange(), 8788 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8789 getSpecifierRange(startSpecifier, specifierLen)); 8790 8791 return true; 8792 } 8793 8794 // Check for using an Objective-C specific conversion specifier 8795 // in a non-ObjC literal. 8796 if (!allowsObjCArg() && CS.isObjCArg()) { 8797 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8798 specifierLen); 8799 } 8800 8801 // %P can only be used with os_log. 8802 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8803 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8804 specifierLen); 8805 } 8806 8807 // %n is not allowed with os_log. 8808 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8809 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8810 getLocationOfByte(CS.getStart()), 8811 /*IsStringLocation*/ false, 8812 getSpecifierRange(startSpecifier, specifierLen)); 8813 8814 return true; 8815 } 8816 8817 // Only scalars are allowed for os_trace. 8818 if (FSType == Sema::FST_OSTrace && 8819 (CS.getKind() == ConversionSpecifier::PArg || 8820 CS.getKind() == ConversionSpecifier::sArg || 8821 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8822 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8823 specifierLen); 8824 } 8825 8826 // Check for use of public/private annotation outside of os_log(). 8827 if (FSType != Sema::FST_OSLog) { 8828 if (FS.isPublic().isSet()) { 8829 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8830 << "public", 8831 getLocationOfByte(FS.isPublic().getPosition()), 8832 /*IsStringLocation*/ false, 8833 getSpecifierRange(startSpecifier, specifierLen)); 8834 } 8835 if (FS.isPrivate().isSet()) { 8836 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8837 << "private", 8838 getLocationOfByte(FS.isPrivate().getPosition()), 8839 /*IsStringLocation*/ false, 8840 getSpecifierRange(startSpecifier, specifierLen)); 8841 } 8842 } 8843 8844 // Check for invalid use of field width 8845 if (!FS.hasValidFieldWidth()) { 8846 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8847 startSpecifier, specifierLen); 8848 } 8849 8850 // Check for invalid use of precision 8851 if (!FS.hasValidPrecision()) { 8852 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8853 startSpecifier, specifierLen); 8854 } 8855 8856 // Precision is mandatory for %P specifier. 8857 if (CS.getKind() == ConversionSpecifier::PArg && 8858 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8859 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8860 getLocationOfByte(startSpecifier), 8861 /*IsStringLocation*/ false, 8862 getSpecifierRange(startSpecifier, specifierLen)); 8863 } 8864 8865 // Check each flag does not conflict with any other component. 8866 if (!FS.hasValidThousandsGroupingPrefix()) 8867 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8868 if (!FS.hasValidLeadingZeros()) 8869 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8870 if (!FS.hasValidPlusPrefix()) 8871 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8872 if (!FS.hasValidSpacePrefix()) 8873 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8874 if (!FS.hasValidAlternativeForm()) 8875 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8876 if (!FS.hasValidLeftJustified()) 8877 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8878 8879 // Check that flags are not ignored by another flag 8880 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8881 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8882 startSpecifier, specifierLen); 8883 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8884 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8885 startSpecifier, specifierLen); 8886 8887 // Check the length modifier is valid with the given conversion specifier. 8888 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8889 S.getLangOpts())) 8890 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8891 diag::warn_format_nonsensical_length); 8892 else if (!FS.hasStandardLengthModifier()) 8893 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8894 else if (!FS.hasStandardLengthConversionCombination()) 8895 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8896 diag::warn_format_non_standard_conversion_spec); 8897 8898 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8899 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8900 8901 // The remaining checks depend on the data arguments. 8902 if (HasVAListArg) 8903 return true; 8904 8905 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8906 return false; 8907 8908 const Expr *Arg = getDataArg(argIndex); 8909 if (!Arg) 8910 return true; 8911 8912 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8913 } 8914 8915 static bool requiresParensToAddCast(const Expr *E) { 8916 // FIXME: We should have a general way to reason about operator 8917 // precedence and whether parens are actually needed here. 8918 // Take care of a few common cases where they aren't. 8919 const Expr *Inside = E->IgnoreImpCasts(); 8920 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8921 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8922 8923 switch (Inside->getStmtClass()) { 8924 case Stmt::ArraySubscriptExprClass: 8925 case Stmt::CallExprClass: 8926 case Stmt::CharacterLiteralClass: 8927 case Stmt::CXXBoolLiteralExprClass: 8928 case Stmt::DeclRefExprClass: 8929 case Stmt::FloatingLiteralClass: 8930 case Stmt::IntegerLiteralClass: 8931 case Stmt::MemberExprClass: 8932 case Stmt::ObjCArrayLiteralClass: 8933 case Stmt::ObjCBoolLiteralExprClass: 8934 case Stmt::ObjCBoxedExprClass: 8935 case Stmt::ObjCDictionaryLiteralClass: 8936 case Stmt::ObjCEncodeExprClass: 8937 case Stmt::ObjCIvarRefExprClass: 8938 case Stmt::ObjCMessageExprClass: 8939 case Stmt::ObjCPropertyRefExprClass: 8940 case Stmt::ObjCStringLiteralClass: 8941 case Stmt::ObjCSubscriptRefExprClass: 8942 case Stmt::ParenExprClass: 8943 case Stmt::StringLiteralClass: 8944 case Stmt::UnaryOperatorClass: 8945 return false; 8946 default: 8947 return true; 8948 } 8949 } 8950 8951 static std::pair<QualType, StringRef> 8952 shouldNotPrintDirectly(const ASTContext &Context, 8953 QualType IntendedTy, 8954 const Expr *E) { 8955 // Use a 'while' to peel off layers of typedefs. 8956 QualType TyTy = IntendedTy; 8957 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8958 StringRef Name = UserTy->getDecl()->getName(); 8959 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8960 .Case("CFIndex", Context.getNSIntegerType()) 8961 .Case("NSInteger", Context.getNSIntegerType()) 8962 .Case("NSUInteger", Context.getNSUIntegerType()) 8963 .Case("SInt32", Context.IntTy) 8964 .Case("UInt32", Context.UnsignedIntTy) 8965 .Default(QualType()); 8966 8967 if (!CastTy.isNull()) 8968 return std::make_pair(CastTy, Name); 8969 8970 TyTy = UserTy->desugar(); 8971 } 8972 8973 // Strip parens if necessary. 8974 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8975 return shouldNotPrintDirectly(Context, 8976 PE->getSubExpr()->getType(), 8977 PE->getSubExpr()); 8978 8979 // If this is a conditional expression, then its result type is constructed 8980 // via usual arithmetic conversions and thus there might be no necessary 8981 // typedef sugar there. Recurse to operands to check for NSInteger & 8982 // Co. usage condition. 8983 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8984 QualType TrueTy, FalseTy; 8985 StringRef TrueName, FalseName; 8986 8987 std::tie(TrueTy, TrueName) = 8988 shouldNotPrintDirectly(Context, 8989 CO->getTrueExpr()->getType(), 8990 CO->getTrueExpr()); 8991 std::tie(FalseTy, FalseName) = 8992 shouldNotPrintDirectly(Context, 8993 CO->getFalseExpr()->getType(), 8994 CO->getFalseExpr()); 8995 8996 if (TrueTy == FalseTy) 8997 return std::make_pair(TrueTy, TrueName); 8998 else if (TrueTy.isNull()) 8999 return std::make_pair(FalseTy, FalseName); 9000 else if (FalseTy.isNull()) 9001 return std::make_pair(TrueTy, TrueName); 9002 } 9003 9004 return std::make_pair(QualType(), StringRef()); 9005 } 9006 9007 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9008 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9009 /// type do not count. 9010 static bool 9011 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9012 QualType From = ICE->getSubExpr()->getType(); 9013 QualType To = ICE->getType(); 9014 // It's an integer promotion if the destination type is the promoted 9015 // source type. 9016 if (ICE->getCastKind() == CK_IntegralCast && 9017 From->isPromotableIntegerType() && 9018 S.Context.getPromotedIntegerType(From) == To) 9019 return true; 9020 // Look through vector types, since we do default argument promotion for 9021 // those in OpenCL. 9022 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9023 From = VecTy->getElementType(); 9024 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9025 To = VecTy->getElementType(); 9026 // It's a floating promotion if the source type is a lower rank. 9027 return ICE->getCastKind() == CK_FloatingCast && 9028 S.Context.getFloatingTypeOrder(From, To) < 0; 9029 } 9030 9031 bool 9032 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9033 const char *StartSpecifier, 9034 unsigned SpecifierLen, 9035 const Expr *E) { 9036 using namespace analyze_format_string; 9037 using namespace analyze_printf; 9038 9039 // Now type check the data expression that matches the 9040 // format specifier. 9041 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9042 if (!AT.isValid()) 9043 return true; 9044 9045 QualType ExprTy = E->getType(); 9046 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9047 ExprTy = TET->getUnderlyingExpr()->getType(); 9048 } 9049 9050 // Diagnose attempts to print a boolean value as a character. Unlike other 9051 // -Wformat diagnostics, this is fine from a type perspective, but it still 9052 // doesn't make sense. 9053 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9054 E->isKnownToHaveBooleanValue()) { 9055 const CharSourceRange &CSR = 9056 getSpecifierRange(StartSpecifier, SpecifierLen); 9057 SmallString<4> FSString; 9058 llvm::raw_svector_ostream os(FSString); 9059 FS.toString(os); 9060 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9061 << FSString, 9062 E->getExprLoc(), false, CSR); 9063 return true; 9064 } 9065 9066 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9067 if (Match == analyze_printf::ArgType::Match) 9068 return true; 9069 9070 // Look through argument promotions for our error message's reported type. 9071 // This includes the integral and floating promotions, but excludes array 9072 // and function pointer decay (seeing that an argument intended to be a 9073 // string has type 'char [6]' is probably more confusing than 'char *') and 9074 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9075 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9076 if (isArithmeticArgumentPromotion(S, ICE)) { 9077 E = ICE->getSubExpr(); 9078 ExprTy = E->getType(); 9079 9080 // Check if we didn't match because of an implicit cast from a 'char' 9081 // or 'short' to an 'int'. This is done because printf is a varargs 9082 // function. 9083 if (ICE->getType() == S.Context.IntTy || 9084 ICE->getType() == S.Context.UnsignedIntTy) { 9085 // All further checking is done on the subexpression 9086 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9087 AT.matchesType(S.Context, ExprTy); 9088 if (ImplicitMatch == analyze_printf::ArgType::Match) 9089 return true; 9090 if (ImplicitMatch == ArgType::NoMatchPedantic || 9091 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9092 Match = ImplicitMatch; 9093 } 9094 } 9095 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9096 // Special case for 'a', which has type 'int' in C. 9097 // Note, however, that we do /not/ want to treat multibyte constants like 9098 // 'MooV' as characters! This form is deprecated but still exists. In 9099 // addition, don't treat expressions as of type 'char' if one byte length 9100 // modifier is provided. 9101 if (ExprTy == S.Context.IntTy && 9102 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9103 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9104 ExprTy = S.Context.CharTy; 9105 } 9106 9107 // Look through enums to their underlying type. 9108 bool IsEnum = false; 9109 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9110 ExprTy = EnumTy->getDecl()->getIntegerType(); 9111 IsEnum = true; 9112 } 9113 9114 // %C in an Objective-C context prints a unichar, not a wchar_t. 9115 // If the argument is an integer of some kind, believe the %C and suggest 9116 // a cast instead of changing the conversion specifier. 9117 QualType IntendedTy = ExprTy; 9118 if (isObjCContext() && 9119 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9120 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9121 !ExprTy->isCharType()) { 9122 // 'unichar' is defined as a typedef of unsigned short, but we should 9123 // prefer using the typedef if it is visible. 9124 IntendedTy = S.Context.UnsignedShortTy; 9125 9126 // While we are here, check if the value is an IntegerLiteral that happens 9127 // to be within the valid range. 9128 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9129 const llvm::APInt &V = IL->getValue(); 9130 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9131 return true; 9132 } 9133 9134 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9135 Sema::LookupOrdinaryName); 9136 if (S.LookupName(Result, S.getCurScope())) { 9137 NamedDecl *ND = Result.getFoundDecl(); 9138 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9139 if (TD->getUnderlyingType() == IntendedTy) 9140 IntendedTy = S.Context.getTypedefType(TD); 9141 } 9142 } 9143 } 9144 9145 // Special-case some of Darwin's platform-independence types by suggesting 9146 // casts to primitive types that are known to be large enough. 9147 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9148 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9149 QualType CastTy; 9150 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9151 if (!CastTy.isNull()) { 9152 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9153 // (long in ASTContext). Only complain to pedants. 9154 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9155 (AT.isSizeT() || AT.isPtrdiffT()) && 9156 AT.matchesType(S.Context, CastTy)) 9157 Match = ArgType::NoMatchPedantic; 9158 IntendedTy = CastTy; 9159 ShouldNotPrintDirectly = true; 9160 } 9161 } 9162 9163 // We may be able to offer a FixItHint if it is a supported type. 9164 PrintfSpecifier fixedFS = FS; 9165 bool Success = 9166 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9167 9168 if (Success) { 9169 // Get the fix string from the fixed format specifier 9170 SmallString<16> buf; 9171 llvm::raw_svector_ostream os(buf); 9172 fixedFS.toString(os); 9173 9174 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9175 9176 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9177 unsigned Diag; 9178 switch (Match) { 9179 case ArgType::Match: llvm_unreachable("expected non-matching"); 9180 case ArgType::NoMatchPedantic: 9181 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9182 break; 9183 case ArgType::NoMatchTypeConfusion: 9184 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9185 break; 9186 case ArgType::NoMatch: 9187 Diag = diag::warn_format_conversion_argument_type_mismatch; 9188 break; 9189 } 9190 9191 // In this case, the specifier is wrong and should be changed to match 9192 // the argument. 9193 EmitFormatDiagnostic(S.PDiag(Diag) 9194 << AT.getRepresentativeTypeName(S.Context) 9195 << IntendedTy << IsEnum << E->getSourceRange(), 9196 E->getBeginLoc(), 9197 /*IsStringLocation*/ false, SpecRange, 9198 FixItHint::CreateReplacement(SpecRange, os.str())); 9199 } else { 9200 // The canonical type for formatting this value is different from the 9201 // actual type of the expression. (This occurs, for example, with Darwin's 9202 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9203 // should be printed as 'long' for 64-bit compatibility.) 9204 // Rather than emitting a normal format/argument mismatch, we want to 9205 // add a cast to the recommended type (and correct the format string 9206 // if necessary). 9207 SmallString<16> CastBuf; 9208 llvm::raw_svector_ostream CastFix(CastBuf); 9209 CastFix << "("; 9210 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9211 CastFix << ")"; 9212 9213 SmallVector<FixItHint,4> Hints; 9214 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9215 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9216 9217 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9218 // If there's already a cast present, just replace it. 9219 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9220 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9221 9222 } else if (!requiresParensToAddCast(E)) { 9223 // If the expression has high enough precedence, 9224 // just write the C-style cast. 9225 Hints.push_back( 9226 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9227 } else { 9228 // Otherwise, add parens around the expression as well as the cast. 9229 CastFix << "("; 9230 Hints.push_back( 9231 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9232 9233 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9234 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9235 } 9236 9237 if (ShouldNotPrintDirectly) { 9238 // The expression has a type that should not be printed directly. 9239 // We extract the name from the typedef because we don't want to show 9240 // the underlying type in the diagnostic. 9241 StringRef Name; 9242 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9243 Name = TypedefTy->getDecl()->getName(); 9244 else 9245 Name = CastTyName; 9246 unsigned Diag = Match == ArgType::NoMatchPedantic 9247 ? diag::warn_format_argument_needs_cast_pedantic 9248 : diag::warn_format_argument_needs_cast; 9249 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9250 << E->getSourceRange(), 9251 E->getBeginLoc(), /*IsStringLocation=*/false, 9252 SpecRange, Hints); 9253 } else { 9254 // In this case, the expression could be printed using a different 9255 // specifier, but we've decided that the specifier is probably correct 9256 // and we should cast instead. Just use the normal warning message. 9257 EmitFormatDiagnostic( 9258 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9259 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9260 << E->getSourceRange(), 9261 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9262 } 9263 } 9264 } else { 9265 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9266 SpecifierLen); 9267 // Since the warning for passing non-POD types to variadic functions 9268 // was deferred until now, we emit a warning for non-POD 9269 // arguments here. 9270 switch (S.isValidVarArgType(ExprTy)) { 9271 case Sema::VAK_Valid: 9272 case Sema::VAK_ValidInCXX11: { 9273 unsigned Diag; 9274 switch (Match) { 9275 case ArgType::Match: llvm_unreachable("expected non-matching"); 9276 case ArgType::NoMatchPedantic: 9277 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9278 break; 9279 case ArgType::NoMatchTypeConfusion: 9280 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9281 break; 9282 case ArgType::NoMatch: 9283 Diag = diag::warn_format_conversion_argument_type_mismatch; 9284 break; 9285 } 9286 9287 EmitFormatDiagnostic( 9288 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9289 << IsEnum << CSR << E->getSourceRange(), 9290 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9291 break; 9292 } 9293 case Sema::VAK_Undefined: 9294 case Sema::VAK_MSVCUndefined: 9295 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9296 << S.getLangOpts().CPlusPlus11 << ExprTy 9297 << CallType 9298 << AT.getRepresentativeTypeName(S.Context) << CSR 9299 << E->getSourceRange(), 9300 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9301 checkForCStrMembers(AT, E); 9302 break; 9303 9304 case Sema::VAK_Invalid: 9305 if (ExprTy->isObjCObjectType()) 9306 EmitFormatDiagnostic( 9307 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9308 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9309 << AT.getRepresentativeTypeName(S.Context) << CSR 9310 << E->getSourceRange(), 9311 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9312 else 9313 // FIXME: If this is an initializer list, suggest removing the braces 9314 // or inserting a cast to the target type. 9315 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9316 << isa<InitListExpr>(E) << ExprTy << CallType 9317 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9318 break; 9319 } 9320 9321 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9322 "format string specifier index out of range"); 9323 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9324 } 9325 9326 return true; 9327 } 9328 9329 //===--- CHECK: Scanf format string checking ------------------------------===// 9330 9331 namespace { 9332 9333 class CheckScanfHandler : public CheckFormatHandler { 9334 public: 9335 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9336 const Expr *origFormatExpr, Sema::FormatStringType type, 9337 unsigned firstDataArg, unsigned numDataArgs, 9338 const char *beg, bool hasVAListArg, 9339 ArrayRef<const Expr *> Args, unsigned formatIdx, 9340 bool inFunctionCall, Sema::VariadicCallType CallType, 9341 llvm::SmallBitVector &CheckedVarArgs, 9342 UncoveredArgHandler &UncoveredArg) 9343 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9344 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9345 inFunctionCall, CallType, CheckedVarArgs, 9346 UncoveredArg) {} 9347 9348 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9349 const char *startSpecifier, 9350 unsigned specifierLen) override; 9351 9352 bool HandleInvalidScanfConversionSpecifier( 9353 const analyze_scanf::ScanfSpecifier &FS, 9354 const char *startSpecifier, 9355 unsigned specifierLen) override; 9356 9357 void HandleIncompleteScanList(const char *start, const char *end) override; 9358 }; 9359 9360 } // namespace 9361 9362 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9363 const char *end) { 9364 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9365 getLocationOfByte(end), /*IsStringLocation*/true, 9366 getSpecifierRange(start, end - start)); 9367 } 9368 9369 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9370 const analyze_scanf::ScanfSpecifier &FS, 9371 const char *startSpecifier, 9372 unsigned specifierLen) { 9373 const analyze_scanf::ScanfConversionSpecifier &CS = 9374 FS.getConversionSpecifier(); 9375 9376 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9377 getLocationOfByte(CS.getStart()), 9378 startSpecifier, specifierLen, 9379 CS.getStart(), CS.getLength()); 9380 } 9381 9382 bool CheckScanfHandler::HandleScanfSpecifier( 9383 const analyze_scanf::ScanfSpecifier &FS, 9384 const char *startSpecifier, 9385 unsigned specifierLen) { 9386 using namespace analyze_scanf; 9387 using namespace analyze_format_string; 9388 9389 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9390 9391 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9392 // be used to decide if we are using positional arguments consistently. 9393 if (FS.consumesDataArgument()) { 9394 if (atFirstArg) { 9395 atFirstArg = false; 9396 usesPositionalArgs = FS.usesPositionalArg(); 9397 } 9398 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9399 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9400 startSpecifier, specifierLen); 9401 return false; 9402 } 9403 } 9404 9405 // Check if the field with is non-zero. 9406 const OptionalAmount &Amt = FS.getFieldWidth(); 9407 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9408 if (Amt.getConstantAmount() == 0) { 9409 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9410 Amt.getConstantLength()); 9411 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9412 getLocationOfByte(Amt.getStart()), 9413 /*IsStringLocation*/true, R, 9414 FixItHint::CreateRemoval(R)); 9415 } 9416 } 9417 9418 if (!FS.consumesDataArgument()) { 9419 // FIXME: Technically specifying a precision or field width here 9420 // makes no sense. Worth issuing a warning at some point. 9421 return true; 9422 } 9423 9424 // Consume the argument. 9425 unsigned argIndex = FS.getArgIndex(); 9426 if (argIndex < NumDataArgs) { 9427 // The check to see if the argIndex is valid will come later. 9428 // We set the bit here because we may exit early from this 9429 // function if we encounter some other error. 9430 CoveredArgs.set(argIndex); 9431 } 9432 9433 // Check the length modifier is valid with the given conversion specifier. 9434 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9435 S.getLangOpts())) 9436 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9437 diag::warn_format_nonsensical_length); 9438 else if (!FS.hasStandardLengthModifier()) 9439 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9440 else if (!FS.hasStandardLengthConversionCombination()) 9441 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9442 diag::warn_format_non_standard_conversion_spec); 9443 9444 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9445 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9446 9447 // The remaining checks depend on the data arguments. 9448 if (HasVAListArg) 9449 return true; 9450 9451 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9452 return false; 9453 9454 // Check that the argument type matches the format specifier. 9455 const Expr *Ex = getDataArg(argIndex); 9456 if (!Ex) 9457 return true; 9458 9459 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9460 9461 if (!AT.isValid()) { 9462 return true; 9463 } 9464 9465 analyze_format_string::ArgType::MatchKind Match = 9466 AT.matchesType(S.Context, Ex->getType()); 9467 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9468 if (Match == analyze_format_string::ArgType::Match) 9469 return true; 9470 9471 ScanfSpecifier fixedFS = FS; 9472 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9473 S.getLangOpts(), S.Context); 9474 9475 unsigned Diag = 9476 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9477 : diag::warn_format_conversion_argument_type_mismatch; 9478 9479 if (Success) { 9480 // Get the fix string from the fixed format specifier. 9481 SmallString<128> buf; 9482 llvm::raw_svector_ostream os(buf); 9483 fixedFS.toString(os); 9484 9485 EmitFormatDiagnostic( 9486 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9487 << Ex->getType() << false << Ex->getSourceRange(), 9488 Ex->getBeginLoc(), 9489 /*IsStringLocation*/ false, 9490 getSpecifierRange(startSpecifier, specifierLen), 9491 FixItHint::CreateReplacement( 9492 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9493 } else { 9494 EmitFormatDiagnostic(S.PDiag(Diag) 9495 << AT.getRepresentativeTypeName(S.Context) 9496 << Ex->getType() << false << Ex->getSourceRange(), 9497 Ex->getBeginLoc(), 9498 /*IsStringLocation*/ false, 9499 getSpecifierRange(startSpecifier, specifierLen)); 9500 } 9501 9502 return true; 9503 } 9504 9505 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9506 const Expr *OrigFormatExpr, 9507 ArrayRef<const Expr *> Args, 9508 bool HasVAListArg, unsigned format_idx, 9509 unsigned firstDataArg, 9510 Sema::FormatStringType Type, 9511 bool inFunctionCall, 9512 Sema::VariadicCallType CallType, 9513 llvm::SmallBitVector &CheckedVarArgs, 9514 UncoveredArgHandler &UncoveredArg, 9515 bool IgnoreStringsWithoutSpecifiers) { 9516 // CHECK: is the format string a wide literal? 9517 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9518 CheckFormatHandler::EmitFormatDiagnostic( 9519 S, inFunctionCall, Args[format_idx], 9520 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9521 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9522 return; 9523 } 9524 9525 // Str - The format string. NOTE: this is NOT null-terminated! 9526 StringRef StrRef = FExpr->getString(); 9527 const char *Str = StrRef.data(); 9528 // Account for cases where the string literal is truncated in a declaration. 9529 const ConstantArrayType *T = 9530 S.Context.getAsConstantArrayType(FExpr->getType()); 9531 assert(T && "String literal not of constant array type!"); 9532 size_t TypeSize = T->getSize().getZExtValue(); 9533 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9534 const unsigned numDataArgs = Args.size() - firstDataArg; 9535 9536 if (IgnoreStringsWithoutSpecifiers && 9537 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9538 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9539 return; 9540 9541 // Emit a warning if the string literal is truncated and does not contain an 9542 // embedded null character. 9543 if (TypeSize <= StrRef.size() && 9544 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9545 CheckFormatHandler::EmitFormatDiagnostic( 9546 S, inFunctionCall, Args[format_idx], 9547 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9548 FExpr->getBeginLoc(), 9549 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9550 return; 9551 } 9552 9553 // CHECK: empty format string? 9554 if (StrLen == 0 && numDataArgs > 0) { 9555 CheckFormatHandler::EmitFormatDiagnostic( 9556 S, inFunctionCall, Args[format_idx], 9557 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9558 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9559 return; 9560 } 9561 9562 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9563 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9564 Type == Sema::FST_OSTrace) { 9565 CheckPrintfHandler H( 9566 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9567 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9568 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9569 CheckedVarArgs, UncoveredArg); 9570 9571 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9572 S.getLangOpts(), 9573 S.Context.getTargetInfo(), 9574 Type == Sema::FST_FreeBSDKPrintf)) 9575 H.DoneProcessing(); 9576 } else if (Type == Sema::FST_Scanf) { 9577 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9578 numDataArgs, Str, HasVAListArg, Args, format_idx, 9579 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9580 9581 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9582 S.getLangOpts(), 9583 S.Context.getTargetInfo())) 9584 H.DoneProcessing(); 9585 } // TODO: handle other formats 9586 } 9587 9588 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9589 // Str - The format string. NOTE: this is NOT null-terminated! 9590 StringRef StrRef = FExpr->getString(); 9591 const char *Str = StrRef.data(); 9592 // Account for cases where the string literal is truncated in a declaration. 9593 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9594 assert(T && "String literal not of constant array type!"); 9595 size_t TypeSize = T->getSize().getZExtValue(); 9596 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9597 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9598 getLangOpts(), 9599 Context.getTargetInfo()); 9600 } 9601 9602 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9603 9604 // Returns the related absolute value function that is larger, of 0 if one 9605 // does not exist. 9606 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9607 switch (AbsFunction) { 9608 default: 9609 return 0; 9610 9611 case Builtin::BI__builtin_abs: 9612 return Builtin::BI__builtin_labs; 9613 case Builtin::BI__builtin_labs: 9614 return Builtin::BI__builtin_llabs; 9615 case Builtin::BI__builtin_llabs: 9616 return 0; 9617 9618 case Builtin::BI__builtin_fabsf: 9619 return Builtin::BI__builtin_fabs; 9620 case Builtin::BI__builtin_fabs: 9621 return Builtin::BI__builtin_fabsl; 9622 case Builtin::BI__builtin_fabsl: 9623 return 0; 9624 9625 case Builtin::BI__builtin_cabsf: 9626 return Builtin::BI__builtin_cabs; 9627 case Builtin::BI__builtin_cabs: 9628 return Builtin::BI__builtin_cabsl; 9629 case Builtin::BI__builtin_cabsl: 9630 return 0; 9631 9632 case Builtin::BIabs: 9633 return Builtin::BIlabs; 9634 case Builtin::BIlabs: 9635 return Builtin::BIllabs; 9636 case Builtin::BIllabs: 9637 return 0; 9638 9639 case Builtin::BIfabsf: 9640 return Builtin::BIfabs; 9641 case Builtin::BIfabs: 9642 return Builtin::BIfabsl; 9643 case Builtin::BIfabsl: 9644 return 0; 9645 9646 case Builtin::BIcabsf: 9647 return Builtin::BIcabs; 9648 case Builtin::BIcabs: 9649 return Builtin::BIcabsl; 9650 case Builtin::BIcabsl: 9651 return 0; 9652 } 9653 } 9654 9655 // Returns the argument type of the absolute value function. 9656 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9657 unsigned AbsType) { 9658 if (AbsType == 0) 9659 return QualType(); 9660 9661 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9662 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9663 if (Error != ASTContext::GE_None) 9664 return QualType(); 9665 9666 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9667 if (!FT) 9668 return QualType(); 9669 9670 if (FT->getNumParams() != 1) 9671 return QualType(); 9672 9673 return FT->getParamType(0); 9674 } 9675 9676 // Returns the best absolute value function, or zero, based on type and 9677 // current absolute value function. 9678 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9679 unsigned AbsFunctionKind) { 9680 unsigned BestKind = 0; 9681 uint64_t ArgSize = Context.getTypeSize(ArgType); 9682 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9683 Kind = getLargerAbsoluteValueFunction(Kind)) { 9684 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9685 if (Context.getTypeSize(ParamType) >= ArgSize) { 9686 if (BestKind == 0) 9687 BestKind = Kind; 9688 else if (Context.hasSameType(ParamType, ArgType)) { 9689 BestKind = Kind; 9690 break; 9691 } 9692 } 9693 } 9694 return BestKind; 9695 } 9696 9697 enum AbsoluteValueKind { 9698 AVK_Integer, 9699 AVK_Floating, 9700 AVK_Complex 9701 }; 9702 9703 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9704 if (T->isIntegralOrEnumerationType()) 9705 return AVK_Integer; 9706 if (T->isRealFloatingType()) 9707 return AVK_Floating; 9708 if (T->isAnyComplexType()) 9709 return AVK_Complex; 9710 9711 llvm_unreachable("Type not integer, floating, or complex"); 9712 } 9713 9714 // Changes the absolute value function to a different type. Preserves whether 9715 // the function is a builtin. 9716 static unsigned changeAbsFunction(unsigned AbsKind, 9717 AbsoluteValueKind ValueKind) { 9718 switch (ValueKind) { 9719 case AVK_Integer: 9720 switch (AbsKind) { 9721 default: 9722 return 0; 9723 case Builtin::BI__builtin_fabsf: 9724 case Builtin::BI__builtin_fabs: 9725 case Builtin::BI__builtin_fabsl: 9726 case Builtin::BI__builtin_cabsf: 9727 case Builtin::BI__builtin_cabs: 9728 case Builtin::BI__builtin_cabsl: 9729 return Builtin::BI__builtin_abs; 9730 case Builtin::BIfabsf: 9731 case Builtin::BIfabs: 9732 case Builtin::BIfabsl: 9733 case Builtin::BIcabsf: 9734 case Builtin::BIcabs: 9735 case Builtin::BIcabsl: 9736 return Builtin::BIabs; 9737 } 9738 case AVK_Floating: 9739 switch (AbsKind) { 9740 default: 9741 return 0; 9742 case Builtin::BI__builtin_abs: 9743 case Builtin::BI__builtin_labs: 9744 case Builtin::BI__builtin_llabs: 9745 case Builtin::BI__builtin_cabsf: 9746 case Builtin::BI__builtin_cabs: 9747 case Builtin::BI__builtin_cabsl: 9748 return Builtin::BI__builtin_fabsf; 9749 case Builtin::BIabs: 9750 case Builtin::BIlabs: 9751 case Builtin::BIllabs: 9752 case Builtin::BIcabsf: 9753 case Builtin::BIcabs: 9754 case Builtin::BIcabsl: 9755 return Builtin::BIfabsf; 9756 } 9757 case AVK_Complex: 9758 switch (AbsKind) { 9759 default: 9760 return 0; 9761 case Builtin::BI__builtin_abs: 9762 case Builtin::BI__builtin_labs: 9763 case Builtin::BI__builtin_llabs: 9764 case Builtin::BI__builtin_fabsf: 9765 case Builtin::BI__builtin_fabs: 9766 case Builtin::BI__builtin_fabsl: 9767 return Builtin::BI__builtin_cabsf; 9768 case Builtin::BIabs: 9769 case Builtin::BIlabs: 9770 case Builtin::BIllabs: 9771 case Builtin::BIfabsf: 9772 case Builtin::BIfabs: 9773 case Builtin::BIfabsl: 9774 return Builtin::BIcabsf; 9775 } 9776 } 9777 llvm_unreachable("Unable to convert function"); 9778 } 9779 9780 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9781 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9782 if (!FnInfo) 9783 return 0; 9784 9785 switch (FDecl->getBuiltinID()) { 9786 default: 9787 return 0; 9788 case Builtin::BI__builtin_abs: 9789 case Builtin::BI__builtin_fabs: 9790 case Builtin::BI__builtin_fabsf: 9791 case Builtin::BI__builtin_fabsl: 9792 case Builtin::BI__builtin_labs: 9793 case Builtin::BI__builtin_llabs: 9794 case Builtin::BI__builtin_cabs: 9795 case Builtin::BI__builtin_cabsf: 9796 case Builtin::BI__builtin_cabsl: 9797 case Builtin::BIabs: 9798 case Builtin::BIlabs: 9799 case Builtin::BIllabs: 9800 case Builtin::BIfabs: 9801 case Builtin::BIfabsf: 9802 case Builtin::BIfabsl: 9803 case Builtin::BIcabs: 9804 case Builtin::BIcabsf: 9805 case Builtin::BIcabsl: 9806 return FDecl->getBuiltinID(); 9807 } 9808 llvm_unreachable("Unknown Builtin type"); 9809 } 9810 9811 // If the replacement is valid, emit a note with replacement function. 9812 // Additionally, suggest including the proper header if not already included. 9813 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9814 unsigned AbsKind, QualType ArgType) { 9815 bool EmitHeaderHint = true; 9816 const char *HeaderName = nullptr; 9817 const char *FunctionName = nullptr; 9818 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9819 FunctionName = "std::abs"; 9820 if (ArgType->isIntegralOrEnumerationType()) { 9821 HeaderName = "cstdlib"; 9822 } else if (ArgType->isRealFloatingType()) { 9823 HeaderName = "cmath"; 9824 } else { 9825 llvm_unreachable("Invalid Type"); 9826 } 9827 9828 // Lookup all std::abs 9829 if (NamespaceDecl *Std = S.getStdNamespace()) { 9830 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9831 R.suppressDiagnostics(); 9832 S.LookupQualifiedName(R, Std); 9833 9834 for (const auto *I : R) { 9835 const FunctionDecl *FDecl = nullptr; 9836 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9837 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9838 } else { 9839 FDecl = dyn_cast<FunctionDecl>(I); 9840 } 9841 if (!FDecl) 9842 continue; 9843 9844 // Found std::abs(), check that they are the right ones. 9845 if (FDecl->getNumParams() != 1) 9846 continue; 9847 9848 // Check that the parameter type can handle the argument. 9849 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9850 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9851 S.Context.getTypeSize(ArgType) <= 9852 S.Context.getTypeSize(ParamType)) { 9853 // Found a function, don't need the header hint. 9854 EmitHeaderHint = false; 9855 break; 9856 } 9857 } 9858 } 9859 } else { 9860 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9861 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9862 9863 if (HeaderName) { 9864 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9865 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9866 R.suppressDiagnostics(); 9867 S.LookupName(R, S.getCurScope()); 9868 9869 if (R.isSingleResult()) { 9870 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9871 if (FD && FD->getBuiltinID() == AbsKind) { 9872 EmitHeaderHint = false; 9873 } else { 9874 return; 9875 } 9876 } else if (!R.empty()) { 9877 return; 9878 } 9879 } 9880 } 9881 9882 S.Diag(Loc, diag::note_replace_abs_function) 9883 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9884 9885 if (!HeaderName) 9886 return; 9887 9888 if (!EmitHeaderHint) 9889 return; 9890 9891 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9892 << FunctionName; 9893 } 9894 9895 template <std::size_t StrLen> 9896 static bool IsStdFunction(const FunctionDecl *FDecl, 9897 const char (&Str)[StrLen]) { 9898 if (!FDecl) 9899 return false; 9900 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9901 return false; 9902 if (!FDecl->isInStdNamespace()) 9903 return false; 9904 9905 return true; 9906 } 9907 9908 // Warn when using the wrong abs() function. 9909 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9910 const FunctionDecl *FDecl) { 9911 if (Call->getNumArgs() != 1) 9912 return; 9913 9914 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9915 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9916 if (AbsKind == 0 && !IsStdAbs) 9917 return; 9918 9919 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9920 QualType ParamType = Call->getArg(0)->getType(); 9921 9922 // Unsigned types cannot be negative. Suggest removing the absolute value 9923 // function call. 9924 if (ArgType->isUnsignedIntegerType()) { 9925 const char *FunctionName = 9926 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9927 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9928 Diag(Call->getExprLoc(), diag::note_remove_abs) 9929 << FunctionName 9930 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9931 return; 9932 } 9933 9934 // Taking the absolute value of a pointer is very suspicious, they probably 9935 // wanted to index into an array, dereference a pointer, call a function, etc. 9936 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9937 unsigned DiagType = 0; 9938 if (ArgType->isFunctionType()) 9939 DiagType = 1; 9940 else if (ArgType->isArrayType()) 9941 DiagType = 2; 9942 9943 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9944 return; 9945 } 9946 9947 // std::abs has overloads which prevent most of the absolute value problems 9948 // from occurring. 9949 if (IsStdAbs) 9950 return; 9951 9952 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9953 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9954 9955 // The argument and parameter are the same kind. Check if they are the right 9956 // size. 9957 if (ArgValueKind == ParamValueKind) { 9958 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9959 return; 9960 9961 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9962 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9963 << FDecl << ArgType << ParamType; 9964 9965 if (NewAbsKind == 0) 9966 return; 9967 9968 emitReplacement(*this, Call->getExprLoc(), 9969 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9970 return; 9971 } 9972 9973 // ArgValueKind != ParamValueKind 9974 // The wrong type of absolute value function was used. Attempt to find the 9975 // proper one. 9976 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9977 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9978 if (NewAbsKind == 0) 9979 return; 9980 9981 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9982 << FDecl << ParamValueKind << ArgValueKind; 9983 9984 emitReplacement(*this, Call->getExprLoc(), 9985 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9986 } 9987 9988 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9989 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9990 const FunctionDecl *FDecl) { 9991 if (!Call || !FDecl) return; 9992 9993 // Ignore template specializations and macros. 9994 if (inTemplateInstantiation()) return; 9995 if (Call->getExprLoc().isMacroID()) return; 9996 9997 // Only care about the one template argument, two function parameter std::max 9998 if (Call->getNumArgs() != 2) return; 9999 if (!IsStdFunction(FDecl, "max")) return; 10000 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10001 if (!ArgList) return; 10002 if (ArgList->size() != 1) return; 10003 10004 // Check that template type argument is unsigned integer. 10005 const auto& TA = ArgList->get(0); 10006 if (TA.getKind() != TemplateArgument::Type) return; 10007 QualType ArgType = TA.getAsType(); 10008 if (!ArgType->isUnsignedIntegerType()) return; 10009 10010 // See if either argument is a literal zero. 10011 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10012 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10013 if (!MTE) return false; 10014 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10015 if (!Num) return false; 10016 if (Num->getValue() != 0) return false; 10017 return true; 10018 }; 10019 10020 const Expr *FirstArg = Call->getArg(0); 10021 const Expr *SecondArg = Call->getArg(1); 10022 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10023 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10024 10025 // Only warn when exactly one argument is zero. 10026 if (IsFirstArgZero == IsSecondArgZero) return; 10027 10028 SourceRange FirstRange = FirstArg->getSourceRange(); 10029 SourceRange SecondRange = SecondArg->getSourceRange(); 10030 10031 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10032 10033 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10034 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10035 10036 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10037 SourceRange RemovalRange; 10038 if (IsFirstArgZero) { 10039 RemovalRange = SourceRange(FirstRange.getBegin(), 10040 SecondRange.getBegin().getLocWithOffset(-1)); 10041 } else { 10042 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10043 SecondRange.getEnd()); 10044 } 10045 10046 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10047 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10048 << FixItHint::CreateRemoval(RemovalRange); 10049 } 10050 10051 //===--- CHECK: Standard memory functions ---------------------------------===// 10052 10053 /// Takes the expression passed to the size_t parameter of functions 10054 /// such as memcmp, strncat, etc and warns if it's a comparison. 10055 /// 10056 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10057 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10058 IdentifierInfo *FnName, 10059 SourceLocation FnLoc, 10060 SourceLocation RParenLoc) { 10061 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10062 if (!Size) 10063 return false; 10064 10065 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10066 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10067 return false; 10068 10069 SourceRange SizeRange = Size->getSourceRange(); 10070 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10071 << SizeRange << FnName; 10072 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10073 << FnName 10074 << FixItHint::CreateInsertion( 10075 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10076 << FixItHint::CreateRemoval(RParenLoc); 10077 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10078 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10079 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10080 ")"); 10081 10082 return true; 10083 } 10084 10085 /// Determine whether the given type is or contains a dynamic class type 10086 /// (e.g., whether it has a vtable). 10087 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10088 bool &IsContained) { 10089 // Look through array types while ignoring qualifiers. 10090 const Type *Ty = T->getBaseElementTypeUnsafe(); 10091 IsContained = false; 10092 10093 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10094 RD = RD ? RD->getDefinition() : nullptr; 10095 if (!RD || RD->isInvalidDecl()) 10096 return nullptr; 10097 10098 if (RD->isDynamicClass()) 10099 return RD; 10100 10101 // Check all the fields. If any bases were dynamic, the class is dynamic. 10102 // It's impossible for a class to transitively contain itself by value, so 10103 // infinite recursion is impossible. 10104 for (auto *FD : RD->fields()) { 10105 bool SubContained; 10106 if (const CXXRecordDecl *ContainedRD = 10107 getContainedDynamicClass(FD->getType(), SubContained)) { 10108 IsContained = true; 10109 return ContainedRD; 10110 } 10111 } 10112 10113 return nullptr; 10114 } 10115 10116 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10117 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10118 if (Unary->getKind() == UETT_SizeOf) 10119 return Unary; 10120 return nullptr; 10121 } 10122 10123 /// If E is a sizeof expression, returns its argument expression, 10124 /// otherwise returns NULL. 10125 static const Expr *getSizeOfExprArg(const Expr *E) { 10126 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10127 if (!SizeOf->isArgumentType()) 10128 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10129 return nullptr; 10130 } 10131 10132 /// If E is a sizeof expression, returns its argument type. 10133 static QualType getSizeOfArgType(const Expr *E) { 10134 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10135 return SizeOf->getTypeOfArgument(); 10136 return QualType(); 10137 } 10138 10139 namespace { 10140 10141 struct SearchNonTrivialToInitializeField 10142 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10143 using Super = 10144 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10145 10146 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10147 10148 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10149 SourceLocation SL) { 10150 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10151 asDerived().visitArray(PDIK, AT, SL); 10152 return; 10153 } 10154 10155 Super::visitWithKind(PDIK, FT, SL); 10156 } 10157 10158 void visitARCStrong(QualType FT, SourceLocation SL) { 10159 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10160 } 10161 void visitARCWeak(QualType FT, SourceLocation SL) { 10162 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10163 } 10164 void visitStruct(QualType FT, SourceLocation SL) { 10165 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10166 visit(FD->getType(), FD->getLocation()); 10167 } 10168 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10169 const ArrayType *AT, SourceLocation SL) { 10170 visit(getContext().getBaseElementType(AT), SL); 10171 } 10172 void visitTrivial(QualType FT, SourceLocation SL) {} 10173 10174 static void diag(QualType RT, const Expr *E, Sema &S) { 10175 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10176 } 10177 10178 ASTContext &getContext() { return S.getASTContext(); } 10179 10180 const Expr *E; 10181 Sema &S; 10182 }; 10183 10184 struct SearchNonTrivialToCopyField 10185 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10186 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10187 10188 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10189 10190 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10191 SourceLocation SL) { 10192 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10193 asDerived().visitArray(PCK, AT, SL); 10194 return; 10195 } 10196 10197 Super::visitWithKind(PCK, FT, SL); 10198 } 10199 10200 void visitARCStrong(QualType FT, SourceLocation SL) { 10201 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10202 } 10203 void visitARCWeak(QualType FT, SourceLocation SL) { 10204 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10205 } 10206 void visitStruct(QualType FT, SourceLocation SL) { 10207 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10208 visit(FD->getType(), FD->getLocation()); 10209 } 10210 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10211 SourceLocation SL) { 10212 visit(getContext().getBaseElementType(AT), SL); 10213 } 10214 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10215 SourceLocation SL) {} 10216 void visitTrivial(QualType FT, SourceLocation SL) {} 10217 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10218 10219 static void diag(QualType RT, const Expr *E, Sema &S) { 10220 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10221 } 10222 10223 ASTContext &getContext() { return S.getASTContext(); } 10224 10225 const Expr *E; 10226 Sema &S; 10227 }; 10228 10229 } 10230 10231 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10232 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10233 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10234 10235 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10236 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10237 return false; 10238 10239 return doesExprLikelyComputeSize(BO->getLHS()) || 10240 doesExprLikelyComputeSize(BO->getRHS()); 10241 } 10242 10243 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10244 } 10245 10246 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10247 /// 10248 /// \code 10249 /// #define MACRO 0 10250 /// foo(MACRO); 10251 /// foo(0); 10252 /// \endcode 10253 /// 10254 /// This should return true for the first call to foo, but not for the second 10255 /// (regardless of whether foo is a macro or function). 10256 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10257 SourceLocation CallLoc, 10258 SourceLocation ArgLoc) { 10259 if (!CallLoc.isMacroID()) 10260 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10261 10262 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10263 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10264 } 10265 10266 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10267 /// last two arguments transposed. 10268 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10269 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10270 return; 10271 10272 const Expr *SizeArg = 10273 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10274 10275 auto isLiteralZero = [](const Expr *E) { 10276 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10277 }; 10278 10279 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10280 SourceLocation CallLoc = Call->getRParenLoc(); 10281 SourceManager &SM = S.getSourceManager(); 10282 if (isLiteralZero(SizeArg) && 10283 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10284 10285 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10286 10287 // Some platforms #define bzero to __builtin_memset. See if this is the 10288 // case, and if so, emit a better diagnostic. 10289 if (BId == Builtin::BIbzero || 10290 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10291 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10292 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10293 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10294 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10295 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10296 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10297 } 10298 return; 10299 } 10300 10301 // If the second argument to a memset is a sizeof expression and the third 10302 // isn't, this is also likely an error. This should catch 10303 // 'memset(buf, sizeof(buf), 0xff)'. 10304 if (BId == Builtin::BImemset && 10305 doesExprLikelyComputeSize(Call->getArg(1)) && 10306 !doesExprLikelyComputeSize(Call->getArg(2))) { 10307 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10308 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10309 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10310 return; 10311 } 10312 } 10313 10314 /// Check for dangerous or invalid arguments to memset(). 10315 /// 10316 /// This issues warnings on known problematic, dangerous or unspecified 10317 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10318 /// function calls. 10319 /// 10320 /// \param Call The call expression to diagnose. 10321 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10322 unsigned BId, 10323 IdentifierInfo *FnName) { 10324 assert(BId != 0); 10325 10326 // It is possible to have a non-standard definition of memset. Validate 10327 // we have enough arguments, and if not, abort further checking. 10328 unsigned ExpectedNumArgs = 10329 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10330 if (Call->getNumArgs() < ExpectedNumArgs) 10331 return; 10332 10333 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10334 BId == Builtin::BIstrndup ? 1 : 2); 10335 unsigned LenArg = 10336 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10337 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10338 10339 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10340 Call->getBeginLoc(), Call->getRParenLoc())) 10341 return; 10342 10343 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10344 CheckMemaccessSize(*this, BId, Call); 10345 10346 // We have special checking when the length is a sizeof expression. 10347 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10348 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10349 llvm::FoldingSetNodeID SizeOfArgID; 10350 10351 // Although widely used, 'bzero' is not a standard function. Be more strict 10352 // with the argument types before allowing diagnostics and only allow the 10353 // form bzero(ptr, sizeof(...)). 10354 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10355 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10356 return; 10357 10358 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10359 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10360 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10361 10362 QualType DestTy = Dest->getType(); 10363 QualType PointeeTy; 10364 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10365 PointeeTy = DestPtrTy->getPointeeType(); 10366 10367 // Never warn about void type pointers. This can be used to suppress 10368 // false positives. 10369 if (PointeeTy->isVoidType()) 10370 continue; 10371 10372 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10373 // actually comparing the expressions for equality. Because computing the 10374 // expression IDs can be expensive, we only do this if the diagnostic is 10375 // enabled. 10376 if (SizeOfArg && 10377 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10378 SizeOfArg->getExprLoc())) { 10379 // We only compute IDs for expressions if the warning is enabled, and 10380 // cache the sizeof arg's ID. 10381 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10382 SizeOfArg->Profile(SizeOfArgID, Context, true); 10383 llvm::FoldingSetNodeID DestID; 10384 Dest->Profile(DestID, Context, true); 10385 if (DestID == SizeOfArgID) { 10386 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10387 // over sizeof(src) as well. 10388 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10389 StringRef ReadableName = FnName->getName(); 10390 10391 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10392 if (UnaryOp->getOpcode() == UO_AddrOf) 10393 ActionIdx = 1; // If its an address-of operator, just remove it. 10394 if (!PointeeTy->isIncompleteType() && 10395 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10396 ActionIdx = 2; // If the pointee's size is sizeof(char), 10397 // suggest an explicit length. 10398 10399 // If the function is defined as a builtin macro, do not show macro 10400 // expansion. 10401 SourceLocation SL = SizeOfArg->getExprLoc(); 10402 SourceRange DSR = Dest->getSourceRange(); 10403 SourceRange SSR = SizeOfArg->getSourceRange(); 10404 SourceManager &SM = getSourceManager(); 10405 10406 if (SM.isMacroArgExpansion(SL)) { 10407 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10408 SL = SM.getSpellingLoc(SL); 10409 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10410 SM.getSpellingLoc(DSR.getEnd())); 10411 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10412 SM.getSpellingLoc(SSR.getEnd())); 10413 } 10414 10415 DiagRuntimeBehavior(SL, SizeOfArg, 10416 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10417 << ReadableName 10418 << PointeeTy 10419 << DestTy 10420 << DSR 10421 << SSR); 10422 DiagRuntimeBehavior(SL, SizeOfArg, 10423 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10424 << ActionIdx 10425 << SSR); 10426 10427 break; 10428 } 10429 } 10430 10431 // Also check for cases where the sizeof argument is the exact same 10432 // type as the memory argument, and where it points to a user-defined 10433 // record type. 10434 if (SizeOfArgTy != QualType()) { 10435 if (PointeeTy->isRecordType() && 10436 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10437 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10438 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10439 << FnName << SizeOfArgTy << ArgIdx 10440 << PointeeTy << Dest->getSourceRange() 10441 << LenExpr->getSourceRange()); 10442 break; 10443 } 10444 } 10445 } else if (DestTy->isArrayType()) { 10446 PointeeTy = DestTy; 10447 } 10448 10449 if (PointeeTy == QualType()) 10450 continue; 10451 10452 // Always complain about dynamic classes. 10453 bool IsContained; 10454 if (const CXXRecordDecl *ContainedRD = 10455 getContainedDynamicClass(PointeeTy, IsContained)) { 10456 10457 unsigned OperationType = 0; 10458 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10459 // "overwritten" if we're warning about the destination for any call 10460 // but memcmp; otherwise a verb appropriate to the call. 10461 if (ArgIdx != 0 || IsCmp) { 10462 if (BId == Builtin::BImemcpy) 10463 OperationType = 1; 10464 else if(BId == Builtin::BImemmove) 10465 OperationType = 2; 10466 else if (IsCmp) 10467 OperationType = 3; 10468 } 10469 10470 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10471 PDiag(diag::warn_dyn_class_memaccess) 10472 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10473 << IsContained << ContainedRD << OperationType 10474 << Call->getCallee()->getSourceRange()); 10475 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10476 BId != Builtin::BImemset) 10477 DiagRuntimeBehavior( 10478 Dest->getExprLoc(), Dest, 10479 PDiag(diag::warn_arc_object_memaccess) 10480 << ArgIdx << FnName << PointeeTy 10481 << Call->getCallee()->getSourceRange()); 10482 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10483 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10484 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10485 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10486 PDiag(diag::warn_cstruct_memaccess) 10487 << ArgIdx << FnName << PointeeTy << 0); 10488 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10489 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10490 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10491 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10492 PDiag(diag::warn_cstruct_memaccess) 10493 << ArgIdx << FnName << PointeeTy << 1); 10494 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10495 } else { 10496 continue; 10497 } 10498 } else 10499 continue; 10500 10501 DiagRuntimeBehavior( 10502 Dest->getExprLoc(), Dest, 10503 PDiag(diag::note_bad_memaccess_silence) 10504 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10505 break; 10506 } 10507 } 10508 10509 // A little helper routine: ignore addition and subtraction of integer literals. 10510 // This intentionally does not ignore all integer constant expressions because 10511 // we don't want to remove sizeof(). 10512 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10513 Ex = Ex->IgnoreParenCasts(); 10514 10515 while (true) { 10516 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10517 if (!BO || !BO->isAdditiveOp()) 10518 break; 10519 10520 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10521 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10522 10523 if (isa<IntegerLiteral>(RHS)) 10524 Ex = LHS; 10525 else if (isa<IntegerLiteral>(LHS)) 10526 Ex = RHS; 10527 else 10528 break; 10529 } 10530 10531 return Ex; 10532 } 10533 10534 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10535 ASTContext &Context) { 10536 // Only handle constant-sized or VLAs, but not flexible members. 10537 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10538 // Only issue the FIXIT for arrays of size > 1. 10539 if (CAT->getSize().getSExtValue() <= 1) 10540 return false; 10541 } else if (!Ty->isVariableArrayType()) { 10542 return false; 10543 } 10544 return true; 10545 } 10546 10547 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10548 // be the size of the source, instead of the destination. 10549 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10550 IdentifierInfo *FnName) { 10551 10552 // Don't crash if the user has the wrong number of arguments 10553 unsigned NumArgs = Call->getNumArgs(); 10554 if ((NumArgs != 3) && (NumArgs != 4)) 10555 return; 10556 10557 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10558 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10559 const Expr *CompareWithSrc = nullptr; 10560 10561 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10562 Call->getBeginLoc(), Call->getRParenLoc())) 10563 return; 10564 10565 // Look for 'strlcpy(dst, x, sizeof(x))' 10566 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10567 CompareWithSrc = Ex; 10568 else { 10569 // Look for 'strlcpy(dst, x, strlen(x))' 10570 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10571 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10572 SizeCall->getNumArgs() == 1) 10573 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10574 } 10575 } 10576 10577 if (!CompareWithSrc) 10578 return; 10579 10580 // Determine if the argument to sizeof/strlen is equal to the source 10581 // argument. In principle there's all kinds of things you could do 10582 // here, for instance creating an == expression and evaluating it with 10583 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10584 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10585 if (!SrcArgDRE) 10586 return; 10587 10588 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10589 if (!CompareWithSrcDRE || 10590 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10591 return; 10592 10593 const Expr *OriginalSizeArg = Call->getArg(2); 10594 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10595 << OriginalSizeArg->getSourceRange() << FnName; 10596 10597 // Output a FIXIT hint if the destination is an array (rather than a 10598 // pointer to an array). This could be enhanced to handle some 10599 // pointers if we know the actual size, like if DstArg is 'array+2' 10600 // we could say 'sizeof(array)-2'. 10601 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10602 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10603 return; 10604 10605 SmallString<128> sizeString; 10606 llvm::raw_svector_ostream OS(sizeString); 10607 OS << "sizeof("; 10608 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10609 OS << ")"; 10610 10611 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10612 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10613 OS.str()); 10614 } 10615 10616 /// Check if two expressions refer to the same declaration. 10617 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10618 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10619 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10620 return D1->getDecl() == D2->getDecl(); 10621 return false; 10622 } 10623 10624 static const Expr *getStrlenExprArg(const Expr *E) { 10625 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10626 const FunctionDecl *FD = CE->getDirectCallee(); 10627 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10628 return nullptr; 10629 return CE->getArg(0)->IgnoreParenCasts(); 10630 } 10631 return nullptr; 10632 } 10633 10634 // Warn on anti-patterns as the 'size' argument to strncat. 10635 // The correct size argument should look like following: 10636 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10637 void Sema::CheckStrncatArguments(const CallExpr *CE, 10638 IdentifierInfo *FnName) { 10639 // Don't crash if the user has the wrong number of arguments. 10640 if (CE->getNumArgs() < 3) 10641 return; 10642 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10643 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10644 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10645 10646 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10647 CE->getRParenLoc())) 10648 return; 10649 10650 // Identify common expressions, which are wrongly used as the size argument 10651 // to strncat and may lead to buffer overflows. 10652 unsigned PatternType = 0; 10653 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10654 // - sizeof(dst) 10655 if (referToTheSameDecl(SizeOfArg, DstArg)) 10656 PatternType = 1; 10657 // - sizeof(src) 10658 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10659 PatternType = 2; 10660 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10661 if (BE->getOpcode() == BO_Sub) { 10662 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10663 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10664 // - sizeof(dst) - strlen(dst) 10665 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10666 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10667 PatternType = 1; 10668 // - sizeof(src) - (anything) 10669 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10670 PatternType = 2; 10671 } 10672 } 10673 10674 if (PatternType == 0) 10675 return; 10676 10677 // Generate the diagnostic. 10678 SourceLocation SL = LenArg->getBeginLoc(); 10679 SourceRange SR = LenArg->getSourceRange(); 10680 SourceManager &SM = getSourceManager(); 10681 10682 // If the function is defined as a builtin macro, do not show macro expansion. 10683 if (SM.isMacroArgExpansion(SL)) { 10684 SL = SM.getSpellingLoc(SL); 10685 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10686 SM.getSpellingLoc(SR.getEnd())); 10687 } 10688 10689 // Check if the destination is an array (rather than a pointer to an array). 10690 QualType DstTy = DstArg->getType(); 10691 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10692 Context); 10693 if (!isKnownSizeArray) { 10694 if (PatternType == 1) 10695 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10696 else 10697 Diag(SL, diag::warn_strncat_src_size) << SR; 10698 return; 10699 } 10700 10701 if (PatternType == 1) 10702 Diag(SL, diag::warn_strncat_large_size) << SR; 10703 else 10704 Diag(SL, diag::warn_strncat_src_size) << SR; 10705 10706 SmallString<128> sizeString; 10707 llvm::raw_svector_ostream OS(sizeString); 10708 OS << "sizeof("; 10709 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10710 OS << ") - "; 10711 OS << "strlen("; 10712 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10713 OS << ") - 1"; 10714 10715 Diag(SL, diag::note_strncat_wrong_size) 10716 << FixItHint::CreateReplacement(SR, OS.str()); 10717 } 10718 10719 namespace { 10720 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10721 const UnaryOperator *UnaryExpr, const Decl *D) { 10722 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10723 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10724 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10725 return; 10726 } 10727 } 10728 10729 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10730 const UnaryOperator *UnaryExpr) { 10731 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10732 const Decl *D = Lvalue->getDecl(); 10733 if (isa<DeclaratorDecl>(D)) 10734 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10735 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10736 } 10737 10738 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10739 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10740 Lvalue->getMemberDecl()); 10741 } 10742 10743 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10744 const UnaryOperator *UnaryExpr) { 10745 const auto *Lambda = dyn_cast<LambdaExpr>( 10746 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10747 if (!Lambda) 10748 return; 10749 10750 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10751 << CalleeName << 2 /*object: lambda expression*/; 10752 } 10753 10754 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10755 const DeclRefExpr *Lvalue) { 10756 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10757 if (Var == nullptr) 10758 return; 10759 10760 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10761 << CalleeName << 0 /*object: */ << Var; 10762 } 10763 10764 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10765 const CastExpr *Cast) { 10766 SmallString<128> SizeString; 10767 llvm::raw_svector_ostream OS(SizeString); 10768 10769 clang::CastKind Kind = Cast->getCastKind(); 10770 if (Kind == clang::CK_BitCast && 10771 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10772 return; 10773 if (Kind == clang::CK_IntegralToPointer && 10774 !isa<IntegerLiteral>( 10775 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10776 return; 10777 10778 switch (Cast->getCastKind()) { 10779 case clang::CK_BitCast: 10780 case clang::CK_IntegralToPointer: 10781 case clang::CK_FunctionToPointerDecay: 10782 OS << '\''; 10783 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10784 OS << '\''; 10785 break; 10786 default: 10787 return; 10788 } 10789 10790 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10791 << CalleeName << 0 /*object: */ << OS.str(); 10792 } 10793 } // namespace 10794 10795 /// Alerts the user that they are attempting to free a non-malloc'd object. 10796 void Sema::CheckFreeArguments(const CallExpr *E) { 10797 const std::string CalleeName = 10798 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10799 10800 { // Prefer something that doesn't involve a cast to make things simpler. 10801 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10802 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10803 switch (UnaryExpr->getOpcode()) { 10804 case UnaryOperator::Opcode::UO_AddrOf: 10805 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10806 case UnaryOperator::Opcode::UO_Plus: 10807 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10808 default: 10809 break; 10810 } 10811 10812 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10813 if (Lvalue->getType()->isArrayType()) 10814 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10815 10816 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10817 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10818 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10819 return; 10820 } 10821 10822 if (isa<BlockExpr>(Arg)) { 10823 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10824 << CalleeName << 1 /*object: block*/; 10825 return; 10826 } 10827 } 10828 // Maybe the cast was important, check after the other cases. 10829 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10830 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10831 } 10832 10833 void 10834 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10835 SourceLocation ReturnLoc, 10836 bool isObjCMethod, 10837 const AttrVec *Attrs, 10838 const FunctionDecl *FD) { 10839 // Check if the return value is null but should not be. 10840 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10841 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10842 CheckNonNullExpr(*this, RetValExp)) 10843 Diag(ReturnLoc, diag::warn_null_ret) 10844 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10845 10846 // C++11 [basic.stc.dynamic.allocation]p4: 10847 // If an allocation function declared with a non-throwing 10848 // exception-specification fails to allocate storage, it shall return 10849 // a null pointer. Any other allocation function that fails to allocate 10850 // storage shall indicate failure only by throwing an exception [...] 10851 if (FD) { 10852 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10853 if (Op == OO_New || Op == OO_Array_New) { 10854 const FunctionProtoType *Proto 10855 = FD->getType()->castAs<FunctionProtoType>(); 10856 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10857 CheckNonNullExpr(*this, RetValExp)) 10858 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10859 << FD << getLangOpts().CPlusPlus11; 10860 } 10861 } 10862 10863 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10864 // here prevent the user from using a PPC MMA type as trailing return type. 10865 if (Context.getTargetInfo().getTriple().isPPC64()) 10866 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10867 } 10868 10869 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10870 10871 /// Check for comparisons of floating point operands using != and ==. 10872 /// Issue a warning if these are no self-comparisons, as they are not likely 10873 /// to do what the programmer intended. 10874 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10875 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10876 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10877 10878 // Special case: check for x == x (which is OK). 10879 // Do not emit warnings for such cases. 10880 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10881 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10882 if (DRL->getDecl() == DRR->getDecl()) 10883 return; 10884 10885 // Special case: check for comparisons against literals that can be exactly 10886 // represented by APFloat. In such cases, do not emit a warning. This 10887 // is a heuristic: often comparison against such literals are used to 10888 // detect if a value in a variable has not changed. This clearly can 10889 // lead to false negatives. 10890 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10891 if (FLL->isExact()) 10892 return; 10893 } else 10894 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10895 if (FLR->isExact()) 10896 return; 10897 10898 // Check for comparisons with builtin types. 10899 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10900 if (CL->getBuiltinCallee()) 10901 return; 10902 10903 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10904 if (CR->getBuiltinCallee()) 10905 return; 10906 10907 // Emit the diagnostic. 10908 Diag(Loc, diag::warn_floatingpoint_eq) 10909 << LHS->getSourceRange() << RHS->getSourceRange(); 10910 } 10911 10912 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10913 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10914 10915 namespace { 10916 10917 /// Structure recording the 'active' range of an integer-valued 10918 /// expression. 10919 struct IntRange { 10920 /// The number of bits active in the int. Note that this includes exactly one 10921 /// sign bit if !NonNegative. 10922 unsigned Width; 10923 10924 /// True if the int is known not to have negative values. If so, all leading 10925 /// bits before Width are known zero, otherwise they are known to be the 10926 /// same as the MSB within Width. 10927 bool NonNegative; 10928 10929 IntRange(unsigned Width, bool NonNegative) 10930 : Width(Width), NonNegative(NonNegative) {} 10931 10932 /// Number of bits excluding the sign bit. 10933 unsigned valueBits() const { 10934 return NonNegative ? Width : Width - 1; 10935 } 10936 10937 /// Returns the range of the bool type. 10938 static IntRange forBoolType() { 10939 return IntRange(1, true); 10940 } 10941 10942 /// Returns the range of an opaque value of the given integral type. 10943 static IntRange forValueOfType(ASTContext &C, QualType T) { 10944 return forValueOfCanonicalType(C, 10945 T->getCanonicalTypeInternal().getTypePtr()); 10946 } 10947 10948 /// Returns the range of an opaque value of a canonical integral type. 10949 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10950 assert(T->isCanonicalUnqualified()); 10951 10952 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10953 T = VT->getElementType().getTypePtr(); 10954 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10955 T = CT->getElementType().getTypePtr(); 10956 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10957 T = AT->getValueType().getTypePtr(); 10958 10959 if (!C.getLangOpts().CPlusPlus) { 10960 // For enum types in C code, use the underlying datatype. 10961 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10962 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10963 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10964 // For enum types in C++, use the known bit width of the enumerators. 10965 EnumDecl *Enum = ET->getDecl(); 10966 // In C++11, enums can have a fixed underlying type. Use this type to 10967 // compute the range. 10968 if (Enum->isFixed()) { 10969 return IntRange(C.getIntWidth(QualType(T, 0)), 10970 !ET->isSignedIntegerOrEnumerationType()); 10971 } 10972 10973 unsigned NumPositive = Enum->getNumPositiveBits(); 10974 unsigned NumNegative = Enum->getNumNegativeBits(); 10975 10976 if (NumNegative == 0) 10977 return IntRange(NumPositive, true/*NonNegative*/); 10978 else 10979 return IntRange(std::max(NumPositive + 1, NumNegative), 10980 false/*NonNegative*/); 10981 } 10982 10983 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10984 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10985 10986 const BuiltinType *BT = cast<BuiltinType>(T); 10987 assert(BT->isInteger()); 10988 10989 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10990 } 10991 10992 /// Returns the "target" range of a canonical integral type, i.e. 10993 /// the range of values expressible in the type. 10994 /// 10995 /// This matches forValueOfCanonicalType except that enums have the 10996 /// full range of their type, not the range of their enumerators. 10997 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10998 assert(T->isCanonicalUnqualified()); 10999 11000 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11001 T = VT->getElementType().getTypePtr(); 11002 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11003 T = CT->getElementType().getTypePtr(); 11004 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11005 T = AT->getValueType().getTypePtr(); 11006 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11007 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11008 11009 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11010 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11011 11012 const BuiltinType *BT = cast<BuiltinType>(T); 11013 assert(BT->isInteger()); 11014 11015 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11016 } 11017 11018 /// Returns the supremum of two ranges: i.e. their conservative merge. 11019 static IntRange join(IntRange L, IntRange R) { 11020 bool Unsigned = L.NonNegative && R.NonNegative; 11021 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11022 L.NonNegative && R.NonNegative); 11023 } 11024 11025 /// Return the range of a bitwise-AND of the two ranges. 11026 static IntRange bit_and(IntRange L, IntRange R) { 11027 unsigned Bits = std::max(L.Width, R.Width); 11028 bool NonNegative = false; 11029 if (L.NonNegative) { 11030 Bits = std::min(Bits, L.Width); 11031 NonNegative = true; 11032 } 11033 if (R.NonNegative) { 11034 Bits = std::min(Bits, R.Width); 11035 NonNegative = true; 11036 } 11037 return IntRange(Bits, NonNegative); 11038 } 11039 11040 /// Return the range of a sum of the two ranges. 11041 static IntRange sum(IntRange L, IntRange R) { 11042 bool Unsigned = L.NonNegative && R.NonNegative; 11043 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11044 Unsigned); 11045 } 11046 11047 /// Return the range of a difference of the two ranges. 11048 static IntRange difference(IntRange L, IntRange R) { 11049 // We need a 1-bit-wider range if: 11050 // 1) LHS can be negative: least value can be reduced. 11051 // 2) RHS can be negative: greatest value can be increased. 11052 bool CanWiden = !L.NonNegative || !R.NonNegative; 11053 bool Unsigned = L.NonNegative && R.Width == 0; 11054 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11055 !Unsigned, 11056 Unsigned); 11057 } 11058 11059 /// Return the range of a product of the two ranges. 11060 static IntRange product(IntRange L, IntRange R) { 11061 // If both LHS and RHS can be negative, we can form 11062 // -2^L * -2^R = 2^(L + R) 11063 // which requires L + R + 1 value bits to represent. 11064 bool CanWiden = !L.NonNegative && !R.NonNegative; 11065 bool Unsigned = L.NonNegative && R.NonNegative; 11066 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11067 Unsigned); 11068 } 11069 11070 /// Return the range of a remainder operation between the two ranges. 11071 static IntRange rem(IntRange L, IntRange R) { 11072 // The result of a remainder can't be larger than the result of 11073 // either side. The sign of the result is the sign of the LHS. 11074 bool Unsigned = L.NonNegative; 11075 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11076 Unsigned); 11077 } 11078 }; 11079 11080 } // namespace 11081 11082 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11083 unsigned MaxWidth) { 11084 if (value.isSigned() && value.isNegative()) 11085 return IntRange(value.getMinSignedBits(), false); 11086 11087 if (value.getBitWidth() > MaxWidth) 11088 value = value.trunc(MaxWidth); 11089 11090 // isNonNegative() just checks the sign bit without considering 11091 // signedness. 11092 return IntRange(value.getActiveBits(), true); 11093 } 11094 11095 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11096 unsigned MaxWidth) { 11097 if (result.isInt()) 11098 return GetValueRange(C, result.getInt(), MaxWidth); 11099 11100 if (result.isVector()) { 11101 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11102 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11103 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11104 R = IntRange::join(R, El); 11105 } 11106 return R; 11107 } 11108 11109 if (result.isComplexInt()) { 11110 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11111 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11112 return IntRange::join(R, I); 11113 } 11114 11115 // This can happen with lossless casts to intptr_t of "based" lvalues. 11116 // Assume it might use arbitrary bits. 11117 // FIXME: The only reason we need to pass the type in here is to get 11118 // the sign right on this one case. It would be nice if APValue 11119 // preserved this. 11120 assert(result.isLValue() || result.isAddrLabelDiff()); 11121 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11122 } 11123 11124 static QualType GetExprType(const Expr *E) { 11125 QualType Ty = E->getType(); 11126 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11127 Ty = AtomicRHS->getValueType(); 11128 return Ty; 11129 } 11130 11131 /// Pseudo-evaluate the given integer expression, estimating the 11132 /// range of values it might take. 11133 /// 11134 /// \param MaxWidth The width to which the value will be truncated. 11135 /// \param Approximate If \c true, return a likely range for the result: in 11136 /// particular, assume that aritmetic on narrower types doesn't leave 11137 /// those types. If \c false, return a range including all possible 11138 /// result values. 11139 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11140 bool InConstantContext, bool Approximate) { 11141 E = E->IgnoreParens(); 11142 11143 // Try a full evaluation first. 11144 Expr::EvalResult result; 11145 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11146 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11147 11148 // I think we only want to look through implicit casts here; if the 11149 // user has an explicit widening cast, we should treat the value as 11150 // being of the new, wider type. 11151 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11152 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11153 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11154 Approximate); 11155 11156 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11157 11158 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11159 CE->getCastKind() == CK_BooleanToSignedIntegral; 11160 11161 // Assume that non-integer casts can span the full range of the type. 11162 if (!isIntegerCast) 11163 return OutputTypeRange; 11164 11165 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11166 std::min(MaxWidth, OutputTypeRange.Width), 11167 InConstantContext, Approximate); 11168 11169 // Bail out if the subexpr's range is as wide as the cast type. 11170 if (SubRange.Width >= OutputTypeRange.Width) 11171 return OutputTypeRange; 11172 11173 // Otherwise, we take the smaller width, and we're non-negative if 11174 // either the output type or the subexpr is. 11175 return IntRange(SubRange.Width, 11176 SubRange.NonNegative || OutputTypeRange.NonNegative); 11177 } 11178 11179 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11180 // If we can fold the condition, just take that operand. 11181 bool CondResult; 11182 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11183 return GetExprRange(C, 11184 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11185 MaxWidth, InConstantContext, Approximate); 11186 11187 // Otherwise, conservatively merge. 11188 // GetExprRange requires an integer expression, but a throw expression 11189 // results in a void type. 11190 Expr *E = CO->getTrueExpr(); 11191 IntRange L = E->getType()->isVoidType() 11192 ? IntRange{0, true} 11193 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11194 E = CO->getFalseExpr(); 11195 IntRange R = E->getType()->isVoidType() 11196 ? IntRange{0, true} 11197 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11198 return IntRange::join(L, R); 11199 } 11200 11201 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11202 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11203 11204 switch (BO->getOpcode()) { 11205 case BO_Cmp: 11206 llvm_unreachable("builtin <=> should have class type"); 11207 11208 // Boolean-valued operations are single-bit and positive. 11209 case BO_LAnd: 11210 case BO_LOr: 11211 case BO_LT: 11212 case BO_GT: 11213 case BO_LE: 11214 case BO_GE: 11215 case BO_EQ: 11216 case BO_NE: 11217 return IntRange::forBoolType(); 11218 11219 // The type of the assignments is the type of the LHS, so the RHS 11220 // is not necessarily the same type. 11221 case BO_MulAssign: 11222 case BO_DivAssign: 11223 case BO_RemAssign: 11224 case BO_AddAssign: 11225 case BO_SubAssign: 11226 case BO_XorAssign: 11227 case BO_OrAssign: 11228 // TODO: bitfields? 11229 return IntRange::forValueOfType(C, GetExprType(E)); 11230 11231 // Simple assignments just pass through the RHS, which will have 11232 // been coerced to the LHS type. 11233 case BO_Assign: 11234 // TODO: bitfields? 11235 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11236 Approximate); 11237 11238 // Operations with opaque sources are black-listed. 11239 case BO_PtrMemD: 11240 case BO_PtrMemI: 11241 return IntRange::forValueOfType(C, GetExprType(E)); 11242 11243 // Bitwise-and uses the *infinum* of the two source ranges. 11244 case BO_And: 11245 case BO_AndAssign: 11246 Combine = IntRange::bit_and; 11247 break; 11248 11249 // Left shift gets black-listed based on a judgement call. 11250 case BO_Shl: 11251 // ...except that we want to treat '1 << (blah)' as logically 11252 // positive. It's an important idiom. 11253 if (IntegerLiteral *I 11254 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11255 if (I->getValue() == 1) { 11256 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11257 return IntRange(R.Width, /*NonNegative*/ true); 11258 } 11259 } 11260 LLVM_FALLTHROUGH; 11261 11262 case BO_ShlAssign: 11263 return IntRange::forValueOfType(C, GetExprType(E)); 11264 11265 // Right shift by a constant can narrow its left argument. 11266 case BO_Shr: 11267 case BO_ShrAssign: { 11268 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11269 Approximate); 11270 11271 // If the shift amount is a positive constant, drop the width by 11272 // that much. 11273 if (Optional<llvm::APSInt> shift = 11274 BO->getRHS()->getIntegerConstantExpr(C)) { 11275 if (shift->isNonNegative()) { 11276 unsigned zext = shift->getZExtValue(); 11277 if (zext >= L.Width) 11278 L.Width = (L.NonNegative ? 0 : 1); 11279 else 11280 L.Width -= zext; 11281 } 11282 } 11283 11284 return L; 11285 } 11286 11287 // Comma acts as its right operand. 11288 case BO_Comma: 11289 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11290 Approximate); 11291 11292 case BO_Add: 11293 if (!Approximate) 11294 Combine = IntRange::sum; 11295 break; 11296 11297 case BO_Sub: 11298 if (BO->getLHS()->getType()->isPointerType()) 11299 return IntRange::forValueOfType(C, GetExprType(E)); 11300 if (!Approximate) 11301 Combine = IntRange::difference; 11302 break; 11303 11304 case BO_Mul: 11305 if (!Approximate) 11306 Combine = IntRange::product; 11307 break; 11308 11309 // The width of a division result is mostly determined by the size 11310 // of the LHS. 11311 case BO_Div: { 11312 // Don't 'pre-truncate' the operands. 11313 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11314 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11315 Approximate); 11316 11317 // If the divisor is constant, use that. 11318 if (Optional<llvm::APSInt> divisor = 11319 BO->getRHS()->getIntegerConstantExpr(C)) { 11320 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11321 if (log2 >= L.Width) 11322 L.Width = (L.NonNegative ? 0 : 1); 11323 else 11324 L.Width = std::min(L.Width - log2, MaxWidth); 11325 return L; 11326 } 11327 11328 // Otherwise, just use the LHS's width. 11329 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11330 // could be -1. 11331 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11332 Approximate); 11333 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11334 } 11335 11336 case BO_Rem: 11337 Combine = IntRange::rem; 11338 break; 11339 11340 // The default behavior is okay for these. 11341 case BO_Xor: 11342 case BO_Or: 11343 break; 11344 } 11345 11346 // Combine the two ranges, but limit the result to the type in which we 11347 // performed the computation. 11348 QualType T = GetExprType(E); 11349 unsigned opWidth = C.getIntWidth(T); 11350 IntRange L = 11351 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11352 IntRange R = 11353 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11354 IntRange C = Combine(L, R); 11355 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11356 C.Width = std::min(C.Width, MaxWidth); 11357 return C; 11358 } 11359 11360 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11361 switch (UO->getOpcode()) { 11362 // Boolean-valued operations are white-listed. 11363 case UO_LNot: 11364 return IntRange::forBoolType(); 11365 11366 // Operations with opaque sources are black-listed. 11367 case UO_Deref: 11368 case UO_AddrOf: // should be impossible 11369 return IntRange::forValueOfType(C, GetExprType(E)); 11370 11371 default: 11372 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11373 Approximate); 11374 } 11375 } 11376 11377 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11378 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11379 Approximate); 11380 11381 if (const auto *BitField = E->getSourceBitField()) 11382 return IntRange(BitField->getBitWidthValue(C), 11383 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11384 11385 return IntRange::forValueOfType(C, GetExprType(E)); 11386 } 11387 11388 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11389 bool InConstantContext, bool Approximate) { 11390 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11391 Approximate); 11392 } 11393 11394 /// Checks whether the given value, which currently has the given 11395 /// source semantics, has the same value when coerced through the 11396 /// target semantics. 11397 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11398 const llvm::fltSemantics &Src, 11399 const llvm::fltSemantics &Tgt) { 11400 llvm::APFloat truncated = value; 11401 11402 bool ignored; 11403 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11404 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11405 11406 return truncated.bitwiseIsEqual(value); 11407 } 11408 11409 /// Checks whether the given value, which currently has the given 11410 /// source semantics, has the same value when coerced through the 11411 /// target semantics. 11412 /// 11413 /// The value might be a vector of floats (or a complex number). 11414 static bool IsSameFloatAfterCast(const APValue &value, 11415 const llvm::fltSemantics &Src, 11416 const llvm::fltSemantics &Tgt) { 11417 if (value.isFloat()) 11418 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11419 11420 if (value.isVector()) { 11421 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11422 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11423 return false; 11424 return true; 11425 } 11426 11427 assert(value.isComplexFloat()); 11428 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11429 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11430 } 11431 11432 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11433 bool IsListInit = false); 11434 11435 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11436 // Suppress cases where we are comparing against an enum constant. 11437 if (const DeclRefExpr *DR = 11438 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11439 if (isa<EnumConstantDecl>(DR->getDecl())) 11440 return true; 11441 11442 // Suppress cases where the value is expanded from a macro, unless that macro 11443 // is how a language represents a boolean literal. This is the case in both C 11444 // and Objective-C. 11445 SourceLocation BeginLoc = E->getBeginLoc(); 11446 if (BeginLoc.isMacroID()) { 11447 StringRef MacroName = Lexer::getImmediateMacroName( 11448 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11449 return MacroName != "YES" && MacroName != "NO" && 11450 MacroName != "true" && MacroName != "false"; 11451 } 11452 11453 return false; 11454 } 11455 11456 static bool isKnownToHaveUnsignedValue(Expr *E) { 11457 return E->getType()->isIntegerType() && 11458 (!E->getType()->isSignedIntegerType() || 11459 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11460 } 11461 11462 namespace { 11463 /// The promoted range of values of a type. In general this has the 11464 /// following structure: 11465 /// 11466 /// |-----------| . . . |-----------| 11467 /// ^ ^ ^ ^ 11468 /// Min HoleMin HoleMax Max 11469 /// 11470 /// ... where there is only a hole if a signed type is promoted to unsigned 11471 /// (in which case Min and Max are the smallest and largest representable 11472 /// values). 11473 struct PromotedRange { 11474 // Min, or HoleMax if there is a hole. 11475 llvm::APSInt PromotedMin; 11476 // Max, or HoleMin if there is a hole. 11477 llvm::APSInt PromotedMax; 11478 11479 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11480 if (R.Width == 0) 11481 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11482 else if (R.Width >= BitWidth && !Unsigned) { 11483 // Promotion made the type *narrower*. This happens when promoting 11484 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11485 // Treat all values of 'signed int' as being in range for now. 11486 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11487 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11488 } else { 11489 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11490 .extOrTrunc(BitWidth); 11491 PromotedMin.setIsUnsigned(Unsigned); 11492 11493 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11494 .extOrTrunc(BitWidth); 11495 PromotedMax.setIsUnsigned(Unsigned); 11496 } 11497 } 11498 11499 // Determine whether this range is contiguous (has no hole). 11500 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11501 11502 // Where a constant value is within the range. 11503 enum ComparisonResult { 11504 LT = 0x1, 11505 LE = 0x2, 11506 GT = 0x4, 11507 GE = 0x8, 11508 EQ = 0x10, 11509 NE = 0x20, 11510 InRangeFlag = 0x40, 11511 11512 Less = LE | LT | NE, 11513 Min = LE | InRangeFlag, 11514 InRange = InRangeFlag, 11515 Max = GE | InRangeFlag, 11516 Greater = GE | GT | NE, 11517 11518 OnlyValue = LE | GE | EQ | InRangeFlag, 11519 InHole = NE 11520 }; 11521 11522 ComparisonResult compare(const llvm::APSInt &Value) const { 11523 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11524 Value.isUnsigned() == PromotedMin.isUnsigned()); 11525 if (!isContiguous()) { 11526 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11527 if (Value.isMinValue()) return Min; 11528 if (Value.isMaxValue()) return Max; 11529 if (Value >= PromotedMin) return InRange; 11530 if (Value <= PromotedMax) return InRange; 11531 return InHole; 11532 } 11533 11534 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11535 case -1: return Less; 11536 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11537 case 1: 11538 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11539 case -1: return InRange; 11540 case 0: return Max; 11541 case 1: return Greater; 11542 } 11543 } 11544 11545 llvm_unreachable("impossible compare result"); 11546 } 11547 11548 static llvm::Optional<StringRef> 11549 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11550 if (Op == BO_Cmp) { 11551 ComparisonResult LTFlag = LT, GTFlag = GT; 11552 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11553 11554 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11555 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11556 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11557 return llvm::None; 11558 } 11559 11560 ComparisonResult TrueFlag, FalseFlag; 11561 if (Op == BO_EQ) { 11562 TrueFlag = EQ; 11563 FalseFlag = NE; 11564 } else if (Op == BO_NE) { 11565 TrueFlag = NE; 11566 FalseFlag = EQ; 11567 } else { 11568 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11569 TrueFlag = LT; 11570 FalseFlag = GE; 11571 } else { 11572 TrueFlag = GT; 11573 FalseFlag = LE; 11574 } 11575 if (Op == BO_GE || Op == BO_LE) 11576 std::swap(TrueFlag, FalseFlag); 11577 } 11578 if (R & TrueFlag) 11579 return StringRef("true"); 11580 if (R & FalseFlag) 11581 return StringRef("false"); 11582 return llvm::None; 11583 } 11584 }; 11585 } 11586 11587 static bool HasEnumType(Expr *E) { 11588 // Strip off implicit integral promotions. 11589 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11590 if (ICE->getCastKind() != CK_IntegralCast && 11591 ICE->getCastKind() != CK_NoOp) 11592 break; 11593 E = ICE->getSubExpr(); 11594 } 11595 11596 return E->getType()->isEnumeralType(); 11597 } 11598 11599 static int classifyConstantValue(Expr *Constant) { 11600 // The values of this enumeration are used in the diagnostics 11601 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11602 enum ConstantValueKind { 11603 Miscellaneous = 0, 11604 LiteralTrue, 11605 LiteralFalse 11606 }; 11607 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11608 return BL->getValue() ? ConstantValueKind::LiteralTrue 11609 : ConstantValueKind::LiteralFalse; 11610 return ConstantValueKind::Miscellaneous; 11611 } 11612 11613 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11614 Expr *Constant, Expr *Other, 11615 const llvm::APSInt &Value, 11616 bool RhsConstant) { 11617 if (S.inTemplateInstantiation()) 11618 return false; 11619 11620 Expr *OriginalOther = Other; 11621 11622 Constant = Constant->IgnoreParenImpCasts(); 11623 Other = Other->IgnoreParenImpCasts(); 11624 11625 // Suppress warnings on tautological comparisons between values of the same 11626 // enumeration type. There are only two ways we could warn on this: 11627 // - If the constant is outside the range of representable values of 11628 // the enumeration. In such a case, we should warn about the cast 11629 // to enumeration type, not about the comparison. 11630 // - If the constant is the maximum / minimum in-range value. For an 11631 // enumeratin type, such comparisons can be meaningful and useful. 11632 if (Constant->getType()->isEnumeralType() && 11633 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11634 return false; 11635 11636 IntRange OtherValueRange = GetExprRange( 11637 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11638 11639 QualType OtherT = Other->getType(); 11640 if (const auto *AT = OtherT->getAs<AtomicType>()) 11641 OtherT = AT->getValueType(); 11642 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11643 11644 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11645 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11646 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11647 S.NSAPIObj->isObjCBOOLType(OtherT) && 11648 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11649 11650 // Whether we're treating Other as being a bool because of the form of 11651 // expression despite it having another type (typically 'int' in C). 11652 bool OtherIsBooleanDespiteType = 11653 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11654 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11655 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11656 11657 // Check if all values in the range of possible values of this expression 11658 // lead to the same comparison outcome. 11659 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11660 Value.isUnsigned()); 11661 auto Cmp = OtherPromotedValueRange.compare(Value); 11662 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11663 if (!Result) 11664 return false; 11665 11666 // Also consider the range determined by the type alone. This allows us to 11667 // classify the warning under the proper diagnostic group. 11668 bool TautologicalTypeCompare = false; 11669 { 11670 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11671 Value.isUnsigned()); 11672 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11673 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11674 RhsConstant)) { 11675 TautologicalTypeCompare = true; 11676 Cmp = TypeCmp; 11677 Result = TypeResult; 11678 } 11679 } 11680 11681 // Don't warn if the non-constant operand actually always evaluates to the 11682 // same value. 11683 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11684 return false; 11685 11686 // Suppress the diagnostic for an in-range comparison if the constant comes 11687 // from a macro or enumerator. We don't want to diagnose 11688 // 11689 // some_long_value <= INT_MAX 11690 // 11691 // when sizeof(int) == sizeof(long). 11692 bool InRange = Cmp & PromotedRange::InRangeFlag; 11693 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11694 return false; 11695 11696 // A comparison of an unsigned bit-field against 0 is really a type problem, 11697 // even though at the type level the bit-field might promote to 'signed int'. 11698 if (Other->refersToBitField() && InRange && Value == 0 && 11699 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11700 TautologicalTypeCompare = true; 11701 11702 // If this is a comparison to an enum constant, include that 11703 // constant in the diagnostic. 11704 const EnumConstantDecl *ED = nullptr; 11705 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11706 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11707 11708 // Should be enough for uint128 (39 decimal digits) 11709 SmallString<64> PrettySourceValue; 11710 llvm::raw_svector_ostream OS(PrettySourceValue); 11711 if (ED) { 11712 OS << '\'' << *ED << "' (" << Value << ")"; 11713 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11714 Constant->IgnoreParenImpCasts())) { 11715 OS << (BL->getValue() ? "YES" : "NO"); 11716 } else { 11717 OS << Value; 11718 } 11719 11720 if (!TautologicalTypeCompare) { 11721 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11722 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11723 << E->getOpcodeStr() << OS.str() << *Result 11724 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11725 return true; 11726 } 11727 11728 if (IsObjCSignedCharBool) { 11729 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11730 S.PDiag(diag::warn_tautological_compare_objc_bool) 11731 << OS.str() << *Result); 11732 return true; 11733 } 11734 11735 // FIXME: We use a somewhat different formatting for the in-range cases and 11736 // cases involving boolean values for historical reasons. We should pick a 11737 // consistent way of presenting these diagnostics. 11738 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11739 11740 S.DiagRuntimeBehavior( 11741 E->getOperatorLoc(), E, 11742 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11743 : diag::warn_tautological_bool_compare) 11744 << OS.str() << classifyConstantValue(Constant) << OtherT 11745 << OtherIsBooleanDespiteType << *Result 11746 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11747 } else { 11748 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11749 unsigned Diag = 11750 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11751 ? (HasEnumType(OriginalOther) 11752 ? diag::warn_unsigned_enum_always_true_comparison 11753 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11754 : diag::warn_unsigned_always_true_comparison) 11755 : diag::warn_tautological_constant_compare; 11756 11757 S.Diag(E->getOperatorLoc(), Diag) 11758 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11759 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11760 } 11761 11762 return true; 11763 } 11764 11765 /// Analyze the operands of the given comparison. Implements the 11766 /// fallback case from AnalyzeComparison. 11767 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11768 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11769 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11770 } 11771 11772 /// Implements -Wsign-compare. 11773 /// 11774 /// \param E the binary operator to check for warnings 11775 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11776 // The type the comparison is being performed in. 11777 QualType T = E->getLHS()->getType(); 11778 11779 // Only analyze comparison operators where both sides have been converted to 11780 // the same type. 11781 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11782 return AnalyzeImpConvsInComparison(S, E); 11783 11784 // Don't analyze value-dependent comparisons directly. 11785 if (E->isValueDependent()) 11786 return AnalyzeImpConvsInComparison(S, E); 11787 11788 Expr *LHS = E->getLHS(); 11789 Expr *RHS = E->getRHS(); 11790 11791 if (T->isIntegralType(S.Context)) { 11792 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11793 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11794 11795 // We don't care about expressions whose result is a constant. 11796 if (RHSValue && LHSValue) 11797 return AnalyzeImpConvsInComparison(S, E); 11798 11799 // We only care about expressions where just one side is literal 11800 if ((bool)RHSValue ^ (bool)LHSValue) { 11801 // Is the constant on the RHS or LHS? 11802 const bool RhsConstant = (bool)RHSValue; 11803 Expr *Const = RhsConstant ? RHS : LHS; 11804 Expr *Other = RhsConstant ? LHS : RHS; 11805 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11806 11807 // Check whether an integer constant comparison results in a value 11808 // of 'true' or 'false'. 11809 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11810 return AnalyzeImpConvsInComparison(S, E); 11811 } 11812 } 11813 11814 if (!T->hasUnsignedIntegerRepresentation()) { 11815 // We don't do anything special if this isn't an unsigned integral 11816 // comparison: we're only interested in integral comparisons, and 11817 // signed comparisons only happen in cases we don't care to warn about. 11818 return AnalyzeImpConvsInComparison(S, E); 11819 } 11820 11821 LHS = LHS->IgnoreParenImpCasts(); 11822 RHS = RHS->IgnoreParenImpCasts(); 11823 11824 if (!S.getLangOpts().CPlusPlus) { 11825 // Avoid warning about comparison of integers with different signs when 11826 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11827 // the type of `E`. 11828 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11829 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11830 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11831 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11832 } 11833 11834 // Check to see if one of the (unmodified) operands is of different 11835 // signedness. 11836 Expr *signedOperand, *unsignedOperand; 11837 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11838 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11839 "unsigned comparison between two signed integer expressions?"); 11840 signedOperand = LHS; 11841 unsignedOperand = RHS; 11842 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11843 signedOperand = RHS; 11844 unsignedOperand = LHS; 11845 } else { 11846 return AnalyzeImpConvsInComparison(S, E); 11847 } 11848 11849 // Otherwise, calculate the effective range of the signed operand. 11850 IntRange signedRange = GetExprRange( 11851 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11852 11853 // Go ahead and analyze implicit conversions in the operands. Note 11854 // that we skip the implicit conversions on both sides. 11855 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11856 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11857 11858 // If the signed range is non-negative, -Wsign-compare won't fire. 11859 if (signedRange.NonNegative) 11860 return; 11861 11862 // For (in)equality comparisons, if the unsigned operand is a 11863 // constant which cannot collide with a overflowed signed operand, 11864 // then reinterpreting the signed operand as unsigned will not 11865 // change the result of the comparison. 11866 if (E->isEqualityOp()) { 11867 unsigned comparisonWidth = S.Context.getIntWidth(T); 11868 IntRange unsignedRange = 11869 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11870 /*Approximate*/ true); 11871 11872 // We should never be unable to prove that the unsigned operand is 11873 // non-negative. 11874 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11875 11876 if (unsignedRange.Width < comparisonWidth) 11877 return; 11878 } 11879 11880 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11881 S.PDiag(diag::warn_mixed_sign_comparison) 11882 << LHS->getType() << RHS->getType() 11883 << LHS->getSourceRange() << RHS->getSourceRange()); 11884 } 11885 11886 /// Analyzes an attempt to assign the given value to a bitfield. 11887 /// 11888 /// Returns true if there was something fishy about the attempt. 11889 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11890 SourceLocation InitLoc) { 11891 assert(Bitfield->isBitField()); 11892 if (Bitfield->isInvalidDecl()) 11893 return false; 11894 11895 // White-list bool bitfields. 11896 QualType BitfieldType = Bitfield->getType(); 11897 if (BitfieldType->isBooleanType()) 11898 return false; 11899 11900 if (BitfieldType->isEnumeralType()) { 11901 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11902 // If the underlying enum type was not explicitly specified as an unsigned 11903 // type and the enum contain only positive values, MSVC++ will cause an 11904 // inconsistency by storing this as a signed type. 11905 if (S.getLangOpts().CPlusPlus11 && 11906 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11907 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11908 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11909 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11910 << BitfieldEnumDecl; 11911 } 11912 } 11913 11914 if (Bitfield->getType()->isBooleanType()) 11915 return false; 11916 11917 // Ignore value- or type-dependent expressions. 11918 if (Bitfield->getBitWidth()->isValueDependent() || 11919 Bitfield->getBitWidth()->isTypeDependent() || 11920 Init->isValueDependent() || 11921 Init->isTypeDependent()) 11922 return false; 11923 11924 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11925 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11926 11927 Expr::EvalResult Result; 11928 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11929 Expr::SE_AllowSideEffects)) { 11930 // The RHS is not constant. If the RHS has an enum type, make sure the 11931 // bitfield is wide enough to hold all the values of the enum without 11932 // truncation. 11933 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11934 EnumDecl *ED = EnumTy->getDecl(); 11935 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11936 11937 // Enum types are implicitly signed on Windows, so check if there are any 11938 // negative enumerators to see if the enum was intended to be signed or 11939 // not. 11940 bool SignedEnum = ED->getNumNegativeBits() > 0; 11941 11942 // Check for surprising sign changes when assigning enum values to a 11943 // bitfield of different signedness. If the bitfield is signed and we 11944 // have exactly the right number of bits to store this unsigned enum, 11945 // suggest changing the enum to an unsigned type. This typically happens 11946 // on Windows where unfixed enums always use an underlying type of 'int'. 11947 unsigned DiagID = 0; 11948 if (SignedEnum && !SignedBitfield) { 11949 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11950 } else if (SignedBitfield && !SignedEnum && 11951 ED->getNumPositiveBits() == FieldWidth) { 11952 DiagID = diag::warn_signed_bitfield_enum_conversion; 11953 } 11954 11955 if (DiagID) { 11956 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11957 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11958 SourceRange TypeRange = 11959 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11960 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11961 << SignedEnum << TypeRange; 11962 } 11963 11964 // Compute the required bitwidth. If the enum has negative values, we need 11965 // one more bit than the normal number of positive bits to represent the 11966 // sign bit. 11967 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11968 ED->getNumNegativeBits()) 11969 : ED->getNumPositiveBits(); 11970 11971 // Check the bitwidth. 11972 if (BitsNeeded > FieldWidth) { 11973 Expr *WidthExpr = Bitfield->getBitWidth(); 11974 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11975 << Bitfield << ED; 11976 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11977 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11978 } 11979 } 11980 11981 return false; 11982 } 11983 11984 llvm::APSInt Value = Result.Val.getInt(); 11985 11986 unsigned OriginalWidth = Value.getBitWidth(); 11987 11988 if (!Value.isSigned() || Value.isNegative()) 11989 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11990 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11991 OriginalWidth = Value.getMinSignedBits(); 11992 11993 if (OriginalWidth <= FieldWidth) 11994 return false; 11995 11996 // Compute the value which the bitfield will contain. 11997 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11998 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11999 12000 // Check whether the stored value is equal to the original value. 12001 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12002 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12003 return false; 12004 12005 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12006 // therefore don't strictly fit into a signed bitfield of width 1. 12007 if (FieldWidth == 1 && Value == 1) 12008 return false; 12009 12010 std::string PrettyValue = toString(Value, 10); 12011 std::string PrettyTrunc = toString(TruncatedValue, 10); 12012 12013 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12014 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12015 << Init->getSourceRange(); 12016 12017 return true; 12018 } 12019 12020 /// Analyze the given simple or compound assignment for warning-worthy 12021 /// operations. 12022 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12023 // Just recurse on the LHS. 12024 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12025 12026 // We want to recurse on the RHS as normal unless we're assigning to 12027 // a bitfield. 12028 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12029 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12030 E->getOperatorLoc())) { 12031 // Recurse, ignoring any implicit conversions on the RHS. 12032 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12033 E->getOperatorLoc()); 12034 } 12035 } 12036 12037 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12038 12039 // Diagnose implicitly sequentially-consistent atomic assignment. 12040 if (E->getLHS()->getType()->isAtomicType()) 12041 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12042 } 12043 12044 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12045 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12046 SourceLocation CContext, unsigned diag, 12047 bool pruneControlFlow = false) { 12048 if (pruneControlFlow) { 12049 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12050 S.PDiag(diag) 12051 << SourceType << T << E->getSourceRange() 12052 << SourceRange(CContext)); 12053 return; 12054 } 12055 S.Diag(E->getExprLoc(), diag) 12056 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12057 } 12058 12059 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12060 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12061 SourceLocation CContext, 12062 unsigned diag, bool pruneControlFlow = false) { 12063 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12064 } 12065 12066 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12067 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12068 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12069 } 12070 12071 static void adornObjCBoolConversionDiagWithTernaryFixit( 12072 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12073 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12074 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12075 Ignored = OVE->getSourceExpr(); 12076 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12077 isa<BinaryOperator>(Ignored) || 12078 isa<CXXOperatorCallExpr>(Ignored); 12079 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12080 if (NeedsParens) 12081 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12082 << FixItHint::CreateInsertion(EndLoc, ")"); 12083 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12084 } 12085 12086 /// Diagnose an implicit cast from a floating point value to an integer value. 12087 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12088 SourceLocation CContext) { 12089 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12090 const bool PruneWarnings = S.inTemplateInstantiation(); 12091 12092 Expr *InnerE = E->IgnoreParenImpCasts(); 12093 // We also want to warn on, e.g., "int i = -1.234" 12094 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12095 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12096 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12097 12098 const bool IsLiteral = 12099 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12100 12101 llvm::APFloat Value(0.0); 12102 bool IsConstant = 12103 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12104 if (!IsConstant) { 12105 if (isObjCSignedCharBool(S, T)) { 12106 return adornObjCBoolConversionDiagWithTernaryFixit( 12107 S, E, 12108 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12109 << E->getType()); 12110 } 12111 12112 return DiagnoseImpCast(S, E, T, CContext, 12113 diag::warn_impcast_float_integer, PruneWarnings); 12114 } 12115 12116 bool isExact = false; 12117 12118 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12119 T->hasUnsignedIntegerRepresentation()); 12120 llvm::APFloat::opStatus Result = Value.convertToInteger( 12121 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12122 12123 // FIXME: Force the precision of the source value down so we don't print 12124 // digits which are usually useless (we don't really care here if we 12125 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12126 // would automatically print the shortest representation, but it's a bit 12127 // tricky to implement. 12128 SmallString<16> PrettySourceValue; 12129 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12130 precision = (precision * 59 + 195) / 196; 12131 Value.toString(PrettySourceValue, precision); 12132 12133 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12134 return adornObjCBoolConversionDiagWithTernaryFixit( 12135 S, E, 12136 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12137 << PrettySourceValue); 12138 } 12139 12140 if (Result == llvm::APFloat::opOK && isExact) { 12141 if (IsLiteral) return; 12142 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12143 PruneWarnings); 12144 } 12145 12146 // Conversion of a floating-point value to a non-bool integer where the 12147 // integral part cannot be represented by the integer type is undefined. 12148 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12149 return DiagnoseImpCast( 12150 S, E, T, CContext, 12151 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12152 : diag::warn_impcast_float_to_integer_out_of_range, 12153 PruneWarnings); 12154 12155 unsigned DiagID = 0; 12156 if (IsLiteral) { 12157 // Warn on floating point literal to integer. 12158 DiagID = diag::warn_impcast_literal_float_to_integer; 12159 } else if (IntegerValue == 0) { 12160 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12161 return DiagnoseImpCast(S, E, T, CContext, 12162 diag::warn_impcast_float_integer, PruneWarnings); 12163 } 12164 // Warn on non-zero to zero conversion. 12165 DiagID = diag::warn_impcast_float_to_integer_zero; 12166 } else { 12167 if (IntegerValue.isUnsigned()) { 12168 if (!IntegerValue.isMaxValue()) { 12169 return DiagnoseImpCast(S, E, T, CContext, 12170 diag::warn_impcast_float_integer, PruneWarnings); 12171 } 12172 } else { // IntegerValue.isSigned() 12173 if (!IntegerValue.isMaxSignedValue() && 12174 !IntegerValue.isMinSignedValue()) { 12175 return DiagnoseImpCast(S, E, T, CContext, 12176 diag::warn_impcast_float_integer, PruneWarnings); 12177 } 12178 } 12179 // Warn on evaluatable floating point expression to integer conversion. 12180 DiagID = diag::warn_impcast_float_to_integer; 12181 } 12182 12183 SmallString<16> PrettyTargetValue; 12184 if (IsBool) 12185 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12186 else 12187 IntegerValue.toString(PrettyTargetValue); 12188 12189 if (PruneWarnings) { 12190 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12191 S.PDiag(DiagID) 12192 << E->getType() << T.getUnqualifiedType() 12193 << PrettySourceValue << PrettyTargetValue 12194 << E->getSourceRange() << SourceRange(CContext)); 12195 } else { 12196 S.Diag(E->getExprLoc(), DiagID) 12197 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12198 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12199 } 12200 } 12201 12202 /// Analyze the given compound assignment for the possible losing of 12203 /// floating-point precision. 12204 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12205 assert(isa<CompoundAssignOperator>(E) && 12206 "Must be compound assignment operation"); 12207 // Recurse on the LHS and RHS in here 12208 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12209 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12210 12211 if (E->getLHS()->getType()->isAtomicType()) 12212 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12213 12214 // Now check the outermost expression 12215 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12216 const auto *RBT = cast<CompoundAssignOperator>(E) 12217 ->getComputationResultType() 12218 ->getAs<BuiltinType>(); 12219 12220 // The below checks assume source is floating point. 12221 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12222 12223 // If source is floating point but target is an integer. 12224 if (ResultBT->isInteger()) 12225 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12226 E->getExprLoc(), diag::warn_impcast_float_integer); 12227 12228 if (!ResultBT->isFloatingPoint()) 12229 return; 12230 12231 // If both source and target are floating points, warn about losing precision. 12232 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12233 QualType(ResultBT, 0), QualType(RBT, 0)); 12234 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12235 // warn about dropping FP rank. 12236 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12237 diag::warn_impcast_float_result_precision); 12238 } 12239 12240 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12241 IntRange Range) { 12242 if (!Range.Width) return "0"; 12243 12244 llvm::APSInt ValueInRange = Value; 12245 ValueInRange.setIsSigned(!Range.NonNegative); 12246 ValueInRange = ValueInRange.trunc(Range.Width); 12247 return toString(ValueInRange, 10); 12248 } 12249 12250 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12251 if (!isa<ImplicitCastExpr>(Ex)) 12252 return false; 12253 12254 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12255 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12256 const Type *Source = 12257 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12258 if (Target->isDependentType()) 12259 return false; 12260 12261 const BuiltinType *FloatCandidateBT = 12262 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12263 const Type *BoolCandidateType = ToBool ? Target : Source; 12264 12265 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12266 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12267 } 12268 12269 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12270 SourceLocation CC) { 12271 unsigned NumArgs = TheCall->getNumArgs(); 12272 for (unsigned i = 0; i < NumArgs; ++i) { 12273 Expr *CurrA = TheCall->getArg(i); 12274 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12275 continue; 12276 12277 bool IsSwapped = ((i > 0) && 12278 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12279 IsSwapped |= ((i < (NumArgs - 1)) && 12280 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12281 if (IsSwapped) { 12282 // Warn on this floating-point to bool conversion. 12283 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12284 CurrA->getType(), CC, 12285 diag::warn_impcast_floating_point_to_bool); 12286 } 12287 } 12288 } 12289 12290 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12291 SourceLocation CC) { 12292 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12293 E->getExprLoc())) 12294 return; 12295 12296 // Don't warn on functions which have return type nullptr_t. 12297 if (isa<CallExpr>(E)) 12298 return; 12299 12300 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12301 const Expr::NullPointerConstantKind NullKind = 12302 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12303 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12304 return; 12305 12306 // Return if target type is a safe conversion. 12307 if (T->isAnyPointerType() || T->isBlockPointerType() || 12308 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12309 return; 12310 12311 SourceLocation Loc = E->getSourceRange().getBegin(); 12312 12313 // Venture through the macro stacks to get to the source of macro arguments. 12314 // The new location is a better location than the complete location that was 12315 // passed in. 12316 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12317 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12318 12319 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12320 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12321 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12322 Loc, S.SourceMgr, S.getLangOpts()); 12323 if (MacroName == "NULL") 12324 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12325 } 12326 12327 // Only warn if the null and context location are in the same macro expansion. 12328 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12329 return; 12330 12331 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12332 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12333 << FixItHint::CreateReplacement(Loc, 12334 S.getFixItZeroLiteralForType(T, Loc)); 12335 } 12336 12337 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12338 ObjCArrayLiteral *ArrayLiteral); 12339 12340 static void 12341 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12342 ObjCDictionaryLiteral *DictionaryLiteral); 12343 12344 /// Check a single element within a collection literal against the 12345 /// target element type. 12346 static void checkObjCCollectionLiteralElement(Sema &S, 12347 QualType TargetElementType, 12348 Expr *Element, 12349 unsigned ElementKind) { 12350 // Skip a bitcast to 'id' or qualified 'id'. 12351 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12352 if (ICE->getCastKind() == CK_BitCast && 12353 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12354 Element = ICE->getSubExpr(); 12355 } 12356 12357 QualType ElementType = Element->getType(); 12358 ExprResult ElementResult(Element); 12359 if (ElementType->getAs<ObjCObjectPointerType>() && 12360 S.CheckSingleAssignmentConstraints(TargetElementType, 12361 ElementResult, 12362 false, false) 12363 != Sema::Compatible) { 12364 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12365 << ElementType << ElementKind << TargetElementType 12366 << Element->getSourceRange(); 12367 } 12368 12369 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12370 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12371 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12372 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12373 } 12374 12375 /// Check an Objective-C array literal being converted to the given 12376 /// target type. 12377 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12378 ObjCArrayLiteral *ArrayLiteral) { 12379 if (!S.NSArrayDecl) 12380 return; 12381 12382 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12383 if (!TargetObjCPtr) 12384 return; 12385 12386 if (TargetObjCPtr->isUnspecialized() || 12387 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12388 != S.NSArrayDecl->getCanonicalDecl()) 12389 return; 12390 12391 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12392 if (TypeArgs.size() != 1) 12393 return; 12394 12395 QualType TargetElementType = TypeArgs[0]; 12396 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12397 checkObjCCollectionLiteralElement(S, TargetElementType, 12398 ArrayLiteral->getElement(I), 12399 0); 12400 } 12401 } 12402 12403 /// Check an Objective-C dictionary literal being converted to the given 12404 /// target type. 12405 static void 12406 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12407 ObjCDictionaryLiteral *DictionaryLiteral) { 12408 if (!S.NSDictionaryDecl) 12409 return; 12410 12411 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12412 if (!TargetObjCPtr) 12413 return; 12414 12415 if (TargetObjCPtr->isUnspecialized() || 12416 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12417 != S.NSDictionaryDecl->getCanonicalDecl()) 12418 return; 12419 12420 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12421 if (TypeArgs.size() != 2) 12422 return; 12423 12424 QualType TargetKeyType = TypeArgs[0]; 12425 QualType TargetObjectType = TypeArgs[1]; 12426 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12427 auto Element = DictionaryLiteral->getKeyValueElement(I); 12428 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12429 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12430 } 12431 } 12432 12433 // Helper function to filter out cases for constant width constant conversion. 12434 // Don't warn on char array initialization or for non-decimal values. 12435 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12436 SourceLocation CC) { 12437 // If initializing from a constant, and the constant starts with '0', 12438 // then it is a binary, octal, or hexadecimal. Allow these constants 12439 // to fill all the bits, even if there is a sign change. 12440 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12441 const char FirstLiteralCharacter = 12442 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12443 if (FirstLiteralCharacter == '0') 12444 return false; 12445 } 12446 12447 // If the CC location points to a '{', and the type is char, then assume 12448 // assume it is an array initialization. 12449 if (CC.isValid() && T->isCharType()) { 12450 const char FirstContextCharacter = 12451 S.getSourceManager().getCharacterData(CC)[0]; 12452 if (FirstContextCharacter == '{') 12453 return false; 12454 } 12455 12456 return true; 12457 } 12458 12459 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12460 const auto *IL = dyn_cast<IntegerLiteral>(E); 12461 if (!IL) { 12462 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12463 if (UO->getOpcode() == UO_Minus) 12464 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12465 } 12466 } 12467 12468 return IL; 12469 } 12470 12471 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12472 E = E->IgnoreParenImpCasts(); 12473 SourceLocation ExprLoc = E->getExprLoc(); 12474 12475 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12476 BinaryOperator::Opcode Opc = BO->getOpcode(); 12477 Expr::EvalResult Result; 12478 // Do not diagnose unsigned shifts. 12479 if (Opc == BO_Shl) { 12480 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12481 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12482 if (LHS && LHS->getValue() == 0) 12483 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12484 else if (!E->isValueDependent() && LHS && RHS && 12485 RHS->getValue().isNonNegative() && 12486 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12487 S.Diag(ExprLoc, diag::warn_left_shift_always) 12488 << (Result.Val.getInt() != 0); 12489 else if (E->getType()->isSignedIntegerType()) 12490 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12491 } 12492 } 12493 12494 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12495 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12496 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12497 if (!LHS || !RHS) 12498 return; 12499 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12500 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12501 // Do not diagnose common idioms. 12502 return; 12503 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12504 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12505 } 12506 } 12507 12508 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12509 SourceLocation CC, 12510 bool *ICContext = nullptr, 12511 bool IsListInit = false) { 12512 if (E->isTypeDependent() || E->isValueDependent()) return; 12513 12514 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12515 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12516 if (Source == Target) return; 12517 if (Target->isDependentType()) return; 12518 12519 // If the conversion context location is invalid don't complain. We also 12520 // don't want to emit a warning if the issue occurs from the expansion of 12521 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12522 // delay this check as long as possible. Once we detect we are in that 12523 // scenario, we just return. 12524 if (CC.isInvalid()) 12525 return; 12526 12527 if (Source->isAtomicType()) 12528 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12529 12530 // Diagnose implicit casts to bool. 12531 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12532 if (isa<StringLiteral>(E)) 12533 // Warn on string literal to bool. Checks for string literals in logical 12534 // and expressions, for instance, assert(0 && "error here"), are 12535 // prevented by a check in AnalyzeImplicitConversions(). 12536 return DiagnoseImpCast(S, E, T, CC, 12537 diag::warn_impcast_string_literal_to_bool); 12538 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12539 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12540 // This covers the literal expressions that evaluate to Objective-C 12541 // objects. 12542 return DiagnoseImpCast(S, E, T, CC, 12543 diag::warn_impcast_objective_c_literal_to_bool); 12544 } 12545 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12546 // Warn on pointer to bool conversion that is always true. 12547 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12548 SourceRange(CC)); 12549 } 12550 } 12551 12552 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12553 // is a typedef for signed char (macOS), then that constant value has to be 1 12554 // or 0. 12555 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12556 Expr::EvalResult Result; 12557 if (E->EvaluateAsInt(Result, S.getASTContext(), 12558 Expr::SE_AllowSideEffects)) { 12559 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12560 adornObjCBoolConversionDiagWithTernaryFixit( 12561 S, E, 12562 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12563 << toString(Result.Val.getInt(), 10)); 12564 } 12565 return; 12566 } 12567 } 12568 12569 // Check implicit casts from Objective-C collection literals to specialized 12570 // collection types, e.g., NSArray<NSString *> *. 12571 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12572 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12573 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12574 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12575 12576 // Strip vector types. 12577 if (isa<VectorType>(Source)) { 12578 if (Target->isVLSTBuiltinType() && 12579 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12580 QualType(Source, 0)) || 12581 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12582 QualType(Source, 0)))) 12583 return; 12584 12585 if (!isa<VectorType>(Target)) { 12586 if (S.SourceMgr.isInSystemMacro(CC)) 12587 return; 12588 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12589 } 12590 12591 // If the vector cast is cast between two vectors of the same size, it is 12592 // a bitcast, not a conversion. 12593 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12594 return; 12595 12596 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12597 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12598 } 12599 if (auto VecTy = dyn_cast<VectorType>(Target)) 12600 Target = VecTy->getElementType().getTypePtr(); 12601 12602 // Strip complex types. 12603 if (isa<ComplexType>(Source)) { 12604 if (!isa<ComplexType>(Target)) { 12605 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12606 return; 12607 12608 return DiagnoseImpCast(S, E, T, CC, 12609 S.getLangOpts().CPlusPlus 12610 ? diag::err_impcast_complex_scalar 12611 : diag::warn_impcast_complex_scalar); 12612 } 12613 12614 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12615 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12616 } 12617 12618 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12619 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12620 12621 // If the source is floating point... 12622 if (SourceBT && SourceBT->isFloatingPoint()) { 12623 // ...and the target is floating point... 12624 if (TargetBT && TargetBT->isFloatingPoint()) { 12625 // ...then warn if we're dropping FP rank. 12626 12627 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12628 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12629 if (Order > 0) { 12630 // Don't warn about float constants that are precisely 12631 // representable in the target type. 12632 Expr::EvalResult result; 12633 if (E->EvaluateAsRValue(result, S.Context)) { 12634 // Value might be a float, a float vector, or a float complex. 12635 if (IsSameFloatAfterCast(result.Val, 12636 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12637 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12638 return; 12639 } 12640 12641 if (S.SourceMgr.isInSystemMacro(CC)) 12642 return; 12643 12644 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12645 } 12646 // ... or possibly if we're increasing rank, too 12647 else if (Order < 0) { 12648 if (S.SourceMgr.isInSystemMacro(CC)) 12649 return; 12650 12651 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12652 } 12653 return; 12654 } 12655 12656 // If the target is integral, always warn. 12657 if (TargetBT && TargetBT->isInteger()) { 12658 if (S.SourceMgr.isInSystemMacro(CC)) 12659 return; 12660 12661 DiagnoseFloatingImpCast(S, E, T, CC); 12662 } 12663 12664 // Detect the case where a call result is converted from floating-point to 12665 // to bool, and the final argument to the call is converted from bool, to 12666 // discover this typo: 12667 // 12668 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12669 // 12670 // FIXME: This is an incredibly special case; is there some more general 12671 // way to detect this class of misplaced-parentheses bug? 12672 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12673 // Check last argument of function call to see if it is an 12674 // implicit cast from a type matching the type the result 12675 // is being cast to. 12676 CallExpr *CEx = cast<CallExpr>(E); 12677 if (unsigned NumArgs = CEx->getNumArgs()) { 12678 Expr *LastA = CEx->getArg(NumArgs - 1); 12679 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12680 if (isa<ImplicitCastExpr>(LastA) && 12681 InnerE->getType()->isBooleanType()) { 12682 // Warn on this floating-point to bool conversion 12683 DiagnoseImpCast(S, E, T, CC, 12684 diag::warn_impcast_floating_point_to_bool); 12685 } 12686 } 12687 } 12688 return; 12689 } 12690 12691 // Valid casts involving fixed point types should be accounted for here. 12692 if (Source->isFixedPointType()) { 12693 if (Target->isUnsaturatedFixedPointType()) { 12694 Expr::EvalResult Result; 12695 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12696 S.isConstantEvaluated())) { 12697 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12698 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12699 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12700 if (Value > MaxVal || Value < MinVal) { 12701 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12702 S.PDiag(diag::warn_impcast_fixed_point_range) 12703 << Value.toString() << T 12704 << E->getSourceRange() 12705 << clang::SourceRange(CC)); 12706 return; 12707 } 12708 } 12709 } else if (Target->isIntegerType()) { 12710 Expr::EvalResult Result; 12711 if (!S.isConstantEvaluated() && 12712 E->EvaluateAsFixedPoint(Result, S.Context, 12713 Expr::SE_AllowSideEffects)) { 12714 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12715 12716 bool Overflowed; 12717 llvm::APSInt IntResult = FXResult.convertToInt( 12718 S.Context.getIntWidth(T), 12719 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12720 12721 if (Overflowed) { 12722 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12723 S.PDiag(diag::warn_impcast_fixed_point_range) 12724 << FXResult.toString() << T 12725 << E->getSourceRange() 12726 << clang::SourceRange(CC)); 12727 return; 12728 } 12729 } 12730 } 12731 } else if (Target->isUnsaturatedFixedPointType()) { 12732 if (Source->isIntegerType()) { 12733 Expr::EvalResult Result; 12734 if (!S.isConstantEvaluated() && 12735 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12736 llvm::APSInt Value = Result.Val.getInt(); 12737 12738 bool Overflowed; 12739 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12740 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12741 12742 if (Overflowed) { 12743 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12744 S.PDiag(diag::warn_impcast_fixed_point_range) 12745 << toString(Value, /*Radix=*/10) << T 12746 << E->getSourceRange() 12747 << clang::SourceRange(CC)); 12748 return; 12749 } 12750 } 12751 } 12752 } 12753 12754 // If we are casting an integer type to a floating point type without 12755 // initialization-list syntax, we might lose accuracy if the floating 12756 // point type has a narrower significand than the integer type. 12757 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12758 TargetBT->isFloatingType() && !IsListInit) { 12759 // Determine the number of precision bits in the source integer type. 12760 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12761 /*Approximate*/ true); 12762 unsigned int SourcePrecision = SourceRange.Width; 12763 12764 // Determine the number of precision bits in the 12765 // target floating point type. 12766 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12767 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12768 12769 if (SourcePrecision > 0 && TargetPrecision > 0 && 12770 SourcePrecision > TargetPrecision) { 12771 12772 if (Optional<llvm::APSInt> SourceInt = 12773 E->getIntegerConstantExpr(S.Context)) { 12774 // If the source integer is a constant, convert it to the target 12775 // floating point type. Issue a warning if the value changes 12776 // during the whole conversion. 12777 llvm::APFloat TargetFloatValue( 12778 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12779 llvm::APFloat::opStatus ConversionStatus = 12780 TargetFloatValue.convertFromAPInt( 12781 *SourceInt, SourceBT->isSignedInteger(), 12782 llvm::APFloat::rmNearestTiesToEven); 12783 12784 if (ConversionStatus != llvm::APFloat::opOK) { 12785 SmallString<32> PrettySourceValue; 12786 SourceInt->toString(PrettySourceValue, 10); 12787 SmallString<32> PrettyTargetValue; 12788 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12789 12790 S.DiagRuntimeBehavior( 12791 E->getExprLoc(), E, 12792 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12793 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12794 << E->getSourceRange() << clang::SourceRange(CC)); 12795 } 12796 } else { 12797 // Otherwise, the implicit conversion may lose precision. 12798 DiagnoseImpCast(S, E, T, CC, 12799 diag::warn_impcast_integer_float_precision); 12800 } 12801 } 12802 } 12803 12804 DiagnoseNullConversion(S, E, T, CC); 12805 12806 S.DiscardMisalignedMemberAddress(Target, E); 12807 12808 if (Target->isBooleanType()) 12809 DiagnoseIntInBoolContext(S, E); 12810 12811 if (!Source->isIntegerType() || !Target->isIntegerType()) 12812 return; 12813 12814 // TODO: remove this early return once the false positives for constant->bool 12815 // in templates, macros, etc, are reduced or removed. 12816 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12817 return; 12818 12819 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12820 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12821 return adornObjCBoolConversionDiagWithTernaryFixit( 12822 S, E, 12823 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12824 << E->getType()); 12825 } 12826 12827 IntRange SourceTypeRange = 12828 IntRange::forTargetOfCanonicalType(S.Context, Source); 12829 IntRange LikelySourceRange = 12830 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12831 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12832 12833 if (LikelySourceRange.Width > TargetRange.Width) { 12834 // If the source is a constant, use a default-on diagnostic. 12835 // TODO: this should happen for bitfield stores, too. 12836 Expr::EvalResult Result; 12837 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12838 S.isConstantEvaluated())) { 12839 llvm::APSInt Value(32); 12840 Value = Result.Val.getInt(); 12841 12842 if (S.SourceMgr.isInSystemMacro(CC)) 12843 return; 12844 12845 std::string PrettySourceValue = toString(Value, 10); 12846 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12847 12848 S.DiagRuntimeBehavior( 12849 E->getExprLoc(), E, 12850 S.PDiag(diag::warn_impcast_integer_precision_constant) 12851 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12852 << E->getSourceRange() << SourceRange(CC)); 12853 return; 12854 } 12855 12856 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12857 if (S.SourceMgr.isInSystemMacro(CC)) 12858 return; 12859 12860 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12861 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12862 /* pruneControlFlow */ true); 12863 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12864 } 12865 12866 if (TargetRange.Width > SourceTypeRange.Width) { 12867 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12868 if (UO->getOpcode() == UO_Minus) 12869 if (Source->isUnsignedIntegerType()) { 12870 if (Target->isUnsignedIntegerType()) 12871 return DiagnoseImpCast(S, E, T, CC, 12872 diag::warn_impcast_high_order_zero_bits); 12873 if (Target->isSignedIntegerType()) 12874 return DiagnoseImpCast(S, E, T, CC, 12875 diag::warn_impcast_nonnegative_result); 12876 } 12877 } 12878 12879 if (TargetRange.Width == LikelySourceRange.Width && 12880 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12881 Source->isSignedIntegerType()) { 12882 // Warn when doing a signed to signed conversion, warn if the positive 12883 // source value is exactly the width of the target type, which will 12884 // cause a negative value to be stored. 12885 12886 Expr::EvalResult Result; 12887 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12888 !S.SourceMgr.isInSystemMacro(CC)) { 12889 llvm::APSInt Value = Result.Val.getInt(); 12890 if (isSameWidthConstantConversion(S, E, T, CC)) { 12891 std::string PrettySourceValue = toString(Value, 10); 12892 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12893 12894 S.DiagRuntimeBehavior( 12895 E->getExprLoc(), E, 12896 S.PDiag(diag::warn_impcast_integer_precision_constant) 12897 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12898 << E->getSourceRange() << SourceRange(CC)); 12899 return; 12900 } 12901 } 12902 12903 // Fall through for non-constants to give a sign conversion warning. 12904 } 12905 12906 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12907 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12908 LikelySourceRange.Width == TargetRange.Width)) { 12909 if (S.SourceMgr.isInSystemMacro(CC)) 12910 return; 12911 12912 unsigned DiagID = diag::warn_impcast_integer_sign; 12913 12914 // Traditionally, gcc has warned about this under -Wsign-compare. 12915 // We also want to warn about it in -Wconversion. 12916 // So if -Wconversion is off, use a completely identical diagnostic 12917 // in the sign-compare group. 12918 // The conditional-checking code will 12919 if (ICContext) { 12920 DiagID = diag::warn_impcast_integer_sign_conditional; 12921 *ICContext = true; 12922 } 12923 12924 return DiagnoseImpCast(S, E, T, CC, DiagID); 12925 } 12926 12927 // Diagnose conversions between different enumeration types. 12928 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12929 // type, to give us better diagnostics. 12930 QualType SourceType = E->getType(); 12931 if (!S.getLangOpts().CPlusPlus) { 12932 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12933 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12934 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12935 SourceType = S.Context.getTypeDeclType(Enum); 12936 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12937 } 12938 } 12939 12940 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12941 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12942 if (SourceEnum->getDecl()->hasNameForLinkage() && 12943 TargetEnum->getDecl()->hasNameForLinkage() && 12944 SourceEnum != TargetEnum) { 12945 if (S.SourceMgr.isInSystemMacro(CC)) 12946 return; 12947 12948 return DiagnoseImpCast(S, E, SourceType, T, CC, 12949 diag::warn_impcast_different_enum_types); 12950 } 12951 } 12952 12953 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12954 SourceLocation CC, QualType T); 12955 12956 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12957 SourceLocation CC, bool &ICContext) { 12958 E = E->IgnoreParenImpCasts(); 12959 12960 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12961 return CheckConditionalOperator(S, CO, CC, T); 12962 12963 AnalyzeImplicitConversions(S, E, CC); 12964 if (E->getType() != T) 12965 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12966 } 12967 12968 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12969 SourceLocation CC, QualType T) { 12970 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12971 12972 Expr *TrueExpr = E->getTrueExpr(); 12973 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12974 TrueExpr = BCO->getCommon(); 12975 12976 bool Suspicious = false; 12977 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12978 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12979 12980 if (T->isBooleanType()) 12981 DiagnoseIntInBoolContext(S, E); 12982 12983 // If -Wconversion would have warned about either of the candidates 12984 // for a signedness conversion to the context type... 12985 if (!Suspicious) return; 12986 12987 // ...but it's currently ignored... 12988 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12989 return; 12990 12991 // ...then check whether it would have warned about either of the 12992 // candidates for a signedness conversion to the condition type. 12993 if (E->getType() == T) return; 12994 12995 Suspicious = false; 12996 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12997 E->getType(), CC, &Suspicious); 12998 if (!Suspicious) 12999 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13000 E->getType(), CC, &Suspicious); 13001 } 13002 13003 /// Check conversion of given expression to boolean. 13004 /// Input argument E is a logical expression. 13005 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13006 if (S.getLangOpts().Bool) 13007 return; 13008 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13009 return; 13010 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13011 } 13012 13013 namespace { 13014 struct AnalyzeImplicitConversionsWorkItem { 13015 Expr *E; 13016 SourceLocation CC; 13017 bool IsListInit; 13018 }; 13019 } 13020 13021 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13022 /// that should be visited are added to WorkList. 13023 static void AnalyzeImplicitConversions( 13024 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13025 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13026 Expr *OrigE = Item.E; 13027 SourceLocation CC = Item.CC; 13028 13029 QualType T = OrigE->getType(); 13030 Expr *E = OrigE->IgnoreParenImpCasts(); 13031 13032 // Propagate whether we are in a C++ list initialization expression. 13033 // If so, we do not issue warnings for implicit int-float conversion 13034 // precision loss, because C++11 narrowing already handles it. 13035 bool IsListInit = Item.IsListInit || 13036 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13037 13038 if (E->isTypeDependent() || E->isValueDependent()) 13039 return; 13040 13041 Expr *SourceExpr = E; 13042 // Examine, but don't traverse into the source expression of an 13043 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13044 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13045 // evaluate it in the context of checking the specific conversion to T though. 13046 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13047 if (auto *Src = OVE->getSourceExpr()) 13048 SourceExpr = Src; 13049 13050 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13051 if (UO->getOpcode() == UO_Not && 13052 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13053 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13054 << OrigE->getSourceRange() << T->isBooleanType() 13055 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13056 13057 // For conditional operators, we analyze the arguments as if they 13058 // were being fed directly into the output. 13059 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13060 CheckConditionalOperator(S, CO, CC, T); 13061 return; 13062 } 13063 13064 // Check implicit argument conversions for function calls. 13065 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13066 CheckImplicitArgumentConversions(S, Call, CC); 13067 13068 // Go ahead and check any implicit conversions we might have skipped. 13069 // The non-canonical typecheck is just an optimization; 13070 // CheckImplicitConversion will filter out dead implicit conversions. 13071 if (SourceExpr->getType() != T) 13072 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13073 13074 // Now continue drilling into this expression. 13075 13076 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13077 // The bound subexpressions in a PseudoObjectExpr are not reachable 13078 // as transitive children. 13079 // FIXME: Use a more uniform representation for this. 13080 for (auto *SE : POE->semantics()) 13081 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13082 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13083 } 13084 13085 // Skip past explicit casts. 13086 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13087 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13088 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13089 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13090 WorkList.push_back({E, CC, IsListInit}); 13091 return; 13092 } 13093 13094 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13095 // Do a somewhat different check with comparison operators. 13096 if (BO->isComparisonOp()) 13097 return AnalyzeComparison(S, BO); 13098 13099 // And with simple assignments. 13100 if (BO->getOpcode() == BO_Assign) 13101 return AnalyzeAssignment(S, BO); 13102 // And with compound assignments. 13103 if (BO->isAssignmentOp()) 13104 return AnalyzeCompoundAssignment(S, BO); 13105 } 13106 13107 // These break the otherwise-useful invariant below. Fortunately, 13108 // we don't really need to recurse into them, because any internal 13109 // expressions should have been analyzed already when they were 13110 // built into statements. 13111 if (isa<StmtExpr>(E)) return; 13112 13113 // Don't descend into unevaluated contexts. 13114 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13115 13116 // Now just recurse over the expression's children. 13117 CC = E->getExprLoc(); 13118 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13119 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13120 for (Stmt *SubStmt : E->children()) { 13121 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13122 if (!ChildExpr) 13123 continue; 13124 13125 if (IsLogicalAndOperator && 13126 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13127 // Ignore checking string literals that are in logical and operators. 13128 // This is a common pattern for asserts. 13129 continue; 13130 WorkList.push_back({ChildExpr, CC, IsListInit}); 13131 } 13132 13133 if (BO && BO->isLogicalOp()) { 13134 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13135 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13136 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13137 13138 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13139 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13140 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13141 } 13142 13143 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13144 if (U->getOpcode() == UO_LNot) { 13145 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13146 } else if (U->getOpcode() != UO_AddrOf) { 13147 if (U->getSubExpr()->getType()->isAtomicType()) 13148 S.Diag(U->getSubExpr()->getBeginLoc(), 13149 diag::warn_atomic_implicit_seq_cst); 13150 } 13151 } 13152 } 13153 13154 /// AnalyzeImplicitConversions - Find and report any interesting 13155 /// implicit conversions in the given expression. There are a couple 13156 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13157 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13158 bool IsListInit/*= false*/) { 13159 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13160 WorkList.push_back({OrigE, CC, IsListInit}); 13161 while (!WorkList.empty()) 13162 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13163 } 13164 13165 /// Diagnose integer type and any valid implicit conversion to it. 13166 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13167 // Taking into account implicit conversions, 13168 // allow any integer. 13169 if (!E->getType()->isIntegerType()) { 13170 S.Diag(E->getBeginLoc(), 13171 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13172 return true; 13173 } 13174 // Potentially emit standard warnings for implicit conversions if enabled 13175 // using -Wconversion. 13176 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13177 return false; 13178 } 13179 13180 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13181 // Returns true when emitting a warning about taking the address of a reference. 13182 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13183 const PartialDiagnostic &PD) { 13184 E = E->IgnoreParenImpCasts(); 13185 13186 const FunctionDecl *FD = nullptr; 13187 13188 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13189 if (!DRE->getDecl()->getType()->isReferenceType()) 13190 return false; 13191 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13192 if (!M->getMemberDecl()->getType()->isReferenceType()) 13193 return false; 13194 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13195 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13196 return false; 13197 FD = Call->getDirectCallee(); 13198 } else { 13199 return false; 13200 } 13201 13202 SemaRef.Diag(E->getExprLoc(), PD); 13203 13204 // If possible, point to location of function. 13205 if (FD) { 13206 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13207 } 13208 13209 return true; 13210 } 13211 13212 // Returns true if the SourceLocation is expanded from any macro body. 13213 // Returns false if the SourceLocation is invalid, is from not in a macro 13214 // expansion, or is from expanded from a top-level macro argument. 13215 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13216 if (Loc.isInvalid()) 13217 return false; 13218 13219 while (Loc.isMacroID()) { 13220 if (SM.isMacroBodyExpansion(Loc)) 13221 return true; 13222 Loc = SM.getImmediateMacroCallerLoc(Loc); 13223 } 13224 13225 return false; 13226 } 13227 13228 /// Diagnose pointers that are always non-null. 13229 /// \param E the expression containing the pointer 13230 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13231 /// compared to a null pointer 13232 /// \param IsEqual True when the comparison is equal to a null pointer 13233 /// \param Range Extra SourceRange to highlight in the diagnostic 13234 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13235 Expr::NullPointerConstantKind NullKind, 13236 bool IsEqual, SourceRange Range) { 13237 if (!E) 13238 return; 13239 13240 // Don't warn inside macros. 13241 if (E->getExprLoc().isMacroID()) { 13242 const SourceManager &SM = getSourceManager(); 13243 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13244 IsInAnyMacroBody(SM, Range.getBegin())) 13245 return; 13246 } 13247 E = E->IgnoreImpCasts(); 13248 13249 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13250 13251 if (isa<CXXThisExpr>(E)) { 13252 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13253 : diag::warn_this_bool_conversion; 13254 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13255 return; 13256 } 13257 13258 bool IsAddressOf = false; 13259 13260 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13261 if (UO->getOpcode() != UO_AddrOf) 13262 return; 13263 IsAddressOf = true; 13264 E = UO->getSubExpr(); 13265 } 13266 13267 if (IsAddressOf) { 13268 unsigned DiagID = IsCompare 13269 ? diag::warn_address_of_reference_null_compare 13270 : diag::warn_address_of_reference_bool_conversion; 13271 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13272 << IsEqual; 13273 if (CheckForReference(*this, E, PD)) { 13274 return; 13275 } 13276 } 13277 13278 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13279 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13280 std::string Str; 13281 llvm::raw_string_ostream S(Str); 13282 E->printPretty(S, nullptr, getPrintingPolicy()); 13283 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13284 : diag::warn_cast_nonnull_to_bool; 13285 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13286 << E->getSourceRange() << Range << IsEqual; 13287 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13288 }; 13289 13290 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13291 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13292 if (auto *Callee = Call->getDirectCallee()) { 13293 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13294 ComplainAboutNonnullParamOrCall(A); 13295 return; 13296 } 13297 } 13298 } 13299 13300 // Expect to find a single Decl. Skip anything more complicated. 13301 ValueDecl *D = nullptr; 13302 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13303 D = R->getDecl(); 13304 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13305 D = M->getMemberDecl(); 13306 } 13307 13308 // Weak Decls can be null. 13309 if (!D || D->isWeak()) 13310 return; 13311 13312 // Check for parameter decl with nonnull attribute 13313 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13314 if (getCurFunction() && 13315 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13316 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13317 ComplainAboutNonnullParamOrCall(A); 13318 return; 13319 } 13320 13321 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13322 // Skip function template not specialized yet. 13323 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13324 return; 13325 auto ParamIter = llvm::find(FD->parameters(), PV); 13326 assert(ParamIter != FD->param_end()); 13327 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13328 13329 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13330 if (!NonNull->args_size()) { 13331 ComplainAboutNonnullParamOrCall(NonNull); 13332 return; 13333 } 13334 13335 for (const ParamIdx &ArgNo : NonNull->args()) { 13336 if (ArgNo.getASTIndex() == ParamNo) { 13337 ComplainAboutNonnullParamOrCall(NonNull); 13338 return; 13339 } 13340 } 13341 } 13342 } 13343 } 13344 } 13345 13346 QualType T = D->getType(); 13347 const bool IsArray = T->isArrayType(); 13348 const bool IsFunction = T->isFunctionType(); 13349 13350 // Address of function is used to silence the function warning. 13351 if (IsAddressOf && IsFunction) { 13352 return; 13353 } 13354 13355 // Found nothing. 13356 if (!IsAddressOf && !IsFunction && !IsArray) 13357 return; 13358 13359 // Pretty print the expression for the diagnostic. 13360 std::string Str; 13361 llvm::raw_string_ostream S(Str); 13362 E->printPretty(S, nullptr, getPrintingPolicy()); 13363 13364 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13365 : diag::warn_impcast_pointer_to_bool; 13366 enum { 13367 AddressOf, 13368 FunctionPointer, 13369 ArrayPointer 13370 } DiagType; 13371 if (IsAddressOf) 13372 DiagType = AddressOf; 13373 else if (IsFunction) 13374 DiagType = FunctionPointer; 13375 else if (IsArray) 13376 DiagType = ArrayPointer; 13377 else 13378 llvm_unreachable("Could not determine diagnostic."); 13379 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13380 << Range << IsEqual; 13381 13382 if (!IsFunction) 13383 return; 13384 13385 // Suggest '&' to silence the function warning. 13386 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13387 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13388 13389 // Check to see if '()' fixit should be emitted. 13390 QualType ReturnType; 13391 UnresolvedSet<4> NonTemplateOverloads; 13392 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13393 if (ReturnType.isNull()) 13394 return; 13395 13396 if (IsCompare) { 13397 // There are two cases here. If there is null constant, the only suggest 13398 // for a pointer return type. If the null is 0, then suggest if the return 13399 // type is a pointer or an integer type. 13400 if (!ReturnType->isPointerType()) { 13401 if (NullKind == Expr::NPCK_ZeroExpression || 13402 NullKind == Expr::NPCK_ZeroLiteral) { 13403 if (!ReturnType->isIntegerType()) 13404 return; 13405 } else { 13406 return; 13407 } 13408 } 13409 } else { // !IsCompare 13410 // For function to bool, only suggest if the function pointer has bool 13411 // return type. 13412 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13413 return; 13414 } 13415 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13416 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13417 } 13418 13419 /// Diagnoses "dangerous" implicit conversions within the given 13420 /// expression (which is a full expression). Implements -Wconversion 13421 /// and -Wsign-compare. 13422 /// 13423 /// \param CC the "context" location of the implicit conversion, i.e. 13424 /// the most location of the syntactic entity requiring the implicit 13425 /// conversion 13426 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13427 // Don't diagnose in unevaluated contexts. 13428 if (isUnevaluatedContext()) 13429 return; 13430 13431 // Don't diagnose for value- or type-dependent expressions. 13432 if (E->isTypeDependent() || E->isValueDependent()) 13433 return; 13434 13435 // Check for array bounds violations in cases where the check isn't triggered 13436 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13437 // ArraySubscriptExpr is on the RHS of a variable initialization. 13438 CheckArrayAccess(E); 13439 13440 // This is not the right CC for (e.g.) a variable initialization. 13441 AnalyzeImplicitConversions(*this, E, CC); 13442 } 13443 13444 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13445 /// Input argument E is a logical expression. 13446 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13447 ::CheckBoolLikeConversion(*this, E, CC); 13448 } 13449 13450 /// Diagnose when expression is an integer constant expression and its evaluation 13451 /// results in integer overflow 13452 void Sema::CheckForIntOverflow (Expr *E) { 13453 // Use a work list to deal with nested struct initializers. 13454 SmallVector<Expr *, 2> Exprs(1, E); 13455 13456 do { 13457 Expr *OriginalE = Exprs.pop_back_val(); 13458 Expr *E = OriginalE->IgnoreParenCasts(); 13459 13460 if (isa<BinaryOperator>(E)) { 13461 E->EvaluateForOverflow(Context); 13462 continue; 13463 } 13464 13465 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13466 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13467 else if (isa<ObjCBoxedExpr>(OriginalE)) 13468 E->EvaluateForOverflow(Context); 13469 else if (auto Call = dyn_cast<CallExpr>(E)) 13470 Exprs.append(Call->arg_begin(), Call->arg_end()); 13471 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13472 Exprs.append(Message->arg_begin(), Message->arg_end()); 13473 } while (!Exprs.empty()); 13474 } 13475 13476 namespace { 13477 13478 /// Visitor for expressions which looks for unsequenced operations on the 13479 /// same object. 13480 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13481 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13482 13483 /// A tree of sequenced regions within an expression. Two regions are 13484 /// unsequenced if one is an ancestor or a descendent of the other. When we 13485 /// finish processing an expression with sequencing, such as a comma 13486 /// expression, we fold its tree nodes into its parent, since they are 13487 /// unsequenced with respect to nodes we will visit later. 13488 class SequenceTree { 13489 struct Value { 13490 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13491 unsigned Parent : 31; 13492 unsigned Merged : 1; 13493 }; 13494 SmallVector<Value, 8> Values; 13495 13496 public: 13497 /// A region within an expression which may be sequenced with respect 13498 /// to some other region. 13499 class Seq { 13500 friend class SequenceTree; 13501 13502 unsigned Index; 13503 13504 explicit Seq(unsigned N) : Index(N) {} 13505 13506 public: 13507 Seq() : Index(0) {} 13508 }; 13509 13510 SequenceTree() { Values.push_back(Value(0)); } 13511 Seq root() const { return Seq(0); } 13512 13513 /// Create a new sequence of operations, which is an unsequenced 13514 /// subset of \p Parent. This sequence of operations is sequenced with 13515 /// respect to other children of \p Parent. 13516 Seq allocate(Seq Parent) { 13517 Values.push_back(Value(Parent.Index)); 13518 return Seq(Values.size() - 1); 13519 } 13520 13521 /// Merge a sequence of operations into its parent. 13522 void merge(Seq S) { 13523 Values[S.Index].Merged = true; 13524 } 13525 13526 /// Determine whether two operations are unsequenced. This operation 13527 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13528 /// should have been merged into its parent as appropriate. 13529 bool isUnsequenced(Seq Cur, Seq Old) { 13530 unsigned C = representative(Cur.Index); 13531 unsigned Target = representative(Old.Index); 13532 while (C >= Target) { 13533 if (C == Target) 13534 return true; 13535 C = Values[C].Parent; 13536 } 13537 return false; 13538 } 13539 13540 private: 13541 /// Pick a representative for a sequence. 13542 unsigned representative(unsigned K) { 13543 if (Values[K].Merged) 13544 // Perform path compression as we go. 13545 return Values[K].Parent = representative(Values[K].Parent); 13546 return K; 13547 } 13548 }; 13549 13550 /// An object for which we can track unsequenced uses. 13551 using Object = const NamedDecl *; 13552 13553 /// Different flavors of object usage which we track. We only track the 13554 /// least-sequenced usage of each kind. 13555 enum UsageKind { 13556 /// A read of an object. Multiple unsequenced reads are OK. 13557 UK_Use, 13558 13559 /// A modification of an object which is sequenced before the value 13560 /// computation of the expression, such as ++n in C++. 13561 UK_ModAsValue, 13562 13563 /// A modification of an object which is not sequenced before the value 13564 /// computation of the expression, such as n++. 13565 UK_ModAsSideEffect, 13566 13567 UK_Count = UK_ModAsSideEffect + 1 13568 }; 13569 13570 /// Bundle together a sequencing region and the expression corresponding 13571 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13572 struct Usage { 13573 const Expr *UsageExpr; 13574 SequenceTree::Seq Seq; 13575 13576 Usage() : UsageExpr(nullptr), Seq() {} 13577 }; 13578 13579 struct UsageInfo { 13580 Usage Uses[UK_Count]; 13581 13582 /// Have we issued a diagnostic for this object already? 13583 bool Diagnosed; 13584 13585 UsageInfo() : Uses(), Diagnosed(false) {} 13586 }; 13587 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13588 13589 Sema &SemaRef; 13590 13591 /// Sequenced regions within the expression. 13592 SequenceTree Tree; 13593 13594 /// Declaration modifications and references which we have seen. 13595 UsageInfoMap UsageMap; 13596 13597 /// The region we are currently within. 13598 SequenceTree::Seq Region; 13599 13600 /// Filled in with declarations which were modified as a side-effect 13601 /// (that is, post-increment operations). 13602 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13603 13604 /// Expressions to check later. We defer checking these to reduce 13605 /// stack usage. 13606 SmallVectorImpl<const Expr *> &WorkList; 13607 13608 /// RAII object wrapping the visitation of a sequenced subexpression of an 13609 /// expression. At the end of this process, the side-effects of the evaluation 13610 /// become sequenced with respect to the value computation of the result, so 13611 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13612 /// UK_ModAsValue. 13613 struct SequencedSubexpression { 13614 SequencedSubexpression(SequenceChecker &Self) 13615 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13616 Self.ModAsSideEffect = &ModAsSideEffect; 13617 } 13618 13619 ~SequencedSubexpression() { 13620 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13621 // Add a new usage with usage kind UK_ModAsValue, and then restore 13622 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13623 // the previous one was empty). 13624 UsageInfo &UI = Self.UsageMap[M.first]; 13625 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13626 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13627 SideEffectUsage = M.second; 13628 } 13629 Self.ModAsSideEffect = OldModAsSideEffect; 13630 } 13631 13632 SequenceChecker &Self; 13633 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13634 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13635 }; 13636 13637 /// RAII object wrapping the visitation of a subexpression which we might 13638 /// choose to evaluate as a constant. If any subexpression is evaluated and 13639 /// found to be non-constant, this allows us to suppress the evaluation of 13640 /// the outer expression. 13641 class EvaluationTracker { 13642 public: 13643 EvaluationTracker(SequenceChecker &Self) 13644 : Self(Self), Prev(Self.EvalTracker) { 13645 Self.EvalTracker = this; 13646 } 13647 13648 ~EvaluationTracker() { 13649 Self.EvalTracker = Prev; 13650 if (Prev) 13651 Prev->EvalOK &= EvalOK; 13652 } 13653 13654 bool evaluate(const Expr *E, bool &Result) { 13655 if (!EvalOK || E->isValueDependent()) 13656 return false; 13657 EvalOK = E->EvaluateAsBooleanCondition( 13658 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13659 return EvalOK; 13660 } 13661 13662 private: 13663 SequenceChecker &Self; 13664 EvaluationTracker *Prev; 13665 bool EvalOK = true; 13666 } *EvalTracker = nullptr; 13667 13668 /// Find the object which is produced by the specified expression, 13669 /// if any. 13670 Object getObject(const Expr *E, bool Mod) const { 13671 E = E->IgnoreParenCasts(); 13672 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13673 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13674 return getObject(UO->getSubExpr(), Mod); 13675 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13676 if (BO->getOpcode() == BO_Comma) 13677 return getObject(BO->getRHS(), Mod); 13678 if (Mod && BO->isAssignmentOp()) 13679 return getObject(BO->getLHS(), Mod); 13680 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13681 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13682 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13683 return ME->getMemberDecl(); 13684 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13685 // FIXME: If this is a reference, map through to its value. 13686 return DRE->getDecl(); 13687 return nullptr; 13688 } 13689 13690 /// Note that an object \p O was modified or used by an expression 13691 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13692 /// the object \p O as obtained via the \p UsageMap. 13693 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13694 // Get the old usage for the given object and usage kind. 13695 Usage &U = UI.Uses[UK]; 13696 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13697 // If we have a modification as side effect and are in a sequenced 13698 // subexpression, save the old Usage so that we can restore it later 13699 // in SequencedSubexpression::~SequencedSubexpression. 13700 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13701 ModAsSideEffect->push_back(std::make_pair(O, U)); 13702 // Then record the new usage with the current sequencing region. 13703 U.UsageExpr = UsageExpr; 13704 U.Seq = Region; 13705 } 13706 } 13707 13708 /// Check whether a modification or use of an object \p O in an expression 13709 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13710 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13711 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13712 /// usage and false we are checking for a mod-use unsequenced usage. 13713 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13714 UsageKind OtherKind, bool IsModMod) { 13715 if (UI.Diagnosed) 13716 return; 13717 13718 const Usage &U = UI.Uses[OtherKind]; 13719 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13720 return; 13721 13722 const Expr *Mod = U.UsageExpr; 13723 const Expr *ModOrUse = UsageExpr; 13724 if (OtherKind == UK_Use) 13725 std::swap(Mod, ModOrUse); 13726 13727 SemaRef.DiagRuntimeBehavior( 13728 Mod->getExprLoc(), {Mod, ModOrUse}, 13729 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13730 : diag::warn_unsequenced_mod_use) 13731 << O << SourceRange(ModOrUse->getExprLoc())); 13732 UI.Diagnosed = true; 13733 } 13734 13735 // A note on note{Pre, Post}{Use, Mod}: 13736 // 13737 // (It helps to follow the algorithm with an expression such as 13738 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13739 // operations before C++17 and both are well-defined in C++17). 13740 // 13741 // When visiting a node which uses/modify an object we first call notePreUse 13742 // or notePreMod before visiting its sub-expression(s). At this point the 13743 // children of the current node have not yet been visited and so the eventual 13744 // uses/modifications resulting from the children of the current node have not 13745 // been recorded yet. 13746 // 13747 // We then visit the children of the current node. After that notePostUse or 13748 // notePostMod is called. These will 1) detect an unsequenced modification 13749 // as side effect (as in "k++ + k") and 2) add a new usage with the 13750 // appropriate usage kind. 13751 // 13752 // We also have to be careful that some operation sequences modification as 13753 // side effect as well (for example: || or ,). To account for this we wrap 13754 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13755 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13756 // which record usages which are modifications as side effect, and then 13757 // downgrade them (or more accurately restore the previous usage which was a 13758 // modification as side effect) when exiting the scope of the sequenced 13759 // subexpression. 13760 13761 void notePreUse(Object O, const Expr *UseExpr) { 13762 UsageInfo &UI = UsageMap[O]; 13763 // Uses conflict with other modifications. 13764 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13765 } 13766 13767 void notePostUse(Object O, const Expr *UseExpr) { 13768 UsageInfo &UI = UsageMap[O]; 13769 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13770 /*IsModMod=*/false); 13771 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13772 } 13773 13774 void notePreMod(Object O, const Expr *ModExpr) { 13775 UsageInfo &UI = UsageMap[O]; 13776 // Modifications conflict with other modifications and with uses. 13777 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13778 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13779 } 13780 13781 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13782 UsageInfo &UI = UsageMap[O]; 13783 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13784 /*IsModMod=*/true); 13785 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13786 } 13787 13788 public: 13789 SequenceChecker(Sema &S, const Expr *E, 13790 SmallVectorImpl<const Expr *> &WorkList) 13791 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13792 Visit(E); 13793 // Silence a -Wunused-private-field since WorkList is now unused. 13794 // TODO: Evaluate if it can be used, and if not remove it. 13795 (void)this->WorkList; 13796 } 13797 13798 void VisitStmt(const Stmt *S) { 13799 // Skip all statements which aren't expressions for now. 13800 } 13801 13802 void VisitExpr(const Expr *E) { 13803 // By default, just recurse to evaluated subexpressions. 13804 Base::VisitStmt(E); 13805 } 13806 13807 void VisitCastExpr(const CastExpr *E) { 13808 Object O = Object(); 13809 if (E->getCastKind() == CK_LValueToRValue) 13810 O = getObject(E->getSubExpr(), false); 13811 13812 if (O) 13813 notePreUse(O, E); 13814 VisitExpr(E); 13815 if (O) 13816 notePostUse(O, E); 13817 } 13818 13819 void VisitSequencedExpressions(const Expr *SequencedBefore, 13820 const Expr *SequencedAfter) { 13821 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13822 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13823 SequenceTree::Seq OldRegion = Region; 13824 13825 { 13826 SequencedSubexpression SeqBefore(*this); 13827 Region = BeforeRegion; 13828 Visit(SequencedBefore); 13829 } 13830 13831 Region = AfterRegion; 13832 Visit(SequencedAfter); 13833 13834 Region = OldRegion; 13835 13836 Tree.merge(BeforeRegion); 13837 Tree.merge(AfterRegion); 13838 } 13839 13840 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13841 // C++17 [expr.sub]p1: 13842 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13843 // expression E1 is sequenced before the expression E2. 13844 if (SemaRef.getLangOpts().CPlusPlus17) 13845 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13846 else { 13847 Visit(ASE->getLHS()); 13848 Visit(ASE->getRHS()); 13849 } 13850 } 13851 13852 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13853 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13854 void VisitBinPtrMem(const BinaryOperator *BO) { 13855 // C++17 [expr.mptr.oper]p4: 13856 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13857 // the expression E1 is sequenced before the expression E2. 13858 if (SemaRef.getLangOpts().CPlusPlus17) 13859 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13860 else { 13861 Visit(BO->getLHS()); 13862 Visit(BO->getRHS()); 13863 } 13864 } 13865 13866 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13867 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13868 void VisitBinShlShr(const BinaryOperator *BO) { 13869 // C++17 [expr.shift]p4: 13870 // The expression E1 is sequenced before the expression E2. 13871 if (SemaRef.getLangOpts().CPlusPlus17) 13872 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13873 else { 13874 Visit(BO->getLHS()); 13875 Visit(BO->getRHS()); 13876 } 13877 } 13878 13879 void VisitBinComma(const BinaryOperator *BO) { 13880 // C++11 [expr.comma]p1: 13881 // Every value computation and side effect associated with the left 13882 // expression is sequenced before every value computation and side 13883 // effect associated with the right expression. 13884 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13885 } 13886 13887 void VisitBinAssign(const BinaryOperator *BO) { 13888 SequenceTree::Seq RHSRegion; 13889 SequenceTree::Seq LHSRegion; 13890 if (SemaRef.getLangOpts().CPlusPlus17) { 13891 RHSRegion = Tree.allocate(Region); 13892 LHSRegion = Tree.allocate(Region); 13893 } else { 13894 RHSRegion = Region; 13895 LHSRegion = Region; 13896 } 13897 SequenceTree::Seq OldRegion = Region; 13898 13899 // C++11 [expr.ass]p1: 13900 // [...] the assignment is sequenced after the value computation 13901 // of the right and left operands, [...] 13902 // 13903 // so check it before inspecting the operands and update the 13904 // map afterwards. 13905 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13906 if (O) 13907 notePreMod(O, BO); 13908 13909 if (SemaRef.getLangOpts().CPlusPlus17) { 13910 // C++17 [expr.ass]p1: 13911 // [...] The right operand is sequenced before the left operand. [...] 13912 { 13913 SequencedSubexpression SeqBefore(*this); 13914 Region = RHSRegion; 13915 Visit(BO->getRHS()); 13916 } 13917 13918 Region = LHSRegion; 13919 Visit(BO->getLHS()); 13920 13921 if (O && isa<CompoundAssignOperator>(BO)) 13922 notePostUse(O, BO); 13923 13924 } else { 13925 // C++11 does not specify any sequencing between the LHS and RHS. 13926 Region = LHSRegion; 13927 Visit(BO->getLHS()); 13928 13929 if (O && isa<CompoundAssignOperator>(BO)) 13930 notePostUse(O, BO); 13931 13932 Region = RHSRegion; 13933 Visit(BO->getRHS()); 13934 } 13935 13936 // C++11 [expr.ass]p1: 13937 // the assignment is sequenced [...] before the value computation of the 13938 // assignment expression. 13939 // C11 6.5.16/3 has no such rule. 13940 Region = OldRegion; 13941 if (O) 13942 notePostMod(O, BO, 13943 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13944 : UK_ModAsSideEffect); 13945 if (SemaRef.getLangOpts().CPlusPlus17) { 13946 Tree.merge(RHSRegion); 13947 Tree.merge(LHSRegion); 13948 } 13949 } 13950 13951 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13952 VisitBinAssign(CAO); 13953 } 13954 13955 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13956 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13957 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13958 Object O = getObject(UO->getSubExpr(), true); 13959 if (!O) 13960 return VisitExpr(UO); 13961 13962 notePreMod(O, UO); 13963 Visit(UO->getSubExpr()); 13964 // C++11 [expr.pre.incr]p1: 13965 // the expression ++x is equivalent to x+=1 13966 notePostMod(O, UO, 13967 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13968 : UK_ModAsSideEffect); 13969 } 13970 13971 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13972 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13973 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13974 Object O = getObject(UO->getSubExpr(), true); 13975 if (!O) 13976 return VisitExpr(UO); 13977 13978 notePreMod(O, UO); 13979 Visit(UO->getSubExpr()); 13980 notePostMod(O, UO, UK_ModAsSideEffect); 13981 } 13982 13983 void VisitBinLOr(const BinaryOperator *BO) { 13984 // C++11 [expr.log.or]p2: 13985 // If the second expression is evaluated, every value computation and 13986 // side effect associated with the first expression is sequenced before 13987 // every value computation and side effect associated with the 13988 // second expression. 13989 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13990 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13991 SequenceTree::Seq OldRegion = Region; 13992 13993 EvaluationTracker Eval(*this); 13994 { 13995 SequencedSubexpression Sequenced(*this); 13996 Region = LHSRegion; 13997 Visit(BO->getLHS()); 13998 } 13999 14000 // C++11 [expr.log.or]p1: 14001 // [...] the second operand is not evaluated if the first operand 14002 // evaluates to true. 14003 bool EvalResult = false; 14004 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14005 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14006 if (ShouldVisitRHS) { 14007 Region = RHSRegion; 14008 Visit(BO->getRHS()); 14009 } 14010 14011 Region = OldRegion; 14012 Tree.merge(LHSRegion); 14013 Tree.merge(RHSRegion); 14014 } 14015 14016 void VisitBinLAnd(const BinaryOperator *BO) { 14017 // C++11 [expr.log.and]p2: 14018 // If the second expression is evaluated, every value computation and 14019 // side effect associated with the first expression is sequenced before 14020 // every value computation and side effect associated with the 14021 // second expression. 14022 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14023 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14024 SequenceTree::Seq OldRegion = Region; 14025 14026 EvaluationTracker Eval(*this); 14027 { 14028 SequencedSubexpression Sequenced(*this); 14029 Region = LHSRegion; 14030 Visit(BO->getLHS()); 14031 } 14032 14033 // C++11 [expr.log.and]p1: 14034 // [...] the second operand is not evaluated if the first operand is false. 14035 bool EvalResult = false; 14036 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14037 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14038 if (ShouldVisitRHS) { 14039 Region = RHSRegion; 14040 Visit(BO->getRHS()); 14041 } 14042 14043 Region = OldRegion; 14044 Tree.merge(LHSRegion); 14045 Tree.merge(RHSRegion); 14046 } 14047 14048 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14049 // C++11 [expr.cond]p1: 14050 // [...] Every value computation and side effect associated with the first 14051 // expression is sequenced before every value computation and side effect 14052 // associated with the second or third expression. 14053 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14054 14055 // No sequencing is specified between the true and false expression. 14056 // However since exactly one of both is going to be evaluated we can 14057 // consider them to be sequenced. This is needed to avoid warning on 14058 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14059 // both the true and false expressions because we can't evaluate x. 14060 // This will still allow us to detect an expression like (pre C++17) 14061 // "(x ? y += 1 : y += 2) = y". 14062 // 14063 // We don't wrap the visitation of the true and false expression with 14064 // SequencedSubexpression because we don't want to downgrade modifications 14065 // as side effect in the true and false expressions after the visition 14066 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14067 // not warn between the two "y++", but we should warn between the "y++" 14068 // and the "y". 14069 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14070 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14071 SequenceTree::Seq OldRegion = Region; 14072 14073 EvaluationTracker Eval(*this); 14074 { 14075 SequencedSubexpression Sequenced(*this); 14076 Region = ConditionRegion; 14077 Visit(CO->getCond()); 14078 } 14079 14080 // C++11 [expr.cond]p1: 14081 // [...] The first expression is contextually converted to bool (Clause 4). 14082 // It is evaluated and if it is true, the result of the conditional 14083 // expression is the value of the second expression, otherwise that of the 14084 // third expression. Only one of the second and third expressions is 14085 // evaluated. [...] 14086 bool EvalResult = false; 14087 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14088 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14089 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14090 if (ShouldVisitTrueExpr) { 14091 Region = TrueRegion; 14092 Visit(CO->getTrueExpr()); 14093 } 14094 if (ShouldVisitFalseExpr) { 14095 Region = FalseRegion; 14096 Visit(CO->getFalseExpr()); 14097 } 14098 14099 Region = OldRegion; 14100 Tree.merge(ConditionRegion); 14101 Tree.merge(TrueRegion); 14102 Tree.merge(FalseRegion); 14103 } 14104 14105 void VisitCallExpr(const CallExpr *CE) { 14106 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14107 14108 if (CE->isUnevaluatedBuiltinCall(Context)) 14109 return; 14110 14111 // C++11 [intro.execution]p15: 14112 // When calling a function [...], every value computation and side effect 14113 // associated with any argument expression, or with the postfix expression 14114 // designating the called function, is sequenced before execution of every 14115 // expression or statement in the body of the function [and thus before 14116 // the value computation of its result]. 14117 SequencedSubexpression Sequenced(*this); 14118 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14119 // C++17 [expr.call]p5 14120 // The postfix-expression is sequenced before each expression in the 14121 // expression-list and any default argument. [...] 14122 SequenceTree::Seq CalleeRegion; 14123 SequenceTree::Seq OtherRegion; 14124 if (SemaRef.getLangOpts().CPlusPlus17) { 14125 CalleeRegion = Tree.allocate(Region); 14126 OtherRegion = Tree.allocate(Region); 14127 } else { 14128 CalleeRegion = Region; 14129 OtherRegion = Region; 14130 } 14131 SequenceTree::Seq OldRegion = Region; 14132 14133 // Visit the callee expression first. 14134 Region = CalleeRegion; 14135 if (SemaRef.getLangOpts().CPlusPlus17) { 14136 SequencedSubexpression Sequenced(*this); 14137 Visit(CE->getCallee()); 14138 } else { 14139 Visit(CE->getCallee()); 14140 } 14141 14142 // Then visit the argument expressions. 14143 Region = OtherRegion; 14144 for (const Expr *Argument : CE->arguments()) 14145 Visit(Argument); 14146 14147 Region = OldRegion; 14148 if (SemaRef.getLangOpts().CPlusPlus17) { 14149 Tree.merge(CalleeRegion); 14150 Tree.merge(OtherRegion); 14151 } 14152 }); 14153 } 14154 14155 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14156 // C++17 [over.match.oper]p2: 14157 // [...] the operator notation is first transformed to the equivalent 14158 // function-call notation as summarized in Table 12 (where @ denotes one 14159 // of the operators covered in the specified subclause). However, the 14160 // operands are sequenced in the order prescribed for the built-in 14161 // operator (Clause 8). 14162 // 14163 // From the above only overloaded binary operators and overloaded call 14164 // operators have sequencing rules in C++17 that we need to handle 14165 // separately. 14166 if (!SemaRef.getLangOpts().CPlusPlus17 || 14167 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14168 return VisitCallExpr(CXXOCE); 14169 14170 enum { 14171 NoSequencing, 14172 LHSBeforeRHS, 14173 RHSBeforeLHS, 14174 LHSBeforeRest 14175 } SequencingKind; 14176 switch (CXXOCE->getOperator()) { 14177 case OO_Equal: 14178 case OO_PlusEqual: 14179 case OO_MinusEqual: 14180 case OO_StarEqual: 14181 case OO_SlashEqual: 14182 case OO_PercentEqual: 14183 case OO_CaretEqual: 14184 case OO_AmpEqual: 14185 case OO_PipeEqual: 14186 case OO_LessLessEqual: 14187 case OO_GreaterGreaterEqual: 14188 SequencingKind = RHSBeforeLHS; 14189 break; 14190 14191 case OO_LessLess: 14192 case OO_GreaterGreater: 14193 case OO_AmpAmp: 14194 case OO_PipePipe: 14195 case OO_Comma: 14196 case OO_ArrowStar: 14197 case OO_Subscript: 14198 SequencingKind = LHSBeforeRHS; 14199 break; 14200 14201 case OO_Call: 14202 SequencingKind = LHSBeforeRest; 14203 break; 14204 14205 default: 14206 SequencingKind = NoSequencing; 14207 break; 14208 } 14209 14210 if (SequencingKind == NoSequencing) 14211 return VisitCallExpr(CXXOCE); 14212 14213 // This is a call, so all subexpressions are sequenced before the result. 14214 SequencedSubexpression Sequenced(*this); 14215 14216 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14217 assert(SemaRef.getLangOpts().CPlusPlus17 && 14218 "Should only get there with C++17 and above!"); 14219 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14220 "Should only get there with an overloaded binary operator" 14221 " or an overloaded call operator!"); 14222 14223 if (SequencingKind == LHSBeforeRest) { 14224 assert(CXXOCE->getOperator() == OO_Call && 14225 "We should only have an overloaded call operator here!"); 14226 14227 // This is very similar to VisitCallExpr, except that we only have the 14228 // C++17 case. The postfix-expression is the first argument of the 14229 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14230 // are in the following arguments. 14231 // 14232 // Note that we intentionally do not visit the callee expression since 14233 // it is just a decayed reference to a function. 14234 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14235 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14236 SequenceTree::Seq OldRegion = Region; 14237 14238 assert(CXXOCE->getNumArgs() >= 1 && 14239 "An overloaded call operator must have at least one argument" 14240 " for the postfix-expression!"); 14241 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14242 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14243 CXXOCE->getNumArgs() - 1); 14244 14245 // Visit the postfix-expression first. 14246 { 14247 Region = PostfixExprRegion; 14248 SequencedSubexpression Sequenced(*this); 14249 Visit(PostfixExpr); 14250 } 14251 14252 // Then visit the argument expressions. 14253 Region = ArgsRegion; 14254 for (const Expr *Arg : Args) 14255 Visit(Arg); 14256 14257 Region = OldRegion; 14258 Tree.merge(PostfixExprRegion); 14259 Tree.merge(ArgsRegion); 14260 } else { 14261 assert(CXXOCE->getNumArgs() == 2 && 14262 "Should only have two arguments here!"); 14263 assert((SequencingKind == LHSBeforeRHS || 14264 SequencingKind == RHSBeforeLHS) && 14265 "Unexpected sequencing kind!"); 14266 14267 // We do not visit the callee expression since it is just a decayed 14268 // reference to a function. 14269 const Expr *E1 = CXXOCE->getArg(0); 14270 const Expr *E2 = CXXOCE->getArg(1); 14271 if (SequencingKind == RHSBeforeLHS) 14272 std::swap(E1, E2); 14273 14274 return VisitSequencedExpressions(E1, E2); 14275 } 14276 }); 14277 } 14278 14279 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14280 // This is a call, so all subexpressions are sequenced before the result. 14281 SequencedSubexpression Sequenced(*this); 14282 14283 if (!CCE->isListInitialization()) 14284 return VisitExpr(CCE); 14285 14286 // In C++11, list initializations are sequenced. 14287 SmallVector<SequenceTree::Seq, 32> Elts; 14288 SequenceTree::Seq Parent = Region; 14289 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14290 E = CCE->arg_end(); 14291 I != E; ++I) { 14292 Region = Tree.allocate(Parent); 14293 Elts.push_back(Region); 14294 Visit(*I); 14295 } 14296 14297 // Forget that the initializers are sequenced. 14298 Region = Parent; 14299 for (unsigned I = 0; I < Elts.size(); ++I) 14300 Tree.merge(Elts[I]); 14301 } 14302 14303 void VisitInitListExpr(const InitListExpr *ILE) { 14304 if (!SemaRef.getLangOpts().CPlusPlus11) 14305 return VisitExpr(ILE); 14306 14307 // In C++11, list initializations are sequenced. 14308 SmallVector<SequenceTree::Seq, 32> Elts; 14309 SequenceTree::Seq Parent = Region; 14310 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14311 const Expr *E = ILE->getInit(I); 14312 if (!E) 14313 continue; 14314 Region = Tree.allocate(Parent); 14315 Elts.push_back(Region); 14316 Visit(E); 14317 } 14318 14319 // Forget that the initializers are sequenced. 14320 Region = Parent; 14321 for (unsigned I = 0; I < Elts.size(); ++I) 14322 Tree.merge(Elts[I]); 14323 } 14324 }; 14325 14326 } // namespace 14327 14328 void Sema::CheckUnsequencedOperations(const Expr *E) { 14329 SmallVector<const Expr *, 8> WorkList; 14330 WorkList.push_back(E); 14331 while (!WorkList.empty()) { 14332 const Expr *Item = WorkList.pop_back_val(); 14333 SequenceChecker(*this, Item, WorkList); 14334 } 14335 } 14336 14337 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14338 bool IsConstexpr) { 14339 llvm::SaveAndRestore<bool> ConstantContext( 14340 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14341 CheckImplicitConversions(E, CheckLoc); 14342 if (!E->isInstantiationDependent()) 14343 CheckUnsequencedOperations(E); 14344 if (!IsConstexpr && !E->isValueDependent()) 14345 CheckForIntOverflow(E); 14346 DiagnoseMisalignedMembers(); 14347 } 14348 14349 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14350 FieldDecl *BitField, 14351 Expr *Init) { 14352 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14353 } 14354 14355 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14356 SourceLocation Loc) { 14357 if (!PType->isVariablyModifiedType()) 14358 return; 14359 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14360 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14361 return; 14362 } 14363 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14364 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14365 return; 14366 } 14367 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14368 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14369 return; 14370 } 14371 14372 const ArrayType *AT = S.Context.getAsArrayType(PType); 14373 if (!AT) 14374 return; 14375 14376 if (AT->getSizeModifier() != ArrayType::Star) { 14377 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14378 return; 14379 } 14380 14381 S.Diag(Loc, diag::err_array_star_in_function_definition); 14382 } 14383 14384 /// CheckParmsForFunctionDef - Check that the parameters of the given 14385 /// function are appropriate for the definition of a function. This 14386 /// takes care of any checks that cannot be performed on the 14387 /// declaration itself, e.g., that the types of each of the function 14388 /// parameters are complete. 14389 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14390 bool CheckParameterNames) { 14391 bool HasInvalidParm = false; 14392 for (ParmVarDecl *Param : Parameters) { 14393 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14394 // function declarator that is part of a function definition of 14395 // that function shall not have incomplete type. 14396 // 14397 // This is also C++ [dcl.fct]p6. 14398 if (!Param->isInvalidDecl() && 14399 RequireCompleteType(Param->getLocation(), Param->getType(), 14400 diag::err_typecheck_decl_incomplete_type)) { 14401 Param->setInvalidDecl(); 14402 HasInvalidParm = true; 14403 } 14404 14405 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14406 // declaration of each parameter shall include an identifier. 14407 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14408 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14409 // Diagnose this as an extension in C17 and earlier. 14410 if (!getLangOpts().C2x) 14411 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14412 } 14413 14414 // C99 6.7.5.3p12: 14415 // If the function declarator is not part of a definition of that 14416 // function, parameters may have incomplete type and may use the [*] 14417 // notation in their sequences of declarator specifiers to specify 14418 // variable length array types. 14419 QualType PType = Param->getOriginalType(); 14420 // FIXME: This diagnostic should point the '[*]' if source-location 14421 // information is added for it. 14422 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14423 14424 // If the parameter is a c++ class type and it has to be destructed in the 14425 // callee function, declare the destructor so that it can be called by the 14426 // callee function. Do not perform any direct access check on the dtor here. 14427 if (!Param->isInvalidDecl()) { 14428 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14429 if (!ClassDecl->isInvalidDecl() && 14430 !ClassDecl->hasIrrelevantDestructor() && 14431 !ClassDecl->isDependentContext() && 14432 ClassDecl->isParamDestroyedInCallee()) { 14433 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14434 MarkFunctionReferenced(Param->getLocation(), Destructor); 14435 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14436 } 14437 } 14438 } 14439 14440 // Parameters with the pass_object_size attribute only need to be marked 14441 // constant at function definitions. Because we lack information about 14442 // whether we're on a declaration or definition when we're instantiating the 14443 // attribute, we need to check for constness here. 14444 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14445 if (!Param->getType().isConstQualified()) 14446 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14447 << Attr->getSpelling() << 1; 14448 14449 // Check for parameter names shadowing fields from the class. 14450 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14451 // The owning context for the parameter should be the function, but we 14452 // want to see if this function's declaration context is a record. 14453 DeclContext *DC = Param->getDeclContext(); 14454 if (DC && DC->isFunctionOrMethod()) { 14455 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14456 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14457 RD, /*DeclIsField*/ false); 14458 } 14459 } 14460 } 14461 14462 return HasInvalidParm; 14463 } 14464 14465 Optional<std::pair<CharUnits, CharUnits>> 14466 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14467 14468 /// Compute the alignment and offset of the base class object given the 14469 /// derived-to-base cast expression and the alignment and offset of the derived 14470 /// class object. 14471 static std::pair<CharUnits, CharUnits> 14472 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14473 CharUnits BaseAlignment, CharUnits Offset, 14474 ASTContext &Ctx) { 14475 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14476 ++PathI) { 14477 const CXXBaseSpecifier *Base = *PathI; 14478 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14479 if (Base->isVirtual()) { 14480 // The complete object may have a lower alignment than the non-virtual 14481 // alignment of the base, in which case the base may be misaligned. Choose 14482 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14483 // conservative lower bound of the complete object alignment. 14484 CharUnits NonVirtualAlignment = 14485 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14486 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14487 Offset = CharUnits::Zero(); 14488 } else { 14489 const ASTRecordLayout &RL = 14490 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14491 Offset += RL.getBaseClassOffset(BaseDecl); 14492 } 14493 DerivedType = Base->getType(); 14494 } 14495 14496 return std::make_pair(BaseAlignment, Offset); 14497 } 14498 14499 /// Compute the alignment and offset of a binary additive operator. 14500 static Optional<std::pair<CharUnits, CharUnits>> 14501 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14502 bool IsSub, ASTContext &Ctx) { 14503 QualType PointeeType = PtrE->getType()->getPointeeType(); 14504 14505 if (!PointeeType->isConstantSizeType()) 14506 return llvm::None; 14507 14508 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14509 14510 if (!P) 14511 return llvm::None; 14512 14513 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14514 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14515 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14516 if (IsSub) 14517 Offset = -Offset; 14518 return std::make_pair(P->first, P->second + Offset); 14519 } 14520 14521 // If the integer expression isn't a constant expression, compute the lower 14522 // bound of the alignment using the alignment and offset of the pointer 14523 // expression and the element size. 14524 return std::make_pair( 14525 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14526 CharUnits::Zero()); 14527 } 14528 14529 /// This helper function takes an lvalue expression and returns the alignment of 14530 /// a VarDecl and a constant offset from the VarDecl. 14531 Optional<std::pair<CharUnits, CharUnits>> 14532 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14533 E = E->IgnoreParens(); 14534 switch (E->getStmtClass()) { 14535 default: 14536 break; 14537 case Stmt::CStyleCastExprClass: 14538 case Stmt::CXXStaticCastExprClass: 14539 case Stmt::ImplicitCastExprClass: { 14540 auto *CE = cast<CastExpr>(E); 14541 const Expr *From = CE->getSubExpr(); 14542 switch (CE->getCastKind()) { 14543 default: 14544 break; 14545 case CK_NoOp: 14546 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14547 case CK_UncheckedDerivedToBase: 14548 case CK_DerivedToBase: { 14549 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14550 if (!P) 14551 break; 14552 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14553 P->second, Ctx); 14554 } 14555 } 14556 break; 14557 } 14558 case Stmt::ArraySubscriptExprClass: { 14559 auto *ASE = cast<ArraySubscriptExpr>(E); 14560 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14561 false, Ctx); 14562 } 14563 case Stmt::DeclRefExprClass: { 14564 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14565 // FIXME: If VD is captured by copy or is an escaping __block variable, 14566 // use the alignment of VD's type. 14567 if (!VD->getType()->isReferenceType()) 14568 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14569 if (VD->hasInit()) 14570 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14571 } 14572 break; 14573 } 14574 case Stmt::MemberExprClass: { 14575 auto *ME = cast<MemberExpr>(E); 14576 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14577 if (!FD || FD->getType()->isReferenceType() || 14578 FD->getParent()->isInvalidDecl()) 14579 break; 14580 Optional<std::pair<CharUnits, CharUnits>> P; 14581 if (ME->isArrow()) 14582 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14583 else 14584 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14585 if (!P) 14586 break; 14587 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14588 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14589 return std::make_pair(P->first, 14590 P->second + CharUnits::fromQuantity(Offset)); 14591 } 14592 case Stmt::UnaryOperatorClass: { 14593 auto *UO = cast<UnaryOperator>(E); 14594 switch (UO->getOpcode()) { 14595 default: 14596 break; 14597 case UO_Deref: 14598 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14599 } 14600 break; 14601 } 14602 case Stmt::BinaryOperatorClass: { 14603 auto *BO = cast<BinaryOperator>(E); 14604 auto Opcode = BO->getOpcode(); 14605 switch (Opcode) { 14606 default: 14607 break; 14608 case BO_Comma: 14609 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14610 } 14611 break; 14612 } 14613 } 14614 return llvm::None; 14615 } 14616 14617 /// This helper function takes a pointer expression and returns the alignment of 14618 /// a VarDecl and a constant offset from the VarDecl. 14619 Optional<std::pair<CharUnits, CharUnits>> 14620 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14621 E = E->IgnoreParens(); 14622 switch (E->getStmtClass()) { 14623 default: 14624 break; 14625 case Stmt::CStyleCastExprClass: 14626 case Stmt::CXXStaticCastExprClass: 14627 case Stmt::ImplicitCastExprClass: { 14628 auto *CE = cast<CastExpr>(E); 14629 const Expr *From = CE->getSubExpr(); 14630 switch (CE->getCastKind()) { 14631 default: 14632 break; 14633 case CK_NoOp: 14634 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14635 case CK_ArrayToPointerDecay: 14636 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14637 case CK_UncheckedDerivedToBase: 14638 case CK_DerivedToBase: { 14639 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14640 if (!P) 14641 break; 14642 return getDerivedToBaseAlignmentAndOffset( 14643 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14644 } 14645 } 14646 break; 14647 } 14648 case Stmt::CXXThisExprClass: { 14649 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14650 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14651 return std::make_pair(Alignment, CharUnits::Zero()); 14652 } 14653 case Stmt::UnaryOperatorClass: { 14654 auto *UO = cast<UnaryOperator>(E); 14655 if (UO->getOpcode() == UO_AddrOf) 14656 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14657 break; 14658 } 14659 case Stmt::BinaryOperatorClass: { 14660 auto *BO = cast<BinaryOperator>(E); 14661 auto Opcode = BO->getOpcode(); 14662 switch (Opcode) { 14663 default: 14664 break; 14665 case BO_Add: 14666 case BO_Sub: { 14667 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14668 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14669 std::swap(LHS, RHS); 14670 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14671 Ctx); 14672 } 14673 case BO_Comma: 14674 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14675 } 14676 break; 14677 } 14678 } 14679 return llvm::None; 14680 } 14681 14682 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14683 // See if we can compute the alignment of a VarDecl and an offset from it. 14684 Optional<std::pair<CharUnits, CharUnits>> P = 14685 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14686 14687 if (P) 14688 return P->first.alignmentAtOffset(P->second); 14689 14690 // If that failed, return the type's alignment. 14691 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14692 } 14693 14694 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14695 /// pointer cast increases the alignment requirements. 14696 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14697 // This is actually a lot of work to potentially be doing on every 14698 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14699 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14700 return; 14701 14702 // Ignore dependent types. 14703 if (T->isDependentType() || Op->getType()->isDependentType()) 14704 return; 14705 14706 // Require that the destination be a pointer type. 14707 const PointerType *DestPtr = T->getAs<PointerType>(); 14708 if (!DestPtr) return; 14709 14710 // If the destination has alignment 1, we're done. 14711 QualType DestPointee = DestPtr->getPointeeType(); 14712 if (DestPointee->isIncompleteType()) return; 14713 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14714 if (DestAlign.isOne()) return; 14715 14716 // Require that the source be a pointer type. 14717 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14718 if (!SrcPtr) return; 14719 QualType SrcPointee = SrcPtr->getPointeeType(); 14720 14721 // Explicitly allow casts from cv void*. We already implicitly 14722 // allowed casts to cv void*, since they have alignment 1. 14723 // Also allow casts involving incomplete types, which implicitly 14724 // includes 'void'. 14725 if (SrcPointee->isIncompleteType()) return; 14726 14727 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14728 14729 if (SrcAlign >= DestAlign) return; 14730 14731 Diag(TRange.getBegin(), diag::warn_cast_align) 14732 << Op->getType() << T 14733 << static_cast<unsigned>(SrcAlign.getQuantity()) 14734 << static_cast<unsigned>(DestAlign.getQuantity()) 14735 << TRange << Op->getSourceRange(); 14736 } 14737 14738 /// Check whether this array fits the idiom of a size-one tail padded 14739 /// array member of a struct. 14740 /// 14741 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14742 /// commonly used to emulate flexible arrays in C89 code. 14743 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14744 const NamedDecl *ND) { 14745 if (Size != 1 || !ND) return false; 14746 14747 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14748 if (!FD) return false; 14749 14750 // Don't consider sizes resulting from macro expansions or template argument 14751 // substitution to form C89 tail-padded arrays. 14752 14753 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14754 while (TInfo) { 14755 TypeLoc TL = TInfo->getTypeLoc(); 14756 // Look through typedefs. 14757 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14758 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14759 TInfo = TDL->getTypeSourceInfo(); 14760 continue; 14761 } 14762 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14763 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14764 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14765 return false; 14766 } 14767 break; 14768 } 14769 14770 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14771 if (!RD) return false; 14772 if (RD->isUnion()) return false; 14773 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14774 if (!CRD->isStandardLayout()) return false; 14775 } 14776 14777 // See if this is the last field decl in the record. 14778 const Decl *D = FD; 14779 while ((D = D->getNextDeclInContext())) 14780 if (isa<FieldDecl>(D)) 14781 return false; 14782 return true; 14783 } 14784 14785 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14786 const ArraySubscriptExpr *ASE, 14787 bool AllowOnePastEnd, bool IndexNegated) { 14788 // Already diagnosed by the constant evaluator. 14789 if (isConstantEvaluated()) 14790 return; 14791 14792 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14793 if (IndexExpr->isValueDependent()) 14794 return; 14795 14796 const Type *EffectiveType = 14797 BaseExpr->getType()->getPointeeOrArrayElementType(); 14798 BaseExpr = BaseExpr->IgnoreParenCasts(); 14799 const ConstantArrayType *ArrayTy = 14800 Context.getAsConstantArrayType(BaseExpr->getType()); 14801 14802 const Type *BaseType = 14803 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 14804 bool IsUnboundedArray = (BaseType == nullptr); 14805 if (EffectiveType->isDependentType() || 14806 (!IsUnboundedArray && BaseType->isDependentType())) 14807 return; 14808 14809 Expr::EvalResult Result; 14810 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14811 return; 14812 14813 llvm::APSInt index = Result.Val.getInt(); 14814 if (IndexNegated) { 14815 index.setIsUnsigned(false); 14816 index = -index; 14817 } 14818 14819 const NamedDecl *ND = nullptr; 14820 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14821 ND = DRE->getDecl(); 14822 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14823 ND = ME->getMemberDecl(); 14824 14825 if (IsUnboundedArray) { 14826 if (index.isUnsigned() || !index.isNegative()) { 14827 const auto &ASTC = getASTContext(); 14828 unsigned AddrBits = 14829 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 14830 EffectiveType->getCanonicalTypeInternal())); 14831 if (index.getBitWidth() < AddrBits) 14832 index = index.zext(AddrBits); 14833 Optional<CharUnits> ElemCharUnits = 14834 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 14835 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 14836 // pointer) bounds-checking isn't meaningful. 14837 if (!ElemCharUnits) 14838 return; 14839 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 14840 // If index has more active bits than address space, we already know 14841 // we have a bounds violation to warn about. Otherwise, compute 14842 // address of (index + 1)th element, and warn about bounds violation 14843 // only if that address exceeds address space. 14844 if (index.getActiveBits() <= AddrBits) { 14845 bool Overflow; 14846 llvm::APInt Product(index); 14847 Product += 1; 14848 Product = Product.umul_ov(ElemBytes, Overflow); 14849 if (!Overflow && Product.getActiveBits() <= AddrBits) 14850 return; 14851 } 14852 14853 // Need to compute max possible elements in address space, since that 14854 // is included in diag message. 14855 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 14856 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 14857 MaxElems += 1; 14858 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 14859 MaxElems = MaxElems.udiv(ElemBytes); 14860 14861 unsigned DiagID = 14862 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 14863 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 14864 14865 // Diag message shows element size in bits and in "bytes" (platform- 14866 // dependent CharUnits) 14867 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14868 PDiag(DiagID) 14869 << toString(index, 10, true) << AddrBits 14870 << (unsigned)ASTC.toBits(*ElemCharUnits) 14871 << toString(ElemBytes, 10, false) 14872 << toString(MaxElems, 10, false) 14873 << (unsigned)MaxElems.getLimitedValue(~0U) 14874 << IndexExpr->getSourceRange()); 14875 14876 if (!ND) { 14877 // Try harder to find a NamedDecl to point at in the note. 14878 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14879 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14880 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14881 ND = DRE->getDecl(); 14882 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14883 ND = ME->getMemberDecl(); 14884 } 14885 14886 if (ND) 14887 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14888 PDiag(diag::note_array_declared_here) << ND); 14889 } 14890 return; 14891 } 14892 14893 if (index.isUnsigned() || !index.isNegative()) { 14894 // It is possible that the type of the base expression after 14895 // IgnoreParenCasts is incomplete, even though the type of the base 14896 // expression before IgnoreParenCasts is complete (see PR39746 for an 14897 // example). In this case we have no information about whether the array 14898 // access exceeds the array bounds. However we can still diagnose an array 14899 // access which precedes the array bounds. 14900 if (BaseType->isIncompleteType()) 14901 return; 14902 14903 llvm::APInt size = ArrayTy->getSize(); 14904 if (!size.isStrictlyPositive()) 14905 return; 14906 14907 if (BaseType != EffectiveType) { 14908 // Make sure we're comparing apples to apples when comparing index to size 14909 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14910 uint64_t array_typesize = Context.getTypeSize(BaseType); 14911 // Handle ptrarith_typesize being zero, such as when casting to void* 14912 if (!ptrarith_typesize) ptrarith_typesize = 1; 14913 if (ptrarith_typesize != array_typesize) { 14914 // There's a cast to a different size type involved 14915 uint64_t ratio = array_typesize / ptrarith_typesize; 14916 // TODO: Be smarter about handling cases where array_typesize is not a 14917 // multiple of ptrarith_typesize 14918 if (ptrarith_typesize * ratio == array_typesize) 14919 size *= llvm::APInt(size.getBitWidth(), ratio); 14920 } 14921 } 14922 14923 if (size.getBitWidth() > index.getBitWidth()) 14924 index = index.zext(size.getBitWidth()); 14925 else if (size.getBitWidth() < index.getBitWidth()) 14926 size = size.zext(index.getBitWidth()); 14927 14928 // For array subscripting the index must be less than size, but for pointer 14929 // arithmetic also allow the index (offset) to be equal to size since 14930 // computing the next address after the end of the array is legal and 14931 // commonly done e.g. in C++ iterators and range-based for loops. 14932 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14933 return; 14934 14935 // Also don't warn for arrays of size 1 which are members of some 14936 // structure. These are often used to approximate flexible arrays in C89 14937 // code. 14938 if (IsTailPaddedMemberArray(*this, size, ND)) 14939 return; 14940 14941 // Suppress the warning if the subscript expression (as identified by the 14942 // ']' location) and the index expression are both from macro expansions 14943 // within a system header. 14944 if (ASE) { 14945 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14946 ASE->getRBracketLoc()); 14947 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14948 SourceLocation IndexLoc = 14949 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14950 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14951 return; 14952 } 14953 } 14954 14955 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 14956 : diag::warn_ptr_arith_exceeds_bounds; 14957 14958 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14959 PDiag(DiagID) << toString(index, 10, true) 14960 << toString(size, 10, true) 14961 << (unsigned)size.getLimitedValue(~0U) 14962 << IndexExpr->getSourceRange()); 14963 } else { 14964 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14965 if (!ASE) { 14966 DiagID = diag::warn_ptr_arith_precedes_bounds; 14967 if (index.isNegative()) index = -index; 14968 } 14969 14970 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14971 PDiag(DiagID) << toString(index, 10, true) 14972 << IndexExpr->getSourceRange()); 14973 } 14974 14975 if (!ND) { 14976 // Try harder to find a NamedDecl to point at in the note. 14977 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14978 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14979 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14980 ND = DRE->getDecl(); 14981 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14982 ND = ME->getMemberDecl(); 14983 } 14984 14985 if (ND) 14986 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14987 PDiag(diag::note_array_declared_here) << ND); 14988 } 14989 14990 void Sema::CheckArrayAccess(const Expr *expr) { 14991 int AllowOnePastEnd = 0; 14992 while (expr) { 14993 expr = expr->IgnoreParenImpCasts(); 14994 switch (expr->getStmtClass()) { 14995 case Stmt::ArraySubscriptExprClass: { 14996 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14997 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14998 AllowOnePastEnd > 0); 14999 expr = ASE->getBase(); 15000 break; 15001 } 15002 case Stmt::MemberExprClass: { 15003 expr = cast<MemberExpr>(expr)->getBase(); 15004 break; 15005 } 15006 case Stmt::OMPArraySectionExprClass: { 15007 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15008 if (ASE->getLowerBound()) 15009 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15010 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15011 return; 15012 } 15013 case Stmt::UnaryOperatorClass: { 15014 // Only unwrap the * and & unary operators 15015 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15016 expr = UO->getSubExpr(); 15017 switch (UO->getOpcode()) { 15018 case UO_AddrOf: 15019 AllowOnePastEnd++; 15020 break; 15021 case UO_Deref: 15022 AllowOnePastEnd--; 15023 break; 15024 default: 15025 return; 15026 } 15027 break; 15028 } 15029 case Stmt::ConditionalOperatorClass: { 15030 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15031 if (const Expr *lhs = cond->getLHS()) 15032 CheckArrayAccess(lhs); 15033 if (const Expr *rhs = cond->getRHS()) 15034 CheckArrayAccess(rhs); 15035 return; 15036 } 15037 case Stmt::CXXOperatorCallExprClass: { 15038 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15039 for (const auto *Arg : OCE->arguments()) 15040 CheckArrayAccess(Arg); 15041 return; 15042 } 15043 default: 15044 return; 15045 } 15046 } 15047 } 15048 15049 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15050 15051 namespace { 15052 15053 struct RetainCycleOwner { 15054 VarDecl *Variable = nullptr; 15055 SourceRange Range; 15056 SourceLocation Loc; 15057 bool Indirect = false; 15058 15059 RetainCycleOwner() = default; 15060 15061 void setLocsFrom(Expr *e) { 15062 Loc = e->getExprLoc(); 15063 Range = e->getSourceRange(); 15064 } 15065 }; 15066 15067 } // namespace 15068 15069 /// Consider whether capturing the given variable can possibly lead to 15070 /// a retain cycle. 15071 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15072 // In ARC, it's captured strongly iff the variable has __strong 15073 // lifetime. In MRR, it's captured strongly if the variable is 15074 // __block and has an appropriate type. 15075 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15076 return false; 15077 15078 owner.Variable = var; 15079 if (ref) 15080 owner.setLocsFrom(ref); 15081 return true; 15082 } 15083 15084 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15085 while (true) { 15086 e = e->IgnoreParens(); 15087 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15088 switch (cast->getCastKind()) { 15089 case CK_BitCast: 15090 case CK_LValueBitCast: 15091 case CK_LValueToRValue: 15092 case CK_ARCReclaimReturnedObject: 15093 e = cast->getSubExpr(); 15094 continue; 15095 15096 default: 15097 return false; 15098 } 15099 } 15100 15101 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15102 ObjCIvarDecl *ivar = ref->getDecl(); 15103 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15104 return false; 15105 15106 // Try to find a retain cycle in the base. 15107 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15108 return false; 15109 15110 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15111 owner.Indirect = true; 15112 return true; 15113 } 15114 15115 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15116 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15117 if (!var) return false; 15118 return considerVariable(var, ref, owner); 15119 } 15120 15121 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15122 if (member->isArrow()) return false; 15123 15124 // Don't count this as an indirect ownership. 15125 e = member->getBase(); 15126 continue; 15127 } 15128 15129 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15130 // Only pay attention to pseudo-objects on property references. 15131 ObjCPropertyRefExpr *pre 15132 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15133 ->IgnoreParens()); 15134 if (!pre) return false; 15135 if (pre->isImplicitProperty()) return false; 15136 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15137 if (!property->isRetaining() && 15138 !(property->getPropertyIvarDecl() && 15139 property->getPropertyIvarDecl()->getType() 15140 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15141 return false; 15142 15143 owner.Indirect = true; 15144 if (pre->isSuperReceiver()) { 15145 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15146 if (!owner.Variable) 15147 return false; 15148 owner.Loc = pre->getLocation(); 15149 owner.Range = pre->getSourceRange(); 15150 return true; 15151 } 15152 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15153 ->getSourceExpr()); 15154 continue; 15155 } 15156 15157 // Array ivars? 15158 15159 return false; 15160 } 15161 } 15162 15163 namespace { 15164 15165 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15166 ASTContext &Context; 15167 VarDecl *Variable; 15168 Expr *Capturer = nullptr; 15169 bool VarWillBeReased = false; 15170 15171 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15172 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15173 Context(Context), Variable(variable) {} 15174 15175 void VisitDeclRefExpr(DeclRefExpr *ref) { 15176 if (ref->getDecl() == Variable && !Capturer) 15177 Capturer = ref; 15178 } 15179 15180 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15181 if (Capturer) return; 15182 Visit(ref->getBase()); 15183 if (Capturer && ref->isFreeIvar()) 15184 Capturer = ref; 15185 } 15186 15187 void VisitBlockExpr(BlockExpr *block) { 15188 // Look inside nested blocks 15189 if (block->getBlockDecl()->capturesVariable(Variable)) 15190 Visit(block->getBlockDecl()->getBody()); 15191 } 15192 15193 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15194 if (Capturer) return; 15195 if (OVE->getSourceExpr()) 15196 Visit(OVE->getSourceExpr()); 15197 } 15198 15199 void VisitBinaryOperator(BinaryOperator *BinOp) { 15200 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15201 return; 15202 Expr *LHS = BinOp->getLHS(); 15203 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15204 if (DRE->getDecl() != Variable) 15205 return; 15206 if (Expr *RHS = BinOp->getRHS()) { 15207 RHS = RHS->IgnoreParenCasts(); 15208 Optional<llvm::APSInt> Value; 15209 VarWillBeReased = 15210 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15211 *Value == 0); 15212 } 15213 } 15214 } 15215 }; 15216 15217 } // namespace 15218 15219 /// Check whether the given argument is a block which captures a 15220 /// variable. 15221 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15222 assert(owner.Variable && owner.Loc.isValid()); 15223 15224 e = e->IgnoreParenCasts(); 15225 15226 // Look through [^{...} copy] and Block_copy(^{...}). 15227 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15228 Selector Cmd = ME->getSelector(); 15229 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15230 e = ME->getInstanceReceiver(); 15231 if (!e) 15232 return nullptr; 15233 e = e->IgnoreParenCasts(); 15234 } 15235 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15236 if (CE->getNumArgs() == 1) { 15237 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15238 if (Fn) { 15239 const IdentifierInfo *FnI = Fn->getIdentifier(); 15240 if (FnI && FnI->isStr("_Block_copy")) { 15241 e = CE->getArg(0)->IgnoreParenCasts(); 15242 } 15243 } 15244 } 15245 } 15246 15247 BlockExpr *block = dyn_cast<BlockExpr>(e); 15248 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15249 return nullptr; 15250 15251 FindCaptureVisitor visitor(S.Context, owner.Variable); 15252 visitor.Visit(block->getBlockDecl()->getBody()); 15253 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15254 } 15255 15256 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15257 RetainCycleOwner &owner) { 15258 assert(capturer); 15259 assert(owner.Variable && owner.Loc.isValid()); 15260 15261 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15262 << owner.Variable << capturer->getSourceRange(); 15263 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15264 << owner.Indirect << owner.Range; 15265 } 15266 15267 /// Check for a keyword selector that starts with the word 'add' or 15268 /// 'set'. 15269 static bool isSetterLikeSelector(Selector sel) { 15270 if (sel.isUnarySelector()) return false; 15271 15272 StringRef str = sel.getNameForSlot(0); 15273 while (!str.empty() && str.front() == '_') str = str.substr(1); 15274 if (str.startswith("set")) 15275 str = str.substr(3); 15276 else if (str.startswith("add")) { 15277 // Specially allow 'addOperationWithBlock:'. 15278 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15279 return false; 15280 str = str.substr(3); 15281 } 15282 else 15283 return false; 15284 15285 if (str.empty()) return true; 15286 return !isLowercase(str.front()); 15287 } 15288 15289 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15290 ObjCMessageExpr *Message) { 15291 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15292 Message->getReceiverInterface(), 15293 NSAPI::ClassId_NSMutableArray); 15294 if (!IsMutableArray) { 15295 return None; 15296 } 15297 15298 Selector Sel = Message->getSelector(); 15299 15300 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15301 S.NSAPIObj->getNSArrayMethodKind(Sel); 15302 if (!MKOpt) { 15303 return None; 15304 } 15305 15306 NSAPI::NSArrayMethodKind MK = *MKOpt; 15307 15308 switch (MK) { 15309 case NSAPI::NSMutableArr_addObject: 15310 case NSAPI::NSMutableArr_insertObjectAtIndex: 15311 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15312 return 0; 15313 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15314 return 1; 15315 15316 default: 15317 return None; 15318 } 15319 15320 return None; 15321 } 15322 15323 static 15324 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15325 ObjCMessageExpr *Message) { 15326 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15327 Message->getReceiverInterface(), 15328 NSAPI::ClassId_NSMutableDictionary); 15329 if (!IsMutableDictionary) { 15330 return None; 15331 } 15332 15333 Selector Sel = Message->getSelector(); 15334 15335 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15336 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15337 if (!MKOpt) { 15338 return None; 15339 } 15340 15341 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15342 15343 switch (MK) { 15344 case NSAPI::NSMutableDict_setObjectForKey: 15345 case NSAPI::NSMutableDict_setValueForKey: 15346 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15347 return 0; 15348 15349 default: 15350 return None; 15351 } 15352 15353 return None; 15354 } 15355 15356 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15357 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15358 Message->getReceiverInterface(), 15359 NSAPI::ClassId_NSMutableSet); 15360 15361 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15362 Message->getReceiverInterface(), 15363 NSAPI::ClassId_NSMutableOrderedSet); 15364 if (!IsMutableSet && !IsMutableOrderedSet) { 15365 return None; 15366 } 15367 15368 Selector Sel = Message->getSelector(); 15369 15370 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15371 if (!MKOpt) { 15372 return None; 15373 } 15374 15375 NSAPI::NSSetMethodKind MK = *MKOpt; 15376 15377 switch (MK) { 15378 case NSAPI::NSMutableSet_addObject: 15379 case NSAPI::NSOrderedSet_setObjectAtIndex: 15380 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15381 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15382 return 0; 15383 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15384 return 1; 15385 } 15386 15387 return None; 15388 } 15389 15390 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15391 if (!Message->isInstanceMessage()) { 15392 return; 15393 } 15394 15395 Optional<int> ArgOpt; 15396 15397 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15398 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15399 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15400 return; 15401 } 15402 15403 int ArgIndex = *ArgOpt; 15404 15405 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15406 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15407 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15408 } 15409 15410 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15411 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15412 if (ArgRE->isObjCSelfExpr()) { 15413 Diag(Message->getSourceRange().getBegin(), 15414 diag::warn_objc_circular_container) 15415 << ArgRE->getDecl() << StringRef("'super'"); 15416 } 15417 } 15418 } else { 15419 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15420 15421 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15422 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15423 } 15424 15425 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15426 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15427 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15428 ValueDecl *Decl = ReceiverRE->getDecl(); 15429 Diag(Message->getSourceRange().getBegin(), 15430 diag::warn_objc_circular_container) 15431 << Decl << Decl; 15432 if (!ArgRE->isObjCSelfExpr()) { 15433 Diag(Decl->getLocation(), 15434 diag::note_objc_circular_container_declared_here) 15435 << Decl; 15436 } 15437 } 15438 } 15439 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15440 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15441 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15442 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15443 Diag(Message->getSourceRange().getBegin(), 15444 diag::warn_objc_circular_container) 15445 << Decl << Decl; 15446 Diag(Decl->getLocation(), 15447 diag::note_objc_circular_container_declared_here) 15448 << Decl; 15449 } 15450 } 15451 } 15452 } 15453 } 15454 15455 /// Check a message send to see if it's likely to cause a retain cycle. 15456 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15457 // Only check instance methods whose selector looks like a setter. 15458 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15459 return; 15460 15461 // Try to find a variable that the receiver is strongly owned by. 15462 RetainCycleOwner owner; 15463 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15464 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15465 return; 15466 } else { 15467 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15468 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15469 owner.Loc = msg->getSuperLoc(); 15470 owner.Range = msg->getSuperLoc(); 15471 } 15472 15473 // Check whether the receiver is captured by any of the arguments. 15474 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15475 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15476 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15477 // noescape blocks should not be retained by the method. 15478 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15479 continue; 15480 return diagnoseRetainCycle(*this, capturer, owner); 15481 } 15482 } 15483 } 15484 15485 /// Check a property assign to see if it's likely to cause a retain cycle. 15486 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15487 RetainCycleOwner owner; 15488 if (!findRetainCycleOwner(*this, receiver, owner)) 15489 return; 15490 15491 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15492 diagnoseRetainCycle(*this, capturer, owner); 15493 } 15494 15495 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15496 RetainCycleOwner Owner; 15497 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15498 return; 15499 15500 // Because we don't have an expression for the variable, we have to set the 15501 // location explicitly here. 15502 Owner.Loc = Var->getLocation(); 15503 Owner.Range = Var->getSourceRange(); 15504 15505 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15506 diagnoseRetainCycle(*this, Capturer, Owner); 15507 } 15508 15509 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15510 Expr *RHS, bool isProperty) { 15511 // Check if RHS is an Objective-C object literal, which also can get 15512 // immediately zapped in a weak reference. Note that we explicitly 15513 // allow ObjCStringLiterals, since those are designed to never really die. 15514 RHS = RHS->IgnoreParenImpCasts(); 15515 15516 // This enum needs to match with the 'select' in 15517 // warn_objc_arc_literal_assign (off-by-1). 15518 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15519 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15520 return false; 15521 15522 S.Diag(Loc, diag::warn_arc_literal_assign) 15523 << (unsigned) Kind 15524 << (isProperty ? 0 : 1) 15525 << RHS->getSourceRange(); 15526 15527 return true; 15528 } 15529 15530 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15531 Qualifiers::ObjCLifetime LT, 15532 Expr *RHS, bool isProperty) { 15533 // Strip off any implicit cast added to get to the one ARC-specific. 15534 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15535 if (cast->getCastKind() == CK_ARCConsumeObject) { 15536 S.Diag(Loc, diag::warn_arc_retained_assign) 15537 << (LT == Qualifiers::OCL_ExplicitNone) 15538 << (isProperty ? 0 : 1) 15539 << RHS->getSourceRange(); 15540 return true; 15541 } 15542 RHS = cast->getSubExpr(); 15543 } 15544 15545 if (LT == Qualifiers::OCL_Weak && 15546 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15547 return true; 15548 15549 return false; 15550 } 15551 15552 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15553 QualType LHS, Expr *RHS) { 15554 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15555 15556 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15557 return false; 15558 15559 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15560 return true; 15561 15562 return false; 15563 } 15564 15565 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15566 Expr *LHS, Expr *RHS) { 15567 QualType LHSType; 15568 // PropertyRef on LHS type need be directly obtained from 15569 // its declaration as it has a PseudoType. 15570 ObjCPropertyRefExpr *PRE 15571 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15572 if (PRE && !PRE->isImplicitProperty()) { 15573 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15574 if (PD) 15575 LHSType = PD->getType(); 15576 } 15577 15578 if (LHSType.isNull()) 15579 LHSType = LHS->getType(); 15580 15581 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15582 15583 if (LT == Qualifiers::OCL_Weak) { 15584 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15585 getCurFunction()->markSafeWeakUse(LHS); 15586 } 15587 15588 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15589 return; 15590 15591 // FIXME. Check for other life times. 15592 if (LT != Qualifiers::OCL_None) 15593 return; 15594 15595 if (PRE) { 15596 if (PRE->isImplicitProperty()) 15597 return; 15598 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15599 if (!PD) 15600 return; 15601 15602 unsigned Attributes = PD->getPropertyAttributes(); 15603 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15604 // when 'assign' attribute was not explicitly specified 15605 // by user, ignore it and rely on property type itself 15606 // for lifetime info. 15607 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15608 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15609 LHSType->isObjCRetainableType()) 15610 return; 15611 15612 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15613 if (cast->getCastKind() == CK_ARCConsumeObject) { 15614 Diag(Loc, diag::warn_arc_retained_property_assign) 15615 << RHS->getSourceRange(); 15616 return; 15617 } 15618 RHS = cast->getSubExpr(); 15619 } 15620 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15621 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15622 return; 15623 } 15624 } 15625 } 15626 15627 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15628 15629 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15630 SourceLocation StmtLoc, 15631 const NullStmt *Body) { 15632 // Do not warn if the body is a macro that expands to nothing, e.g: 15633 // 15634 // #define CALL(x) 15635 // if (condition) 15636 // CALL(0); 15637 if (Body->hasLeadingEmptyMacro()) 15638 return false; 15639 15640 // Get line numbers of statement and body. 15641 bool StmtLineInvalid; 15642 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15643 &StmtLineInvalid); 15644 if (StmtLineInvalid) 15645 return false; 15646 15647 bool BodyLineInvalid; 15648 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15649 &BodyLineInvalid); 15650 if (BodyLineInvalid) 15651 return false; 15652 15653 // Warn if null statement and body are on the same line. 15654 if (StmtLine != BodyLine) 15655 return false; 15656 15657 return true; 15658 } 15659 15660 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15661 const Stmt *Body, 15662 unsigned DiagID) { 15663 // Since this is a syntactic check, don't emit diagnostic for template 15664 // instantiations, this just adds noise. 15665 if (CurrentInstantiationScope) 15666 return; 15667 15668 // The body should be a null statement. 15669 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15670 if (!NBody) 15671 return; 15672 15673 // Do the usual checks. 15674 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15675 return; 15676 15677 Diag(NBody->getSemiLoc(), DiagID); 15678 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15679 } 15680 15681 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15682 const Stmt *PossibleBody) { 15683 assert(!CurrentInstantiationScope); // Ensured by caller 15684 15685 SourceLocation StmtLoc; 15686 const Stmt *Body; 15687 unsigned DiagID; 15688 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15689 StmtLoc = FS->getRParenLoc(); 15690 Body = FS->getBody(); 15691 DiagID = diag::warn_empty_for_body; 15692 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15693 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15694 Body = WS->getBody(); 15695 DiagID = diag::warn_empty_while_body; 15696 } else 15697 return; // Neither `for' nor `while'. 15698 15699 // The body should be a null statement. 15700 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15701 if (!NBody) 15702 return; 15703 15704 // Skip expensive checks if diagnostic is disabled. 15705 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15706 return; 15707 15708 // Do the usual checks. 15709 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15710 return; 15711 15712 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15713 // noise level low, emit diagnostics only if for/while is followed by a 15714 // CompoundStmt, e.g.: 15715 // for (int i = 0; i < n; i++); 15716 // { 15717 // a(i); 15718 // } 15719 // or if for/while is followed by a statement with more indentation 15720 // than for/while itself: 15721 // for (int i = 0; i < n; i++); 15722 // a(i); 15723 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15724 if (!ProbableTypo) { 15725 bool BodyColInvalid; 15726 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15727 PossibleBody->getBeginLoc(), &BodyColInvalid); 15728 if (BodyColInvalid) 15729 return; 15730 15731 bool StmtColInvalid; 15732 unsigned StmtCol = 15733 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15734 if (StmtColInvalid) 15735 return; 15736 15737 if (BodyCol > StmtCol) 15738 ProbableTypo = true; 15739 } 15740 15741 if (ProbableTypo) { 15742 Diag(NBody->getSemiLoc(), DiagID); 15743 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15744 } 15745 } 15746 15747 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15748 15749 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15750 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15751 SourceLocation OpLoc) { 15752 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15753 return; 15754 15755 if (inTemplateInstantiation()) 15756 return; 15757 15758 // Strip parens and casts away. 15759 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15760 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15761 15762 // Check for a call expression 15763 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15764 if (!CE || CE->getNumArgs() != 1) 15765 return; 15766 15767 // Check for a call to std::move 15768 if (!CE->isCallToStdMove()) 15769 return; 15770 15771 // Get argument from std::move 15772 RHSExpr = CE->getArg(0); 15773 15774 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15775 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15776 15777 // Two DeclRefExpr's, check that the decls are the same. 15778 if (LHSDeclRef && RHSDeclRef) { 15779 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15780 return; 15781 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15782 RHSDeclRef->getDecl()->getCanonicalDecl()) 15783 return; 15784 15785 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15786 << LHSExpr->getSourceRange() 15787 << RHSExpr->getSourceRange(); 15788 return; 15789 } 15790 15791 // Member variables require a different approach to check for self moves. 15792 // MemberExpr's are the same if every nested MemberExpr refers to the same 15793 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15794 // the base Expr's are CXXThisExpr's. 15795 const Expr *LHSBase = LHSExpr; 15796 const Expr *RHSBase = RHSExpr; 15797 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15798 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15799 if (!LHSME || !RHSME) 15800 return; 15801 15802 while (LHSME && RHSME) { 15803 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15804 RHSME->getMemberDecl()->getCanonicalDecl()) 15805 return; 15806 15807 LHSBase = LHSME->getBase(); 15808 RHSBase = RHSME->getBase(); 15809 LHSME = dyn_cast<MemberExpr>(LHSBase); 15810 RHSME = dyn_cast<MemberExpr>(RHSBase); 15811 } 15812 15813 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15814 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15815 if (LHSDeclRef && RHSDeclRef) { 15816 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15817 return; 15818 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15819 RHSDeclRef->getDecl()->getCanonicalDecl()) 15820 return; 15821 15822 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15823 << LHSExpr->getSourceRange() 15824 << RHSExpr->getSourceRange(); 15825 return; 15826 } 15827 15828 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15829 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15830 << LHSExpr->getSourceRange() 15831 << RHSExpr->getSourceRange(); 15832 } 15833 15834 //===--- Layout compatibility ----------------------------------------------// 15835 15836 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15837 15838 /// Check if two enumeration types are layout-compatible. 15839 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15840 // C++11 [dcl.enum] p8: 15841 // Two enumeration types are layout-compatible if they have the same 15842 // underlying type. 15843 return ED1->isComplete() && ED2->isComplete() && 15844 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15845 } 15846 15847 /// Check if two fields are layout-compatible. 15848 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15849 FieldDecl *Field2) { 15850 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15851 return false; 15852 15853 if (Field1->isBitField() != Field2->isBitField()) 15854 return false; 15855 15856 if (Field1->isBitField()) { 15857 // Make sure that the bit-fields are the same length. 15858 unsigned Bits1 = Field1->getBitWidthValue(C); 15859 unsigned Bits2 = Field2->getBitWidthValue(C); 15860 15861 if (Bits1 != Bits2) 15862 return false; 15863 } 15864 15865 return true; 15866 } 15867 15868 /// Check if two standard-layout structs are layout-compatible. 15869 /// (C++11 [class.mem] p17) 15870 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15871 RecordDecl *RD2) { 15872 // If both records are C++ classes, check that base classes match. 15873 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15874 // If one of records is a CXXRecordDecl we are in C++ mode, 15875 // thus the other one is a CXXRecordDecl, too. 15876 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15877 // Check number of base classes. 15878 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15879 return false; 15880 15881 // Check the base classes. 15882 for (CXXRecordDecl::base_class_const_iterator 15883 Base1 = D1CXX->bases_begin(), 15884 BaseEnd1 = D1CXX->bases_end(), 15885 Base2 = D2CXX->bases_begin(); 15886 Base1 != BaseEnd1; 15887 ++Base1, ++Base2) { 15888 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15889 return false; 15890 } 15891 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15892 // If only RD2 is a C++ class, it should have zero base classes. 15893 if (D2CXX->getNumBases() > 0) 15894 return false; 15895 } 15896 15897 // Check the fields. 15898 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15899 Field2End = RD2->field_end(), 15900 Field1 = RD1->field_begin(), 15901 Field1End = RD1->field_end(); 15902 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15903 if (!isLayoutCompatible(C, *Field1, *Field2)) 15904 return false; 15905 } 15906 if (Field1 != Field1End || Field2 != Field2End) 15907 return false; 15908 15909 return true; 15910 } 15911 15912 /// Check if two standard-layout unions are layout-compatible. 15913 /// (C++11 [class.mem] p18) 15914 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15915 RecordDecl *RD2) { 15916 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15917 for (auto *Field2 : RD2->fields()) 15918 UnmatchedFields.insert(Field2); 15919 15920 for (auto *Field1 : RD1->fields()) { 15921 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15922 I = UnmatchedFields.begin(), 15923 E = UnmatchedFields.end(); 15924 15925 for ( ; I != E; ++I) { 15926 if (isLayoutCompatible(C, Field1, *I)) { 15927 bool Result = UnmatchedFields.erase(*I); 15928 (void) Result; 15929 assert(Result); 15930 break; 15931 } 15932 } 15933 if (I == E) 15934 return false; 15935 } 15936 15937 return UnmatchedFields.empty(); 15938 } 15939 15940 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15941 RecordDecl *RD2) { 15942 if (RD1->isUnion() != RD2->isUnion()) 15943 return false; 15944 15945 if (RD1->isUnion()) 15946 return isLayoutCompatibleUnion(C, RD1, RD2); 15947 else 15948 return isLayoutCompatibleStruct(C, RD1, RD2); 15949 } 15950 15951 /// Check if two types are layout-compatible in C++11 sense. 15952 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15953 if (T1.isNull() || T2.isNull()) 15954 return false; 15955 15956 // C++11 [basic.types] p11: 15957 // If two types T1 and T2 are the same type, then T1 and T2 are 15958 // layout-compatible types. 15959 if (C.hasSameType(T1, T2)) 15960 return true; 15961 15962 T1 = T1.getCanonicalType().getUnqualifiedType(); 15963 T2 = T2.getCanonicalType().getUnqualifiedType(); 15964 15965 const Type::TypeClass TC1 = T1->getTypeClass(); 15966 const Type::TypeClass TC2 = T2->getTypeClass(); 15967 15968 if (TC1 != TC2) 15969 return false; 15970 15971 if (TC1 == Type::Enum) { 15972 return isLayoutCompatible(C, 15973 cast<EnumType>(T1)->getDecl(), 15974 cast<EnumType>(T2)->getDecl()); 15975 } else if (TC1 == Type::Record) { 15976 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15977 return false; 15978 15979 return isLayoutCompatible(C, 15980 cast<RecordType>(T1)->getDecl(), 15981 cast<RecordType>(T2)->getDecl()); 15982 } 15983 15984 return false; 15985 } 15986 15987 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15988 15989 /// Given a type tag expression find the type tag itself. 15990 /// 15991 /// \param TypeExpr Type tag expression, as it appears in user's code. 15992 /// 15993 /// \param VD Declaration of an identifier that appears in a type tag. 15994 /// 15995 /// \param MagicValue Type tag magic value. 15996 /// 15997 /// \param isConstantEvaluated wether the evalaution should be performed in 15998 15999 /// constant context. 16000 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16001 const ValueDecl **VD, uint64_t *MagicValue, 16002 bool isConstantEvaluated) { 16003 while(true) { 16004 if (!TypeExpr) 16005 return false; 16006 16007 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16008 16009 switch (TypeExpr->getStmtClass()) { 16010 case Stmt::UnaryOperatorClass: { 16011 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16012 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16013 TypeExpr = UO->getSubExpr(); 16014 continue; 16015 } 16016 return false; 16017 } 16018 16019 case Stmt::DeclRefExprClass: { 16020 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16021 *VD = DRE->getDecl(); 16022 return true; 16023 } 16024 16025 case Stmt::IntegerLiteralClass: { 16026 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16027 llvm::APInt MagicValueAPInt = IL->getValue(); 16028 if (MagicValueAPInt.getActiveBits() <= 64) { 16029 *MagicValue = MagicValueAPInt.getZExtValue(); 16030 return true; 16031 } else 16032 return false; 16033 } 16034 16035 case Stmt::BinaryConditionalOperatorClass: 16036 case Stmt::ConditionalOperatorClass: { 16037 const AbstractConditionalOperator *ACO = 16038 cast<AbstractConditionalOperator>(TypeExpr); 16039 bool Result; 16040 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16041 isConstantEvaluated)) { 16042 if (Result) 16043 TypeExpr = ACO->getTrueExpr(); 16044 else 16045 TypeExpr = ACO->getFalseExpr(); 16046 continue; 16047 } 16048 return false; 16049 } 16050 16051 case Stmt::BinaryOperatorClass: { 16052 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16053 if (BO->getOpcode() == BO_Comma) { 16054 TypeExpr = BO->getRHS(); 16055 continue; 16056 } 16057 return false; 16058 } 16059 16060 default: 16061 return false; 16062 } 16063 } 16064 } 16065 16066 /// Retrieve the C type corresponding to type tag TypeExpr. 16067 /// 16068 /// \param TypeExpr Expression that specifies a type tag. 16069 /// 16070 /// \param MagicValues Registered magic values. 16071 /// 16072 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16073 /// kind. 16074 /// 16075 /// \param TypeInfo Information about the corresponding C type. 16076 /// 16077 /// \param isConstantEvaluated wether the evalaution should be performed in 16078 /// constant context. 16079 /// 16080 /// \returns true if the corresponding C type was found. 16081 static bool GetMatchingCType( 16082 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16083 const ASTContext &Ctx, 16084 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16085 *MagicValues, 16086 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16087 bool isConstantEvaluated) { 16088 FoundWrongKind = false; 16089 16090 // Variable declaration that has type_tag_for_datatype attribute. 16091 const ValueDecl *VD = nullptr; 16092 16093 uint64_t MagicValue; 16094 16095 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16096 return false; 16097 16098 if (VD) { 16099 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16100 if (I->getArgumentKind() != ArgumentKind) { 16101 FoundWrongKind = true; 16102 return false; 16103 } 16104 TypeInfo.Type = I->getMatchingCType(); 16105 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16106 TypeInfo.MustBeNull = I->getMustBeNull(); 16107 return true; 16108 } 16109 return false; 16110 } 16111 16112 if (!MagicValues) 16113 return false; 16114 16115 llvm::DenseMap<Sema::TypeTagMagicValue, 16116 Sema::TypeTagData>::const_iterator I = 16117 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16118 if (I == MagicValues->end()) 16119 return false; 16120 16121 TypeInfo = I->second; 16122 return true; 16123 } 16124 16125 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16126 uint64_t MagicValue, QualType Type, 16127 bool LayoutCompatible, 16128 bool MustBeNull) { 16129 if (!TypeTagForDatatypeMagicValues) 16130 TypeTagForDatatypeMagicValues.reset( 16131 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16132 16133 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16134 (*TypeTagForDatatypeMagicValues)[Magic] = 16135 TypeTagData(Type, LayoutCompatible, MustBeNull); 16136 } 16137 16138 static bool IsSameCharType(QualType T1, QualType T2) { 16139 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16140 if (!BT1) 16141 return false; 16142 16143 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16144 if (!BT2) 16145 return false; 16146 16147 BuiltinType::Kind T1Kind = BT1->getKind(); 16148 BuiltinType::Kind T2Kind = BT2->getKind(); 16149 16150 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16151 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16152 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16153 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16154 } 16155 16156 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16157 const ArrayRef<const Expr *> ExprArgs, 16158 SourceLocation CallSiteLoc) { 16159 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16160 bool IsPointerAttr = Attr->getIsPointer(); 16161 16162 // Retrieve the argument representing the 'type_tag'. 16163 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16164 if (TypeTagIdxAST >= ExprArgs.size()) { 16165 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16166 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16167 return; 16168 } 16169 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16170 bool FoundWrongKind; 16171 TypeTagData TypeInfo; 16172 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16173 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16174 TypeInfo, isConstantEvaluated())) { 16175 if (FoundWrongKind) 16176 Diag(TypeTagExpr->getExprLoc(), 16177 diag::warn_type_tag_for_datatype_wrong_kind) 16178 << TypeTagExpr->getSourceRange(); 16179 return; 16180 } 16181 16182 // Retrieve the argument representing the 'arg_idx'. 16183 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16184 if (ArgumentIdxAST >= ExprArgs.size()) { 16185 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16186 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16187 return; 16188 } 16189 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16190 if (IsPointerAttr) { 16191 // Skip implicit cast of pointer to `void *' (as a function argument). 16192 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16193 if (ICE->getType()->isVoidPointerType() && 16194 ICE->getCastKind() == CK_BitCast) 16195 ArgumentExpr = ICE->getSubExpr(); 16196 } 16197 QualType ArgumentType = ArgumentExpr->getType(); 16198 16199 // Passing a `void*' pointer shouldn't trigger a warning. 16200 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16201 return; 16202 16203 if (TypeInfo.MustBeNull) { 16204 // Type tag with matching void type requires a null pointer. 16205 if (!ArgumentExpr->isNullPointerConstant(Context, 16206 Expr::NPC_ValueDependentIsNotNull)) { 16207 Diag(ArgumentExpr->getExprLoc(), 16208 diag::warn_type_safety_null_pointer_required) 16209 << ArgumentKind->getName() 16210 << ArgumentExpr->getSourceRange() 16211 << TypeTagExpr->getSourceRange(); 16212 } 16213 return; 16214 } 16215 16216 QualType RequiredType = TypeInfo.Type; 16217 if (IsPointerAttr) 16218 RequiredType = Context.getPointerType(RequiredType); 16219 16220 bool mismatch = false; 16221 if (!TypeInfo.LayoutCompatible) { 16222 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16223 16224 // C++11 [basic.fundamental] p1: 16225 // Plain char, signed char, and unsigned char are three distinct types. 16226 // 16227 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16228 // char' depending on the current char signedness mode. 16229 if (mismatch) 16230 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16231 RequiredType->getPointeeType())) || 16232 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16233 mismatch = false; 16234 } else 16235 if (IsPointerAttr) 16236 mismatch = !isLayoutCompatible(Context, 16237 ArgumentType->getPointeeType(), 16238 RequiredType->getPointeeType()); 16239 else 16240 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16241 16242 if (mismatch) 16243 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16244 << ArgumentType << ArgumentKind 16245 << TypeInfo.LayoutCompatible << RequiredType 16246 << ArgumentExpr->getSourceRange() 16247 << TypeTagExpr->getSourceRange(); 16248 } 16249 16250 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16251 CharUnits Alignment) { 16252 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16253 } 16254 16255 void Sema::DiagnoseMisalignedMembers() { 16256 for (MisalignedMember &m : MisalignedMembers) { 16257 const NamedDecl *ND = m.RD; 16258 if (ND->getName().empty()) { 16259 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16260 ND = TD; 16261 } 16262 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16263 << m.MD << ND << m.E->getSourceRange(); 16264 } 16265 MisalignedMembers.clear(); 16266 } 16267 16268 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16269 E = E->IgnoreParens(); 16270 if (!T->isPointerType() && !T->isIntegerType()) 16271 return; 16272 if (isa<UnaryOperator>(E) && 16273 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16274 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16275 if (isa<MemberExpr>(Op)) { 16276 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16277 if (MA != MisalignedMembers.end() && 16278 (T->isIntegerType() || 16279 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16280 Context.getTypeAlignInChars( 16281 T->getPointeeType()) <= MA->Alignment)))) 16282 MisalignedMembers.erase(MA); 16283 } 16284 } 16285 } 16286 16287 void Sema::RefersToMemberWithReducedAlignment( 16288 Expr *E, 16289 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16290 Action) { 16291 const auto *ME = dyn_cast<MemberExpr>(E); 16292 if (!ME) 16293 return; 16294 16295 // No need to check expressions with an __unaligned-qualified type. 16296 if (E->getType().getQualifiers().hasUnaligned()) 16297 return; 16298 16299 // For a chain of MemberExpr like "a.b.c.d" this list 16300 // will keep FieldDecl's like [d, c, b]. 16301 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16302 const MemberExpr *TopME = nullptr; 16303 bool AnyIsPacked = false; 16304 do { 16305 QualType BaseType = ME->getBase()->getType(); 16306 if (BaseType->isDependentType()) 16307 return; 16308 if (ME->isArrow()) 16309 BaseType = BaseType->getPointeeType(); 16310 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16311 if (RD->isInvalidDecl()) 16312 return; 16313 16314 ValueDecl *MD = ME->getMemberDecl(); 16315 auto *FD = dyn_cast<FieldDecl>(MD); 16316 // We do not care about non-data members. 16317 if (!FD || FD->isInvalidDecl()) 16318 return; 16319 16320 AnyIsPacked = 16321 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16322 ReverseMemberChain.push_back(FD); 16323 16324 TopME = ME; 16325 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16326 } while (ME); 16327 assert(TopME && "We did not compute a topmost MemberExpr!"); 16328 16329 // Not the scope of this diagnostic. 16330 if (!AnyIsPacked) 16331 return; 16332 16333 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16334 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16335 // TODO: The innermost base of the member expression may be too complicated. 16336 // For now, just disregard these cases. This is left for future 16337 // improvement. 16338 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16339 return; 16340 16341 // Alignment expected by the whole expression. 16342 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16343 16344 // No need to do anything else with this case. 16345 if (ExpectedAlignment.isOne()) 16346 return; 16347 16348 // Synthesize offset of the whole access. 16349 CharUnits Offset; 16350 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16351 I++) { 16352 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16353 } 16354 16355 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16356 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16357 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16358 16359 // The base expression of the innermost MemberExpr may give 16360 // stronger guarantees than the class containing the member. 16361 if (DRE && !TopME->isArrow()) { 16362 const ValueDecl *VD = DRE->getDecl(); 16363 if (!VD->getType()->isReferenceType()) 16364 CompleteObjectAlignment = 16365 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16366 } 16367 16368 // Check if the synthesized offset fulfills the alignment. 16369 if (Offset % ExpectedAlignment != 0 || 16370 // It may fulfill the offset it but the effective alignment may still be 16371 // lower than the expected expression alignment. 16372 CompleteObjectAlignment < ExpectedAlignment) { 16373 // If this happens, we want to determine a sensible culprit of this. 16374 // Intuitively, watching the chain of member expressions from right to 16375 // left, we start with the required alignment (as required by the field 16376 // type) but some packed attribute in that chain has reduced the alignment. 16377 // It may happen that another packed structure increases it again. But if 16378 // we are here such increase has not been enough. So pointing the first 16379 // FieldDecl that either is packed or else its RecordDecl is, 16380 // seems reasonable. 16381 FieldDecl *FD = nullptr; 16382 CharUnits Alignment; 16383 for (FieldDecl *FDI : ReverseMemberChain) { 16384 if (FDI->hasAttr<PackedAttr>() || 16385 FDI->getParent()->hasAttr<PackedAttr>()) { 16386 FD = FDI; 16387 Alignment = std::min( 16388 Context.getTypeAlignInChars(FD->getType()), 16389 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16390 break; 16391 } 16392 } 16393 assert(FD && "We did not find a packed FieldDecl!"); 16394 Action(E, FD->getParent(), FD, Alignment); 16395 } 16396 } 16397 16398 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16399 using namespace std::placeholders; 16400 16401 RefersToMemberWithReducedAlignment( 16402 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16403 _2, _3, _4)); 16404 } 16405 16406 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16407 ExprResult CallResult) { 16408 if (checkArgCount(*this, TheCall, 1)) 16409 return ExprError(); 16410 16411 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16412 if (MatrixArg.isInvalid()) 16413 return MatrixArg; 16414 Expr *Matrix = MatrixArg.get(); 16415 16416 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16417 if (!MType) { 16418 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16419 return ExprError(); 16420 } 16421 16422 // Create returned matrix type by swapping rows and columns of the argument 16423 // matrix type. 16424 QualType ResultType = Context.getConstantMatrixType( 16425 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16426 16427 // Change the return type to the type of the returned matrix. 16428 TheCall->setType(ResultType); 16429 16430 // Update call argument to use the possibly converted matrix argument. 16431 TheCall->setArg(0, Matrix); 16432 return CallResult; 16433 } 16434 16435 // Get and verify the matrix dimensions. 16436 static llvm::Optional<unsigned> 16437 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16438 SourceLocation ErrorPos; 16439 Optional<llvm::APSInt> Value = 16440 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16441 if (!Value) { 16442 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16443 << Name; 16444 return {}; 16445 } 16446 uint64_t Dim = Value->getZExtValue(); 16447 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16448 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16449 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16450 return {}; 16451 } 16452 return Dim; 16453 } 16454 16455 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16456 ExprResult CallResult) { 16457 if (!getLangOpts().MatrixTypes) { 16458 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16459 return ExprError(); 16460 } 16461 16462 if (checkArgCount(*this, TheCall, 4)) 16463 return ExprError(); 16464 16465 unsigned PtrArgIdx = 0; 16466 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16467 Expr *RowsExpr = TheCall->getArg(1); 16468 Expr *ColumnsExpr = TheCall->getArg(2); 16469 Expr *StrideExpr = TheCall->getArg(3); 16470 16471 bool ArgError = false; 16472 16473 // Check pointer argument. 16474 { 16475 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16476 if (PtrConv.isInvalid()) 16477 return PtrConv; 16478 PtrExpr = PtrConv.get(); 16479 TheCall->setArg(0, PtrExpr); 16480 if (PtrExpr->isTypeDependent()) { 16481 TheCall->setType(Context.DependentTy); 16482 return TheCall; 16483 } 16484 } 16485 16486 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16487 QualType ElementTy; 16488 if (!PtrTy) { 16489 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16490 << PtrArgIdx + 1; 16491 ArgError = true; 16492 } else { 16493 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16494 16495 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16496 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16497 << PtrArgIdx + 1; 16498 ArgError = true; 16499 } 16500 } 16501 16502 // Apply default Lvalue conversions and convert the expression to size_t. 16503 auto ApplyArgumentConversions = [this](Expr *E) { 16504 ExprResult Conv = DefaultLvalueConversion(E); 16505 if (Conv.isInvalid()) 16506 return Conv; 16507 16508 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16509 }; 16510 16511 // Apply conversion to row and column expressions. 16512 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16513 if (!RowsConv.isInvalid()) { 16514 RowsExpr = RowsConv.get(); 16515 TheCall->setArg(1, RowsExpr); 16516 } else 16517 RowsExpr = nullptr; 16518 16519 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16520 if (!ColumnsConv.isInvalid()) { 16521 ColumnsExpr = ColumnsConv.get(); 16522 TheCall->setArg(2, ColumnsExpr); 16523 } else 16524 ColumnsExpr = nullptr; 16525 16526 // If any any part of the result matrix type is still pending, just use 16527 // Context.DependentTy, until all parts are resolved. 16528 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16529 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16530 TheCall->setType(Context.DependentTy); 16531 return CallResult; 16532 } 16533 16534 // Check row and column dimenions. 16535 llvm::Optional<unsigned> MaybeRows; 16536 if (RowsExpr) 16537 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16538 16539 llvm::Optional<unsigned> MaybeColumns; 16540 if (ColumnsExpr) 16541 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16542 16543 // Check stride argument. 16544 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16545 if (StrideConv.isInvalid()) 16546 return ExprError(); 16547 StrideExpr = StrideConv.get(); 16548 TheCall->setArg(3, StrideExpr); 16549 16550 if (MaybeRows) { 16551 if (Optional<llvm::APSInt> Value = 16552 StrideExpr->getIntegerConstantExpr(Context)) { 16553 uint64_t Stride = Value->getZExtValue(); 16554 if (Stride < *MaybeRows) { 16555 Diag(StrideExpr->getBeginLoc(), 16556 diag::err_builtin_matrix_stride_too_small); 16557 ArgError = true; 16558 } 16559 } 16560 } 16561 16562 if (ArgError || !MaybeRows || !MaybeColumns) 16563 return ExprError(); 16564 16565 TheCall->setType( 16566 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16567 return CallResult; 16568 } 16569 16570 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16571 ExprResult CallResult) { 16572 if (checkArgCount(*this, TheCall, 3)) 16573 return ExprError(); 16574 16575 unsigned PtrArgIdx = 1; 16576 Expr *MatrixExpr = TheCall->getArg(0); 16577 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16578 Expr *StrideExpr = TheCall->getArg(2); 16579 16580 bool ArgError = false; 16581 16582 { 16583 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16584 if (MatrixConv.isInvalid()) 16585 return MatrixConv; 16586 MatrixExpr = MatrixConv.get(); 16587 TheCall->setArg(0, MatrixExpr); 16588 } 16589 if (MatrixExpr->isTypeDependent()) { 16590 TheCall->setType(Context.DependentTy); 16591 return TheCall; 16592 } 16593 16594 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16595 if (!MatrixTy) { 16596 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16597 ArgError = true; 16598 } 16599 16600 { 16601 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16602 if (PtrConv.isInvalid()) 16603 return PtrConv; 16604 PtrExpr = PtrConv.get(); 16605 TheCall->setArg(1, PtrExpr); 16606 if (PtrExpr->isTypeDependent()) { 16607 TheCall->setType(Context.DependentTy); 16608 return TheCall; 16609 } 16610 } 16611 16612 // Check pointer argument. 16613 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16614 if (!PtrTy) { 16615 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16616 << PtrArgIdx + 1; 16617 ArgError = true; 16618 } else { 16619 QualType ElementTy = PtrTy->getPointeeType(); 16620 if (ElementTy.isConstQualified()) { 16621 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16622 ArgError = true; 16623 } 16624 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16625 if (MatrixTy && 16626 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16627 Diag(PtrExpr->getBeginLoc(), 16628 diag::err_builtin_matrix_pointer_arg_mismatch) 16629 << ElementTy << MatrixTy->getElementType(); 16630 ArgError = true; 16631 } 16632 } 16633 16634 // Apply default Lvalue conversions and convert the stride expression to 16635 // size_t. 16636 { 16637 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16638 if (StrideConv.isInvalid()) 16639 return StrideConv; 16640 16641 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16642 if (StrideConv.isInvalid()) 16643 return StrideConv; 16644 StrideExpr = StrideConv.get(); 16645 TheCall->setArg(2, StrideExpr); 16646 } 16647 16648 // Check stride argument. 16649 if (MatrixTy) { 16650 if (Optional<llvm::APSInt> Value = 16651 StrideExpr->getIntegerConstantExpr(Context)) { 16652 uint64_t Stride = Value->getZExtValue(); 16653 if (Stride < MatrixTy->getNumRows()) { 16654 Diag(StrideExpr->getBeginLoc(), 16655 diag::err_builtin_matrix_stride_too_small); 16656 ArgError = true; 16657 } 16658 } 16659 } 16660 16661 if (ArgError) 16662 return ExprError(); 16663 16664 return CallResult; 16665 } 16666 16667 /// \brief Enforce the bounds of a TCB 16668 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16669 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16670 /// and enforce_tcb_leaf attributes. 16671 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16672 const FunctionDecl *Callee) { 16673 const FunctionDecl *Caller = getCurFunctionDecl(); 16674 16675 // Calls to builtins are not enforced. 16676 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16677 Callee->getBuiltinID() != 0) 16678 return; 16679 16680 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16681 // all TCBs the callee is a part of. 16682 llvm::StringSet<> CalleeTCBs; 16683 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16684 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16685 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16686 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16687 16688 // Go through the TCBs the caller is a part of and emit warnings if Caller 16689 // is in a TCB that the Callee is not. 16690 for_each( 16691 Caller->specific_attrs<EnforceTCBAttr>(), 16692 [&](const auto *A) { 16693 StringRef CallerTCB = A->getTCBName(); 16694 if (CalleeTCBs.count(CallerTCB) == 0) { 16695 this->Diag(TheCall->getExprLoc(), 16696 diag::warn_tcb_enforcement_violation) << Callee 16697 << CallerTCB; 16698 } 16699 }); 16700 } 16701