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/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/SaveAndRestore.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <bitset> 92 #include <cassert> 93 #include <cstddef> 94 #include <cstdint> 95 #include <functional> 96 #include <limits> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 using namespace sema; 103 104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 105 unsigned ByteNo) const { 106 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 107 Context.getTargetInfo()); 108 } 109 110 /// Checks that a call expression's argument count is the desired number. 111 /// This is useful when doing custom type-checking. Returns true on error. 112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 113 unsigned argCount = call->getNumArgs(); 114 if (argCount == desiredArgCount) return false; 115 116 if (argCount < desiredArgCount) 117 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 118 << 0 /*function call*/ << desiredArgCount << argCount 119 << call->getSourceRange(); 120 121 // Highlight all the excess arguments. 122 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 123 call->getArg(argCount - 1)->getEndLoc()); 124 125 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 126 << 0 /*function call*/ << desiredArgCount << argCount 127 << call->getArg(1)->getSourceRange(); 128 } 129 130 /// Check that the first argument to __builtin_annotation is an integer 131 /// and the second argument is a non-wide string literal. 132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 133 if (checkArgCount(S, TheCall, 2)) 134 return true; 135 136 // First argument should be an integer. 137 Expr *ValArg = TheCall->getArg(0); 138 QualType Ty = ValArg->getType(); 139 if (!Ty->isIntegerType()) { 140 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 141 << ValArg->getSourceRange(); 142 return true; 143 } 144 145 // Second argument should be a constant string. 146 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 147 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 148 if (!Literal || !Literal->isAscii()) { 149 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 150 << StrArg->getSourceRange(); 151 return true; 152 } 153 154 TheCall->setType(Ty); 155 return false; 156 } 157 158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 159 // We need at least one argument. 160 if (TheCall->getNumArgs() < 1) { 161 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 162 << 0 << 1 << TheCall->getNumArgs() 163 << TheCall->getCallee()->getSourceRange(); 164 return true; 165 } 166 167 // All arguments should be wide string literals. 168 for (Expr *Arg : TheCall->arguments()) { 169 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 170 if (!Literal || !Literal->isWide()) { 171 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 172 << Arg->getSourceRange(); 173 return true; 174 } 175 } 176 177 return false; 178 } 179 180 /// Check that the argument to __builtin_addressof is a glvalue, and set the 181 /// result type to the corresponding pointer type. 182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 183 if (checkArgCount(S, TheCall, 1)) 184 return true; 185 186 ExprResult Arg(TheCall->getArg(0)); 187 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 188 if (ResultType.isNull()) 189 return true; 190 191 TheCall->setArg(0, Arg.get()); 192 TheCall->setType(ResultType); 193 return false; 194 } 195 196 /// Check the number of arguments and set the result type to 197 /// the argument type. 198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 199 if (checkArgCount(S, TheCall, 1)) 200 return true; 201 202 TheCall->setType(TheCall->getArg(0)->getType()); 203 return false; 204 } 205 206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 208 /// type (but not a function pointer) and that the alignment is a power-of-two. 209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 210 if (checkArgCount(S, TheCall, 2)) 211 return true; 212 213 clang::Expr *Source = TheCall->getArg(0); 214 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 215 216 auto IsValidIntegerType = [](QualType Ty) { 217 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 218 }; 219 QualType SrcTy = Source->getType(); 220 // We should also be able to use it with arrays (but not functions!). 221 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 222 SrcTy = S.Context.getDecayedType(SrcTy); 223 } 224 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 225 SrcTy->isFunctionPointerType()) { 226 // FIXME: this is not quite the right error message since we don't allow 227 // floating point types, or member pointers. 228 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 229 << SrcTy; 230 return true; 231 } 232 233 clang::Expr *AlignOp = TheCall->getArg(1); 234 if (!IsValidIntegerType(AlignOp->getType())) { 235 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 236 << AlignOp->getType(); 237 return true; 238 } 239 Expr::EvalResult AlignResult; 240 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 241 // We can't check validity of alignment if it is value dependent. 242 if (!AlignOp->isValueDependent() && 243 AlignOp->EvaluateAsInt(AlignResult, S.Context, 244 Expr::SE_AllowSideEffects)) { 245 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 246 llvm::APSInt MaxValue( 247 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 248 if (AlignValue < 1) { 249 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 250 return true; 251 } 252 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 253 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 254 << MaxValue.toString(10); 255 return true; 256 } 257 if (!AlignValue.isPowerOf2()) { 258 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 259 return true; 260 } 261 if (AlignValue == 1) { 262 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 263 << IsBooleanAlignBuiltin; 264 } 265 } 266 267 ExprResult SrcArg = S.PerformCopyInitialization( 268 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 269 SourceLocation(), Source); 270 if (SrcArg.isInvalid()) 271 return true; 272 TheCall->setArg(0, SrcArg.get()); 273 ExprResult AlignArg = 274 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 275 S.Context, AlignOp->getType(), false), 276 SourceLocation(), AlignOp); 277 if (AlignArg.isInvalid()) 278 return true; 279 TheCall->setArg(1, AlignArg.get()); 280 // For align_up/align_down, the return type is the same as the (potentially 281 // decayed) argument type including qualifiers. For is_aligned(), the result 282 // is always bool. 283 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 284 return false; 285 } 286 287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 288 unsigned BuiltinID) { 289 if (checkArgCount(S, TheCall, 3)) 290 return true; 291 292 // First two arguments should be integers. 293 for (unsigned I = 0; I < 2; ++I) { 294 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 295 if (Arg.isInvalid()) return true; 296 TheCall->setArg(I, Arg.get()); 297 298 QualType Ty = Arg.get()->getType(); 299 if (!Ty->isIntegerType()) { 300 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 301 << Ty << Arg.get()->getSourceRange(); 302 return true; 303 } 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 311 if (Arg.isInvalid()) return true; 312 TheCall->setArg(2, Arg.get()); 313 314 QualType Ty = Arg.get()->getType(); 315 const auto *PtrTy = Ty->getAs<PointerType>(); 316 if (!PtrTy || 317 !PtrTy->getPointeeType()->isIntegerType() || 318 PtrTy->getPointeeType().isConstQualified()) { 319 S.Diag(Arg.get()->getBeginLoc(), 320 diag::err_overflow_builtin_must_be_ptr_int) 321 << Ty << Arg.get()->getSourceRange(); 322 return true; 323 } 324 } 325 326 // Disallow signed ExtIntType args larger than 128 bits to mul function until 327 // we improve backend support. 328 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 329 for (unsigned I = 0; I < 3; ++I) { 330 const auto Arg = TheCall->getArg(I); 331 // Third argument will be a pointer. 332 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 333 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 334 S.getASTContext().getIntWidth(Ty) > 128) 335 return S.Diag(Arg->getBeginLoc(), 336 diag::err_overflow_builtin_ext_int_max_size) 337 << 128; 338 } 339 } 340 341 return false; 342 } 343 344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 345 if (checkArgCount(S, BuiltinCall, 2)) 346 return true; 347 348 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 349 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 350 Expr *Call = BuiltinCall->getArg(0); 351 Expr *Chain = BuiltinCall->getArg(1); 352 353 if (Call->getStmtClass() != Stmt::CallExprClass) { 354 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 355 << Call->getSourceRange(); 356 return true; 357 } 358 359 auto CE = cast<CallExpr>(Call); 360 if (CE->getCallee()->getType()->isBlockPointerType()) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 const Decl *TargetDecl = CE->getCalleeDecl(); 367 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 368 if (FD->getBuiltinID()) { 369 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 370 << Call->getSourceRange(); 371 return true; 372 } 373 374 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 375 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 376 << Call->getSourceRange(); 377 return true; 378 } 379 380 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 381 if (ChainResult.isInvalid()) 382 return true; 383 if (!ChainResult.get()->getType()->isPointerType()) { 384 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 385 << Chain->getSourceRange(); 386 return true; 387 } 388 389 QualType ReturnTy = CE->getCallReturnType(S.Context); 390 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 391 QualType BuiltinTy = S.Context.getFunctionType( 392 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 393 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 394 395 Builtin = 396 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 397 398 BuiltinCall->setType(CE->getType()); 399 BuiltinCall->setValueKind(CE->getValueKind()); 400 BuiltinCall->setObjectKind(CE->getObjectKind()); 401 BuiltinCall->setCallee(Builtin); 402 BuiltinCall->setArg(1, ChainResult.get()); 403 404 return false; 405 } 406 407 namespace { 408 409 class EstimateSizeFormatHandler 410 : public analyze_format_string::FormatStringHandler { 411 size_t Size; 412 413 public: 414 EstimateSizeFormatHandler(StringRef Format) 415 : Size(std::min(Format.find(0), Format.size()) + 416 1 /* null byte always written by sprintf */) {} 417 418 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 419 const char *, unsigned SpecifierLen) override { 420 421 const size_t FieldWidth = computeFieldWidth(FS); 422 const size_t Precision = computePrecision(FS); 423 424 // The actual format. 425 switch (FS.getConversionSpecifier().getKind()) { 426 // Just a char. 427 case analyze_format_string::ConversionSpecifier::cArg: 428 case analyze_format_string::ConversionSpecifier::CArg: 429 Size += std::max(FieldWidth, (size_t)1); 430 break; 431 // Just an integer. 432 case analyze_format_string::ConversionSpecifier::dArg: 433 case analyze_format_string::ConversionSpecifier::DArg: 434 case analyze_format_string::ConversionSpecifier::iArg: 435 case analyze_format_string::ConversionSpecifier::oArg: 436 case analyze_format_string::ConversionSpecifier::OArg: 437 case analyze_format_string::ConversionSpecifier::uArg: 438 case analyze_format_string::ConversionSpecifier::UArg: 439 case analyze_format_string::ConversionSpecifier::xArg: 440 case analyze_format_string::ConversionSpecifier::XArg: 441 Size += std::max(FieldWidth, Precision); 442 break; 443 444 // %g style conversion switches between %f or %e style dynamically. 445 // %f always takes less space, so default to it. 446 case analyze_format_string::ConversionSpecifier::gArg: 447 case analyze_format_string::ConversionSpecifier::GArg: 448 449 // Floating point number in the form '[+]ddd.ddd'. 450 case analyze_format_string::ConversionSpecifier::fArg: 451 case analyze_format_string::ConversionSpecifier::FArg: 452 Size += std::max(FieldWidth, 1 /* integer part */ + 453 (Precision ? 1 + Precision 454 : 0) /* period + decimal */); 455 break; 456 457 // Floating point number in the form '[-]d.ddde[+-]dd'. 458 case analyze_format_string::ConversionSpecifier::eArg: 459 case analyze_format_string::ConversionSpecifier::EArg: 460 Size += 461 std::max(FieldWidth, 462 1 /* integer part */ + 463 (Precision ? 1 + Precision : 0) /* period + decimal */ + 464 1 /* e or E letter */ + 2 /* exponent */); 465 break; 466 467 // Floating point number in the form '[-]0xh.hhhhp±dd'. 468 case analyze_format_string::ConversionSpecifier::aArg: 469 case analyze_format_string::ConversionSpecifier::AArg: 470 Size += 471 std::max(FieldWidth, 472 2 /* 0x */ + 1 /* integer part */ + 473 (Precision ? 1 + Precision : 0) /* period + decimal */ + 474 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 475 break; 476 477 // Just a string. 478 case analyze_format_string::ConversionSpecifier::sArg: 479 case analyze_format_string::ConversionSpecifier::SArg: 480 Size += FieldWidth; 481 break; 482 483 // Just a pointer in the form '0xddd'. 484 case analyze_format_string::ConversionSpecifier::pArg: 485 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 486 break; 487 488 // A plain percent. 489 case analyze_format_string::ConversionSpecifier::PercentArg: 490 Size += 1; 491 break; 492 493 default: 494 break; 495 } 496 497 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 498 499 if (FS.hasAlternativeForm()) { 500 switch (FS.getConversionSpecifier().getKind()) { 501 default: 502 break; 503 // Force a leading '0'. 504 case analyze_format_string::ConversionSpecifier::oArg: 505 Size += 1; 506 break; 507 // Force a leading '0x'. 508 case analyze_format_string::ConversionSpecifier::xArg: 509 case analyze_format_string::ConversionSpecifier::XArg: 510 Size += 2; 511 break; 512 // Force a period '.' before decimal, even if precision is 0. 513 case analyze_format_string::ConversionSpecifier::aArg: 514 case analyze_format_string::ConversionSpecifier::AArg: 515 case analyze_format_string::ConversionSpecifier::eArg: 516 case analyze_format_string::ConversionSpecifier::EArg: 517 case analyze_format_string::ConversionSpecifier::fArg: 518 case analyze_format_string::ConversionSpecifier::FArg: 519 case analyze_format_string::ConversionSpecifier::gArg: 520 case analyze_format_string::ConversionSpecifier::GArg: 521 Size += (Precision ? 0 : 1); 522 break; 523 } 524 } 525 assert(SpecifierLen <= Size && "no underflow"); 526 Size -= SpecifierLen; 527 return true; 528 } 529 530 size_t getSizeLowerBound() const { return Size; } 531 532 private: 533 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 534 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 535 size_t FieldWidth = 0; 536 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 537 FieldWidth = FW.getConstantAmount(); 538 return FieldWidth; 539 } 540 541 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 542 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 543 size_t Precision = 0; 544 545 // See man 3 printf for default precision value based on the specifier. 546 switch (FW.getHowSpecified()) { 547 case analyze_format_string::OptionalAmount::NotSpecified: 548 switch (FS.getConversionSpecifier().getKind()) { 549 default: 550 break; 551 case analyze_format_string::ConversionSpecifier::dArg: // %d 552 case analyze_format_string::ConversionSpecifier::DArg: // %D 553 case analyze_format_string::ConversionSpecifier::iArg: // %i 554 Precision = 1; 555 break; 556 case analyze_format_string::ConversionSpecifier::oArg: // %d 557 case analyze_format_string::ConversionSpecifier::OArg: // %D 558 case analyze_format_string::ConversionSpecifier::uArg: // %d 559 case analyze_format_string::ConversionSpecifier::UArg: // %D 560 case analyze_format_string::ConversionSpecifier::xArg: // %d 561 case analyze_format_string::ConversionSpecifier::XArg: // %D 562 Precision = 1; 563 break; 564 case analyze_format_string::ConversionSpecifier::fArg: // %f 565 case analyze_format_string::ConversionSpecifier::FArg: // %F 566 case analyze_format_string::ConversionSpecifier::eArg: // %e 567 case analyze_format_string::ConversionSpecifier::EArg: // %E 568 case analyze_format_string::ConversionSpecifier::gArg: // %g 569 case analyze_format_string::ConversionSpecifier::GArg: // %G 570 Precision = 6; 571 break; 572 case analyze_format_string::ConversionSpecifier::pArg: // %d 573 Precision = 1; 574 break; 575 } 576 break; 577 case analyze_format_string::OptionalAmount::Constant: 578 Precision = FW.getConstantAmount(); 579 break; 580 default: 581 break; 582 } 583 return Precision; 584 } 585 }; 586 587 } // namespace 588 589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 590 /// __builtin_*_chk function, then use the object size argument specified in the 591 /// source. Otherwise, infer the object size using __builtin_object_size. 592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 593 CallExpr *TheCall) { 594 // FIXME: There are some more useful checks we could be doing here: 595 // - Evaluate strlen of strcpy arguments, use as object size. 596 597 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 598 isConstantEvaluated()) 599 return; 600 601 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 602 if (!BuiltinID) 603 return; 604 605 const TargetInfo &TI = getASTContext().getTargetInfo(); 606 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 607 608 unsigned DiagID = 0; 609 bool IsChkVariant = false; 610 Optional<llvm::APSInt> UsedSize; 611 unsigned SizeIndex, ObjectIndex; 612 switch (BuiltinID) { 613 default: 614 return; 615 case Builtin::BIsprintf: 616 case Builtin::BI__builtin___sprintf_chk: { 617 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 618 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 619 620 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 621 622 if (!Format->isAscii() && !Format->isUTF8()) 623 return; 624 625 StringRef FormatStrRef = Format->getString(); 626 EstimateSizeFormatHandler H(FormatStrRef); 627 const char *FormatBytes = FormatStrRef.data(); 628 const ConstantArrayType *T = 629 Context.getAsConstantArrayType(Format->getType()); 630 assert(T && "String literal not of constant array type!"); 631 size_t TypeSize = T->getSize().getZExtValue(); 632 633 // In case there's a null byte somewhere. 634 size_t StrLen = 635 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 636 if (!analyze_format_string::ParsePrintfString( 637 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 638 Context.getTargetInfo(), false)) { 639 DiagID = diag::warn_fortify_source_format_overflow; 640 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 641 .extOrTrunc(SizeTypeWidth); 642 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 643 IsChkVariant = true; 644 ObjectIndex = 2; 645 } else { 646 IsChkVariant = false; 647 ObjectIndex = 0; 648 } 649 break; 650 } 651 } 652 return; 653 } 654 case Builtin::BI__builtin___memcpy_chk: 655 case Builtin::BI__builtin___memmove_chk: 656 case Builtin::BI__builtin___memset_chk: 657 case Builtin::BI__builtin___strlcat_chk: 658 case Builtin::BI__builtin___strlcpy_chk: 659 case Builtin::BI__builtin___strncat_chk: 660 case Builtin::BI__builtin___strncpy_chk: 661 case Builtin::BI__builtin___stpncpy_chk: 662 case Builtin::BI__builtin___memccpy_chk: 663 case Builtin::BI__builtin___mempcpy_chk: { 664 DiagID = diag::warn_builtin_chk_overflow; 665 IsChkVariant = true; 666 SizeIndex = TheCall->getNumArgs() - 2; 667 ObjectIndex = TheCall->getNumArgs() - 1; 668 break; 669 } 670 671 case Builtin::BI__builtin___snprintf_chk: 672 case Builtin::BI__builtin___vsnprintf_chk: { 673 DiagID = diag::warn_builtin_chk_overflow; 674 IsChkVariant = true; 675 SizeIndex = 1; 676 ObjectIndex = 3; 677 break; 678 } 679 680 case Builtin::BIstrncat: 681 case Builtin::BI__builtin_strncat: 682 case Builtin::BIstrncpy: 683 case Builtin::BI__builtin_strncpy: 684 case Builtin::BIstpncpy: 685 case Builtin::BI__builtin_stpncpy: { 686 // Whether these functions overflow depends on the runtime strlen of the 687 // string, not just the buffer size, so emitting the "always overflow" 688 // diagnostic isn't quite right. We should still diagnose passing a buffer 689 // size larger than the destination buffer though; this is a runtime abort 690 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 691 DiagID = diag::warn_fortify_source_size_mismatch; 692 SizeIndex = TheCall->getNumArgs() - 1; 693 ObjectIndex = 0; 694 break; 695 } 696 697 case Builtin::BImemcpy: 698 case Builtin::BI__builtin_memcpy: 699 case Builtin::BImemmove: 700 case Builtin::BI__builtin_memmove: 701 case Builtin::BImemset: 702 case Builtin::BI__builtin_memset: 703 case Builtin::BImempcpy: 704 case Builtin::BI__builtin_mempcpy: { 705 DiagID = diag::warn_fortify_source_overflow; 706 SizeIndex = TheCall->getNumArgs() - 1; 707 ObjectIndex = 0; 708 break; 709 } 710 case Builtin::BIsnprintf: 711 case Builtin::BI__builtin_snprintf: 712 case Builtin::BIvsnprintf: 713 case Builtin::BI__builtin_vsnprintf: { 714 DiagID = diag::warn_fortify_source_size_mismatch; 715 SizeIndex = 1; 716 ObjectIndex = 0; 717 break; 718 } 719 } 720 721 llvm::APSInt ObjectSize; 722 // For __builtin___*_chk, the object size is explicitly provided by the caller 723 // (usually using __builtin_object_size). Use that value to check this call. 724 if (IsChkVariant) { 725 Expr::EvalResult Result; 726 Expr *SizeArg = TheCall->getArg(ObjectIndex); 727 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 728 return; 729 ObjectSize = Result.Val.getInt(); 730 731 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 732 } else { 733 // If the parameter has a pass_object_size attribute, then we should use its 734 // (potentially) more strict checking mode. Otherwise, conservatively assume 735 // type 0. 736 int BOSType = 0; 737 if (const auto *POS = 738 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 739 BOSType = POS->getType(); 740 741 Expr *ObjArg = TheCall->getArg(ObjectIndex); 742 uint64_t Result; 743 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 744 return; 745 // Get the object size in the target's size_t width. 746 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 747 } 748 749 // Evaluate the number of bytes of the object that this call will use. 750 if (!UsedSize) { 751 Expr::EvalResult Result; 752 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 753 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 754 return; 755 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 756 } 757 758 if (UsedSize.getValue().ule(ObjectSize)) 759 return; 760 761 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 762 // Skim off the details of whichever builtin was called to produce a better 763 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 764 if (IsChkVariant) { 765 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 766 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 767 } else if (FunctionName.startswith("__builtin_")) { 768 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 769 } 770 771 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 772 PDiag(DiagID) 773 << FunctionName << ObjectSize.toString(/*Radix=*/10) 774 << UsedSize.getValue().toString(/*Radix=*/10)); 775 } 776 777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 778 Scope::ScopeFlags NeededScopeFlags, 779 unsigned DiagID) { 780 // Scopes aren't available during instantiation. Fortunately, builtin 781 // functions cannot be template args so they cannot be formed through template 782 // instantiation. Therefore checking once during the parse is sufficient. 783 if (SemaRef.inTemplateInstantiation()) 784 return false; 785 786 Scope *S = SemaRef.getCurScope(); 787 while (S && !S->isSEHExceptScope()) 788 S = S->getParent(); 789 if (!S || !(S->getFlags() & NeededScopeFlags)) { 790 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 791 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 792 << DRE->getDecl()->getIdentifier(); 793 return true; 794 } 795 796 return false; 797 } 798 799 static inline bool isBlockPointer(Expr *Arg) { 800 return Arg->getType()->isBlockPointerType(); 801 } 802 803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 804 /// void*, which is a requirement of device side enqueue. 805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 806 const BlockPointerType *BPT = 807 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 808 ArrayRef<QualType> Params = 809 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 810 unsigned ArgCounter = 0; 811 bool IllegalParams = false; 812 // Iterate through the block parameters until either one is found that is not 813 // a local void*, or the block is valid. 814 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 815 I != E; ++I, ++ArgCounter) { 816 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 817 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 818 LangAS::opencl_local) { 819 // Get the location of the error. If a block literal has been passed 820 // (BlockExpr) then we can point straight to the offending argument, 821 // else we just point to the variable reference. 822 SourceLocation ErrorLoc; 823 if (isa<BlockExpr>(BlockArg)) { 824 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 825 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 826 } else if (isa<DeclRefExpr>(BlockArg)) { 827 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 828 } 829 S.Diag(ErrorLoc, 830 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 831 IllegalParams = true; 832 } 833 } 834 835 return IllegalParams; 836 } 837 838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 839 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 840 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 841 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 842 return true; 843 } 844 return false; 845 } 846 847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 848 if (checkArgCount(S, TheCall, 2)) 849 return true; 850 851 if (checkOpenCLSubgroupExt(S, TheCall)) 852 return true; 853 854 // First argument is an ndrange_t type. 855 Expr *NDRangeArg = TheCall->getArg(0); 856 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 857 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 858 << TheCall->getDirectCallee() << "'ndrange_t'"; 859 return true; 860 } 861 862 Expr *BlockArg = TheCall->getArg(1); 863 if (!isBlockPointer(BlockArg)) { 864 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 865 << TheCall->getDirectCallee() << "block"; 866 return true; 867 } 868 return checkOpenCLBlockArgs(S, BlockArg); 869 } 870 871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 872 /// get_kernel_work_group_size 873 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 875 if (checkArgCount(S, TheCall, 1)) 876 return true; 877 878 Expr *BlockArg = TheCall->getArg(0); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// Diagnose integer type and any valid implicit conversion to it. 888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 889 const QualType &IntType); 890 891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 892 unsigned Start, unsigned End) { 893 bool IllegalParams = false; 894 for (unsigned I = Start; I <= End; ++I) 895 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 896 S.Context.getSizeType()); 897 return IllegalParams; 898 } 899 900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 901 /// 'local void*' parameter of passed block. 902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 903 Expr *BlockArg, 904 unsigned NumNonVarArgs) { 905 const BlockPointerType *BPT = 906 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 907 unsigned NumBlockParams = 908 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 909 unsigned TotalNumArgs = TheCall->getNumArgs(); 910 911 // For each argument passed to the block, a corresponding uint needs to 912 // be passed to describe the size of the local memory. 913 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 914 S.Diag(TheCall->getBeginLoc(), 915 diag::err_opencl_enqueue_kernel_local_size_args); 916 return true; 917 } 918 919 // Check that the sizes of the local memory are specified by integers. 920 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 921 TotalNumArgs - 1); 922 } 923 924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 925 /// overload formats specified in Table 6.13.17.1. 926 /// int enqueue_kernel(queue_t queue, 927 /// kernel_enqueue_flags_t flags, 928 /// const ndrange_t ndrange, 929 /// void (^block)(void)) 930 /// int enqueue_kernel(queue_t queue, 931 /// kernel_enqueue_flags_t flags, 932 /// const ndrange_t ndrange, 933 /// uint num_events_in_wait_list, 934 /// clk_event_t *event_wait_list, 935 /// clk_event_t *event_ret, 936 /// void (^block)(void)) 937 /// int enqueue_kernel(queue_t queue, 938 /// kernel_enqueue_flags_t flags, 939 /// const ndrange_t ndrange, 940 /// void (^block)(local void*, ...), 941 /// uint size0, ...) 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// uint num_events_in_wait_list, 946 /// clk_event_t *event_wait_list, 947 /// clk_event_t *event_ret, 948 /// void (^block)(local void*, ...), 949 /// uint size0, ...) 950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 951 unsigned NumArgs = TheCall->getNumArgs(); 952 953 if (NumArgs < 4) { 954 S.Diag(TheCall->getBeginLoc(), 955 diag::err_typecheck_call_too_few_args_at_least) 956 << 0 << 4 << NumArgs; 957 return true; 958 } 959 960 Expr *Arg0 = TheCall->getArg(0); 961 Expr *Arg1 = TheCall->getArg(1); 962 Expr *Arg2 = TheCall->getArg(2); 963 Expr *Arg3 = TheCall->getArg(3); 964 965 // First argument always needs to be a queue_t type. 966 if (!Arg0->getType()->isQueueT()) { 967 S.Diag(TheCall->getArg(0)->getBeginLoc(), 968 diag::err_opencl_builtin_expected_type) 969 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 970 return true; 971 } 972 973 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 974 if (!Arg1->getType()->isIntegerType()) { 975 S.Diag(TheCall->getArg(1)->getBeginLoc(), 976 diag::err_opencl_builtin_expected_type) 977 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 978 return true; 979 } 980 981 // Third argument is always an ndrange_t type. 982 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 983 S.Diag(TheCall->getArg(2)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << "'ndrange_t'"; 986 return true; 987 } 988 989 // With four arguments, there is only one form that the function could be 990 // called in: no events and no variable arguments. 991 if (NumArgs == 4) { 992 // check that the last argument is the right block type. 993 if (!isBlockPointer(Arg3)) { 994 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 995 << TheCall->getDirectCallee() << "block"; 996 return true; 997 } 998 // we have a block type, check the prototype 999 const BlockPointerType *BPT = 1000 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1001 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1002 S.Diag(Arg3->getBeginLoc(), 1003 diag::err_opencl_enqueue_kernel_blocks_no_args); 1004 return true; 1005 } 1006 return false; 1007 } 1008 // we can have block + varargs. 1009 if (isBlockPointer(Arg3)) 1010 return (checkOpenCLBlockArgs(S, Arg3) || 1011 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1012 // last two cases with either exactly 7 args or 7 args and varargs. 1013 if (NumArgs >= 7) { 1014 // check common block argument. 1015 Expr *Arg6 = TheCall->getArg(6); 1016 if (!isBlockPointer(Arg6)) { 1017 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1018 << TheCall->getDirectCallee() << "block"; 1019 return true; 1020 } 1021 if (checkOpenCLBlockArgs(S, Arg6)) 1022 return true; 1023 1024 // Forth argument has to be any integer type. 1025 if (!Arg3->getType()->isIntegerType()) { 1026 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1027 diag::err_opencl_builtin_expected_type) 1028 << TheCall->getDirectCallee() << "integer"; 1029 return true; 1030 } 1031 // check remaining common arguments. 1032 Expr *Arg4 = TheCall->getArg(4); 1033 Expr *Arg5 = TheCall->getArg(5); 1034 1035 // Fifth argument is always passed as a pointer to clk_event_t. 1036 if (!Arg4->isNullPointerConstant(S.Context, 1037 Expr::NPC_ValueDependentIsNotNull) && 1038 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1039 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1040 diag::err_opencl_builtin_expected_type) 1041 << TheCall->getDirectCallee() 1042 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1043 return true; 1044 } 1045 1046 // Sixth argument is always passed as a pointer to clk_event_t. 1047 if (!Arg5->isNullPointerConstant(S.Context, 1048 Expr::NPC_ValueDependentIsNotNull) && 1049 !(Arg5->getType()->isPointerType() && 1050 Arg5->getType()->getPointeeType()->isClkEventT())) { 1051 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1052 diag::err_opencl_builtin_expected_type) 1053 << TheCall->getDirectCallee() 1054 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1055 return true; 1056 } 1057 1058 if (NumArgs == 7) 1059 return false; 1060 1061 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1062 } 1063 1064 // None of the specific case has been detected, give generic error 1065 S.Diag(TheCall->getBeginLoc(), 1066 diag::err_opencl_enqueue_kernel_incorrect_args); 1067 return true; 1068 } 1069 1070 /// Returns OpenCL access qual. 1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1072 return D->getAttr<OpenCLAccessAttr>(); 1073 } 1074 1075 /// Returns true if pipe element type is different from the pointer. 1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1077 const Expr *Arg0 = Call->getArg(0); 1078 // First argument type should always be pipe. 1079 if (!Arg0->getType()->isPipeType()) { 1080 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1081 << Call->getDirectCallee() << Arg0->getSourceRange(); 1082 return true; 1083 } 1084 OpenCLAccessAttr *AccessQual = 1085 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1086 // Validates the access qualifier is compatible with the call. 1087 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1088 // read_only and write_only, and assumed to be read_only if no qualifier is 1089 // specified. 1090 switch (Call->getDirectCallee()->getBuiltinID()) { 1091 case Builtin::BIread_pipe: 1092 case Builtin::BIreserve_read_pipe: 1093 case Builtin::BIcommit_read_pipe: 1094 case Builtin::BIwork_group_reserve_read_pipe: 1095 case Builtin::BIsub_group_reserve_read_pipe: 1096 case Builtin::BIwork_group_commit_read_pipe: 1097 case Builtin::BIsub_group_commit_read_pipe: 1098 if (!(!AccessQual || AccessQual->isReadOnly())) { 1099 S.Diag(Arg0->getBeginLoc(), 1100 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1101 << "read_only" << Arg0->getSourceRange(); 1102 return true; 1103 } 1104 break; 1105 case Builtin::BIwrite_pipe: 1106 case Builtin::BIreserve_write_pipe: 1107 case Builtin::BIcommit_write_pipe: 1108 case Builtin::BIwork_group_reserve_write_pipe: 1109 case Builtin::BIsub_group_reserve_write_pipe: 1110 case Builtin::BIwork_group_commit_write_pipe: 1111 case Builtin::BIsub_group_commit_write_pipe: 1112 if (!(AccessQual && AccessQual->isWriteOnly())) { 1113 S.Diag(Arg0->getBeginLoc(), 1114 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1115 << "write_only" << Arg0->getSourceRange(); 1116 return true; 1117 } 1118 break; 1119 default: 1120 break; 1121 } 1122 return false; 1123 } 1124 1125 /// Returns true if pipe element type is different from the pointer. 1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1127 const Expr *Arg0 = Call->getArg(0); 1128 const Expr *ArgIdx = Call->getArg(Idx); 1129 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1130 const QualType EltTy = PipeTy->getElementType(); 1131 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1132 // The Idx argument should be a pointer and the type of the pointer and 1133 // the type of pipe element should also be the same. 1134 if (!ArgTy || 1135 !S.Context.hasSameType( 1136 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1137 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1138 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1139 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1140 return true; 1141 } 1142 return false; 1143 } 1144 1145 // Performs semantic analysis for the read/write_pipe call. 1146 // \param S Reference to the semantic analyzer. 1147 // \param Call A pointer to the builtin call. 1148 // \return True if a semantic error has been found, false otherwise. 1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1150 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1151 // functions have two forms. 1152 switch (Call->getNumArgs()) { 1153 case 2: 1154 if (checkOpenCLPipeArg(S, Call)) 1155 return true; 1156 // The call with 2 arguments should be 1157 // read/write_pipe(pipe T, T*). 1158 // Check packet type T. 1159 if (checkOpenCLPipePacketType(S, Call, 1)) 1160 return true; 1161 break; 1162 1163 case 4: { 1164 if (checkOpenCLPipeArg(S, Call)) 1165 return true; 1166 // The call with 4 arguments should be 1167 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1168 // Check reserve_id_t. 1169 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1170 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1171 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1172 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1173 return true; 1174 } 1175 1176 // Check the index. 1177 const Expr *Arg2 = Call->getArg(2); 1178 if (!Arg2->getType()->isIntegerType() && 1179 !Arg2->getType()->isUnsignedIntegerType()) { 1180 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1181 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1182 << Arg2->getType() << Arg2->getSourceRange(); 1183 return true; 1184 } 1185 1186 // Check packet type T. 1187 if (checkOpenCLPipePacketType(S, Call, 3)) 1188 return true; 1189 } break; 1190 default: 1191 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1192 << Call->getDirectCallee() << Call->getSourceRange(); 1193 return true; 1194 } 1195 1196 return false; 1197 } 1198 1199 // Performs a semantic analysis on the {work_group_/sub_group_ 1200 // /_}reserve_{read/write}_pipe 1201 // \param S Reference to the semantic analyzer. 1202 // \param Call The call to the builtin function to be analyzed. 1203 // \return True if a semantic error was found, false otherwise. 1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1205 if (checkArgCount(S, Call, 2)) 1206 return true; 1207 1208 if (checkOpenCLPipeArg(S, Call)) 1209 return true; 1210 1211 // Check the reserve size. 1212 if (!Call->getArg(1)->getType()->isIntegerType() && 1213 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1214 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1215 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1216 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1217 return true; 1218 } 1219 1220 // Since return type of reserve_read/write_pipe built-in function is 1221 // reserve_id_t, which is not defined in the builtin def file , we used int 1222 // as return type and need to override the return type of these functions. 1223 Call->setType(S.Context.OCLReserveIDTy); 1224 1225 return false; 1226 } 1227 1228 // Performs a semantic analysis on {work_group_/sub_group_ 1229 // /_}commit_{read/write}_pipe 1230 // \param S Reference to the semantic analyzer. 1231 // \param Call The call to the builtin function to be analyzed. 1232 // \return True if a semantic error was found, false otherwise. 1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1234 if (checkArgCount(S, Call, 2)) 1235 return true; 1236 1237 if (checkOpenCLPipeArg(S, Call)) 1238 return true; 1239 1240 // Check reserve_id_t. 1241 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1242 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1243 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1244 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1245 return true; 1246 } 1247 1248 return false; 1249 } 1250 1251 // Performs a semantic analysis on the call to built-in Pipe 1252 // Query Functions. 1253 // \param S Reference to the semantic analyzer. 1254 // \param Call The call to the builtin function to be analyzed. 1255 // \return True if a semantic error was found, false otherwise. 1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1257 if (checkArgCount(S, Call, 1)) 1258 return true; 1259 1260 if (!Call->getArg(0)->getType()->isPipeType()) { 1261 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1262 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1263 return true; 1264 } 1265 1266 return false; 1267 } 1268 1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1270 // Performs semantic analysis for the to_global/local/private call. 1271 // \param S Reference to the semantic analyzer. 1272 // \param BuiltinID ID of the builtin function. 1273 // \param Call A pointer to the builtin call. 1274 // \return True if a semantic error has been found, false otherwise. 1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1276 CallExpr *Call) { 1277 if (checkArgCount(S, Call, 1)) 1278 return true; 1279 1280 auto RT = Call->getArg(0)->getType(); 1281 if (!RT->isPointerType() || RT->getPointeeType() 1282 .getAddressSpace() == LangAS::opencl_constant) { 1283 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1284 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1285 return true; 1286 } 1287 1288 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1289 S.Diag(Call->getArg(0)->getBeginLoc(), 1290 diag::warn_opencl_generic_address_space_arg) 1291 << Call->getDirectCallee()->getNameInfo().getAsString() 1292 << Call->getArg(0)->getSourceRange(); 1293 } 1294 1295 RT = RT->getPointeeType(); 1296 auto Qual = RT.getQualifiers(); 1297 switch (BuiltinID) { 1298 case Builtin::BIto_global: 1299 Qual.setAddressSpace(LangAS::opencl_global); 1300 break; 1301 case Builtin::BIto_local: 1302 Qual.setAddressSpace(LangAS::opencl_local); 1303 break; 1304 case Builtin::BIto_private: 1305 Qual.setAddressSpace(LangAS::opencl_private); 1306 break; 1307 default: 1308 llvm_unreachable("Invalid builtin function"); 1309 } 1310 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1311 RT.getUnqualifiedType(), Qual))); 1312 1313 return false; 1314 } 1315 1316 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1317 if (checkArgCount(S, TheCall, 1)) 1318 return ExprError(); 1319 1320 // Compute __builtin_launder's parameter type from the argument. 1321 // The parameter type is: 1322 // * The type of the argument if it's not an array or function type, 1323 // Otherwise, 1324 // * The decayed argument type. 1325 QualType ParamTy = [&]() { 1326 QualType ArgTy = TheCall->getArg(0)->getType(); 1327 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1328 return S.Context.getPointerType(Ty->getElementType()); 1329 if (ArgTy->isFunctionType()) { 1330 return S.Context.getPointerType(ArgTy); 1331 } 1332 return ArgTy; 1333 }(); 1334 1335 TheCall->setType(ParamTy); 1336 1337 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1338 if (!ParamTy->isPointerType()) 1339 return 0; 1340 if (ParamTy->isFunctionPointerType()) 1341 return 1; 1342 if (ParamTy->isVoidPointerType()) 1343 return 2; 1344 return llvm::Optional<unsigned>{}; 1345 }(); 1346 if (DiagSelect.hasValue()) { 1347 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1348 << DiagSelect.getValue() << TheCall->getSourceRange(); 1349 return ExprError(); 1350 } 1351 1352 // We either have an incomplete class type, or we have a class template 1353 // whose instantiation has not been forced. Example: 1354 // 1355 // template <class T> struct Foo { T value; }; 1356 // Foo<int> *p = nullptr; 1357 // auto *d = __builtin_launder(p); 1358 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1359 diag::err_incomplete_type)) 1360 return ExprError(); 1361 1362 assert(ParamTy->getPointeeType()->isObjectType() && 1363 "Unhandled non-object pointer case"); 1364 1365 InitializedEntity Entity = 1366 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1367 ExprResult Arg = 1368 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1369 if (Arg.isInvalid()) 1370 return ExprError(); 1371 TheCall->setArg(0, Arg.get()); 1372 1373 return TheCall; 1374 } 1375 1376 // Emit an error and return true if the current architecture is not in the list 1377 // of supported architectures. 1378 static bool 1379 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1380 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1381 llvm::Triple::ArchType CurArch = 1382 S.getASTContext().getTargetInfo().getTriple().getArch(); 1383 if (llvm::is_contained(SupportedArchs, CurArch)) 1384 return false; 1385 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1386 << TheCall->getSourceRange(); 1387 return true; 1388 } 1389 1390 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1391 SourceLocation CallSiteLoc); 1392 1393 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1394 CallExpr *TheCall) { 1395 switch (TI.getTriple().getArch()) { 1396 default: 1397 // Some builtins don't require additional checking, so just consider these 1398 // acceptable. 1399 return false; 1400 case llvm::Triple::arm: 1401 case llvm::Triple::armeb: 1402 case llvm::Triple::thumb: 1403 case llvm::Triple::thumbeb: 1404 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1405 case llvm::Triple::aarch64: 1406 case llvm::Triple::aarch64_32: 1407 case llvm::Triple::aarch64_be: 1408 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1409 case llvm::Triple::bpfeb: 1410 case llvm::Triple::bpfel: 1411 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1412 case llvm::Triple::hexagon: 1413 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::mips: 1415 case llvm::Triple::mipsel: 1416 case llvm::Triple::mips64: 1417 case llvm::Triple::mips64el: 1418 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1419 case llvm::Triple::systemz: 1420 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1421 case llvm::Triple::x86: 1422 case llvm::Triple::x86_64: 1423 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1424 case llvm::Triple::ppc: 1425 case llvm::Triple::ppc64: 1426 case llvm::Triple::ppc64le: 1427 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1428 case llvm::Triple::amdgcn: 1429 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1430 } 1431 } 1432 1433 ExprResult 1434 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1435 CallExpr *TheCall) { 1436 ExprResult TheCallResult(TheCall); 1437 1438 // Find out if any arguments are required to be integer constant expressions. 1439 unsigned ICEArguments = 0; 1440 ASTContext::GetBuiltinTypeError Error; 1441 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1442 if (Error != ASTContext::GE_None) 1443 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1444 1445 // If any arguments are required to be ICE's, check and diagnose. 1446 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1447 // Skip arguments not required to be ICE's. 1448 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1449 1450 llvm::APSInt Result; 1451 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1452 return true; 1453 ICEArguments &= ~(1 << ArgNo); 1454 } 1455 1456 switch (BuiltinID) { 1457 case Builtin::BI__builtin___CFStringMakeConstantString: 1458 assert(TheCall->getNumArgs() == 1 && 1459 "Wrong # arguments to builtin CFStringMakeConstantString"); 1460 if (CheckObjCString(TheCall->getArg(0))) 1461 return ExprError(); 1462 break; 1463 case Builtin::BI__builtin_ms_va_start: 1464 case Builtin::BI__builtin_stdarg_start: 1465 case Builtin::BI__builtin_va_start: 1466 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__va_start: { 1470 switch (Context.getTargetInfo().getTriple().getArch()) { 1471 case llvm::Triple::aarch64: 1472 case llvm::Triple::arm: 1473 case llvm::Triple::thumb: 1474 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1475 return ExprError(); 1476 break; 1477 default: 1478 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1479 return ExprError(); 1480 break; 1481 } 1482 break; 1483 } 1484 1485 // The acquire, release, and no fence variants are ARM and AArch64 only. 1486 case Builtin::BI_interlockedbittestandset_acq: 1487 case Builtin::BI_interlockedbittestandset_rel: 1488 case Builtin::BI_interlockedbittestandset_nf: 1489 case Builtin::BI_interlockedbittestandreset_acq: 1490 case Builtin::BI_interlockedbittestandreset_rel: 1491 case Builtin::BI_interlockedbittestandreset_nf: 1492 if (CheckBuiltinTargetSupport( 1493 *this, BuiltinID, TheCall, 1494 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1495 return ExprError(); 1496 break; 1497 1498 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1499 case Builtin::BI_bittest64: 1500 case Builtin::BI_bittestandcomplement64: 1501 case Builtin::BI_bittestandreset64: 1502 case Builtin::BI_bittestandset64: 1503 case Builtin::BI_interlockedbittestandreset64: 1504 case Builtin::BI_interlockedbittestandset64: 1505 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1506 {llvm::Triple::x86_64, llvm::Triple::arm, 1507 llvm::Triple::thumb, llvm::Triple::aarch64})) 1508 return ExprError(); 1509 break; 1510 1511 case Builtin::BI__builtin_isgreater: 1512 case Builtin::BI__builtin_isgreaterequal: 1513 case Builtin::BI__builtin_isless: 1514 case Builtin::BI__builtin_islessequal: 1515 case Builtin::BI__builtin_islessgreater: 1516 case Builtin::BI__builtin_isunordered: 1517 if (SemaBuiltinUnorderedCompare(TheCall)) 1518 return ExprError(); 1519 break; 1520 case Builtin::BI__builtin_fpclassify: 1521 if (SemaBuiltinFPClassification(TheCall, 6)) 1522 return ExprError(); 1523 break; 1524 case Builtin::BI__builtin_isfinite: 1525 case Builtin::BI__builtin_isinf: 1526 case Builtin::BI__builtin_isinf_sign: 1527 case Builtin::BI__builtin_isnan: 1528 case Builtin::BI__builtin_isnormal: 1529 case Builtin::BI__builtin_signbit: 1530 case Builtin::BI__builtin_signbitf: 1531 case Builtin::BI__builtin_signbitl: 1532 if (SemaBuiltinFPClassification(TheCall, 1)) 1533 return ExprError(); 1534 break; 1535 case Builtin::BI__builtin_shufflevector: 1536 return SemaBuiltinShuffleVector(TheCall); 1537 // TheCall will be freed by the smart pointer here, but that's fine, since 1538 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1539 case Builtin::BI__builtin_prefetch: 1540 if (SemaBuiltinPrefetch(TheCall)) 1541 return ExprError(); 1542 break; 1543 case Builtin::BI__builtin_alloca_with_align: 1544 if (SemaBuiltinAllocaWithAlign(TheCall)) 1545 return ExprError(); 1546 LLVM_FALLTHROUGH; 1547 case Builtin::BI__builtin_alloca: 1548 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1549 << TheCall->getDirectCallee(); 1550 break; 1551 case Builtin::BI__assume: 1552 case Builtin::BI__builtin_assume: 1553 if (SemaBuiltinAssume(TheCall)) 1554 return ExprError(); 1555 break; 1556 case Builtin::BI__builtin_assume_aligned: 1557 if (SemaBuiltinAssumeAligned(TheCall)) 1558 return ExprError(); 1559 break; 1560 case Builtin::BI__builtin_dynamic_object_size: 1561 case Builtin::BI__builtin_object_size: 1562 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1563 return ExprError(); 1564 break; 1565 case Builtin::BI__builtin_longjmp: 1566 if (SemaBuiltinLongjmp(TheCall)) 1567 return ExprError(); 1568 break; 1569 case Builtin::BI__builtin_setjmp: 1570 if (SemaBuiltinSetjmp(TheCall)) 1571 return ExprError(); 1572 break; 1573 case Builtin::BI_setjmp: 1574 case Builtin::BI_setjmpex: 1575 if (checkArgCount(*this, TheCall, 1)) 1576 return true; 1577 break; 1578 case Builtin::BI__builtin_classify_type: 1579 if (checkArgCount(*this, TheCall, 1)) return true; 1580 TheCall->setType(Context.IntTy); 1581 break; 1582 case Builtin::BI__builtin_complex: 1583 if (SemaBuiltinComplex(TheCall)) 1584 return ExprError(); 1585 break; 1586 case Builtin::BI__builtin_constant_p: { 1587 if (checkArgCount(*this, TheCall, 1)) return true; 1588 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1589 if (Arg.isInvalid()) return true; 1590 TheCall->setArg(0, Arg.get()); 1591 TheCall->setType(Context.IntTy); 1592 break; 1593 } 1594 case Builtin::BI__builtin_launder: 1595 return SemaBuiltinLaunder(*this, TheCall); 1596 case Builtin::BI__sync_fetch_and_add: 1597 case Builtin::BI__sync_fetch_and_add_1: 1598 case Builtin::BI__sync_fetch_and_add_2: 1599 case Builtin::BI__sync_fetch_and_add_4: 1600 case Builtin::BI__sync_fetch_and_add_8: 1601 case Builtin::BI__sync_fetch_and_add_16: 1602 case Builtin::BI__sync_fetch_and_sub: 1603 case Builtin::BI__sync_fetch_and_sub_1: 1604 case Builtin::BI__sync_fetch_and_sub_2: 1605 case Builtin::BI__sync_fetch_and_sub_4: 1606 case Builtin::BI__sync_fetch_and_sub_8: 1607 case Builtin::BI__sync_fetch_and_sub_16: 1608 case Builtin::BI__sync_fetch_and_or: 1609 case Builtin::BI__sync_fetch_and_or_1: 1610 case Builtin::BI__sync_fetch_and_or_2: 1611 case Builtin::BI__sync_fetch_and_or_4: 1612 case Builtin::BI__sync_fetch_and_or_8: 1613 case Builtin::BI__sync_fetch_and_or_16: 1614 case Builtin::BI__sync_fetch_and_and: 1615 case Builtin::BI__sync_fetch_and_and_1: 1616 case Builtin::BI__sync_fetch_and_and_2: 1617 case Builtin::BI__sync_fetch_and_and_4: 1618 case Builtin::BI__sync_fetch_and_and_8: 1619 case Builtin::BI__sync_fetch_and_and_16: 1620 case Builtin::BI__sync_fetch_and_xor: 1621 case Builtin::BI__sync_fetch_and_xor_1: 1622 case Builtin::BI__sync_fetch_and_xor_2: 1623 case Builtin::BI__sync_fetch_and_xor_4: 1624 case Builtin::BI__sync_fetch_and_xor_8: 1625 case Builtin::BI__sync_fetch_and_xor_16: 1626 case Builtin::BI__sync_fetch_and_nand: 1627 case Builtin::BI__sync_fetch_and_nand_1: 1628 case Builtin::BI__sync_fetch_and_nand_2: 1629 case Builtin::BI__sync_fetch_and_nand_4: 1630 case Builtin::BI__sync_fetch_and_nand_8: 1631 case Builtin::BI__sync_fetch_and_nand_16: 1632 case Builtin::BI__sync_add_and_fetch: 1633 case Builtin::BI__sync_add_and_fetch_1: 1634 case Builtin::BI__sync_add_and_fetch_2: 1635 case Builtin::BI__sync_add_and_fetch_4: 1636 case Builtin::BI__sync_add_and_fetch_8: 1637 case Builtin::BI__sync_add_and_fetch_16: 1638 case Builtin::BI__sync_sub_and_fetch: 1639 case Builtin::BI__sync_sub_and_fetch_1: 1640 case Builtin::BI__sync_sub_and_fetch_2: 1641 case Builtin::BI__sync_sub_and_fetch_4: 1642 case Builtin::BI__sync_sub_and_fetch_8: 1643 case Builtin::BI__sync_sub_and_fetch_16: 1644 case Builtin::BI__sync_and_and_fetch: 1645 case Builtin::BI__sync_and_and_fetch_1: 1646 case Builtin::BI__sync_and_and_fetch_2: 1647 case Builtin::BI__sync_and_and_fetch_4: 1648 case Builtin::BI__sync_and_and_fetch_8: 1649 case Builtin::BI__sync_and_and_fetch_16: 1650 case Builtin::BI__sync_or_and_fetch: 1651 case Builtin::BI__sync_or_and_fetch_1: 1652 case Builtin::BI__sync_or_and_fetch_2: 1653 case Builtin::BI__sync_or_and_fetch_4: 1654 case Builtin::BI__sync_or_and_fetch_8: 1655 case Builtin::BI__sync_or_and_fetch_16: 1656 case Builtin::BI__sync_xor_and_fetch: 1657 case Builtin::BI__sync_xor_and_fetch_1: 1658 case Builtin::BI__sync_xor_and_fetch_2: 1659 case Builtin::BI__sync_xor_and_fetch_4: 1660 case Builtin::BI__sync_xor_and_fetch_8: 1661 case Builtin::BI__sync_xor_and_fetch_16: 1662 case Builtin::BI__sync_nand_and_fetch: 1663 case Builtin::BI__sync_nand_and_fetch_1: 1664 case Builtin::BI__sync_nand_and_fetch_2: 1665 case Builtin::BI__sync_nand_and_fetch_4: 1666 case Builtin::BI__sync_nand_and_fetch_8: 1667 case Builtin::BI__sync_nand_and_fetch_16: 1668 case Builtin::BI__sync_val_compare_and_swap: 1669 case Builtin::BI__sync_val_compare_and_swap_1: 1670 case Builtin::BI__sync_val_compare_and_swap_2: 1671 case Builtin::BI__sync_val_compare_and_swap_4: 1672 case Builtin::BI__sync_val_compare_and_swap_8: 1673 case Builtin::BI__sync_val_compare_and_swap_16: 1674 case Builtin::BI__sync_bool_compare_and_swap: 1675 case Builtin::BI__sync_bool_compare_and_swap_1: 1676 case Builtin::BI__sync_bool_compare_and_swap_2: 1677 case Builtin::BI__sync_bool_compare_and_swap_4: 1678 case Builtin::BI__sync_bool_compare_and_swap_8: 1679 case Builtin::BI__sync_bool_compare_and_swap_16: 1680 case Builtin::BI__sync_lock_test_and_set: 1681 case Builtin::BI__sync_lock_test_and_set_1: 1682 case Builtin::BI__sync_lock_test_and_set_2: 1683 case Builtin::BI__sync_lock_test_and_set_4: 1684 case Builtin::BI__sync_lock_test_and_set_8: 1685 case Builtin::BI__sync_lock_test_and_set_16: 1686 case Builtin::BI__sync_lock_release: 1687 case Builtin::BI__sync_lock_release_1: 1688 case Builtin::BI__sync_lock_release_2: 1689 case Builtin::BI__sync_lock_release_4: 1690 case Builtin::BI__sync_lock_release_8: 1691 case Builtin::BI__sync_lock_release_16: 1692 case Builtin::BI__sync_swap: 1693 case Builtin::BI__sync_swap_1: 1694 case Builtin::BI__sync_swap_2: 1695 case Builtin::BI__sync_swap_4: 1696 case Builtin::BI__sync_swap_8: 1697 case Builtin::BI__sync_swap_16: 1698 return SemaBuiltinAtomicOverloaded(TheCallResult); 1699 case Builtin::BI__sync_synchronize: 1700 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1701 << TheCall->getCallee()->getSourceRange(); 1702 break; 1703 case Builtin::BI__builtin_nontemporal_load: 1704 case Builtin::BI__builtin_nontemporal_store: 1705 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1706 case Builtin::BI__builtin_memcpy_inline: { 1707 clang::Expr *SizeOp = TheCall->getArg(2); 1708 // We warn about copying to or from `nullptr` pointers when `size` is 1709 // greater than 0. When `size` is value dependent we cannot evaluate its 1710 // value so we bail out. 1711 if (SizeOp->isValueDependent()) 1712 break; 1713 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1714 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1715 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1716 } 1717 break; 1718 } 1719 #define BUILTIN(ID, TYPE, ATTRS) 1720 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1721 case Builtin::BI##ID: \ 1722 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1723 #include "clang/Basic/Builtins.def" 1724 case Builtin::BI__annotation: 1725 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1726 return ExprError(); 1727 break; 1728 case Builtin::BI__builtin_annotation: 1729 if (SemaBuiltinAnnotation(*this, TheCall)) 1730 return ExprError(); 1731 break; 1732 case Builtin::BI__builtin_addressof: 1733 if (SemaBuiltinAddressof(*this, TheCall)) 1734 return ExprError(); 1735 break; 1736 case Builtin::BI__builtin_is_aligned: 1737 case Builtin::BI__builtin_align_up: 1738 case Builtin::BI__builtin_align_down: 1739 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1740 return ExprError(); 1741 break; 1742 case Builtin::BI__builtin_add_overflow: 1743 case Builtin::BI__builtin_sub_overflow: 1744 case Builtin::BI__builtin_mul_overflow: 1745 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1746 return ExprError(); 1747 break; 1748 case Builtin::BI__builtin_operator_new: 1749 case Builtin::BI__builtin_operator_delete: { 1750 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1751 ExprResult Res = 1752 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1753 if (Res.isInvalid()) 1754 CorrectDelayedTyposInExpr(TheCallResult.get()); 1755 return Res; 1756 } 1757 case Builtin::BI__builtin_dump_struct: { 1758 // We first want to ensure we are called with 2 arguments 1759 if (checkArgCount(*this, TheCall, 2)) 1760 return ExprError(); 1761 // Ensure that the first argument is of type 'struct XX *' 1762 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1763 const QualType PtrArgType = PtrArg->getType(); 1764 if (!PtrArgType->isPointerType() || 1765 !PtrArgType->getPointeeType()->isRecordType()) { 1766 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1767 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1768 << "structure pointer"; 1769 return ExprError(); 1770 } 1771 1772 // Ensure that the second argument is of type 'FunctionType' 1773 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1774 const QualType FnPtrArgType = FnPtrArg->getType(); 1775 if (!FnPtrArgType->isPointerType()) { 1776 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1777 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1778 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1779 return ExprError(); 1780 } 1781 1782 const auto *FuncType = 1783 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1784 1785 if (!FuncType) { 1786 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1787 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1788 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1789 return ExprError(); 1790 } 1791 1792 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1793 if (!FT->getNumParams()) { 1794 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1795 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1796 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1797 return ExprError(); 1798 } 1799 QualType PT = FT->getParamType(0); 1800 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1801 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1802 !PT->getPointeeType().isConstQualified()) { 1803 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1804 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1805 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1806 return ExprError(); 1807 } 1808 } 1809 1810 TheCall->setType(Context.IntTy); 1811 break; 1812 } 1813 case Builtin::BI__builtin_expect_with_probability: { 1814 // We first want to ensure we are called with 3 arguments 1815 if (checkArgCount(*this, TheCall, 3)) 1816 return ExprError(); 1817 // then check probability is constant float in range [0.0, 1.0] 1818 const Expr *ProbArg = TheCall->getArg(2); 1819 SmallVector<PartialDiagnosticAt, 8> Notes; 1820 Expr::EvalResult Eval; 1821 Eval.Diag = &Notes; 1822 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 1823 Context)) || 1824 !Eval.Val.isFloat()) { 1825 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1826 << ProbArg->getSourceRange(); 1827 for (const PartialDiagnosticAt &PDiag : Notes) 1828 Diag(PDiag.first, PDiag.second); 1829 return ExprError(); 1830 } 1831 llvm::APFloat Probability = Eval.Val.getFloat(); 1832 bool LoseInfo = false; 1833 Probability.convert(llvm::APFloat::IEEEdouble(), 1834 llvm::RoundingMode::Dynamic, &LoseInfo); 1835 if (!(Probability >= llvm::APFloat(0.0) && 1836 Probability <= llvm::APFloat(1.0))) { 1837 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1838 << ProbArg->getSourceRange(); 1839 return ExprError(); 1840 } 1841 break; 1842 } 1843 case Builtin::BI__builtin_preserve_access_index: 1844 if (SemaBuiltinPreserveAI(*this, TheCall)) 1845 return ExprError(); 1846 break; 1847 case Builtin::BI__builtin_call_with_static_chain: 1848 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__exception_code: 1852 case Builtin::BI_exception_code: 1853 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1854 diag::err_seh___except_block)) 1855 return ExprError(); 1856 break; 1857 case Builtin::BI__exception_info: 1858 case Builtin::BI_exception_info: 1859 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1860 diag::err_seh___except_filter)) 1861 return ExprError(); 1862 break; 1863 case Builtin::BI__GetExceptionInfo: 1864 if (checkArgCount(*this, TheCall, 1)) 1865 return ExprError(); 1866 1867 if (CheckCXXThrowOperand( 1868 TheCall->getBeginLoc(), 1869 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1870 TheCall)) 1871 return ExprError(); 1872 1873 TheCall->setType(Context.VoidPtrTy); 1874 break; 1875 // OpenCL v2.0, s6.13.16 - Pipe functions 1876 case Builtin::BIread_pipe: 1877 case Builtin::BIwrite_pipe: 1878 // Since those two functions are declared with var args, we need a semantic 1879 // check for the argument. 1880 if (SemaBuiltinRWPipe(*this, TheCall)) 1881 return ExprError(); 1882 break; 1883 case Builtin::BIreserve_read_pipe: 1884 case Builtin::BIreserve_write_pipe: 1885 case Builtin::BIwork_group_reserve_read_pipe: 1886 case Builtin::BIwork_group_reserve_write_pipe: 1887 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1888 return ExprError(); 1889 break; 1890 case Builtin::BIsub_group_reserve_read_pipe: 1891 case Builtin::BIsub_group_reserve_write_pipe: 1892 if (checkOpenCLSubgroupExt(*this, TheCall) || 1893 SemaBuiltinReserveRWPipe(*this, TheCall)) 1894 return ExprError(); 1895 break; 1896 case Builtin::BIcommit_read_pipe: 1897 case Builtin::BIcommit_write_pipe: 1898 case Builtin::BIwork_group_commit_read_pipe: 1899 case Builtin::BIwork_group_commit_write_pipe: 1900 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1901 return ExprError(); 1902 break; 1903 case Builtin::BIsub_group_commit_read_pipe: 1904 case Builtin::BIsub_group_commit_write_pipe: 1905 if (checkOpenCLSubgroupExt(*this, TheCall) || 1906 SemaBuiltinCommitRWPipe(*this, TheCall)) 1907 return ExprError(); 1908 break; 1909 case Builtin::BIget_pipe_num_packets: 1910 case Builtin::BIget_pipe_max_packets: 1911 if (SemaBuiltinPipePackets(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIto_global: 1915 case Builtin::BIto_local: 1916 case Builtin::BIto_private: 1917 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1918 return ExprError(); 1919 break; 1920 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1921 case Builtin::BIenqueue_kernel: 1922 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1923 return ExprError(); 1924 break; 1925 case Builtin::BIget_kernel_work_group_size: 1926 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1927 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1928 return ExprError(); 1929 break; 1930 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1931 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1932 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1933 return ExprError(); 1934 break; 1935 case Builtin::BI__builtin_os_log_format: 1936 Cleanup.setExprNeedsCleanups(true); 1937 LLVM_FALLTHROUGH; 1938 case Builtin::BI__builtin_os_log_format_buffer_size: 1939 if (SemaBuiltinOSLogFormat(TheCall)) 1940 return ExprError(); 1941 break; 1942 case Builtin::BI__builtin_frame_address: 1943 case Builtin::BI__builtin_return_address: { 1944 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1945 return ExprError(); 1946 1947 // -Wframe-address warning if non-zero passed to builtin 1948 // return/frame address. 1949 Expr::EvalResult Result; 1950 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1951 Result.Val.getInt() != 0) 1952 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1953 << ((BuiltinID == Builtin::BI__builtin_return_address) 1954 ? "__builtin_return_address" 1955 : "__builtin_frame_address") 1956 << TheCall->getSourceRange(); 1957 break; 1958 } 1959 1960 case Builtin::BI__builtin_matrix_transpose: 1961 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1962 1963 case Builtin::BI__builtin_matrix_column_major_load: 1964 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1965 1966 case Builtin::BI__builtin_matrix_column_major_store: 1967 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1968 } 1969 1970 // Since the target specific builtins for each arch overlap, only check those 1971 // of the arch we are compiling for. 1972 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1973 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1974 assert(Context.getAuxTargetInfo() && 1975 "Aux Target Builtin, but not an aux target?"); 1976 1977 if (CheckTSBuiltinFunctionCall( 1978 *Context.getAuxTargetInfo(), 1979 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1980 return ExprError(); 1981 } else { 1982 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1983 TheCall)) 1984 return ExprError(); 1985 } 1986 } 1987 1988 return TheCallResult; 1989 } 1990 1991 // Get the valid immediate range for the specified NEON type code. 1992 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1993 NeonTypeFlags Type(t); 1994 int IsQuad = ForceQuad ? true : Type.isQuad(); 1995 switch (Type.getEltType()) { 1996 case NeonTypeFlags::Int8: 1997 case NeonTypeFlags::Poly8: 1998 return shift ? 7 : (8 << IsQuad) - 1; 1999 case NeonTypeFlags::Int16: 2000 case NeonTypeFlags::Poly16: 2001 return shift ? 15 : (4 << IsQuad) - 1; 2002 case NeonTypeFlags::Int32: 2003 return shift ? 31 : (2 << IsQuad) - 1; 2004 case NeonTypeFlags::Int64: 2005 case NeonTypeFlags::Poly64: 2006 return shift ? 63 : (1 << IsQuad) - 1; 2007 case NeonTypeFlags::Poly128: 2008 return shift ? 127 : (1 << IsQuad) - 1; 2009 case NeonTypeFlags::Float16: 2010 assert(!shift && "cannot shift float types!"); 2011 return (4 << IsQuad) - 1; 2012 case NeonTypeFlags::Float32: 2013 assert(!shift && "cannot shift float types!"); 2014 return (2 << IsQuad) - 1; 2015 case NeonTypeFlags::Float64: 2016 assert(!shift && "cannot shift float types!"); 2017 return (1 << IsQuad) - 1; 2018 case NeonTypeFlags::BFloat16: 2019 assert(!shift && "cannot shift float types!"); 2020 return (4 << IsQuad) - 1; 2021 } 2022 llvm_unreachable("Invalid NeonTypeFlag!"); 2023 } 2024 2025 /// getNeonEltType - Return the QualType corresponding to the elements of 2026 /// the vector type specified by the NeonTypeFlags. This is used to check 2027 /// the pointer arguments for Neon load/store intrinsics. 2028 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2029 bool IsPolyUnsigned, bool IsInt64Long) { 2030 switch (Flags.getEltType()) { 2031 case NeonTypeFlags::Int8: 2032 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2033 case NeonTypeFlags::Int16: 2034 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2035 case NeonTypeFlags::Int32: 2036 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2037 case NeonTypeFlags::Int64: 2038 if (IsInt64Long) 2039 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2040 else 2041 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2042 : Context.LongLongTy; 2043 case NeonTypeFlags::Poly8: 2044 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2045 case NeonTypeFlags::Poly16: 2046 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2047 case NeonTypeFlags::Poly64: 2048 if (IsInt64Long) 2049 return Context.UnsignedLongTy; 2050 else 2051 return Context.UnsignedLongLongTy; 2052 case NeonTypeFlags::Poly128: 2053 break; 2054 case NeonTypeFlags::Float16: 2055 return Context.HalfTy; 2056 case NeonTypeFlags::Float32: 2057 return Context.FloatTy; 2058 case NeonTypeFlags::Float64: 2059 return Context.DoubleTy; 2060 case NeonTypeFlags::BFloat16: 2061 return Context.BFloat16Ty; 2062 } 2063 llvm_unreachable("Invalid NeonTypeFlag!"); 2064 } 2065 2066 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2067 // Range check SVE intrinsics that take immediate values. 2068 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2069 2070 switch (BuiltinID) { 2071 default: 2072 return false; 2073 #define GET_SVE_IMMEDIATE_CHECK 2074 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2075 #undef GET_SVE_IMMEDIATE_CHECK 2076 } 2077 2078 // Perform all the immediate checks for this builtin call. 2079 bool HasError = false; 2080 for (auto &I : ImmChecks) { 2081 int ArgNum, CheckTy, ElementSizeInBits; 2082 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2083 2084 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2085 2086 // Function that checks whether the operand (ArgNum) is an immediate 2087 // that is one of the predefined values. 2088 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2089 int ErrDiag) -> bool { 2090 // We can't check the value of a dependent argument. 2091 Expr *Arg = TheCall->getArg(ArgNum); 2092 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2093 return false; 2094 2095 // Check constant-ness first. 2096 llvm::APSInt Imm; 2097 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2098 return true; 2099 2100 if (!CheckImm(Imm.getSExtValue())) 2101 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2102 return false; 2103 }; 2104 2105 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2106 case SVETypeFlags::ImmCheck0_31: 2107 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2108 HasError = true; 2109 break; 2110 case SVETypeFlags::ImmCheck0_13: 2111 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2112 HasError = true; 2113 break; 2114 case SVETypeFlags::ImmCheck1_16: 2115 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2116 HasError = true; 2117 break; 2118 case SVETypeFlags::ImmCheck0_7: 2119 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2120 HasError = true; 2121 break; 2122 case SVETypeFlags::ImmCheckExtract: 2123 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2124 (2048 / ElementSizeInBits) - 1)) 2125 HasError = true; 2126 break; 2127 case SVETypeFlags::ImmCheckShiftRight: 2128 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2129 HasError = true; 2130 break; 2131 case SVETypeFlags::ImmCheckShiftRightNarrow: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2133 ElementSizeInBits / 2)) 2134 HasError = true; 2135 break; 2136 case SVETypeFlags::ImmCheckShiftLeft: 2137 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2138 ElementSizeInBits - 1)) 2139 HasError = true; 2140 break; 2141 case SVETypeFlags::ImmCheckLaneIndex: 2142 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2143 (128 / (1 * ElementSizeInBits)) - 1)) 2144 HasError = true; 2145 break; 2146 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2147 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2148 (128 / (2 * ElementSizeInBits)) - 1)) 2149 HasError = true; 2150 break; 2151 case SVETypeFlags::ImmCheckLaneIndexDot: 2152 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2153 (128 / (4 * ElementSizeInBits)) - 1)) 2154 HasError = true; 2155 break; 2156 case SVETypeFlags::ImmCheckComplexRot90_270: 2157 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2158 diag::err_rotation_argument_to_cadd)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckComplexRotAll90: 2162 if (CheckImmediateInSet( 2163 [](int64_t V) { 2164 return V == 0 || V == 90 || V == 180 || V == 270; 2165 }, 2166 diag::err_rotation_argument_to_cmla)) 2167 HasError = true; 2168 break; 2169 case SVETypeFlags::ImmCheck0_1: 2170 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2171 HasError = true; 2172 break; 2173 case SVETypeFlags::ImmCheck0_2: 2174 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2175 HasError = true; 2176 break; 2177 case SVETypeFlags::ImmCheck0_3: 2178 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2179 HasError = true; 2180 break; 2181 } 2182 } 2183 2184 return HasError; 2185 } 2186 2187 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2188 unsigned BuiltinID, CallExpr *TheCall) { 2189 llvm::APSInt Result; 2190 uint64_t mask = 0; 2191 unsigned TV = 0; 2192 int PtrArgNum = -1; 2193 bool HasConstPtr = false; 2194 switch (BuiltinID) { 2195 #define GET_NEON_OVERLOAD_CHECK 2196 #include "clang/Basic/arm_neon.inc" 2197 #include "clang/Basic/arm_fp16.inc" 2198 #undef GET_NEON_OVERLOAD_CHECK 2199 } 2200 2201 // For NEON intrinsics which are overloaded on vector element type, validate 2202 // the immediate which specifies which variant to emit. 2203 unsigned ImmArg = TheCall->getNumArgs()-1; 2204 if (mask) { 2205 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2206 return true; 2207 2208 TV = Result.getLimitedValue(64); 2209 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2210 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2211 << TheCall->getArg(ImmArg)->getSourceRange(); 2212 } 2213 2214 if (PtrArgNum >= 0) { 2215 // Check that pointer arguments have the specified type. 2216 Expr *Arg = TheCall->getArg(PtrArgNum); 2217 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2218 Arg = ICE->getSubExpr(); 2219 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2220 QualType RHSTy = RHS.get()->getType(); 2221 2222 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2223 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2224 Arch == llvm::Triple::aarch64_32 || 2225 Arch == llvm::Triple::aarch64_be; 2226 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2227 QualType EltTy = 2228 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2229 if (HasConstPtr) 2230 EltTy = EltTy.withConst(); 2231 QualType LHSTy = Context.getPointerType(EltTy); 2232 AssignConvertType ConvTy; 2233 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2234 if (RHS.isInvalid()) 2235 return true; 2236 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2237 RHS.get(), AA_Assigning)) 2238 return true; 2239 } 2240 2241 // For NEON intrinsics which take an immediate value as part of the 2242 // instruction, range check them here. 2243 unsigned i = 0, l = 0, u = 0; 2244 switch (BuiltinID) { 2245 default: 2246 return false; 2247 #define GET_NEON_IMMEDIATE_CHECK 2248 #include "clang/Basic/arm_neon.inc" 2249 #include "clang/Basic/arm_fp16.inc" 2250 #undef GET_NEON_IMMEDIATE_CHECK 2251 } 2252 2253 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2254 } 2255 2256 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2257 switch (BuiltinID) { 2258 default: 2259 return false; 2260 #include "clang/Basic/arm_mve_builtin_sema.inc" 2261 } 2262 } 2263 2264 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2265 CallExpr *TheCall) { 2266 bool Err = false; 2267 switch (BuiltinID) { 2268 default: 2269 return false; 2270 #include "clang/Basic/arm_cde_builtin_sema.inc" 2271 } 2272 2273 if (Err) 2274 return true; 2275 2276 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2277 } 2278 2279 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2280 const Expr *CoprocArg, bool WantCDE) { 2281 if (isConstantEvaluated()) 2282 return false; 2283 2284 // We can't check the value of a dependent argument. 2285 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2286 return false; 2287 2288 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2289 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2290 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2291 2292 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2293 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2294 2295 if (IsCDECoproc != WantCDE) 2296 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2297 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2298 2299 return false; 2300 } 2301 2302 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2303 unsigned MaxWidth) { 2304 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2305 BuiltinID == ARM::BI__builtin_arm_ldaex || 2306 BuiltinID == ARM::BI__builtin_arm_strex || 2307 BuiltinID == ARM::BI__builtin_arm_stlex || 2308 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2309 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2310 BuiltinID == AArch64::BI__builtin_arm_strex || 2311 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2312 "unexpected ARM builtin"); 2313 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2314 BuiltinID == ARM::BI__builtin_arm_ldaex || 2315 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2316 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2317 2318 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2319 2320 // Ensure that we have the proper number of arguments. 2321 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2322 return true; 2323 2324 // Inspect the pointer argument of the atomic builtin. This should always be 2325 // a pointer type, whose element is an integral scalar or pointer type. 2326 // Because it is a pointer type, we don't have to worry about any implicit 2327 // casts here. 2328 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2329 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2330 if (PointerArgRes.isInvalid()) 2331 return true; 2332 PointerArg = PointerArgRes.get(); 2333 2334 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2335 if (!pointerType) { 2336 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2337 << PointerArg->getType() << PointerArg->getSourceRange(); 2338 return true; 2339 } 2340 2341 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2342 // task is to insert the appropriate casts into the AST. First work out just 2343 // what the appropriate type is. 2344 QualType ValType = pointerType->getPointeeType(); 2345 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2346 if (IsLdrex) 2347 AddrType.addConst(); 2348 2349 // Issue a warning if the cast is dodgy. 2350 CastKind CastNeeded = CK_NoOp; 2351 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2352 CastNeeded = CK_BitCast; 2353 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2354 << PointerArg->getType() << Context.getPointerType(AddrType) 2355 << AA_Passing << PointerArg->getSourceRange(); 2356 } 2357 2358 // Finally, do the cast and replace the argument with the corrected version. 2359 AddrType = Context.getPointerType(AddrType); 2360 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2361 if (PointerArgRes.isInvalid()) 2362 return true; 2363 PointerArg = PointerArgRes.get(); 2364 2365 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2366 2367 // In general, we allow ints, floats and pointers to be loaded and stored. 2368 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2369 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2370 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2371 << PointerArg->getType() << PointerArg->getSourceRange(); 2372 return true; 2373 } 2374 2375 // But ARM doesn't have instructions to deal with 128-bit versions. 2376 if (Context.getTypeSize(ValType) > MaxWidth) { 2377 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2378 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2379 << PointerArg->getType() << PointerArg->getSourceRange(); 2380 return true; 2381 } 2382 2383 switch (ValType.getObjCLifetime()) { 2384 case Qualifiers::OCL_None: 2385 case Qualifiers::OCL_ExplicitNone: 2386 // okay 2387 break; 2388 2389 case Qualifiers::OCL_Weak: 2390 case Qualifiers::OCL_Strong: 2391 case Qualifiers::OCL_Autoreleasing: 2392 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2393 << ValType << PointerArg->getSourceRange(); 2394 return true; 2395 } 2396 2397 if (IsLdrex) { 2398 TheCall->setType(ValType); 2399 return false; 2400 } 2401 2402 // Initialize the argument to be stored. 2403 ExprResult ValArg = TheCall->getArg(0); 2404 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2405 Context, ValType, /*consume*/ false); 2406 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2407 if (ValArg.isInvalid()) 2408 return true; 2409 TheCall->setArg(0, ValArg.get()); 2410 2411 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2412 // but the custom checker bypasses all default analysis. 2413 TheCall->setType(Context.IntTy); 2414 return false; 2415 } 2416 2417 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2418 CallExpr *TheCall) { 2419 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2420 BuiltinID == ARM::BI__builtin_arm_ldaex || 2421 BuiltinID == ARM::BI__builtin_arm_strex || 2422 BuiltinID == ARM::BI__builtin_arm_stlex) { 2423 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2424 } 2425 2426 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2427 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2428 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2429 } 2430 2431 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2432 BuiltinID == ARM::BI__builtin_arm_wsr64) 2433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2434 2435 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2436 BuiltinID == ARM::BI__builtin_arm_rsrp || 2437 BuiltinID == ARM::BI__builtin_arm_wsr || 2438 BuiltinID == ARM::BI__builtin_arm_wsrp) 2439 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2440 2441 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2442 return true; 2443 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2444 return true; 2445 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2446 return true; 2447 2448 // For intrinsics which take an immediate value as part of the instruction, 2449 // range check them here. 2450 // FIXME: VFP Intrinsics should error if VFP not present. 2451 switch (BuiltinID) { 2452 default: return false; 2453 case ARM::BI__builtin_arm_ssat: 2454 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2455 case ARM::BI__builtin_arm_usat: 2456 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2457 case ARM::BI__builtin_arm_ssat16: 2458 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2459 case ARM::BI__builtin_arm_usat16: 2460 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2461 case ARM::BI__builtin_arm_vcvtr_f: 2462 case ARM::BI__builtin_arm_vcvtr_d: 2463 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2464 case ARM::BI__builtin_arm_dmb: 2465 case ARM::BI__builtin_arm_dsb: 2466 case ARM::BI__builtin_arm_isb: 2467 case ARM::BI__builtin_arm_dbg: 2468 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2469 case ARM::BI__builtin_arm_cdp: 2470 case ARM::BI__builtin_arm_cdp2: 2471 case ARM::BI__builtin_arm_mcr: 2472 case ARM::BI__builtin_arm_mcr2: 2473 case ARM::BI__builtin_arm_mrc: 2474 case ARM::BI__builtin_arm_mrc2: 2475 case ARM::BI__builtin_arm_mcrr: 2476 case ARM::BI__builtin_arm_mcrr2: 2477 case ARM::BI__builtin_arm_mrrc: 2478 case ARM::BI__builtin_arm_mrrc2: 2479 case ARM::BI__builtin_arm_ldc: 2480 case ARM::BI__builtin_arm_ldcl: 2481 case ARM::BI__builtin_arm_ldc2: 2482 case ARM::BI__builtin_arm_ldc2l: 2483 case ARM::BI__builtin_arm_stc: 2484 case ARM::BI__builtin_arm_stcl: 2485 case ARM::BI__builtin_arm_stc2: 2486 case ARM::BI__builtin_arm_stc2l: 2487 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2488 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2489 /*WantCDE*/ false); 2490 } 2491 } 2492 2493 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2494 unsigned BuiltinID, 2495 CallExpr *TheCall) { 2496 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2497 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2498 BuiltinID == AArch64::BI__builtin_arm_strex || 2499 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2500 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2501 } 2502 2503 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2504 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2505 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2506 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2507 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2508 } 2509 2510 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2511 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2512 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2513 2514 // Memory Tagging Extensions (MTE) Intrinsics 2515 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2516 BuiltinID == AArch64::BI__builtin_arm_addg || 2517 BuiltinID == AArch64::BI__builtin_arm_gmi || 2518 BuiltinID == AArch64::BI__builtin_arm_ldg || 2519 BuiltinID == AArch64::BI__builtin_arm_stg || 2520 BuiltinID == AArch64::BI__builtin_arm_subp) { 2521 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2522 } 2523 2524 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2525 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2526 BuiltinID == AArch64::BI__builtin_arm_wsr || 2527 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2528 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2529 2530 // Only check the valid encoding range. Any constant in this range would be 2531 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2532 // an exception for incorrect registers. This matches MSVC behavior. 2533 if (BuiltinID == AArch64::BI_ReadStatusReg || 2534 BuiltinID == AArch64::BI_WriteStatusReg) 2535 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2536 2537 if (BuiltinID == AArch64::BI__getReg) 2538 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2539 2540 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2541 return true; 2542 2543 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2544 return true; 2545 2546 // For intrinsics which take an immediate value as part of the instruction, 2547 // range check them here. 2548 unsigned i = 0, l = 0, u = 0; 2549 switch (BuiltinID) { 2550 default: return false; 2551 case AArch64::BI__builtin_arm_dmb: 2552 case AArch64::BI__builtin_arm_dsb: 2553 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2554 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2555 } 2556 2557 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2558 } 2559 2560 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2561 CallExpr *TheCall) { 2562 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2563 BuiltinID == BPF::BI__builtin_btf_type_id) && 2564 "unexpected ARM builtin"); 2565 2566 if (checkArgCount(*this, TheCall, 2)) 2567 return true; 2568 2569 Expr *Arg; 2570 if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2571 // The second argument needs to be a constant int 2572 Arg = TheCall->getArg(1); 2573 if (!Arg->isIntegerConstantExpr(Context)) { 2574 Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const) 2575 << 2 << Arg->getSourceRange(); 2576 return true; 2577 } 2578 2579 TheCall->setType(Context.UnsignedIntTy); 2580 return false; 2581 } 2582 2583 // The first argument needs to be a record field access. 2584 // If it is an array element access, we delay decision 2585 // to BPF backend to check whether the access is a 2586 // field access or not. 2587 Arg = TheCall->getArg(0); 2588 if (Arg->getType()->getAsPlaceholderType() || 2589 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2590 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2591 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2592 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2593 << 1 << Arg->getSourceRange(); 2594 return true; 2595 } 2596 2597 // The second argument needs to be a constant int 2598 Arg = TheCall->getArg(1); 2599 if (!Arg->isIntegerConstantExpr(Context)) { 2600 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2601 << 2 << Arg->getSourceRange(); 2602 return true; 2603 } 2604 2605 TheCall->setType(Context.UnsignedIntTy); 2606 return false; 2607 } 2608 2609 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2610 struct ArgInfo { 2611 uint8_t OpNum; 2612 bool IsSigned; 2613 uint8_t BitWidth; 2614 uint8_t Align; 2615 }; 2616 struct BuiltinInfo { 2617 unsigned BuiltinID; 2618 ArgInfo Infos[2]; 2619 }; 2620 2621 static BuiltinInfo Infos[] = { 2622 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2623 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2624 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2625 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2626 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2627 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2628 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2629 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2630 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2631 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2632 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2633 2634 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2645 2646 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2648 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2649 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2698 {{ 1, false, 6, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2706 {{ 1, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2713 { 2, false, 5, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2715 { 2, false, 6, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2717 { 3, false, 5, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2719 { 3, false, 6, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2736 {{ 2, false, 4, 0 }, 2737 { 3, false, 5, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2739 {{ 2, false, 4, 0 }, 2740 { 3, false, 5, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2742 {{ 2, false, 4, 0 }, 2743 { 3, false, 5, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2745 {{ 2, false, 4, 0 }, 2746 { 3, false, 5, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2758 { 2, false, 5, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2760 { 2, false, 6, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2770 {{ 1, false, 4, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2773 {{ 1, false, 4, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2794 {{ 3, false, 1, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2799 {{ 3, false, 1, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2804 {{ 3, false, 1, 0 }} }, 2805 }; 2806 2807 // Use a dynamically initialized static to sort the table exactly once on 2808 // first run. 2809 static const bool SortOnce = 2810 (llvm::sort(Infos, 2811 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2812 return LHS.BuiltinID < RHS.BuiltinID; 2813 }), 2814 true); 2815 (void)SortOnce; 2816 2817 const BuiltinInfo *F = llvm::partition_point( 2818 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2819 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2820 return false; 2821 2822 bool Error = false; 2823 2824 for (const ArgInfo &A : F->Infos) { 2825 // Ignore empty ArgInfo elements. 2826 if (A.BitWidth == 0) 2827 continue; 2828 2829 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2830 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2831 if (!A.Align) { 2832 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2833 } else { 2834 unsigned M = 1 << A.Align; 2835 Min *= M; 2836 Max *= M; 2837 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2838 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2839 } 2840 } 2841 return Error; 2842 } 2843 2844 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2845 CallExpr *TheCall) { 2846 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2847 } 2848 2849 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2850 unsigned BuiltinID, CallExpr *TheCall) { 2851 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2852 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2853 } 2854 2855 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2856 CallExpr *TheCall) { 2857 2858 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2859 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2860 if (!TI.hasFeature("dsp")) 2861 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2862 } 2863 2864 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2865 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2866 if (!TI.hasFeature("dspr2")) 2867 return Diag(TheCall->getBeginLoc(), 2868 diag::err_mips_builtin_requires_dspr2); 2869 } 2870 2871 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2872 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2873 if (!TI.hasFeature("msa")) 2874 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2875 } 2876 2877 return false; 2878 } 2879 2880 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2881 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2882 // ordering for DSP is unspecified. MSA is ordered by the data format used 2883 // by the underlying instruction i.e., df/m, df/n and then by size. 2884 // 2885 // FIXME: The size tests here should instead be tablegen'd along with the 2886 // definitions from include/clang/Basic/BuiltinsMips.def. 2887 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2888 // be too. 2889 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2890 unsigned i = 0, l = 0, u = 0, m = 0; 2891 switch (BuiltinID) { 2892 default: return false; 2893 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2894 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2895 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2896 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2897 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2898 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2899 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2900 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2901 // df/m field. 2902 // These intrinsics take an unsigned 3 bit immediate. 2903 case Mips::BI__builtin_msa_bclri_b: 2904 case Mips::BI__builtin_msa_bnegi_b: 2905 case Mips::BI__builtin_msa_bseti_b: 2906 case Mips::BI__builtin_msa_sat_s_b: 2907 case Mips::BI__builtin_msa_sat_u_b: 2908 case Mips::BI__builtin_msa_slli_b: 2909 case Mips::BI__builtin_msa_srai_b: 2910 case Mips::BI__builtin_msa_srari_b: 2911 case Mips::BI__builtin_msa_srli_b: 2912 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2913 case Mips::BI__builtin_msa_binsli_b: 2914 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2915 // These intrinsics take an unsigned 4 bit immediate. 2916 case Mips::BI__builtin_msa_bclri_h: 2917 case Mips::BI__builtin_msa_bnegi_h: 2918 case Mips::BI__builtin_msa_bseti_h: 2919 case Mips::BI__builtin_msa_sat_s_h: 2920 case Mips::BI__builtin_msa_sat_u_h: 2921 case Mips::BI__builtin_msa_slli_h: 2922 case Mips::BI__builtin_msa_srai_h: 2923 case Mips::BI__builtin_msa_srari_h: 2924 case Mips::BI__builtin_msa_srli_h: 2925 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2926 case Mips::BI__builtin_msa_binsli_h: 2927 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2928 // These intrinsics take an unsigned 5 bit immediate. 2929 // The first block of intrinsics actually have an unsigned 5 bit field, 2930 // not a df/n field. 2931 case Mips::BI__builtin_msa_cfcmsa: 2932 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2933 case Mips::BI__builtin_msa_clei_u_b: 2934 case Mips::BI__builtin_msa_clei_u_h: 2935 case Mips::BI__builtin_msa_clei_u_w: 2936 case Mips::BI__builtin_msa_clei_u_d: 2937 case Mips::BI__builtin_msa_clti_u_b: 2938 case Mips::BI__builtin_msa_clti_u_h: 2939 case Mips::BI__builtin_msa_clti_u_w: 2940 case Mips::BI__builtin_msa_clti_u_d: 2941 case Mips::BI__builtin_msa_maxi_u_b: 2942 case Mips::BI__builtin_msa_maxi_u_h: 2943 case Mips::BI__builtin_msa_maxi_u_w: 2944 case Mips::BI__builtin_msa_maxi_u_d: 2945 case Mips::BI__builtin_msa_mini_u_b: 2946 case Mips::BI__builtin_msa_mini_u_h: 2947 case Mips::BI__builtin_msa_mini_u_w: 2948 case Mips::BI__builtin_msa_mini_u_d: 2949 case Mips::BI__builtin_msa_addvi_b: 2950 case Mips::BI__builtin_msa_addvi_h: 2951 case Mips::BI__builtin_msa_addvi_w: 2952 case Mips::BI__builtin_msa_addvi_d: 2953 case Mips::BI__builtin_msa_bclri_w: 2954 case Mips::BI__builtin_msa_bnegi_w: 2955 case Mips::BI__builtin_msa_bseti_w: 2956 case Mips::BI__builtin_msa_sat_s_w: 2957 case Mips::BI__builtin_msa_sat_u_w: 2958 case Mips::BI__builtin_msa_slli_w: 2959 case Mips::BI__builtin_msa_srai_w: 2960 case Mips::BI__builtin_msa_srari_w: 2961 case Mips::BI__builtin_msa_srli_w: 2962 case Mips::BI__builtin_msa_srlri_w: 2963 case Mips::BI__builtin_msa_subvi_b: 2964 case Mips::BI__builtin_msa_subvi_h: 2965 case Mips::BI__builtin_msa_subvi_w: 2966 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2967 case Mips::BI__builtin_msa_binsli_w: 2968 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2969 // These intrinsics take an unsigned 6 bit immediate. 2970 case Mips::BI__builtin_msa_bclri_d: 2971 case Mips::BI__builtin_msa_bnegi_d: 2972 case Mips::BI__builtin_msa_bseti_d: 2973 case Mips::BI__builtin_msa_sat_s_d: 2974 case Mips::BI__builtin_msa_sat_u_d: 2975 case Mips::BI__builtin_msa_slli_d: 2976 case Mips::BI__builtin_msa_srai_d: 2977 case Mips::BI__builtin_msa_srari_d: 2978 case Mips::BI__builtin_msa_srli_d: 2979 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2980 case Mips::BI__builtin_msa_binsli_d: 2981 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2982 // These intrinsics take a signed 5 bit immediate. 2983 case Mips::BI__builtin_msa_ceqi_b: 2984 case Mips::BI__builtin_msa_ceqi_h: 2985 case Mips::BI__builtin_msa_ceqi_w: 2986 case Mips::BI__builtin_msa_ceqi_d: 2987 case Mips::BI__builtin_msa_clti_s_b: 2988 case Mips::BI__builtin_msa_clti_s_h: 2989 case Mips::BI__builtin_msa_clti_s_w: 2990 case Mips::BI__builtin_msa_clti_s_d: 2991 case Mips::BI__builtin_msa_clei_s_b: 2992 case Mips::BI__builtin_msa_clei_s_h: 2993 case Mips::BI__builtin_msa_clei_s_w: 2994 case Mips::BI__builtin_msa_clei_s_d: 2995 case Mips::BI__builtin_msa_maxi_s_b: 2996 case Mips::BI__builtin_msa_maxi_s_h: 2997 case Mips::BI__builtin_msa_maxi_s_w: 2998 case Mips::BI__builtin_msa_maxi_s_d: 2999 case Mips::BI__builtin_msa_mini_s_b: 3000 case Mips::BI__builtin_msa_mini_s_h: 3001 case Mips::BI__builtin_msa_mini_s_w: 3002 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3003 // These intrinsics take an unsigned 8 bit immediate. 3004 case Mips::BI__builtin_msa_andi_b: 3005 case Mips::BI__builtin_msa_nori_b: 3006 case Mips::BI__builtin_msa_ori_b: 3007 case Mips::BI__builtin_msa_shf_b: 3008 case Mips::BI__builtin_msa_shf_h: 3009 case Mips::BI__builtin_msa_shf_w: 3010 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3011 case Mips::BI__builtin_msa_bseli_b: 3012 case Mips::BI__builtin_msa_bmnzi_b: 3013 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3014 // df/n format 3015 // These intrinsics take an unsigned 4 bit immediate. 3016 case Mips::BI__builtin_msa_copy_s_b: 3017 case Mips::BI__builtin_msa_copy_u_b: 3018 case Mips::BI__builtin_msa_insve_b: 3019 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3020 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3021 // These intrinsics take an unsigned 3 bit immediate. 3022 case Mips::BI__builtin_msa_copy_s_h: 3023 case Mips::BI__builtin_msa_copy_u_h: 3024 case Mips::BI__builtin_msa_insve_h: 3025 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3026 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3027 // These intrinsics take an unsigned 2 bit immediate. 3028 case Mips::BI__builtin_msa_copy_s_w: 3029 case Mips::BI__builtin_msa_copy_u_w: 3030 case Mips::BI__builtin_msa_insve_w: 3031 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3032 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3033 // These intrinsics take an unsigned 1 bit immediate. 3034 case Mips::BI__builtin_msa_copy_s_d: 3035 case Mips::BI__builtin_msa_copy_u_d: 3036 case Mips::BI__builtin_msa_insve_d: 3037 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3038 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3039 // Memory offsets and immediate loads. 3040 // These intrinsics take a signed 10 bit immediate. 3041 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3042 case Mips::BI__builtin_msa_ldi_h: 3043 case Mips::BI__builtin_msa_ldi_w: 3044 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3045 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3046 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3047 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3048 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3049 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3050 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3051 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3052 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3053 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3054 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3055 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3056 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3057 } 3058 3059 if (!m) 3060 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3061 3062 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3063 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3064 } 3065 3066 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3067 CallExpr *TheCall) { 3068 unsigned i = 0, l = 0, u = 0; 3069 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3070 BuiltinID == PPC::BI__builtin_divdeu || 3071 BuiltinID == PPC::BI__builtin_bpermd; 3072 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3073 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3074 BuiltinID == PPC::BI__builtin_divweu || 3075 BuiltinID == PPC::BI__builtin_divde || 3076 BuiltinID == PPC::BI__builtin_divdeu; 3077 3078 if (Is64BitBltin && !IsTarget64Bit) 3079 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3080 << TheCall->getSourceRange(); 3081 3082 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3083 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3084 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3085 << TheCall->getSourceRange(); 3086 3087 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3088 if (!TI.hasFeature("vsx")) 3089 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3090 << TheCall->getSourceRange(); 3091 return false; 3092 }; 3093 3094 switch (BuiltinID) { 3095 default: return false; 3096 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3097 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3098 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3099 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3100 case PPC::BI__builtin_altivec_dss: 3101 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3102 case PPC::BI__builtin_tbegin: 3103 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3104 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3105 case PPC::BI__builtin_tabortwc: 3106 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3107 case PPC::BI__builtin_tabortwci: 3108 case PPC::BI__builtin_tabortdci: 3109 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3110 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3111 case PPC::BI__builtin_altivec_dst: 3112 case PPC::BI__builtin_altivec_dstt: 3113 case PPC::BI__builtin_altivec_dstst: 3114 case PPC::BI__builtin_altivec_dststt: 3115 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3116 case PPC::BI__builtin_vsx_xxpermdi: 3117 case PPC::BI__builtin_vsx_xxsldwi: 3118 return SemaBuiltinVSX(TheCall); 3119 case PPC::BI__builtin_unpack_vector_int128: 3120 return SemaVSXCheck(TheCall) || 3121 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3122 case PPC::BI__builtin_pack_vector_int128: 3123 return SemaVSXCheck(TheCall); 3124 case PPC::BI__builtin_altivec_vgnb: 3125 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3126 case PPC::BI__builtin_vsx_xxeval: 3127 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3128 case PPC::BI__builtin_altivec_vsldbi: 3129 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3130 case PPC::BI__builtin_altivec_vsrdbi: 3131 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3132 case PPC::BI__builtin_vsx_xxpermx: 3133 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3134 } 3135 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3136 } 3137 3138 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3139 CallExpr *TheCall) { 3140 // position of memory order and scope arguments in the builtin 3141 unsigned OrderIndex, ScopeIndex; 3142 switch (BuiltinID) { 3143 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3144 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3145 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3146 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3147 OrderIndex = 2; 3148 ScopeIndex = 3; 3149 break; 3150 case AMDGPU::BI__builtin_amdgcn_fence: 3151 OrderIndex = 0; 3152 ScopeIndex = 1; 3153 break; 3154 default: 3155 return false; 3156 } 3157 3158 ExprResult Arg = TheCall->getArg(OrderIndex); 3159 auto ArgExpr = Arg.get(); 3160 Expr::EvalResult ArgResult; 3161 3162 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3163 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3164 << ArgExpr->getType(); 3165 int ord = ArgResult.Val.getInt().getZExtValue(); 3166 3167 // Check valididty of memory ordering as per C11 / C++11's memody model. 3168 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3169 case llvm::AtomicOrderingCABI::acquire: 3170 case llvm::AtomicOrderingCABI::release: 3171 case llvm::AtomicOrderingCABI::acq_rel: 3172 case llvm::AtomicOrderingCABI::seq_cst: 3173 break; 3174 default: { 3175 return Diag(ArgExpr->getBeginLoc(), 3176 diag::warn_atomic_op_has_invalid_memory_order) 3177 << ArgExpr->getSourceRange(); 3178 } 3179 } 3180 3181 Arg = TheCall->getArg(ScopeIndex); 3182 ArgExpr = Arg.get(); 3183 Expr::EvalResult ArgResult1; 3184 // Check that sync scope is a constant literal 3185 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3186 Context)) 3187 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3188 << ArgExpr->getType(); 3189 3190 return false; 3191 } 3192 3193 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3194 CallExpr *TheCall) { 3195 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3196 Expr *Arg = TheCall->getArg(0); 3197 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3198 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3199 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3200 << Arg->getSourceRange(); 3201 } 3202 3203 // For intrinsics which take an immediate value as part of the instruction, 3204 // range check them here. 3205 unsigned i = 0, l = 0, u = 0; 3206 switch (BuiltinID) { 3207 default: return false; 3208 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3209 case SystemZ::BI__builtin_s390_verimb: 3210 case SystemZ::BI__builtin_s390_verimh: 3211 case SystemZ::BI__builtin_s390_verimf: 3212 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3213 case SystemZ::BI__builtin_s390_vfaeb: 3214 case SystemZ::BI__builtin_s390_vfaeh: 3215 case SystemZ::BI__builtin_s390_vfaef: 3216 case SystemZ::BI__builtin_s390_vfaebs: 3217 case SystemZ::BI__builtin_s390_vfaehs: 3218 case SystemZ::BI__builtin_s390_vfaefs: 3219 case SystemZ::BI__builtin_s390_vfaezb: 3220 case SystemZ::BI__builtin_s390_vfaezh: 3221 case SystemZ::BI__builtin_s390_vfaezf: 3222 case SystemZ::BI__builtin_s390_vfaezbs: 3223 case SystemZ::BI__builtin_s390_vfaezhs: 3224 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3225 case SystemZ::BI__builtin_s390_vfisb: 3226 case SystemZ::BI__builtin_s390_vfidb: 3227 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3228 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3229 case SystemZ::BI__builtin_s390_vftcisb: 3230 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3231 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3232 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3233 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3234 case SystemZ::BI__builtin_s390_vstrcb: 3235 case SystemZ::BI__builtin_s390_vstrch: 3236 case SystemZ::BI__builtin_s390_vstrcf: 3237 case SystemZ::BI__builtin_s390_vstrczb: 3238 case SystemZ::BI__builtin_s390_vstrczh: 3239 case SystemZ::BI__builtin_s390_vstrczf: 3240 case SystemZ::BI__builtin_s390_vstrcbs: 3241 case SystemZ::BI__builtin_s390_vstrchs: 3242 case SystemZ::BI__builtin_s390_vstrcfs: 3243 case SystemZ::BI__builtin_s390_vstrczbs: 3244 case SystemZ::BI__builtin_s390_vstrczhs: 3245 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3246 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3247 case SystemZ::BI__builtin_s390_vfminsb: 3248 case SystemZ::BI__builtin_s390_vfmaxsb: 3249 case SystemZ::BI__builtin_s390_vfmindb: 3250 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3251 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3252 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3253 } 3254 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3255 } 3256 3257 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3258 /// This checks that the target supports __builtin_cpu_supports and 3259 /// that the string argument is constant and valid. 3260 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3261 CallExpr *TheCall) { 3262 Expr *Arg = TheCall->getArg(0); 3263 3264 // Check if the argument is a string literal. 3265 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3266 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3267 << Arg->getSourceRange(); 3268 3269 // Check the contents of the string. 3270 StringRef Feature = 3271 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3272 if (!TI.validateCpuSupports(Feature)) 3273 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3274 << Arg->getSourceRange(); 3275 return false; 3276 } 3277 3278 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3279 /// This checks that the target supports __builtin_cpu_is and 3280 /// that the string argument is constant and valid. 3281 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3282 Expr *Arg = TheCall->getArg(0); 3283 3284 // Check if the argument is a string literal. 3285 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3286 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3287 << Arg->getSourceRange(); 3288 3289 // Check the contents of the string. 3290 StringRef Feature = 3291 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3292 if (!TI.validateCpuIs(Feature)) 3293 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3294 << Arg->getSourceRange(); 3295 return false; 3296 } 3297 3298 // Check if the rounding mode is legal. 3299 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3300 // Indicates if this instruction has rounding control or just SAE. 3301 bool HasRC = false; 3302 3303 unsigned ArgNum = 0; 3304 switch (BuiltinID) { 3305 default: 3306 return false; 3307 case X86::BI__builtin_ia32_vcvttsd2si32: 3308 case X86::BI__builtin_ia32_vcvttsd2si64: 3309 case X86::BI__builtin_ia32_vcvttsd2usi32: 3310 case X86::BI__builtin_ia32_vcvttsd2usi64: 3311 case X86::BI__builtin_ia32_vcvttss2si32: 3312 case X86::BI__builtin_ia32_vcvttss2si64: 3313 case X86::BI__builtin_ia32_vcvttss2usi32: 3314 case X86::BI__builtin_ia32_vcvttss2usi64: 3315 ArgNum = 1; 3316 break; 3317 case X86::BI__builtin_ia32_maxpd512: 3318 case X86::BI__builtin_ia32_maxps512: 3319 case X86::BI__builtin_ia32_minpd512: 3320 case X86::BI__builtin_ia32_minps512: 3321 ArgNum = 2; 3322 break; 3323 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3324 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3325 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3326 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3327 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3328 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3329 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3330 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3331 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3332 case X86::BI__builtin_ia32_exp2pd_mask: 3333 case X86::BI__builtin_ia32_exp2ps_mask: 3334 case X86::BI__builtin_ia32_getexppd512_mask: 3335 case X86::BI__builtin_ia32_getexpps512_mask: 3336 case X86::BI__builtin_ia32_rcp28pd_mask: 3337 case X86::BI__builtin_ia32_rcp28ps_mask: 3338 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3339 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3340 case X86::BI__builtin_ia32_vcomisd: 3341 case X86::BI__builtin_ia32_vcomiss: 3342 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3343 ArgNum = 3; 3344 break; 3345 case X86::BI__builtin_ia32_cmppd512_mask: 3346 case X86::BI__builtin_ia32_cmpps512_mask: 3347 case X86::BI__builtin_ia32_cmpsd_mask: 3348 case X86::BI__builtin_ia32_cmpss_mask: 3349 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3350 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3351 case X86::BI__builtin_ia32_getexpss128_round_mask: 3352 case X86::BI__builtin_ia32_getmantpd512_mask: 3353 case X86::BI__builtin_ia32_getmantps512_mask: 3354 case X86::BI__builtin_ia32_maxsd_round_mask: 3355 case X86::BI__builtin_ia32_maxss_round_mask: 3356 case X86::BI__builtin_ia32_minsd_round_mask: 3357 case X86::BI__builtin_ia32_minss_round_mask: 3358 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3359 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3360 case X86::BI__builtin_ia32_reducepd512_mask: 3361 case X86::BI__builtin_ia32_reduceps512_mask: 3362 case X86::BI__builtin_ia32_rndscalepd_mask: 3363 case X86::BI__builtin_ia32_rndscaleps_mask: 3364 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3365 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3366 ArgNum = 4; 3367 break; 3368 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3369 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3370 case X86::BI__builtin_ia32_fixupimmps512_mask: 3371 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3372 case X86::BI__builtin_ia32_fixupimmsd_mask: 3373 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3374 case X86::BI__builtin_ia32_fixupimmss_mask: 3375 case X86::BI__builtin_ia32_fixupimmss_maskz: 3376 case X86::BI__builtin_ia32_getmantsd_round_mask: 3377 case X86::BI__builtin_ia32_getmantss_round_mask: 3378 case X86::BI__builtin_ia32_rangepd512_mask: 3379 case X86::BI__builtin_ia32_rangeps512_mask: 3380 case X86::BI__builtin_ia32_rangesd128_round_mask: 3381 case X86::BI__builtin_ia32_rangess128_round_mask: 3382 case X86::BI__builtin_ia32_reducesd_mask: 3383 case X86::BI__builtin_ia32_reducess_mask: 3384 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3385 case X86::BI__builtin_ia32_rndscaless_round_mask: 3386 ArgNum = 5; 3387 break; 3388 case X86::BI__builtin_ia32_vcvtsd2si64: 3389 case X86::BI__builtin_ia32_vcvtsd2si32: 3390 case X86::BI__builtin_ia32_vcvtsd2usi32: 3391 case X86::BI__builtin_ia32_vcvtsd2usi64: 3392 case X86::BI__builtin_ia32_vcvtss2si32: 3393 case X86::BI__builtin_ia32_vcvtss2si64: 3394 case X86::BI__builtin_ia32_vcvtss2usi32: 3395 case X86::BI__builtin_ia32_vcvtss2usi64: 3396 case X86::BI__builtin_ia32_sqrtpd512: 3397 case X86::BI__builtin_ia32_sqrtps512: 3398 ArgNum = 1; 3399 HasRC = true; 3400 break; 3401 case X86::BI__builtin_ia32_addpd512: 3402 case X86::BI__builtin_ia32_addps512: 3403 case X86::BI__builtin_ia32_divpd512: 3404 case X86::BI__builtin_ia32_divps512: 3405 case X86::BI__builtin_ia32_mulpd512: 3406 case X86::BI__builtin_ia32_mulps512: 3407 case X86::BI__builtin_ia32_subpd512: 3408 case X86::BI__builtin_ia32_subps512: 3409 case X86::BI__builtin_ia32_cvtsi2sd64: 3410 case X86::BI__builtin_ia32_cvtsi2ss32: 3411 case X86::BI__builtin_ia32_cvtsi2ss64: 3412 case X86::BI__builtin_ia32_cvtusi2sd64: 3413 case X86::BI__builtin_ia32_cvtusi2ss32: 3414 case X86::BI__builtin_ia32_cvtusi2ss64: 3415 ArgNum = 2; 3416 HasRC = true; 3417 break; 3418 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3419 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3420 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3421 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3422 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3423 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3424 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3425 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3426 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3427 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3428 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3429 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3430 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3431 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3432 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3433 ArgNum = 3; 3434 HasRC = true; 3435 break; 3436 case X86::BI__builtin_ia32_addss_round_mask: 3437 case X86::BI__builtin_ia32_addsd_round_mask: 3438 case X86::BI__builtin_ia32_divss_round_mask: 3439 case X86::BI__builtin_ia32_divsd_round_mask: 3440 case X86::BI__builtin_ia32_mulss_round_mask: 3441 case X86::BI__builtin_ia32_mulsd_round_mask: 3442 case X86::BI__builtin_ia32_subss_round_mask: 3443 case X86::BI__builtin_ia32_subsd_round_mask: 3444 case X86::BI__builtin_ia32_scalefpd512_mask: 3445 case X86::BI__builtin_ia32_scalefps512_mask: 3446 case X86::BI__builtin_ia32_scalefsd_round_mask: 3447 case X86::BI__builtin_ia32_scalefss_round_mask: 3448 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3449 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3450 case X86::BI__builtin_ia32_sqrtss_round_mask: 3451 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3452 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3453 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3454 case X86::BI__builtin_ia32_vfmaddss3_mask: 3455 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3456 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3457 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3458 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3459 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3460 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3461 case X86::BI__builtin_ia32_vfmaddps512_mask: 3462 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3463 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3464 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3465 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3466 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3467 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3468 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3469 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3470 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3471 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3472 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3473 ArgNum = 4; 3474 HasRC = true; 3475 break; 3476 } 3477 3478 llvm::APSInt Result; 3479 3480 // We can't check the value of a dependent argument. 3481 Expr *Arg = TheCall->getArg(ArgNum); 3482 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3483 return false; 3484 3485 // Check constant-ness first. 3486 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3487 return true; 3488 3489 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3490 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3491 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3492 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3493 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3494 Result == 8/*ROUND_NO_EXC*/ || 3495 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3496 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3497 return false; 3498 3499 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3500 << Arg->getSourceRange(); 3501 } 3502 3503 // Check if the gather/scatter scale is legal. 3504 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3505 CallExpr *TheCall) { 3506 unsigned ArgNum = 0; 3507 switch (BuiltinID) { 3508 default: 3509 return false; 3510 case X86::BI__builtin_ia32_gatherpfdpd: 3511 case X86::BI__builtin_ia32_gatherpfdps: 3512 case X86::BI__builtin_ia32_gatherpfqpd: 3513 case X86::BI__builtin_ia32_gatherpfqps: 3514 case X86::BI__builtin_ia32_scatterpfdpd: 3515 case X86::BI__builtin_ia32_scatterpfdps: 3516 case X86::BI__builtin_ia32_scatterpfqpd: 3517 case X86::BI__builtin_ia32_scatterpfqps: 3518 ArgNum = 3; 3519 break; 3520 case X86::BI__builtin_ia32_gatherd_pd: 3521 case X86::BI__builtin_ia32_gatherd_pd256: 3522 case X86::BI__builtin_ia32_gatherq_pd: 3523 case X86::BI__builtin_ia32_gatherq_pd256: 3524 case X86::BI__builtin_ia32_gatherd_ps: 3525 case X86::BI__builtin_ia32_gatherd_ps256: 3526 case X86::BI__builtin_ia32_gatherq_ps: 3527 case X86::BI__builtin_ia32_gatherq_ps256: 3528 case X86::BI__builtin_ia32_gatherd_q: 3529 case X86::BI__builtin_ia32_gatherd_q256: 3530 case X86::BI__builtin_ia32_gatherq_q: 3531 case X86::BI__builtin_ia32_gatherq_q256: 3532 case X86::BI__builtin_ia32_gatherd_d: 3533 case X86::BI__builtin_ia32_gatherd_d256: 3534 case X86::BI__builtin_ia32_gatherq_d: 3535 case X86::BI__builtin_ia32_gatherq_d256: 3536 case X86::BI__builtin_ia32_gather3div2df: 3537 case X86::BI__builtin_ia32_gather3div2di: 3538 case X86::BI__builtin_ia32_gather3div4df: 3539 case X86::BI__builtin_ia32_gather3div4di: 3540 case X86::BI__builtin_ia32_gather3div4sf: 3541 case X86::BI__builtin_ia32_gather3div4si: 3542 case X86::BI__builtin_ia32_gather3div8sf: 3543 case X86::BI__builtin_ia32_gather3div8si: 3544 case X86::BI__builtin_ia32_gather3siv2df: 3545 case X86::BI__builtin_ia32_gather3siv2di: 3546 case X86::BI__builtin_ia32_gather3siv4df: 3547 case X86::BI__builtin_ia32_gather3siv4di: 3548 case X86::BI__builtin_ia32_gather3siv4sf: 3549 case X86::BI__builtin_ia32_gather3siv4si: 3550 case X86::BI__builtin_ia32_gather3siv8sf: 3551 case X86::BI__builtin_ia32_gather3siv8si: 3552 case X86::BI__builtin_ia32_gathersiv8df: 3553 case X86::BI__builtin_ia32_gathersiv16sf: 3554 case X86::BI__builtin_ia32_gatherdiv8df: 3555 case X86::BI__builtin_ia32_gatherdiv16sf: 3556 case X86::BI__builtin_ia32_gathersiv8di: 3557 case X86::BI__builtin_ia32_gathersiv16si: 3558 case X86::BI__builtin_ia32_gatherdiv8di: 3559 case X86::BI__builtin_ia32_gatherdiv16si: 3560 case X86::BI__builtin_ia32_scatterdiv2df: 3561 case X86::BI__builtin_ia32_scatterdiv2di: 3562 case X86::BI__builtin_ia32_scatterdiv4df: 3563 case X86::BI__builtin_ia32_scatterdiv4di: 3564 case X86::BI__builtin_ia32_scatterdiv4sf: 3565 case X86::BI__builtin_ia32_scatterdiv4si: 3566 case X86::BI__builtin_ia32_scatterdiv8sf: 3567 case X86::BI__builtin_ia32_scatterdiv8si: 3568 case X86::BI__builtin_ia32_scattersiv2df: 3569 case X86::BI__builtin_ia32_scattersiv2di: 3570 case X86::BI__builtin_ia32_scattersiv4df: 3571 case X86::BI__builtin_ia32_scattersiv4di: 3572 case X86::BI__builtin_ia32_scattersiv4sf: 3573 case X86::BI__builtin_ia32_scattersiv4si: 3574 case X86::BI__builtin_ia32_scattersiv8sf: 3575 case X86::BI__builtin_ia32_scattersiv8si: 3576 case X86::BI__builtin_ia32_scattersiv8df: 3577 case X86::BI__builtin_ia32_scattersiv16sf: 3578 case X86::BI__builtin_ia32_scatterdiv8df: 3579 case X86::BI__builtin_ia32_scatterdiv16sf: 3580 case X86::BI__builtin_ia32_scattersiv8di: 3581 case X86::BI__builtin_ia32_scattersiv16si: 3582 case X86::BI__builtin_ia32_scatterdiv8di: 3583 case X86::BI__builtin_ia32_scatterdiv16si: 3584 ArgNum = 4; 3585 break; 3586 } 3587 3588 llvm::APSInt Result; 3589 3590 // We can't check the value of a dependent argument. 3591 Expr *Arg = TheCall->getArg(ArgNum); 3592 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3593 return false; 3594 3595 // Check constant-ness first. 3596 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3597 return true; 3598 3599 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3600 return false; 3601 3602 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3603 << Arg->getSourceRange(); 3604 } 3605 3606 enum { TileRegLow = 0, TileRegHigh = 7 }; 3607 3608 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3609 ArrayRef<int> ArgNums) { 3610 for (int ArgNum : ArgNums) { 3611 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3612 return true; 3613 } 3614 return false; 3615 } 3616 3617 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum) { 3618 return SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh); 3619 } 3620 3621 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3622 ArrayRef<int> ArgNums) { 3623 // Because the max number of tile register is TileRegHigh + 1, so here we use 3624 // each bit to represent the usage of them in bitset. 3625 std::bitset<TileRegHigh + 1> ArgValues; 3626 for (int ArgNum : ArgNums) { 3627 llvm::APSInt Arg; 3628 SemaBuiltinConstantArg(TheCall, ArgNum, Arg); 3629 int ArgExtValue = Arg.getExtValue(); 3630 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3631 "Incorrect tile register num."); 3632 if (ArgValues.test(ArgExtValue)) 3633 return Diag(TheCall->getBeginLoc(), 3634 diag::err_x86_builtin_tile_arg_duplicate) 3635 << TheCall->getArg(ArgNum)->getSourceRange(); 3636 ArgValues.set(ArgExtValue); 3637 } 3638 return false; 3639 } 3640 3641 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3642 ArrayRef<int> ArgNums) { 3643 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3644 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3645 } 3646 3647 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3648 switch (BuiltinID) { 3649 default: 3650 return false; 3651 case X86::BI__builtin_ia32_tileloadd64: 3652 case X86::BI__builtin_ia32_tileloaddt164: 3653 case X86::BI__builtin_ia32_tilestored64: 3654 case X86::BI__builtin_ia32_tilezero: 3655 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3656 case X86::BI__builtin_ia32_tdpbssd: 3657 case X86::BI__builtin_ia32_tdpbsud: 3658 case X86::BI__builtin_ia32_tdpbusd: 3659 case X86::BI__builtin_ia32_tdpbuud: 3660 case X86::BI__builtin_ia32_tdpbf16ps: 3661 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3662 } 3663 } 3664 static bool isX86_32Builtin(unsigned BuiltinID) { 3665 // These builtins only work on x86-32 targets. 3666 switch (BuiltinID) { 3667 case X86::BI__builtin_ia32_readeflags_u32: 3668 case X86::BI__builtin_ia32_writeeflags_u32: 3669 return true; 3670 } 3671 3672 return false; 3673 } 3674 3675 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3676 CallExpr *TheCall) { 3677 if (BuiltinID == X86::BI__builtin_cpu_supports) 3678 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3679 3680 if (BuiltinID == X86::BI__builtin_cpu_is) 3681 return SemaBuiltinCpuIs(*this, TI, TheCall); 3682 3683 // Check for 32-bit only builtins on a 64-bit target. 3684 const llvm::Triple &TT = TI.getTriple(); 3685 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3686 return Diag(TheCall->getCallee()->getBeginLoc(), 3687 diag::err_32_bit_builtin_64_bit_tgt); 3688 3689 // If the intrinsic has rounding or SAE make sure its valid. 3690 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3691 return true; 3692 3693 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3694 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3695 return true; 3696 3697 // If the intrinsic has a tile arguments, make sure they are valid. 3698 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3699 return true; 3700 3701 // For intrinsics which take an immediate value as part of the instruction, 3702 // range check them here. 3703 int i = 0, l = 0, u = 0; 3704 switch (BuiltinID) { 3705 default: 3706 return false; 3707 case X86::BI__builtin_ia32_vec_ext_v2si: 3708 case X86::BI__builtin_ia32_vec_ext_v2di: 3709 case X86::BI__builtin_ia32_vextractf128_pd256: 3710 case X86::BI__builtin_ia32_vextractf128_ps256: 3711 case X86::BI__builtin_ia32_vextractf128_si256: 3712 case X86::BI__builtin_ia32_extract128i256: 3713 case X86::BI__builtin_ia32_extractf64x4_mask: 3714 case X86::BI__builtin_ia32_extracti64x4_mask: 3715 case X86::BI__builtin_ia32_extractf32x8_mask: 3716 case X86::BI__builtin_ia32_extracti32x8_mask: 3717 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3718 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3719 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3720 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3721 i = 1; l = 0; u = 1; 3722 break; 3723 case X86::BI__builtin_ia32_vec_set_v2di: 3724 case X86::BI__builtin_ia32_vinsertf128_pd256: 3725 case X86::BI__builtin_ia32_vinsertf128_ps256: 3726 case X86::BI__builtin_ia32_vinsertf128_si256: 3727 case X86::BI__builtin_ia32_insert128i256: 3728 case X86::BI__builtin_ia32_insertf32x8: 3729 case X86::BI__builtin_ia32_inserti32x8: 3730 case X86::BI__builtin_ia32_insertf64x4: 3731 case X86::BI__builtin_ia32_inserti64x4: 3732 case X86::BI__builtin_ia32_insertf64x2_256: 3733 case X86::BI__builtin_ia32_inserti64x2_256: 3734 case X86::BI__builtin_ia32_insertf32x4_256: 3735 case X86::BI__builtin_ia32_inserti32x4_256: 3736 i = 2; l = 0; u = 1; 3737 break; 3738 case X86::BI__builtin_ia32_vpermilpd: 3739 case X86::BI__builtin_ia32_vec_ext_v4hi: 3740 case X86::BI__builtin_ia32_vec_ext_v4si: 3741 case X86::BI__builtin_ia32_vec_ext_v4sf: 3742 case X86::BI__builtin_ia32_vec_ext_v4di: 3743 case X86::BI__builtin_ia32_extractf32x4_mask: 3744 case X86::BI__builtin_ia32_extracti32x4_mask: 3745 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3746 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3747 i = 1; l = 0; u = 3; 3748 break; 3749 case X86::BI_mm_prefetch: 3750 case X86::BI__builtin_ia32_vec_ext_v8hi: 3751 case X86::BI__builtin_ia32_vec_ext_v8si: 3752 i = 1; l = 0; u = 7; 3753 break; 3754 case X86::BI__builtin_ia32_sha1rnds4: 3755 case X86::BI__builtin_ia32_blendpd: 3756 case X86::BI__builtin_ia32_shufpd: 3757 case X86::BI__builtin_ia32_vec_set_v4hi: 3758 case X86::BI__builtin_ia32_vec_set_v4si: 3759 case X86::BI__builtin_ia32_vec_set_v4di: 3760 case X86::BI__builtin_ia32_shuf_f32x4_256: 3761 case X86::BI__builtin_ia32_shuf_f64x2_256: 3762 case X86::BI__builtin_ia32_shuf_i32x4_256: 3763 case X86::BI__builtin_ia32_shuf_i64x2_256: 3764 case X86::BI__builtin_ia32_insertf64x2_512: 3765 case X86::BI__builtin_ia32_inserti64x2_512: 3766 case X86::BI__builtin_ia32_insertf32x4: 3767 case X86::BI__builtin_ia32_inserti32x4: 3768 i = 2; l = 0; u = 3; 3769 break; 3770 case X86::BI__builtin_ia32_vpermil2pd: 3771 case X86::BI__builtin_ia32_vpermil2pd256: 3772 case X86::BI__builtin_ia32_vpermil2ps: 3773 case X86::BI__builtin_ia32_vpermil2ps256: 3774 i = 3; l = 0; u = 3; 3775 break; 3776 case X86::BI__builtin_ia32_cmpb128_mask: 3777 case X86::BI__builtin_ia32_cmpw128_mask: 3778 case X86::BI__builtin_ia32_cmpd128_mask: 3779 case X86::BI__builtin_ia32_cmpq128_mask: 3780 case X86::BI__builtin_ia32_cmpb256_mask: 3781 case X86::BI__builtin_ia32_cmpw256_mask: 3782 case X86::BI__builtin_ia32_cmpd256_mask: 3783 case X86::BI__builtin_ia32_cmpq256_mask: 3784 case X86::BI__builtin_ia32_cmpb512_mask: 3785 case X86::BI__builtin_ia32_cmpw512_mask: 3786 case X86::BI__builtin_ia32_cmpd512_mask: 3787 case X86::BI__builtin_ia32_cmpq512_mask: 3788 case X86::BI__builtin_ia32_ucmpb128_mask: 3789 case X86::BI__builtin_ia32_ucmpw128_mask: 3790 case X86::BI__builtin_ia32_ucmpd128_mask: 3791 case X86::BI__builtin_ia32_ucmpq128_mask: 3792 case X86::BI__builtin_ia32_ucmpb256_mask: 3793 case X86::BI__builtin_ia32_ucmpw256_mask: 3794 case X86::BI__builtin_ia32_ucmpd256_mask: 3795 case X86::BI__builtin_ia32_ucmpq256_mask: 3796 case X86::BI__builtin_ia32_ucmpb512_mask: 3797 case X86::BI__builtin_ia32_ucmpw512_mask: 3798 case X86::BI__builtin_ia32_ucmpd512_mask: 3799 case X86::BI__builtin_ia32_ucmpq512_mask: 3800 case X86::BI__builtin_ia32_vpcomub: 3801 case X86::BI__builtin_ia32_vpcomuw: 3802 case X86::BI__builtin_ia32_vpcomud: 3803 case X86::BI__builtin_ia32_vpcomuq: 3804 case X86::BI__builtin_ia32_vpcomb: 3805 case X86::BI__builtin_ia32_vpcomw: 3806 case X86::BI__builtin_ia32_vpcomd: 3807 case X86::BI__builtin_ia32_vpcomq: 3808 case X86::BI__builtin_ia32_vec_set_v8hi: 3809 case X86::BI__builtin_ia32_vec_set_v8si: 3810 i = 2; l = 0; u = 7; 3811 break; 3812 case X86::BI__builtin_ia32_vpermilpd256: 3813 case X86::BI__builtin_ia32_roundps: 3814 case X86::BI__builtin_ia32_roundpd: 3815 case X86::BI__builtin_ia32_roundps256: 3816 case X86::BI__builtin_ia32_roundpd256: 3817 case X86::BI__builtin_ia32_getmantpd128_mask: 3818 case X86::BI__builtin_ia32_getmantpd256_mask: 3819 case X86::BI__builtin_ia32_getmantps128_mask: 3820 case X86::BI__builtin_ia32_getmantps256_mask: 3821 case X86::BI__builtin_ia32_getmantpd512_mask: 3822 case X86::BI__builtin_ia32_getmantps512_mask: 3823 case X86::BI__builtin_ia32_vec_ext_v16qi: 3824 case X86::BI__builtin_ia32_vec_ext_v16hi: 3825 i = 1; l = 0; u = 15; 3826 break; 3827 case X86::BI__builtin_ia32_pblendd128: 3828 case X86::BI__builtin_ia32_blendps: 3829 case X86::BI__builtin_ia32_blendpd256: 3830 case X86::BI__builtin_ia32_shufpd256: 3831 case X86::BI__builtin_ia32_roundss: 3832 case X86::BI__builtin_ia32_roundsd: 3833 case X86::BI__builtin_ia32_rangepd128_mask: 3834 case X86::BI__builtin_ia32_rangepd256_mask: 3835 case X86::BI__builtin_ia32_rangepd512_mask: 3836 case X86::BI__builtin_ia32_rangeps128_mask: 3837 case X86::BI__builtin_ia32_rangeps256_mask: 3838 case X86::BI__builtin_ia32_rangeps512_mask: 3839 case X86::BI__builtin_ia32_getmantsd_round_mask: 3840 case X86::BI__builtin_ia32_getmantss_round_mask: 3841 case X86::BI__builtin_ia32_vec_set_v16qi: 3842 case X86::BI__builtin_ia32_vec_set_v16hi: 3843 i = 2; l = 0; u = 15; 3844 break; 3845 case X86::BI__builtin_ia32_vec_ext_v32qi: 3846 i = 1; l = 0; u = 31; 3847 break; 3848 case X86::BI__builtin_ia32_cmpps: 3849 case X86::BI__builtin_ia32_cmpss: 3850 case X86::BI__builtin_ia32_cmppd: 3851 case X86::BI__builtin_ia32_cmpsd: 3852 case X86::BI__builtin_ia32_cmpps256: 3853 case X86::BI__builtin_ia32_cmppd256: 3854 case X86::BI__builtin_ia32_cmpps128_mask: 3855 case X86::BI__builtin_ia32_cmppd128_mask: 3856 case X86::BI__builtin_ia32_cmpps256_mask: 3857 case X86::BI__builtin_ia32_cmppd256_mask: 3858 case X86::BI__builtin_ia32_cmpps512_mask: 3859 case X86::BI__builtin_ia32_cmppd512_mask: 3860 case X86::BI__builtin_ia32_cmpsd_mask: 3861 case X86::BI__builtin_ia32_cmpss_mask: 3862 case X86::BI__builtin_ia32_vec_set_v32qi: 3863 i = 2; l = 0; u = 31; 3864 break; 3865 case X86::BI__builtin_ia32_permdf256: 3866 case X86::BI__builtin_ia32_permdi256: 3867 case X86::BI__builtin_ia32_permdf512: 3868 case X86::BI__builtin_ia32_permdi512: 3869 case X86::BI__builtin_ia32_vpermilps: 3870 case X86::BI__builtin_ia32_vpermilps256: 3871 case X86::BI__builtin_ia32_vpermilpd512: 3872 case X86::BI__builtin_ia32_vpermilps512: 3873 case X86::BI__builtin_ia32_pshufd: 3874 case X86::BI__builtin_ia32_pshufd256: 3875 case X86::BI__builtin_ia32_pshufd512: 3876 case X86::BI__builtin_ia32_pshufhw: 3877 case X86::BI__builtin_ia32_pshufhw256: 3878 case X86::BI__builtin_ia32_pshufhw512: 3879 case X86::BI__builtin_ia32_pshuflw: 3880 case X86::BI__builtin_ia32_pshuflw256: 3881 case X86::BI__builtin_ia32_pshuflw512: 3882 case X86::BI__builtin_ia32_vcvtps2ph: 3883 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3884 case X86::BI__builtin_ia32_vcvtps2ph256: 3885 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3886 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3887 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3888 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3889 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3890 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3891 case X86::BI__builtin_ia32_rndscaleps_mask: 3892 case X86::BI__builtin_ia32_rndscalepd_mask: 3893 case X86::BI__builtin_ia32_reducepd128_mask: 3894 case X86::BI__builtin_ia32_reducepd256_mask: 3895 case X86::BI__builtin_ia32_reducepd512_mask: 3896 case X86::BI__builtin_ia32_reduceps128_mask: 3897 case X86::BI__builtin_ia32_reduceps256_mask: 3898 case X86::BI__builtin_ia32_reduceps512_mask: 3899 case X86::BI__builtin_ia32_prold512: 3900 case X86::BI__builtin_ia32_prolq512: 3901 case X86::BI__builtin_ia32_prold128: 3902 case X86::BI__builtin_ia32_prold256: 3903 case X86::BI__builtin_ia32_prolq128: 3904 case X86::BI__builtin_ia32_prolq256: 3905 case X86::BI__builtin_ia32_prord512: 3906 case X86::BI__builtin_ia32_prorq512: 3907 case X86::BI__builtin_ia32_prord128: 3908 case X86::BI__builtin_ia32_prord256: 3909 case X86::BI__builtin_ia32_prorq128: 3910 case X86::BI__builtin_ia32_prorq256: 3911 case X86::BI__builtin_ia32_fpclasspd128_mask: 3912 case X86::BI__builtin_ia32_fpclasspd256_mask: 3913 case X86::BI__builtin_ia32_fpclassps128_mask: 3914 case X86::BI__builtin_ia32_fpclassps256_mask: 3915 case X86::BI__builtin_ia32_fpclassps512_mask: 3916 case X86::BI__builtin_ia32_fpclasspd512_mask: 3917 case X86::BI__builtin_ia32_fpclasssd_mask: 3918 case X86::BI__builtin_ia32_fpclassss_mask: 3919 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3920 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3921 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3922 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3923 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3924 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3925 case X86::BI__builtin_ia32_kshiftliqi: 3926 case X86::BI__builtin_ia32_kshiftlihi: 3927 case X86::BI__builtin_ia32_kshiftlisi: 3928 case X86::BI__builtin_ia32_kshiftlidi: 3929 case X86::BI__builtin_ia32_kshiftriqi: 3930 case X86::BI__builtin_ia32_kshiftrihi: 3931 case X86::BI__builtin_ia32_kshiftrisi: 3932 case X86::BI__builtin_ia32_kshiftridi: 3933 i = 1; l = 0; u = 255; 3934 break; 3935 case X86::BI__builtin_ia32_vperm2f128_pd256: 3936 case X86::BI__builtin_ia32_vperm2f128_ps256: 3937 case X86::BI__builtin_ia32_vperm2f128_si256: 3938 case X86::BI__builtin_ia32_permti256: 3939 case X86::BI__builtin_ia32_pblendw128: 3940 case X86::BI__builtin_ia32_pblendw256: 3941 case X86::BI__builtin_ia32_blendps256: 3942 case X86::BI__builtin_ia32_pblendd256: 3943 case X86::BI__builtin_ia32_palignr128: 3944 case X86::BI__builtin_ia32_palignr256: 3945 case X86::BI__builtin_ia32_palignr512: 3946 case X86::BI__builtin_ia32_alignq512: 3947 case X86::BI__builtin_ia32_alignd512: 3948 case X86::BI__builtin_ia32_alignd128: 3949 case X86::BI__builtin_ia32_alignd256: 3950 case X86::BI__builtin_ia32_alignq128: 3951 case X86::BI__builtin_ia32_alignq256: 3952 case X86::BI__builtin_ia32_vcomisd: 3953 case X86::BI__builtin_ia32_vcomiss: 3954 case X86::BI__builtin_ia32_shuf_f32x4: 3955 case X86::BI__builtin_ia32_shuf_f64x2: 3956 case X86::BI__builtin_ia32_shuf_i32x4: 3957 case X86::BI__builtin_ia32_shuf_i64x2: 3958 case X86::BI__builtin_ia32_shufpd512: 3959 case X86::BI__builtin_ia32_shufps: 3960 case X86::BI__builtin_ia32_shufps256: 3961 case X86::BI__builtin_ia32_shufps512: 3962 case X86::BI__builtin_ia32_dbpsadbw128: 3963 case X86::BI__builtin_ia32_dbpsadbw256: 3964 case X86::BI__builtin_ia32_dbpsadbw512: 3965 case X86::BI__builtin_ia32_vpshldd128: 3966 case X86::BI__builtin_ia32_vpshldd256: 3967 case X86::BI__builtin_ia32_vpshldd512: 3968 case X86::BI__builtin_ia32_vpshldq128: 3969 case X86::BI__builtin_ia32_vpshldq256: 3970 case X86::BI__builtin_ia32_vpshldq512: 3971 case X86::BI__builtin_ia32_vpshldw128: 3972 case X86::BI__builtin_ia32_vpshldw256: 3973 case X86::BI__builtin_ia32_vpshldw512: 3974 case X86::BI__builtin_ia32_vpshrdd128: 3975 case X86::BI__builtin_ia32_vpshrdd256: 3976 case X86::BI__builtin_ia32_vpshrdd512: 3977 case X86::BI__builtin_ia32_vpshrdq128: 3978 case X86::BI__builtin_ia32_vpshrdq256: 3979 case X86::BI__builtin_ia32_vpshrdq512: 3980 case X86::BI__builtin_ia32_vpshrdw128: 3981 case X86::BI__builtin_ia32_vpshrdw256: 3982 case X86::BI__builtin_ia32_vpshrdw512: 3983 i = 2; l = 0; u = 255; 3984 break; 3985 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3986 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3987 case X86::BI__builtin_ia32_fixupimmps512_mask: 3988 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3989 case X86::BI__builtin_ia32_fixupimmsd_mask: 3990 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3991 case X86::BI__builtin_ia32_fixupimmss_mask: 3992 case X86::BI__builtin_ia32_fixupimmss_maskz: 3993 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3994 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3995 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3996 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3997 case X86::BI__builtin_ia32_fixupimmps128_mask: 3998 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3999 case X86::BI__builtin_ia32_fixupimmps256_mask: 4000 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4001 case X86::BI__builtin_ia32_pternlogd512_mask: 4002 case X86::BI__builtin_ia32_pternlogd512_maskz: 4003 case X86::BI__builtin_ia32_pternlogq512_mask: 4004 case X86::BI__builtin_ia32_pternlogq512_maskz: 4005 case X86::BI__builtin_ia32_pternlogd128_mask: 4006 case X86::BI__builtin_ia32_pternlogd128_maskz: 4007 case X86::BI__builtin_ia32_pternlogd256_mask: 4008 case X86::BI__builtin_ia32_pternlogd256_maskz: 4009 case X86::BI__builtin_ia32_pternlogq128_mask: 4010 case X86::BI__builtin_ia32_pternlogq128_maskz: 4011 case X86::BI__builtin_ia32_pternlogq256_mask: 4012 case X86::BI__builtin_ia32_pternlogq256_maskz: 4013 i = 3; l = 0; u = 255; 4014 break; 4015 case X86::BI__builtin_ia32_gatherpfdpd: 4016 case X86::BI__builtin_ia32_gatherpfdps: 4017 case X86::BI__builtin_ia32_gatherpfqpd: 4018 case X86::BI__builtin_ia32_gatherpfqps: 4019 case X86::BI__builtin_ia32_scatterpfdpd: 4020 case X86::BI__builtin_ia32_scatterpfdps: 4021 case X86::BI__builtin_ia32_scatterpfqpd: 4022 case X86::BI__builtin_ia32_scatterpfqps: 4023 i = 4; l = 2; u = 3; 4024 break; 4025 case X86::BI__builtin_ia32_reducesd_mask: 4026 case X86::BI__builtin_ia32_reducess_mask: 4027 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4028 case X86::BI__builtin_ia32_rndscaless_round_mask: 4029 i = 4; l = 0; u = 255; 4030 break; 4031 } 4032 4033 // Note that we don't force a hard error on the range check here, allowing 4034 // template-generated or macro-generated dead code to potentially have out-of- 4035 // range values. These need to code generate, but don't need to necessarily 4036 // make any sense. We use a warning that defaults to an error. 4037 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4038 } 4039 4040 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4041 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4042 /// Returns true when the format fits the function and the FormatStringInfo has 4043 /// been populated. 4044 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4045 FormatStringInfo *FSI) { 4046 FSI->HasVAListArg = Format->getFirstArg() == 0; 4047 FSI->FormatIdx = Format->getFormatIdx() - 1; 4048 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4049 4050 // The way the format attribute works in GCC, the implicit this argument 4051 // of member functions is counted. However, it doesn't appear in our own 4052 // lists, so decrement format_idx in that case. 4053 if (IsCXXMember) { 4054 if(FSI->FormatIdx == 0) 4055 return false; 4056 --FSI->FormatIdx; 4057 if (FSI->FirstDataArg != 0) 4058 --FSI->FirstDataArg; 4059 } 4060 return true; 4061 } 4062 4063 /// Checks if a the given expression evaluates to null. 4064 /// 4065 /// Returns true if the value evaluates to null. 4066 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4067 // If the expression has non-null type, it doesn't evaluate to null. 4068 if (auto nullability 4069 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4070 if (*nullability == NullabilityKind::NonNull) 4071 return false; 4072 } 4073 4074 // As a special case, transparent unions initialized with zero are 4075 // considered null for the purposes of the nonnull attribute. 4076 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4077 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4078 if (const CompoundLiteralExpr *CLE = 4079 dyn_cast<CompoundLiteralExpr>(Expr)) 4080 if (const InitListExpr *ILE = 4081 dyn_cast<InitListExpr>(CLE->getInitializer())) 4082 Expr = ILE->getInit(0); 4083 } 4084 4085 bool Result; 4086 return (!Expr->isValueDependent() && 4087 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4088 !Result); 4089 } 4090 4091 static void CheckNonNullArgument(Sema &S, 4092 const Expr *ArgExpr, 4093 SourceLocation CallSiteLoc) { 4094 if (CheckNonNullExpr(S, ArgExpr)) 4095 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4096 S.PDiag(diag::warn_null_arg) 4097 << ArgExpr->getSourceRange()); 4098 } 4099 4100 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4101 FormatStringInfo FSI; 4102 if ((GetFormatStringType(Format) == FST_NSString) && 4103 getFormatStringInfo(Format, false, &FSI)) { 4104 Idx = FSI.FormatIdx; 4105 return true; 4106 } 4107 return false; 4108 } 4109 4110 /// Diagnose use of %s directive in an NSString which is being passed 4111 /// as formatting string to formatting method. 4112 static void 4113 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4114 const NamedDecl *FDecl, 4115 Expr **Args, 4116 unsigned NumArgs) { 4117 unsigned Idx = 0; 4118 bool Format = false; 4119 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4120 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4121 Idx = 2; 4122 Format = true; 4123 } 4124 else 4125 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4126 if (S.GetFormatNSStringIdx(I, Idx)) { 4127 Format = true; 4128 break; 4129 } 4130 } 4131 if (!Format || NumArgs <= Idx) 4132 return; 4133 const Expr *FormatExpr = Args[Idx]; 4134 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4135 FormatExpr = CSCE->getSubExpr(); 4136 const StringLiteral *FormatString; 4137 if (const ObjCStringLiteral *OSL = 4138 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4139 FormatString = OSL->getString(); 4140 else 4141 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4142 if (!FormatString) 4143 return; 4144 if (S.FormatStringHasSArg(FormatString)) { 4145 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4146 << "%s" << 1 << 1; 4147 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4148 << FDecl->getDeclName(); 4149 } 4150 } 4151 4152 /// Determine whether the given type has a non-null nullability annotation. 4153 static bool isNonNullType(ASTContext &ctx, QualType type) { 4154 if (auto nullability = type->getNullability(ctx)) 4155 return *nullability == NullabilityKind::NonNull; 4156 4157 return false; 4158 } 4159 4160 static void CheckNonNullArguments(Sema &S, 4161 const NamedDecl *FDecl, 4162 const FunctionProtoType *Proto, 4163 ArrayRef<const Expr *> Args, 4164 SourceLocation CallSiteLoc) { 4165 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4166 4167 // Already checked by by constant evaluator. 4168 if (S.isConstantEvaluated()) 4169 return; 4170 // Check the attributes attached to the method/function itself. 4171 llvm::SmallBitVector NonNullArgs; 4172 if (FDecl) { 4173 // Handle the nonnull attribute on the function/method declaration itself. 4174 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4175 if (!NonNull->args_size()) { 4176 // Easy case: all pointer arguments are nonnull. 4177 for (const auto *Arg : Args) 4178 if (S.isValidPointerAttrType(Arg->getType())) 4179 CheckNonNullArgument(S, Arg, CallSiteLoc); 4180 return; 4181 } 4182 4183 for (const ParamIdx &Idx : NonNull->args()) { 4184 unsigned IdxAST = Idx.getASTIndex(); 4185 if (IdxAST >= Args.size()) 4186 continue; 4187 if (NonNullArgs.empty()) 4188 NonNullArgs.resize(Args.size()); 4189 NonNullArgs.set(IdxAST); 4190 } 4191 } 4192 } 4193 4194 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4195 // Handle the nonnull attribute on the parameters of the 4196 // function/method. 4197 ArrayRef<ParmVarDecl*> parms; 4198 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4199 parms = FD->parameters(); 4200 else 4201 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4202 4203 unsigned ParamIndex = 0; 4204 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4205 I != E; ++I, ++ParamIndex) { 4206 const ParmVarDecl *PVD = *I; 4207 if (PVD->hasAttr<NonNullAttr>() || 4208 isNonNullType(S.Context, PVD->getType())) { 4209 if (NonNullArgs.empty()) 4210 NonNullArgs.resize(Args.size()); 4211 4212 NonNullArgs.set(ParamIndex); 4213 } 4214 } 4215 } else { 4216 // If we have a non-function, non-method declaration but no 4217 // function prototype, try to dig out the function prototype. 4218 if (!Proto) { 4219 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4220 QualType type = VD->getType().getNonReferenceType(); 4221 if (auto pointerType = type->getAs<PointerType>()) 4222 type = pointerType->getPointeeType(); 4223 else if (auto blockType = type->getAs<BlockPointerType>()) 4224 type = blockType->getPointeeType(); 4225 // FIXME: data member pointers? 4226 4227 // Dig out the function prototype, if there is one. 4228 Proto = type->getAs<FunctionProtoType>(); 4229 } 4230 } 4231 4232 // Fill in non-null argument information from the nullability 4233 // information on the parameter types (if we have them). 4234 if (Proto) { 4235 unsigned Index = 0; 4236 for (auto paramType : Proto->getParamTypes()) { 4237 if (isNonNullType(S.Context, paramType)) { 4238 if (NonNullArgs.empty()) 4239 NonNullArgs.resize(Args.size()); 4240 4241 NonNullArgs.set(Index); 4242 } 4243 4244 ++Index; 4245 } 4246 } 4247 } 4248 4249 // Check for non-null arguments. 4250 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4251 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4252 if (NonNullArgs[ArgIndex]) 4253 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4254 } 4255 } 4256 4257 /// Handles the checks for format strings, non-POD arguments to vararg 4258 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4259 /// attributes. 4260 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4261 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4262 bool IsMemberFunction, SourceLocation Loc, 4263 SourceRange Range, VariadicCallType CallType) { 4264 // FIXME: We should check as much as we can in the template definition. 4265 if (CurContext->isDependentContext()) 4266 return; 4267 4268 // Printf and scanf checking. 4269 llvm::SmallBitVector CheckedVarArgs; 4270 if (FDecl) { 4271 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4272 // Only create vector if there are format attributes. 4273 CheckedVarArgs.resize(Args.size()); 4274 4275 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4276 CheckedVarArgs); 4277 } 4278 } 4279 4280 // Refuse POD arguments that weren't caught by the format string 4281 // checks above. 4282 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4283 if (CallType != VariadicDoesNotApply && 4284 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4285 unsigned NumParams = Proto ? Proto->getNumParams() 4286 : FDecl && isa<FunctionDecl>(FDecl) 4287 ? cast<FunctionDecl>(FDecl)->getNumParams() 4288 : FDecl && isa<ObjCMethodDecl>(FDecl) 4289 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4290 : 0; 4291 4292 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4293 // Args[ArgIdx] can be null in malformed code. 4294 if (const Expr *Arg = Args[ArgIdx]) { 4295 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4296 checkVariadicArgument(Arg, CallType); 4297 } 4298 } 4299 } 4300 4301 if (FDecl || Proto) { 4302 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4303 4304 // Type safety checking. 4305 if (FDecl) { 4306 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4307 CheckArgumentWithTypeTag(I, Args, Loc); 4308 } 4309 } 4310 4311 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4312 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4313 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4314 if (!Arg->isValueDependent()) { 4315 Expr::EvalResult Align; 4316 if (Arg->EvaluateAsInt(Align, Context)) { 4317 const llvm::APSInt &I = Align.Val.getInt(); 4318 if (!I.isPowerOf2()) 4319 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4320 << Arg->getSourceRange(); 4321 4322 if (I > Sema::MaximumAlignment) 4323 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4324 << Arg->getSourceRange() << Sema::MaximumAlignment; 4325 } 4326 } 4327 } 4328 4329 if (FD) 4330 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4331 } 4332 4333 /// CheckConstructorCall - Check a constructor call for correctness and safety 4334 /// properties not enforced by the C type system. 4335 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4336 ArrayRef<const Expr *> Args, 4337 const FunctionProtoType *Proto, 4338 SourceLocation Loc) { 4339 VariadicCallType CallType = 4340 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4341 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4342 Loc, SourceRange(), CallType); 4343 } 4344 4345 /// CheckFunctionCall - Check a direct function call for various correctness 4346 /// and safety properties not strictly enforced by the C type system. 4347 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4348 const FunctionProtoType *Proto) { 4349 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4350 isa<CXXMethodDecl>(FDecl); 4351 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4352 IsMemberOperatorCall; 4353 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4354 TheCall->getCallee()); 4355 Expr** Args = TheCall->getArgs(); 4356 unsigned NumArgs = TheCall->getNumArgs(); 4357 4358 Expr *ImplicitThis = nullptr; 4359 if (IsMemberOperatorCall) { 4360 // If this is a call to a member operator, hide the first argument 4361 // from checkCall. 4362 // FIXME: Our choice of AST representation here is less than ideal. 4363 ImplicitThis = Args[0]; 4364 ++Args; 4365 --NumArgs; 4366 } else if (IsMemberFunction) 4367 ImplicitThis = 4368 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4369 4370 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4371 IsMemberFunction, TheCall->getRParenLoc(), 4372 TheCall->getCallee()->getSourceRange(), CallType); 4373 4374 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4375 // None of the checks below are needed for functions that don't have 4376 // simple names (e.g., C++ conversion functions). 4377 if (!FnInfo) 4378 return false; 4379 4380 CheckAbsoluteValueFunction(TheCall, FDecl); 4381 CheckMaxUnsignedZero(TheCall, FDecl); 4382 4383 if (getLangOpts().ObjC) 4384 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4385 4386 unsigned CMId = FDecl->getMemoryFunctionKind(); 4387 if (CMId == 0) 4388 return false; 4389 4390 // Handle memory setting and copying functions. 4391 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4392 CheckStrlcpycatArguments(TheCall, FnInfo); 4393 else if (CMId == Builtin::BIstrncat) 4394 CheckStrncatArguments(TheCall, FnInfo); 4395 else 4396 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4397 4398 return false; 4399 } 4400 4401 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4402 ArrayRef<const Expr *> Args) { 4403 VariadicCallType CallType = 4404 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4405 4406 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4407 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4408 CallType); 4409 4410 return false; 4411 } 4412 4413 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4414 const FunctionProtoType *Proto) { 4415 QualType Ty; 4416 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4417 Ty = V->getType().getNonReferenceType(); 4418 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4419 Ty = F->getType().getNonReferenceType(); 4420 else 4421 return false; 4422 4423 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4424 !Ty->isFunctionProtoType()) 4425 return false; 4426 4427 VariadicCallType CallType; 4428 if (!Proto || !Proto->isVariadic()) { 4429 CallType = VariadicDoesNotApply; 4430 } else if (Ty->isBlockPointerType()) { 4431 CallType = VariadicBlock; 4432 } else { // Ty->isFunctionPointerType() 4433 CallType = VariadicFunction; 4434 } 4435 4436 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4437 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4438 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4439 TheCall->getCallee()->getSourceRange(), CallType); 4440 4441 return false; 4442 } 4443 4444 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4445 /// such as function pointers returned from functions. 4446 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4447 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4448 TheCall->getCallee()); 4449 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4450 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4451 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4452 TheCall->getCallee()->getSourceRange(), CallType); 4453 4454 return false; 4455 } 4456 4457 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4458 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4459 return false; 4460 4461 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4462 switch (Op) { 4463 case AtomicExpr::AO__c11_atomic_init: 4464 case AtomicExpr::AO__opencl_atomic_init: 4465 llvm_unreachable("There is no ordering argument for an init"); 4466 4467 case AtomicExpr::AO__c11_atomic_load: 4468 case AtomicExpr::AO__opencl_atomic_load: 4469 case AtomicExpr::AO__atomic_load_n: 4470 case AtomicExpr::AO__atomic_load: 4471 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4472 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4473 4474 case AtomicExpr::AO__c11_atomic_store: 4475 case AtomicExpr::AO__opencl_atomic_store: 4476 case AtomicExpr::AO__atomic_store: 4477 case AtomicExpr::AO__atomic_store_n: 4478 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4479 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4480 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4481 4482 default: 4483 return true; 4484 } 4485 } 4486 4487 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4488 AtomicExpr::AtomicOp Op) { 4489 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4490 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4491 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4492 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4493 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4494 Op); 4495 } 4496 4497 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4498 SourceLocation RParenLoc, MultiExprArg Args, 4499 AtomicExpr::AtomicOp Op, 4500 AtomicArgumentOrder ArgOrder) { 4501 // All the non-OpenCL operations take one of the following forms. 4502 // The OpenCL operations take the __c11 forms with one extra argument for 4503 // synchronization scope. 4504 enum { 4505 // C __c11_atomic_init(A *, C) 4506 Init, 4507 4508 // C __c11_atomic_load(A *, int) 4509 Load, 4510 4511 // void __atomic_load(A *, CP, int) 4512 LoadCopy, 4513 4514 // void __atomic_store(A *, CP, int) 4515 Copy, 4516 4517 // C __c11_atomic_add(A *, M, int) 4518 Arithmetic, 4519 4520 // C __atomic_exchange_n(A *, CP, int) 4521 Xchg, 4522 4523 // void __atomic_exchange(A *, C *, CP, int) 4524 GNUXchg, 4525 4526 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4527 C11CmpXchg, 4528 4529 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4530 GNUCmpXchg 4531 } Form = Init; 4532 4533 const unsigned NumForm = GNUCmpXchg + 1; 4534 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4535 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4536 // where: 4537 // C is an appropriate type, 4538 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4539 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4540 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4541 // the int parameters are for orderings. 4542 4543 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4544 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4545 "need to update code for modified forms"); 4546 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4547 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4548 AtomicExpr::AO__atomic_load, 4549 "need to update code for modified C11 atomics"); 4550 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4551 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4552 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4553 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4554 IsOpenCL; 4555 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4556 Op == AtomicExpr::AO__atomic_store_n || 4557 Op == AtomicExpr::AO__atomic_exchange_n || 4558 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4559 bool IsAddSub = false; 4560 4561 switch (Op) { 4562 case AtomicExpr::AO__c11_atomic_init: 4563 case AtomicExpr::AO__opencl_atomic_init: 4564 Form = Init; 4565 break; 4566 4567 case AtomicExpr::AO__c11_atomic_load: 4568 case AtomicExpr::AO__opencl_atomic_load: 4569 case AtomicExpr::AO__atomic_load_n: 4570 Form = Load; 4571 break; 4572 4573 case AtomicExpr::AO__atomic_load: 4574 Form = LoadCopy; 4575 break; 4576 4577 case AtomicExpr::AO__c11_atomic_store: 4578 case AtomicExpr::AO__opencl_atomic_store: 4579 case AtomicExpr::AO__atomic_store: 4580 case AtomicExpr::AO__atomic_store_n: 4581 Form = Copy; 4582 break; 4583 4584 case AtomicExpr::AO__c11_atomic_fetch_add: 4585 case AtomicExpr::AO__c11_atomic_fetch_sub: 4586 case AtomicExpr::AO__opencl_atomic_fetch_add: 4587 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4588 case AtomicExpr::AO__atomic_fetch_add: 4589 case AtomicExpr::AO__atomic_fetch_sub: 4590 case AtomicExpr::AO__atomic_add_fetch: 4591 case AtomicExpr::AO__atomic_sub_fetch: 4592 IsAddSub = true; 4593 LLVM_FALLTHROUGH; 4594 case AtomicExpr::AO__c11_atomic_fetch_and: 4595 case AtomicExpr::AO__c11_atomic_fetch_or: 4596 case AtomicExpr::AO__c11_atomic_fetch_xor: 4597 case AtomicExpr::AO__opencl_atomic_fetch_and: 4598 case AtomicExpr::AO__opencl_atomic_fetch_or: 4599 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4600 case AtomicExpr::AO__atomic_fetch_and: 4601 case AtomicExpr::AO__atomic_fetch_or: 4602 case AtomicExpr::AO__atomic_fetch_xor: 4603 case AtomicExpr::AO__atomic_fetch_nand: 4604 case AtomicExpr::AO__atomic_and_fetch: 4605 case AtomicExpr::AO__atomic_or_fetch: 4606 case AtomicExpr::AO__atomic_xor_fetch: 4607 case AtomicExpr::AO__atomic_nand_fetch: 4608 case AtomicExpr::AO__c11_atomic_fetch_min: 4609 case AtomicExpr::AO__c11_atomic_fetch_max: 4610 case AtomicExpr::AO__opencl_atomic_fetch_min: 4611 case AtomicExpr::AO__opencl_atomic_fetch_max: 4612 case AtomicExpr::AO__atomic_min_fetch: 4613 case AtomicExpr::AO__atomic_max_fetch: 4614 case AtomicExpr::AO__atomic_fetch_min: 4615 case AtomicExpr::AO__atomic_fetch_max: 4616 Form = Arithmetic; 4617 break; 4618 4619 case AtomicExpr::AO__c11_atomic_exchange: 4620 case AtomicExpr::AO__opencl_atomic_exchange: 4621 case AtomicExpr::AO__atomic_exchange_n: 4622 Form = Xchg; 4623 break; 4624 4625 case AtomicExpr::AO__atomic_exchange: 4626 Form = GNUXchg; 4627 break; 4628 4629 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4630 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4631 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4632 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4633 Form = C11CmpXchg; 4634 break; 4635 4636 case AtomicExpr::AO__atomic_compare_exchange: 4637 case AtomicExpr::AO__atomic_compare_exchange_n: 4638 Form = GNUCmpXchg; 4639 break; 4640 } 4641 4642 unsigned AdjustedNumArgs = NumArgs[Form]; 4643 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4644 ++AdjustedNumArgs; 4645 // Check we have the right number of arguments. 4646 if (Args.size() < AdjustedNumArgs) { 4647 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4648 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4649 << ExprRange; 4650 return ExprError(); 4651 } else if (Args.size() > AdjustedNumArgs) { 4652 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4653 diag::err_typecheck_call_too_many_args) 4654 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4655 << ExprRange; 4656 return ExprError(); 4657 } 4658 4659 // Inspect the first argument of the atomic operation. 4660 Expr *Ptr = Args[0]; 4661 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4662 if (ConvertedPtr.isInvalid()) 4663 return ExprError(); 4664 4665 Ptr = ConvertedPtr.get(); 4666 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4667 if (!pointerType) { 4668 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4669 << Ptr->getType() << Ptr->getSourceRange(); 4670 return ExprError(); 4671 } 4672 4673 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4674 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4675 QualType ValType = AtomTy; // 'C' 4676 if (IsC11) { 4677 if (!AtomTy->isAtomicType()) { 4678 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4679 << Ptr->getType() << Ptr->getSourceRange(); 4680 return ExprError(); 4681 } 4682 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4683 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4684 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4685 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4686 << Ptr->getSourceRange(); 4687 return ExprError(); 4688 } 4689 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4690 } else if (Form != Load && Form != LoadCopy) { 4691 if (ValType.isConstQualified()) { 4692 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4693 << Ptr->getType() << Ptr->getSourceRange(); 4694 return ExprError(); 4695 } 4696 } 4697 4698 // For an arithmetic operation, the implied arithmetic must be well-formed. 4699 if (Form == Arithmetic) { 4700 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4701 if (IsAddSub && !ValType->isIntegerType() 4702 && !ValType->isPointerType()) { 4703 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4704 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4705 return ExprError(); 4706 } 4707 if (!IsAddSub && !ValType->isIntegerType()) { 4708 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4709 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4710 return ExprError(); 4711 } 4712 if (IsC11 && ValType->isPointerType() && 4713 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4714 diag::err_incomplete_type)) { 4715 return ExprError(); 4716 } 4717 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4718 // For __atomic_*_n operations, the value type must be a scalar integral or 4719 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4720 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4721 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4722 return ExprError(); 4723 } 4724 4725 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4726 !AtomTy->isScalarType()) { 4727 // For GNU atomics, require a trivially-copyable type. This is not part of 4728 // the GNU atomics specification, but we enforce it for sanity. 4729 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4730 << Ptr->getType() << Ptr->getSourceRange(); 4731 return ExprError(); 4732 } 4733 4734 switch (ValType.getObjCLifetime()) { 4735 case Qualifiers::OCL_None: 4736 case Qualifiers::OCL_ExplicitNone: 4737 // okay 4738 break; 4739 4740 case Qualifiers::OCL_Weak: 4741 case Qualifiers::OCL_Strong: 4742 case Qualifiers::OCL_Autoreleasing: 4743 // FIXME: Can this happen? By this point, ValType should be known 4744 // to be trivially copyable. 4745 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4746 << ValType << Ptr->getSourceRange(); 4747 return ExprError(); 4748 } 4749 4750 // All atomic operations have an overload which takes a pointer to a volatile 4751 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4752 // into the result or the other operands. Similarly atomic_load takes a 4753 // pointer to a const 'A'. 4754 ValType.removeLocalVolatile(); 4755 ValType.removeLocalConst(); 4756 QualType ResultType = ValType; 4757 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4758 Form == Init) 4759 ResultType = Context.VoidTy; 4760 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4761 ResultType = Context.BoolTy; 4762 4763 // The type of a parameter passed 'by value'. In the GNU atomics, such 4764 // arguments are actually passed as pointers. 4765 QualType ByValType = ValType; // 'CP' 4766 bool IsPassedByAddress = false; 4767 if (!IsC11 && !IsN) { 4768 ByValType = Ptr->getType(); 4769 IsPassedByAddress = true; 4770 } 4771 4772 SmallVector<Expr *, 5> APIOrderedArgs; 4773 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4774 APIOrderedArgs.push_back(Args[0]); 4775 switch (Form) { 4776 case Init: 4777 case Load: 4778 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4779 break; 4780 case LoadCopy: 4781 case Copy: 4782 case Arithmetic: 4783 case Xchg: 4784 APIOrderedArgs.push_back(Args[2]); // Val1 4785 APIOrderedArgs.push_back(Args[1]); // Order 4786 break; 4787 case GNUXchg: 4788 APIOrderedArgs.push_back(Args[2]); // Val1 4789 APIOrderedArgs.push_back(Args[3]); // Val2 4790 APIOrderedArgs.push_back(Args[1]); // Order 4791 break; 4792 case C11CmpXchg: 4793 APIOrderedArgs.push_back(Args[2]); // Val1 4794 APIOrderedArgs.push_back(Args[4]); // Val2 4795 APIOrderedArgs.push_back(Args[1]); // Order 4796 APIOrderedArgs.push_back(Args[3]); // OrderFail 4797 break; 4798 case GNUCmpXchg: 4799 APIOrderedArgs.push_back(Args[2]); // Val1 4800 APIOrderedArgs.push_back(Args[4]); // Val2 4801 APIOrderedArgs.push_back(Args[5]); // Weak 4802 APIOrderedArgs.push_back(Args[1]); // Order 4803 APIOrderedArgs.push_back(Args[3]); // OrderFail 4804 break; 4805 } 4806 } else 4807 APIOrderedArgs.append(Args.begin(), Args.end()); 4808 4809 // The first argument's non-CV pointer type is used to deduce the type of 4810 // subsequent arguments, except for: 4811 // - weak flag (always converted to bool) 4812 // - memory order (always converted to int) 4813 // - scope (always converted to int) 4814 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4815 QualType Ty; 4816 if (i < NumVals[Form] + 1) { 4817 switch (i) { 4818 case 0: 4819 // The first argument is always a pointer. It has a fixed type. 4820 // It is always dereferenced, a nullptr is undefined. 4821 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4822 // Nothing else to do: we already know all we want about this pointer. 4823 continue; 4824 case 1: 4825 // The second argument is the non-atomic operand. For arithmetic, this 4826 // is always passed by value, and for a compare_exchange it is always 4827 // passed by address. For the rest, GNU uses by-address and C11 uses 4828 // by-value. 4829 assert(Form != Load); 4830 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4831 Ty = ValType; 4832 else if (Form == Copy || Form == Xchg) { 4833 if (IsPassedByAddress) { 4834 // The value pointer is always dereferenced, a nullptr is undefined. 4835 CheckNonNullArgument(*this, APIOrderedArgs[i], 4836 ExprRange.getBegin()); 4837 } 4838 Ty = ByValType; 4839 } else if (Form == Arithmetic) 4840 Ty = Context.getPointerDiffType(); 4841 else { 4842 Expr *ValArg = APIOrderedArgs[i]; 4843 // The value pointer is always dereferenced, a nullptr is undefined. 4844 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4845 LangAS AS = LangAS::Default; 4846 // Keep address space of non-atomic pointer type. 4847 if (const PointerType *PtrTy = 4848 ValArg->getType()->getAs<PointerType>()) { 4849 AS = PtrTy->getPointeeType().getAddressSpace(); 4850 } 4851 Ty = Context.getPointerType( 4852 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4853 } 4854 break; 4855 case 2: 4856 // The third argument to compare_exchange / GNU exchange is the desired 4857 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4858 if (IsPassedByAddress) 4859 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4860 Ty = ByValType; 4861 break; 4862 case 3: 4863 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4864 Ty = Context.BoolTy; 4865 break; 4866 } 4867 } else { 4868 // The order(s) and scope are always converted to int. 4869 Ty = Context.IntTy; 4870 } 4871 4872 InitializedEntity Entity = 4873 InitializedEntity::InitializeParameter(Context, Ty, false); 4874 ExprResult Arg = APIOrderedArgs[i]; 4875 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4876 if (Arg.isInvalid()) 4877 return true; 4878 APIOrderedArgs[i] = Arg.get(); 4879 } 4880 4881 // Permute the arguments into a 'consistent' order. 4882 SmallVector<Expr*, 5> SubExprs; 4883 SubExprs.push_back(Ptr); 4884 switch (Form) { 4885 case Init: 4886 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4887 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4888 break; 4889 case Load: 4890 SubExprs.push_back(APIOrderedArgs[1]); // Order 4891 break; 4892 case LoadCopy: 4893 case Copy: 4894 case Arithmetic: 4895 case Xchg: 4896 SubExprs.push_back(APIOrderedArgs[2]); // Order 4897 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4898 break; 4899 case GNUXchg: 4900 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4901 SubExprs.push_back(APIOrderedArgs[3]); // Order 4902 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4903 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4904 break; 4905 case C11CmpXchg: 4906 SubExprs.push_back(APIOrderedArgs[3]); // Order 4907 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4908 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4909 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4910 break; 4911 case GNUCmpXchg: 4912 SubExprs.push_back(APIOrderedArgs[4]); // Order 4913 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4914 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4915 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4916 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4917 break; 4918 } 4919 4920 if (SubExprs.size() >= 2 && Form != Init) { 4921 if (Optional<llvm::APSInt> Result = 4922 SubExprs[1]->getIntegerConstantExpr(Context)) 4923 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 4924 Diag(SubExprs[1]->getBeginLoc(), 4925 diag::warn_atomic_op_has_invalid_memory_order) 4926 << SubExprs[1]->getSourceRange(); 4927 } 4928 4929 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4930 auto *Scope = Args[Args.size() - 1]; 4931 if (Optional<llvm::APSInt> Result = 4932 Scope->getIntegerConstantExpr(Context)) { 4933 if (!ScopeModel->isValid(Result->getZExtValue())) 4934 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4935 << Scope->getSourceRange(); 4936 } 4937 SubExprs.push_back(Scope); 4938 } 4939 4940 AtomicExpr *AE = new (Context) 4941 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4942 4943 if ((Op == AtomicExpr::AO__c11_atomic_load || 4944 Op == AtomicExpr::AO__c11_atomic_store || 4945 Op == AtomicExpr::AO__opencl_atomic_load || 4946 Op == AtomicExpr::AO__opencl_atomic_store ) && 4947 Context.AtomicUsesUnsupportedLibcall(AE)) 4948 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4949 << ((Op == AtomicExpr::AO__c11_atomic_load || 4950 Op == AtomicExpr::AO__opencl_atomic_load) 4951 ? 0 4952 : 1); 4953 4954 return AE; 4955 } 4956 4957 /// checkBuiltinArgument - Given a call to a builtin function, perform 4958 /// normal type-checking on the given argument, updating the call in 4959 /// place. This is useful when a builtin function requires custom 4960 /// type-checking for some of its arguments but not necessarily all of 4961 /// them. 4962 /// 4963 /// Returns true on error. 4964 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4965 FunctionDecl *Fn = E->getDirectCallee(); 4966 assert(Fn && "builtin call without direct callee!"); 4967 4968 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4969 InitializedEntity Entity = 4970 InitializedEntity::InitializeParameter(S.Context, Param); 4971 4972 ExprResult Arg = E->getArg(0); 4973 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4974 if (Arg.isInvalid()) 4975 return true; 4976 4977 E->setArg(ArgIndex, Arg.get()); 4978 return false; 4979 } 4980 4981 /// We have a call to a function like __sync_fetch_and_add, which is an 4982 /// overloaded function based on the pointer type of its first argument. 4983 /// The main BuildCallExpr routines have already promoted the types of 4984 /// arguments because all of these calls are prototyped as void(...). 4985 /// 4986 /// This function goes through and does final semantic checking for these 4987 /// builtins, as well as generating any warnings. 4988 ExprResult 4989 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4990 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4991 Expr *Callee = TheCall->getCallee(); 4992 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4993 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4994 4995 // Ensure that we have at least one argument to do type inference from. 4996 if (TheCall->getNumArgs() < 1) { 4997 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4998 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4999 return ExprError(); 5000 } 5001 5002 // Inspect the first argument of the atomic builtin. This should always be 5003 // a pointer type, whose element is an integral scalar or pointer type. 5004 // Because it is a pointer type, we don't have to worry about any implicit 5005 // casts here. 5006 // FIXME: We don't allow floating point scalars as input. 5007 Expr *FirstArg = TheCall->getArg(0); 5008 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5009 if (FirstArgResult.isInvalid()) 5010 return ExprError(); 5011 FirstArg = FirstArgResult.get(); 5012 TheCall->setArg(0, FirstArg); 5013 5014 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5015 if (!pointerType) { 5016 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5017 << FirstArg->getType() << FirstArg->getSourceRange(); 5018 return ExprError(); 5019 } 5020 5021 QualType ValType = pointerType->getPointeeType(); 5022 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5023 !ValType->isBlockPointerType()) { 5024 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5025 << FirstArg->getType() << FirstArg->getSourceRange(); 5026 return ExprError(); 5027 } 5028 5029 if (ValType.isConstQualified()) { 5030 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5031 << FirstArg->getType() << FirstArg->getSourceRange(); 5032 return ExprError(); 5033 } 5034 5035 switch (ValType.getObjCLifetime()) { 5036 case Qualifiers::OCL_None: 5037 case Qualifiers::OCL_ExplicitNone: 5038 // okay 5039 break; 5040 5041 case Qualifiers::OCL_Weak: 5042 case Qualifiers::OCL_Strong: 5043 case Qualifiers::OCL_Autoreleasing: 5044 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5045 << ValType << FirstArg->getSourceRange(); 5046 return ExprError(); 5047 } 5048 5049 // Strip any qualifiers off ValType. 5050 ValType = ValType.getUnqualifiedType(); 5051 5052 // The majority of builtins return a value, but a few have special return 5053 // types, so allow them to override appropriately below. 5054 QualType ResultType = ValType; 5055 5056 // We need to figure out which concrete builtin this maps onto. For example, 5057 // __sync_fetch_and_add with a 2 byte object turns into 5058 // __sync_fetch_and_add_2. 5059 #define BUILTIN_ROW(x) \ 5060 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5061 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5062 5063 static const unsigned BuiltinIndices[][5] = { 5064 BUILTIN_ROW(__sync_fetch_and_add), 5065 BUILTIN_ROW(__sync_fetch_and_sub), 5066 BUILTIN_ROW(__sync_fetch_and_or), 5067 BUILTIN_ROW(__sync_fetch_and_and), 5068 BUILTIN_ROW(__sync_fetch_and_xor), 5069 BUILTIN_ROW(__sync_fetch_and_nand), 5070 5071 BUILTIN_ROW(__sync_add_and_fetch), 5072 BUILTIN_ROW(__sync_sub_and_fetch), 5073 BUILTIN_ROW(__sync_and_and_fetch), 5074 BUILTIN_ROW(__sync_or_and_fetch), 5075 BUILTIN_ROW(__sync_xor_and_fetch), 5076 BUILTIN_ROW(__sync_nand_and_fetch), 5077 5078 BUILTIN_ROW(__sync_val_compare_and_swap), 5079 BUILTIN_ROW(__sync_bool_compare_and_swap), 5080 BUILTIN_ROW(__sync_lock_test_and_set), 5081 BUILTIN_ROW(__sync_lock_release), 5082 BUILTIN_ROW(__sync_swap) 5083 }; 5084 #undef BUILTIN_ROW 5085 5086 // Determine the index of the size. 5087 unsigned SizeIndex; 5088 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5089 case 1: SizeIndex = 0; break; 5090 case 2: SizeIndex = 1; break; 5091 case 4: SizeIndex = 2; break; 5092 case 8: SizeIndex = 3; break; 5093 case 16: SizeIndex = 4; break; 5094 default: 5095 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5096 << FirstArg->getType() << FirstArg->getSourceRange(); 5097 return ExprError(); 5098 } 5099 5100 // Each of these builtins has one pointer argument, followed by some number of 5101 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5102 // that we ignore. Find out which row of BuiltinIndices to read from as well 5103 // as the number of fixed args. 5104 unsigned BuiltinID = FDecl->getBuiltinID(); 5105 unsigned BuiltinIndex, NumFixed = 1; 5106 bool WarnAboutSemanticsChange = false; 5107 switch (BuiltinID) { 5108 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5109 case Builtin::BI__sync_fetch_and_add: 5110 case Builtin::BI__sync_fetch_and_add_1: 5111 case Builtin::BI__sync_fetch_and_add_2: 5112 case Builtin::BI__sync_fetch_and_add_4: 5113 case Builtin::BI__sync_fetch_and_add_8: 5114 case Builtin::BI__sync_fetch_and_add_16: 5115 BuiltinIndex = 0; 5116 break; 5117 5118 case Builtin::BI__sync_fetch_and_sub: 5119 case Builtin::BI__sync_fetch_and_sub_1: 5120 case Builtin::BI__sync_fetch_and_sub_2: 5121 case Builtin::BI__sync_fetch_and_sub_4: 5122 case Builtin::BI__sync_fetch_and_sub_8: 5123 case Builtin::BI__sync_fetch_and_sub_16: 5124 BuiltinIndex = 1; 5125 break; 5126 5127 case Builtin::BI__sync_fetch_and_or: 5128 case Builtin::BI__sync_fetch_and_or_1: 5129 case Builtin::BI__sync_fetch_and_or_2: 5130 case Builtin::BI__sync_fetch_and_or_4: 5131 case Builtin::BI__sync_fetch_and_or_8: 5132 case Builtin::BI__sync_fetch_and_or_16: 5133 BuiltinIndex = 2; 5134 break; 5135 5136 case Builtin::BI__sync_fetch_and_and: 5137 case Builtin::BI__sync_fetch_and_and_1: 5138 case Builtin::BI__sync_fetch_and_and_2: 5139 case Builtin::BI__sync_fetch_and_and_4: 5140 case Builtin::BI__sync_fetch_and_and_8: 5141 case Builtin::BI__sync_fetch_and_and_16: 5142 BuiltinIndex = 3; 5143 break; 5144 5145 case Builtin::BI__sync_fetch_and_xor: 5146 case Builtin::BI__sync_fetch_and_xor_1: 5147 case Builtin::BI__sync_fetch_and_xor_2: 5148 case Builtin::BI__sync_fetch_and_xor_4: 5149 case Builtin::BI__sync_fetch_and_xor_8: 5150 case Builtin::BI__sync_fetch_and_xor_16: 5151 BuiltinIndex = 4; 5152 break; 5153 5154 case Builtin::BI__sync_fetch_and_nand: 5155 case Builtin::BI__sync_fetch_and_nand_1: 5156 case Builtin::BI__sync_fetch_and_nand_2: 5157 case Builtin::BI__sync_fetch_and_nand_4: 5158 case Builtin::BI__sync_fetch_and_nand_8: 5159 case Builtin::BI__sync_fetch_and_nand_16: 5160 BuiltinIndex = 5; 5161 WarnAboutSemanticsChange = true; 5162 break; 5163 5164 case Builtin::BI__sync_add_and_fetch: 5165 case Builtin::BI__sync_add_and_fetch_1: 5166 case Builtin::BI__sync_add_and_fetch_2: 5167 case Builtin::BI__sync_add_and_fetch_4: 5168 case Builtin::BI__sync_add_and_fetch_8: 5169 case Builtin::BI__sync_add_and_fetch_16: 5170 BuiltinIndex = 6; 5171 break; 5172 5173 case Builtin::BI__sync_sub_and_fetch: 5174 case Builtin::BI__sync_sub_and_fetch_1: 5175 case Builtin::BI__sync_sub_and_fetch_2: 5176 case Builtin::BI__sync_sub_and_fetch_4: 5177 case Builtin::BI__sync_sub_and_fetch_8: 5178 case Builtin::BI__sync_sub_and_fetch_16: 5179 BuiltinIndex = 7; 5180 break; 5181 5182 case Builtin::BI__sync_and_and_fetch: 5183 case Builtin::BI__sync_and_and_fetch_1: 5184 case Builtin::BI__sync_and_and_fetch_2: 5185 case Builtin::BI__sync_and_and_fetch_4: 5186 case Builtin::BI__sync_and_and_fetch_8: 5187 case Builtin::BI__sync_and_and_fetch_16: 5188 BuiltinIndex = 8; 5189 break; 5190 5191 case Builtin::BI__sync_or_and_fetch: 5192 case Builtin::BI__sync_or_and_fetch_1: 5193 case Builtin::BI__sync_or_and_fetch_2: 5194 case Builtin::BI__sync_or_and_fetch_4: 5195 case Builtin::BI__sync_or_and_fetch_8: 5196 case Builtin::BI__sync_or_and_fetch_16: 5197 BuiltinIndex = 9; 5198 break; 5199 5200 case Builtin::BI__sync_xor_and_fetch: 5201 case Builtin::BI__sync_xor_and_fetch_1: 5202 case Builtin::BI__sync_xor_and_fetch_2: 5203 case Builtin::BI__sync_xor_and_fetch_4: 5204 case Builtin::BI__sync_xor_and_fetch_8: 5205 case Builtin::BI__sync_xor_and_fetch_16: 5206 BuiltinIndex = 10; 5207 break; 5208 5209 case Builtin::BI__sync_nand_and_fetch: 5210 case Builtin::BI__sync_nand_and_fetch_1: 5211 case Builtin::BI__sync_nand_and_fetch_2: 5212 case Builtin::BI__sync_nand_and_fetch_4: 5213 case Builtin::BI__sync_nand_and_fetch_8: 5214 case Builtin::BI__sync_nand_and_fetch_16: 5215 BuiltinIndex = 11; 5216 WarnAboutSemanticsChange = true; 5217 break; 5218 5219 case Builtin::BI__sync_val_compare_and_swap: 5220 case Builtin::BI__sync_val_compare_and_swap_1: 5221 case Builtin::BI__sync_val_compare_and_swap_2: 5222 case Builtin::BI__sync_val_compare_and_swap_4: 5223 case Builtin::BI__sync_val_compare_and_swap_8: 5224 case Builtin::BI__sync_val_compare_and_swap_16: 5225 BuiltinIndex = 12; 5226 NumFixed = 2; 5227 break; 5228 5229 case Builtin::BI__sync_bool_compare_and_swap: 5230 case Builtin::BI__sync_bool_compare_and_swap_1: 5231 case Builtin::BI__sync_bool_compare_and_swap_2: 5232 case Builtin::BI__sync_bool_compare_and_swap_4: 5233 case Builtin::BI__sync_bool_compare_and_swap_8: 5234 case Builtin::BI__sync_bool_compare_and_swap_16: 5235 BuiltinIndex = 13; 5236 NumFixed = 2; 5237 ResultType = Context.BoolTy; 5238 break; 5239 5240 case Builtin::BI__sync_lock_test_and_set: 5241 case Builtin::BI__sync_lock_test_and_set_1: 5242 case Builtin::BI__sync_lock_test_and_set_2: 5243 case Builtin::BI__sync_lock_test_and_set_4: 5244 case Builtin::BI__sync_lock_test_and_set_8: 5245 case Builtin::BI__sync_lock_test_and_set_16: 5246 BuiltinIndex = 14; 5247 break; 5248 5249 case Builtin::BI__sync_lock_release: 5250 case Builtin::BI__sync_lock_release_1: 5251 case Builtin::BI__sync_lock_release_2: 5252 case Builtin::BI__sync_lock_release_4: 5253 case Builtin::BI__sync_lock_release_8: 5254 case Builtin::BI__sync_lock_release_16: 5255 BuiltinIndex = 15; 5256 NumFixed = 0; 5257 ResultType = Context.VoidTy; 5258 break; 5259 5260 case Builtin::BI__sync_swap: 5261 case Builtin::BI__sync_swap_1: 5262 case Builtin::BI__sync_swap_2: 5263 case Builtin::BI__sync_swap_4: 5264 case Builtin::BI__sync_swap_8: 5265 case Builtin::BI__sync_swap_16: 5266 BuiltinIndex = 16; 5267 break; 5268 } 5269 5270 // Now that we know how many fixed arguments we expect, first check that we 5271 // have at least that many. 5272 if (TheCall->getNumArgs() < 1+NumFixed) { 5273 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5274 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5275 << Callee->getSourceRange(); 5276 return ExprError(); 5277 } 5278 5279 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5280 << Callee->getSourceRange(); 5281 5282 if (WarnAboutSemanticsChange) { 5283 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5284 << Callee->getSourceRange(); 5285 } 5286 5287 // Get the decl for the concrete builtin from this, we can tell what the 5288 // concrete integer type we should convert to is. 5289 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5290 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5291 FunctionDecl *NewBuiltinDecl; 5292 if (NewBuiltinID == BuiltinID) 5293 NewBuiltinDecl = FDecl; 5294 else { 5295 // Perform builtin lookup to avoid redeclaring it. 5296 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5297 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5298 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5299 assert(Res.getFoundDecl()); 5300 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5301 if (!NewBuiltinDecl) 5302 return ExprError(); 5303 } 5304 5305 // The first argument --- the pointer --- has a fixed type; we 5306 // deduce the types of the rest of the arguments accordingly. Walk 5307 // the remaining arguments, converting them to the deduced value type. 5308 for (unsigned i = 0; i != NumFixed; ++i) { 5309 ExprResult Arg = TheCall->getArg(i+1); 5310 5311 // GCC does an implicit conversion to the pointer or integer ValType. This 5312 // can fail in some cases (1i -> int**), check for this error case now. 5313 // Initialize the argument. 5314 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5315 ValType, /*consume*/ false); 5316 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5317 if (Arg.isInvalid()) 5318 return ExprError(); 5319 5320 // Okay, we have something that *can* be converted to the right type. Check 5321 // to see if there is a potentially weird extension going on here. This can 5322 // happen when you do an atomic operation on something like an char* and 5323 // pass in 42. The 42 gets converted to char. This is even more strange 5324 // for things like 45.123 -> char, etc. 5325 // FIXME: Do this check. 5326 TheCall->setArg(i+1, Arg.get()); 5327 } 5328 5329 // Create a new DeclRefExpr to refer to the new decl. 5330 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5331 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5332 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5333 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5334 5335 // Set the callee in the CallExpr. 5336 // FIXME: This loses syntactic information. 5337 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5338 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5339 CK_BuiltinFnToFnPtr); 5340 TheCall->setCallee(PromotedCall.get()); 5341 5342 // Change the result type of the call to match the original value type. This 5343 // is arbitrary, but the codegen for these builtins ins design to handle it 5344 // gracefully. 5345 TheCall->setType(ResultType); 5346 5347 // Prohibit use of _ExtInt with atomic builtins. 5348 // The arguments would have already been converted to the first argument's 5349 // type, so only need to check the first argument. 5350 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5351 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5352 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5353 return ExprError(); 5354 } 5355 5356 return TheCallResult; 5357 } 5358 5359 /// SemaBuiltinNontemporalOverloaded - We have a call to 5360 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5361 /// overloaded function based on the pointer type of its last argument. 5362 /// 5363 /// This function goes through and does final semantic checking for these 5364 /// builtins. 5365 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5366 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5367 DeclRefExpr *DRE = 5368 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5369 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5370 unsigned BuiltinID = FDecl->getBuiltinID(); 5371 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5372 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5373 "Unexpected nontemporal load/store builtin!"); 5374 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5375 unsigned numArgs = isStore ? 2 : 1; 5376 5377 // Ensure that we have the proper number of arguments. 5378 if (checkArgCount(*this, TheCall, numArgs)) 5379 return ExprError(); 5380 5381 // Inspect the last argument of the nontemporal builtin. This should always 5382 // be a pointer type, from which we imply the type of the memory access. 5383 // Because it is a pointer type, we don't have to worry about any implicit 5384 // casts here. 5385 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5386 ExprResult PointerArgResult = 5387 DefaultFunctionArrayLvalueConversion(PointerArg); 5388 5389 if (PointerArgResult.isInvalid()) 5390 return ExprError(); 5391 PointerArg = PointerArgResult.get(); 5392 TheCall->setArg(numArgs - 1, PointerArg); 5393 5394 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5395 if (!pointerType) { 5396 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5397 << PointerArg->getType() << PointerArg->getSourceRange(); 5398 return ExprError(); 5399 } 5400 5401 QualType ValType = pointerType->getPointeeType(); 5402 5403 // Strip any qualifiers off ValType. 5404 ValType = ValType.getUnqualifiedType(); 5405 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5406 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5407 !ValType->isVectorType()) { 5408 Diag(DRE->getBeginLoc(), 5409 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5410 << PointerArg->getType() << PointerArg->getSourceRange(); 5411 return ExprError(); 5412 } 5413 5414 if (!isStore) { 5415 TheCall->setType(ValType); 5416 return TheCallResult; 5417 } 5418 5419 ExprResult ValArg = TheCall->getArg(0); 5420 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5421 Context, ValType, /*consume*/ false); 5422 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5423 if (ValArg.isInvalid()) 5424 return ExprError(); 5425 5426 TheCall->setArg(0, ValArg.get()); 5427 TheCall->setType(Context.VoidTy); 5428 return TheCallResult; 5429 } 5430 5431 /// CheckObjCString - Checks that the argument to the builtin 5432 /// CFString constructor is correct 5433 /// Note: It might also make sense to do the UTF-16 conversion here (would 5434 /// simplify the backend). 5435 bool Sema::CheckObjCString(Expr *Arg) { 5436 Arg = Arg->IgnoreParenCasts(); 5437 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5438 5439 if (!Literal || !Literal->isAscii()) { 5440 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5441 << Arg->getSourceRange(); 5442 return true; 5443 } 5444 5445 if (Literal->containsNonAsciiOrNull()) { 5446 StringRef String = Literal->getString(); 5447 unsigned NumBytes = String.size(); 5448 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5449 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5450 llvm::UTF16 *ToPtr = &ToBuf[0]; 5451 5452 llvm::ConversionResult Result = 5453 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5454 ToPtr + NumBytes, llvm::strictConversion); 5455 // Check for conversion failure. 5456 if (Result != llvm::conversionOK) 5457 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5458 << Arg->getSourceRange(); 5459 } 5460 return false; 5461 } 5462 5463 /// CheckObjCString - Checks that the format string argument to the os_log() 5464 /// and os_trace() functions is correct, and converts it to const char *. 5465 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5466 Arg = Arg->IgnoreParenCasts(); 5467 auto *Literal = dyn_cast<StringLiteral>(Arg); 5468 if (!Literal) { 5469 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5470 Literal = ObjcLiteral->getString(); 5471 } 5472 } 5473 5474 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5475 return ExprError( 5476 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5477 << Arg->getSourceRange()); 5478 } 5479 5480 ExprResult Result(Literal); 5481 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5482 InitializedEntity Entity = 5483 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5484 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5485 return Result; 5486 } 5487 5488 /// Check that the user is calling the appropriate va_start builtin for the 5489 /// target and calling convention. 5490 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5491 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5492 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5493 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5494 TT.getArch() == llvm::Triple::aarch64_32); 5495 bool IsWindows = TT.isOSWindows(); 5496 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5497 if (IsX64 || IsAArch64) { 5498 CallingConv CC = CC_C; 5499 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5500 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5501 if (IsMSVAStart) { 5502 // Don't allow this in System V ABI functions. 5503 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5504 return S.Diag(Fn->getBeginLoc(), 5505 diag::err_ms_va_start_used_in_sysv_function); 5506 } else { 5507 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5508 // On x64 Windows, don't allow this in System V ABI functions. 5509 // (Yes, that means there's no corresponding way to support variadic 5510 // System V ABI functions on Windows.) 5511 if ((IsWindows && CC == CC_X86_64SysV) || 5512 (!IsWindows && CC == CC_Win64)) 5513 return S.Diag(Fn->getBeginLoc(), 5514 diag::err_va_start_used_in_wrong_abi_function) 5515 << !IsWindows; 5516 } 5517 return false; 5518 } 5519 5520 if (IsMSVAStart) 5521 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5522 return false; 5523 } 5524 5525 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5526 ParmVarDecl **LastParam = nullptr) { 5527 // Determine whether the current function, block, or obj-c method is variadic 5528 // and get its parameter list. 5529 bool IsVariadic = false; 5530 ArrayRef<ParmVarDecl *> Params; 5531 DeclContext *Caller = S.CurContext; 5532 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5533 IsVariadic = Block->isVariadic(); 5534 Params = Block->parameters(); 5535 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5536 IsVariadic = FD->isVariadic(); 5537 Params = FD->parameters(); 5538 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5539 IsVariadic = MD->isVariadic(); 5540 // FIXME: This isn't correct for methods (results in bogus warning). 5541 Params = MD->parameters(); 5542 } else if (isa<CapturedDecl>(Caller)) { 5543 // We don't support va_start in a CapturedDecl. 5544 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5545 return true; 5546 } else { 5547 // This must be some other declcontext that parses exprs. 5548 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5549 return true; 5550 } 5551 5552 if (!IsVariadic) { 5553 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5554 return true; 5555 } 5556 5557 if (LastParam) 5558 *LastParam = Params.empty() ? nullptr : Params.back(); 5559 5560 return false; 5561 } 5562 5563 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5564 /// for validity. Emit an error and return true on failure; return false 5565 /// on success. 5566 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5567 Expr *Fn = TheCall->getCallee(); 5568 5569 if (checkVAStartABI(*this, BuiltinID, Fn)) 5570 return true; 5571 5572 if (checkArgCount(*this, TheCall, 2)) 5573 return true; 5574 5575 // Type-check the first argument normally. 5576 if (checkBuiltinArgument(*this, TheCall, 0)) 5577 return true; 5578 5579 // Check that the current function is variadic, and get its last parameter. 5580 ParmVarDecl *LastParam; 5581 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5582 return true; 5583 5584 // Verify that the second argument to the builtin is the last argument of the 5585 // current function or method. 5586 bool SecondArgIsLastNamedArgument = false; 5587 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5588 5589 // These are valid if SecondArgIsLastNamedArgument is false after the next 5590 // block. 5591 QualType Type; 5592 SourceLocation ParamLoc; 5593 bool IsCRegister = false; 5594 5595 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5596 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5597 SecondArgIsLastNamedArgument = PV == LastParam; 5598 5599 Type = PV->getType(); 5600 ParamLoc = PV->getLocation(); 5601 IsCRegister = 5602 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5603 } 5604 } 5605 5606 if (!SecondArgIsLastNamedArgument) 5607 Diag(TheCall->getArg(1)->getBeginLoc(), 5608 diag::warn_second_arg_of_va_start_not_last_named_param); 5609 else if (IsCRegister || Type->isReferenceType() || 5610 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5611 // Promotable integers are UB, but enumerations need a bit of 5612 // extra checking to see what their promotable type actually is. 5613 if (!Type->isPromotableIntegerType()) 5614 return false; 5615 if (!Type->isEnumeralType()) 5616 return true; 5617 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5618 return !(ED && 5619 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5620 }()) { 5621 unsigned Reason = 0; 5622 if (Type->isReferenceType()) Reason = 1; 5623 else if (IsCRegister) Reason = 2; 5624 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5625 Diag(ParamLoc, diag::note_parameter_type) << Type; 5626 } 5627 5628 TheCall->setType(Context.VoidTy); 5629 return false; 5630 } 5631 5632 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5633 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5634 // const char *named_addr); 5635 5636 Expr *Func = Call->getCallee(); 5637 5638 if (Call->getNumArgs() < 3) 5639 return Diag(Call->getEndLoc(), 5640 diag::err_typecheck_call_too_few_args_at_least) 5641 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5642 5643 // Type-check the first argument normally. 5644 if (checkBuiltinArgument(*this, Call, 0)) 5645 return true; 5646 5647 // Check that the current function is variadic. 5648 if (checkVAStartIsInVariadicFunction(*this, Func)) 5649 return true; 5650 5651 // __va_start on Windows does not validate the parameter qualifiers 5652 5653 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5654 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5655 5656 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5657 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5658 5659 const QualType &ConstCharPtrTy = 5660 Context.getPointerType(Context.CharTy.withConst()); 5661 if (!Arg1Ty->isPointerType() || 5662 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5663 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5664 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5665 << 0 /* qualifier difference */ 5666 << 3 /* parameter mismatch */ 5667 << 2 << Arg1->getType() << ConstCharPtrTy; 5668 5669 const QualType SizeTy = Context.getSizeType(); 5670 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5671 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5672 << Arg2->getType() << SizeTy << 1 /* different class */ 5673 << 0 /* qualifier difference */ 5674 << 3 /* parameter mismatch */ 5675 << 3 << Arg2->getType() << SizeTy; 5676 5677 return false; 5678 } 5679 5680 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5681 /// friends. This is declared to take (...), so we have to check everything. 5682 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5683 if (checkArgCount(*this, TheCall, 2)) 5684 return true; 5685 5686 ExprResult OrigArg0 = TheCall->getArg(0); 5687 ExprResult OrigArg1 = TheCall->getArg(1); 5688 5689 // Do standard promotions between the two arguments, returning their common 5690 // type. 5691 QualType Res = UsualArithmeticConversions( 5692 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5693 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5694 return true; 5695 5696 // Make sure any conversions are pushed back into the call; this is 5697 // type safe since unordered compare builtins are declared as "_Bool 5698 // foo(...)". 5699 TheCall->setArg(0, OrigArg0.get()); 5700 TheCall->setArg(1, OrigArg1.get()); 5701 5702 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5703 return false; 5704 5705 // If the common type isn't a real floating type, then the arguments were 5706 // invalid for this operation. 5707 if (Res.isNull() || !Res->isRealFloatingType()) 5708 return Diag(OrigArg0.get()->getBeginLoc(), 5709 diag::err_typecheck_call_invalid_ordered_compare) 5710 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5711 << SourceRange(OrigArg0.get()->getBeginLoc(), 5712 OrigArg1.get()->getEndLoc()); 5713 5714 return false; 5715 } 5716 5717 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5718 /// __builtin_isnan and friends. This is declared to take (...), so we have 5719 /// to check everything. We expect the last argument to be a floating point 5720 /// value. 5721 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5722 if (checkArgCount(*this, TheCall, NumArgs)) 5723 return true; 5724 5725 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5726 // on all preceding parameters just being int. Try all of those. 5727 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5728 Expr *Arg = TheCall->getArg(i); 5729 5730 if (Arg->isTypeDependent()) 5731 return false; 5732 5733 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5734 5735 if (Res.isInvalid()) 5736 return true; 5737 TheCall->setArg(i, Res.get()); 5738 } 5739 5740 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5741 5742 if (OrigArg->isTypeDependent()) 5743 return false; 5744 5745 // Usual Unary Conversions will convert half to float, which we want for 5746 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5747 // type how it is, but do normal L->Rvalue conversions. 5748 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5749 OrigArg = UsualUnaryConversions(OrigArg).get(); 5750 else 5751 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5752 TheCall->setArg(NumArgs - 1, OrigArg); 5753 5754 // This operation requires a non-_Complex floating-point number. 5755 if (!OrigArg->getType()->isRealFloatingType()) 5756 return Diag(OrigArg->getBeginLoc(), 5757 diag::err_typecheck_call_invalid_unary_fp) 5758 << OrigArg->getType() << OrigArg->getSourceRange(); 5759 5760 return false; 5761 } 5762 5763 /// Perform semantic analysis for a call to __builtin_complex. 5764 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5765 if (checkArgCount(*this, TheCall, 2)) 5766 return true; 5767 5768 bool Dependent = false; 5769 for (unsigned I = 0; I != 2; ++I) { 5770 Expr *Arg = TheCall->getArg(I); 5771 QualType T = Arg->getType(); 5772 if (T->isDependentType()) { 5773 Dependent = true; 5774 continue; 5775 } 5776 5777 // Despite supporting _Complex int, GCC requires a real floating point type 5778 // for the operands of __builtin_complex. 5779 if (!T->isRealFloatingType()) { 5780 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5781 << Arg->getType() << Arg->getSourceRange(); 5782 } 5783 5784 ExprResult Converted = DefaultLvalueConversion(Arg); 5785 if (Converted.isInvalid()) 5786 return true; 5787 TheCall->setArg(I, Converted.get()); 5788 } 5789 5790 if (Dependent) { 5791 TheCall->setType(Context.DependentTy); 5792 return false; 5793 } 5794 5795 Expr *Real = TheCall->getArg(0); 5796 Expr *Imag = TheCall->getArg(1); 5797 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 5798 return Diag(Real->getBeginLoc(), 5799 diag::err_typecheck_call_different_arg_types) 5800 << Real->getType() << Imag->getType() 5801 << Real->getSourceRange() << Imag->getSourceRange(); 5802 } 5803 5804 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 5805 // don't allow this builtin to form those types either. 5806 // FIXME: Should we allow these types? 5807 if (Real->getType()->isFloat16Type()) 5808 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5809 << "_Float16"; 5810 if (Real->getType()->isHalfType()) 5811 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5812 << "half"; 5813 5814 TheCall->setType(Context.getComplexType(Real->getType())); 5815 return false; 5816 } 5817 5818 // Customized Sema Checking for VSX builtins that have the following signature: 5819 // vector [...] builtinName(vector [...], vector [...], const int); 5820 // Which takes the same type of vectors (any legal vector type) for the first 5821 // two arguments and takes compile time constant for the third argument. 5822 // Example builtins are : 5823 // vector double vec_xxpermdi(vector double, vector double, int); 5824 // vector short vec_xxsldwi(vector short, vector short, int); 5825 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5826 unsigned ExpectedNumArgs = 3; 5827 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 5828 return true; 5829 5830 // Check the third argument is a compile time constant 5831 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 5832 return Diag(TheCall->getBeginLoc(), 5833 diag::err_vsx_builtin_nonconstant_argument) 5834 << 3 /* argument index */ << TheCall->getDirectCallee() 5835 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5836 TheCall->getArg(2)->getEndLoc()); 5837 5838 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5839 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5840 5841 // Check the type of argument 1 and argument 2 are vectors. 5842 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5843 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5844 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5845 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5846 << TheCall->getDirectCallee() 5847 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5848 TheCall->getArg(1)->getEndLoc()); 5849 } 5850 5851 // Check the first two arguments are the same type. 5852 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5853 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5854 << TheCall->getDirectCallee() 5855 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5856 TheCall->getArg(1)->getEndLoc()); 5857 } 5858 5859 // When default clang type checking is turned off and the customized type 5860 // checking is used, the returning type of the function must be explicitly 5861 // set. Otherwise it is _Bool by default. 5862 TheCall->setType(Arg1Ty); 5863 5864 return false; 5865 } 5866 5867 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5868 // This is declared to take (...), so we have to check everything. 5869 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5870 if (TheCall->getNumArgs() < 2) 5871 return ExprError(Diag(TheCall->getEndLoc(), 5872 diag::err_typecheck_call_too_few_args_at_least) 5873 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5874 << TheCall->getSourceRange()); 5875 5876 // Determine which of the following types of shufflevector we're checking: 5877 // 1) unary, vector mask: (lhs, mask) 5878 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5879 QualType resType = TheCall->getArg(0)->getType(); 5880 unsigned numElements = 0; 5881 5882 if (!TheCall->getArg(0)->isTypeDependent() && 5883 !TheCall->getArg(1)->isTypeDependent()) { 5884 QualType LHSType = TheCall->getArg(0)->getType(); 5885 QualType RHSType = TheCall->getArg(1)->getType(); 5886 5887 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5888 return ExprError( 5889 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5890 << TheCall->getDirectCallee() 5891 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5892 TheCall->getArg(1)->getEndLoc())); 5893 5894 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5895 unsigned numResElements = TheCall->getNumArgs() - 2; 5896 5897 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5898 // with mask. If so, verify that RHS is an integer vector type with the 5899 // same number of elts as lhs. 5900 if (TheCall->getNumArgs() == 2) { 5901 if (!RHSType->hasIntegerRepresentation() || 5902 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5903 return ExprError(Diag(TheCall->getBeginLoc(), 5904 diag::err_vec_builtin_incompatible_vector) 5905 << TheCall->getDirectCallee() 5906 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5907 TheCall->getArg(1)->getEndLoc())); 5908 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5909 return ExprError(Diag(TheCall->getBeginLoc(), 5910 diag::err_vec_builtin_incompatible_vector) 5911 << TheCall->getDirectCallee() 5912 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5913 TheCall->getArg(1)->getEndLoc())); 5914 } else if (numElements != numResElements) { 5915 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5916 resType = Context.getVectorType(eltType, numResElements, 5917 VectorType::GenericVector); 5918 } 5919 } 5920 5921 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5922 if (TheCall->getArg(i)->isTypeDependent() || 5923 TheCall->getArg(i)->isValueDependent()) 5924 continue; 5925 5926 Optional<llvm::APSInt> Result; 5927 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 5928 return ExprError(Diag(TheCall->getBeginLoc(), 5929 diag::err_shufflevector_nonconstant_argument) 5930 << TheCall->getArg(i)->getSourceRange()); 5931 5932 // Allow -1 which will be translated to undef in the IR. 5933 if (Result->isSigned() && Result->isAllOnesValue()) 5934 continue; 5935 5936 if (Result->getActiveBits() > 64 || 5937 Result->getZExtValue() >= numElements * 2) 5938 return ExprError(Diag(TheCall->getBeginLoc(), 5939 diag::err_shufflevector_argument_too_large) 5940 << TheCall->getArg(i)->getSourceRange()); 5941 } 5942 5943 SmallVector<Expr*, 32> exprs; 5944 5945 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5946 exprs.push_back(TheCall->getArg(i)); 5947 TheCall->setArg(i, nullptr); 5948 } 5949 5950 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5951 TheCall->getCallee()->getBeginLoc(), 5952 TheCall->getRParenLoc()); 5953 } 5954 5955 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5956 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5957 SourceLocation BuiltinLoc, 5958 SourceLocation RParenLoc) { 5959 ExprValueKind VK = VK_RValue; 5960 ExprObjectKind OK = OK_Ordinary; 5961 QualType DstTy = TInfo->getType(); 5962 QualType SrcTy = E->getType(); 5963 5964 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5965 return ExprError(Diag(BuiltinLoc, 5966 diag::err_convertvector_non_vector) 5967 << E->getSourceRange()); 5968 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5969 return ExprError(Diag(BuiltinLoc, 5970 diag::err_convertvector_non_vector_type)); 5971 5972 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5973 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5974 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5975 if (SrcElts != DstElts) 5976 return ExprError(Diag(BuiltinLoc, 5977 diag::err_convertvector_incompatible_vector) 5978 << E->getSourceRange()); 5979 } 5980 5981 return new (Context) 5982 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5983 } 5984 5985 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5986 // This is declared to take (const void*, ...) and can take two 5987 // optional constant int args. 5988 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5989 unsigned NumArgs = TheCall->getNumArgs(); 5990 5991 if (NumArgs > 3) 5992 return Diag(TheCall->getEndLoc(), 5993 diag::err_typecheck_call_too_many_args_at_most) 5994 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5995 5996 // Argument 0 is checked for us and the remaining arguments must be 5997 // constant integers. 5998 for (unsigned i = 1; i != NumArgs; ++i) 5999 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6000 return true; 6001 6002 return false; 6003 } 6004 6005 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6006 // __assume does not evaluate its arguments, and should warn if its argument 6007 // has side effects. 6008 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6009 Expr *Arg = TheCall->getArg(0); 6010 if (Arg->isInstantiationDependent()) return false; 6011 6012 if (Arg->HasSideEffects(Context)) 6013 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6014 << Arg->getSourceRange() 6015 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6016 6017 return false; 6018 } 6019 6020 /// Handle __builtin_alloca_with_align. This is declared 6021 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6022 /// than 8. 6023 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6024 // The alignment must be a constant integer. 6025 Expr *Arg = TheCall->getArg(1); 6026 6027 // We can't check the value of a dependent argument. 6028 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6029 if (const auto *UE = 6030 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6031 if (UE->getKind() == UETT_AlignOf || 6032 UE->getKind() == UETT_PreferredAlignOf) 6033 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6034 << Arg->getSourceRange(); 6035 6036 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6037 6038 if (!Result.isPowerOf2()) 6039 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6040 << Arg->getSourceRange(); 6041 6042 if (Result < Context.getCharWidth()) 6043 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6044 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6045 6046 if (Result > std::numeric_limits<int32_t>::max()) 6047 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6048 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6049 } 6050 6051 return false; 6052 } 6053 6054 /// Handle __builtin_assume_aligned. This is declared 6055 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6056 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6057 unsigned NumArgs = TheCall->getNumArgs(); 6058 6059 if (NumArgs > 3) 6060 return Diag(TheCall->getEndLoc(), 6061 diag::err_typecheck_call_too_many_args_at_most) 6062 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6063 6064 // The alignment must be a constant integer. 6065 Expr *Arg = TheCall->getArg(1); 6066 6067 // We can't check the value of a dependent argument. 6068 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6069 llvm::APSInt Result; 6070 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6071 return true; 6072 6073 if (!Result.isPowerOf2()) 6074 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6075 << Arg->getSourceRange(); 6076 6077 if (Result > Sema::MaximumAlignment) 6078 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6079 << Arg->getSourceRange() << Sema::MaximumAlignment; 6080 } 6081 6082 if (NumArgs > 2) { 6083 ExprResult Arg(TheCall->getArg(2)); 6084 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6085 Context.getSizeType(), false); 6086 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6087 if (Arg.isInvalid()) return true; 6088 TheCall->setArg(2, Arg.get()); 6089 } 6090 6091 return false; 6092 } 6093 6094 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6095 unsigned BuiltinID = 6096 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6097 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6098 6099 unsigned NumArgs = TheCall->getNumArgs(); 6100 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6101 if (NumArgs < NumRequiredArgs) { 6102 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6103 << 0 /* function call */ << NumRequiredArgs << NumArgs 6104 << TheCall->getSourceRange(); 6105 } 6106 if (NumArgs >= NumRequiredArgs + 0x100) { 6107 return Diag(TheCall->getEndLoc(), 6108 diag::err_typecheck_call_too_many_args_at_most) 6109 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6110 << TheCall->getSourceRange(); 6111 } 6112 unsigned i = 0; 6113 6114 // For formatting call, check buffer arg. 6115 if (!IsSizeCall) { 6116 ExprResult Arg(TheCall->getArg(i)); 6117 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6118 Context, Context.VoidPtrTy, false); 6119 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6120 if (Arg.isInvalid()) 6121 return true; 6122 TheCall->setArg(i, Arg.get()); 6123 i++; 6124 } 6125 6126 // Check string literal arg. 6127 unsigned FormatIdx = i; 6128 { 6129 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6130 if (Arg.isInvalid()) 6131 return true; 6132 TheCall->setArg(i, Arg.get()); 6133 i++; 6134 } 6135 6136 // Make sure variadic args are scalar. 6137 unsigned FirstDataArg = i; 6138 while (i < NumArgs) { 6139 ExprResult Arg = DefaultVariadicArgumentPromotion( 6140 TheCall->getArg(i), VariadicFunction, nullptr); 6141 if (Arg.isInvalid()) 6142 return true; 6143 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6144 if (ArgSize.getQuantity() >= 0x100) { 6145 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6146 << i << (int)ArgSize.getQuantity() << 0xff 6147 << TheCall->getSourceRange(); 6148 } 6149 TheCall->setArg(i, Arg.get()); 6150 i++; 6151 } 6152 6153 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6154 // call to avoid duplicate diagnostics. 6155 if (!IsSizeCall) { 6156 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6157 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6158 bool Success = CheckFormatArguments( 6159 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6160 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6161 CheckedVarArgs); 6162 if (!Success) 6163 return true; 6164 } 6165 6166 if (IsSizeCall) { 6167 TheCall->setType(Context.getSizeType()); 6168 } else { 6169 TheCall->setType(Context.VoidPtrTy); 6170 } 6171 return false; 6172 } 6173 6174 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6175 /// TheCall is a constant expression. 6176 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6177 llvm::APSInt &Result) { 6178 Expr *Arg = TheCall->getArg(ArgNum); 6179 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6180 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6181 6182 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6183 6184 Optional<llvm::APSInt> R; 6185 if (!(R = Arg->getIntegerConstantExpr(Context))) 6186 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6187 << FDecl->getDeclName() << Arg->getSourceRange(); 6188 Result = *R; 6189 return false; 6190 } 6191 6192 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6193 /// TheCall is a constant expression in the range [Low, High]. 6194 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6195 int Low, int High, bool RangeIsError) { 6196 if (isConstantEvaluated()) 6197 return false; 6198 llvm::APSInt Result; 6199 6200 // We can't check the value of a dependent argument. 6201 Expr *Arg = TheCall->getArg(ArgNum); 6202 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6203 return false; 6204 6205 // Check constant-ness first. 6206 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6207 return true; 6208 6209 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6210 if (RangeIsError) 6211 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6212 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6213 else 6214 // Defer the warning until we know if the code will be emitted so that 6215 // dead code can ignore this. 6216 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6217 PDiag(diag::warn_argument_invalid_range) 6218 << Result.toString(10) << Low << High 6219 << Arg->getSourceRange()); 6220 } 6221 6222 return false; 6223 } 6224 6225 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6226 /// TheCall is a constant expression is a multiple of Num.. 6227 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6228 unsigned Num) { 6229 llvm::APSInt Result; 6230 6231 // We can't check the value of a dependent argument. 6232 Expr *Arg = TheCall->getArg(ArgNum); 6233 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6234 return false; 6235 6236 // Check constant-ness first. 6237 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6238 return true; 6239 6240 if (Result.getSExtValue() % Num != 0) 6241 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6242 << Num << Arg->getSourceRange(); 6243 6244 return false; 6245 } 6246 6247 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6248 /// constant expression representing a power of 2. 6249 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6250 llvm::APSInt Result; 6251 6252 // We can't check the value of a dependent argument. 6253 Expr *Arg = TheCall->getArg(ArgNum); 6254 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6255 return false; 6256 6257 // Check constant-ness first. 6258 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6259 return true; 6260 6261 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6262 // and only if x is a power of 2. 6263 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6264 return false; 6265 6266 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6267 << Arg->getSourceRange(); 6268 } 6269 6270 static bool IsShiftedByte(llvm::APSInt Value) { 6271 if (Value.isNegative()) 6272 return false; 6273 6274 // Check if it's a shifted byte, by shifting it down 6275 while (true) { 6276 // If the value fits in the bottom byte, the check passes. 6277 if (Value < 0x100) 6278 return true; 6279 6280 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6281 // fails. 6282 if ((Value & 0xFF) != 0) 6283 return false; 6284 6285 // If the bottom 8 bits are all 0, but something above that is nonzero, 6286 // then shifting the value right by 8 bits won't affect whether it's a 6287 // shifted byte or not. So do that, and go round again. 6288 Value >>= 8; 6289 } 6290 } 6291 6292 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6293 /// a constant expression representing an arbitrary byte value shifted left by 6294 /// a multiple of 8 bits. 6295 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6296 unsigned ArgBits) { 6297 llvm::APSInt Result; 6298 6299 // We can't check the value of a dependent argument. 6300 Expr *Arg = TheCall->getArg(ArgNum); 6301 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6302 return false; 6303 6304 // Check constant-ness first. 6305 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6306 return true; 6307 6308 // Truncate to the given size. 6309 Result = Result.getLoBits(ArgBits); 6310 Result.setIsUnsigned(true); 6311 6312 if (IsShiftedByte(Result)) 6313 return false; 6314 6315 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6316 << Arg->getSourceRange(); 6317 } 6318 6319 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6320 /// TheCall is a constant expression representing either a shifted byte value, 6321 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6322 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6323 /// Arm MVE intrinsics. 6324 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6325 int ArgNum, 6326 unsigned ArgBits) { 6327 llvm::APSInt Result; 6328 6329 // We can't check the value of a dependent argument. 6330 Expr *Arg = TheCall->getArg(ArgNum); 6331 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6332 return false; 6333 6334 // Check constant-ness first. 6335 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6336 return true; 6337 6338 // Truncate to the given size. 6339 Result = Result.getLoBits(ArgBits); 6340 Result.setIsUnsigned(true); 6341 6342 // Check to see if it's in either of the required forms. 6343 if (IsShiftedByte(Result) || 6344 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6345 return false; 6346 6347 return Diag(TheCall->getBeginLoc(), 6348 diag::err_argument_not_shifted_byte_or_xxff) 6349 << Arg->getSourceRange(); 6350 } 6351 6352 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6353 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6354 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6355 if (checkArgCount(*this, TheCall, 2)) 6356 return true; 6357 Expr *Arg0 = TheCall->getArg(0); 6358 Expr *Arg1 = TheCall->getArg(1); 6359 6360 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6361 if (FirstArg.isInvalid()) 6362 return true; 6363 QualType FirstArgType = FirstArg.get()->getType(); 6364 if (!FirstArgType->isAnyPointerType()) 6365 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6366 << "first" << FirstArgType << Arg0->getSourceRange(); 6367 TheCall->setArg(0, FirstArg.get()); 6368 6369 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6370 if (SecArg.isInvalid()) 6371 return true; 6372 QualType SecArgType = SecArg.get()->getType(); 6373 if (!SecArgType->isIntegerType()) 6374 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6375 << "second" << SecArgType << Arg1->getSourceRange(); 6376 6377 // Derive the return type from the pointer argument. 6378 TheCall->setType(FirstArgType); 6379 return false; 6380 } 6381 6382 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6383 if (checkArgCount(*this, TheCall, 2)) 6384 return true; 6385 6386 Expr *Arg0 = TheCall->getArg(0); 6387 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6388 if (FirstArg.isInvalid()) 6389 return true; 6390 QualType FirstArgType = FirstArg.get()->getType(); 6391 if (!FirstArgType->isAnyPointerType()) 6392 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6393 << "first" << FirstArgType << Arg0->getSourceRange(); 6394 TheCall->setArg(0, FirstArg.get()); 6395 6396 // Derive the return type from the pointer argument. 6397 TheCall->setType(FirstArgType); 6398 6399 // Second arg must be an constant in range [0,15] 6400 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6401 } 6402 6403 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6404 if (checkArgCount(*this, TheCall, 2)) 6405 return true; 6406 Expr *Arg0 = TheCall->getArg(0); 6407 Expr *Arg1 = TheCall->getArg(1); 6408 6409 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6410 if (FirstArg.isInvalid()) 6411 return true; 6412 QualType FirstArgType = FirstArg.get()->getType(); 6413 if (!FirstArgType->isAnyPointerType()) 6414 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6415 << "first" << FirstArgType << Arg0->getSourceRange(); 6416 6417 QualType SecArgType = Arg1->getType(); 6418 if (!SecArgType->isIntegerType()) 6419 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6420 << "second" << SecArgType << Arg1->getSourceRange(); 6421 TheCall->setType(Context.IntTy); 6422 return false; 6423 } 6424 6425 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6426 BuiltinID == AArch64::BI__builtin_arm_stg) { 6427 if (checkArgCount(*this, TheCall, 1)) 6428 return true; 6429 Expr *Arg0 = TheCall->getArg(0); 6430 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6431 if (FirstArg.isInvalid()) 6432 return true; 6433 6434 QualType FirstArgType = FirstArg.get()->getType(); 6435 if (!FirstArgType->isAnyPointerType()) 6436 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6437 << "first" << FirstArgType << Arg0->getSourceRange(); 6438 TheCall->setArg(0, FirstArg.get()); 6439 6440 // Derive the return type from the pointer argument. 6441 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6442 TheCall->setType(FirstArgType); 6443 return false; 6444 } 6445 6446 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6447 Expr *ArgA = TheCall->getArg(0); 6448 Expr *ArgB = TheCall->getArg(1); 6449 6450 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6451 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6452 6453 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6454 return true; 6455 6456 QualType ArgTypeA = ArgExprA.get()->getType(); 6457 QualType ArgTypeB = ArgExprB.get()->getType(); 6458 6459 auto isNull = [&] (Expr *E) -> bool { 6460 return E->isNullPointerConstant( 6461 Context, Expr::NPC_ValueDependentIsNotNull); }; 6462 6463 // argument should be either a pointer or null 6464 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6465 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6466 << "first" << ArgTypeA << ArgA->getSourceRange(); 6467 6468 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6469 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6470 << "second" << ArgTypeB << ArgB->getSourceRange(); 6471 6472 // Ensure Pointee types are compatible 6473 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6474 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6475 QualType pointeeA = ArgTypeA->getPointeeType(); 6476 QualType pointeeB = ArgTypeB->getPointeeType(); 6477 if (!Context.typesAreCompatible( 6478 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6479 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6480 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6481 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6482 << ArgB->getSourceRange(); 6483 } 6484 } 6485 6486 // at least one argument should be pointer type 6487 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6488 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6489 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6490 6491 if (isNull(ArgA)) // adopt type of the other pointer 6492 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6493 6494 if (isNull(ArgB)) 6495 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6496 6497 TheCall->setArg(0, ArgExprA.get()); 6498 TheCall->setArg(1, ArgExprB.get()); 6499 TheCall->setType(Context.LongLongTy); 6500 return false; 6501 } 6502 assert(false && "Unhandled ARM MTE intrinsic"); 6503 return true; 6504 } 6505 6506 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6507 /// TheCall is an ARM/AArch64 special register string literal. 6508 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6509 int ArgNum, unsigned ExpectedFieldNum, 6510 bool AllowName) { 6511 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6512 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6513 BuiltinID == ARM::BI__builtin_arm_rsr || 6514 BuiltinID == ARM::BI__builtin_arm_rsrp || 6515 BuiltinID == ARM::BI__builtin_arm_wsr || 6516 BuiltinID == ARM::BI__builtin_arm_wsrp; 6517 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6518 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6519 BuiltinID == AArch64::BI__builtin_arm_rsr || 6520 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6521 BuiltinID == AArch64::BI__builtin_arm_wsr || 6522 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6523 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6524 6525 // We can't check the value of a dependent argument. 6526 Expr *Arg = TheCall->getArg(ArgNum); 6527 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6528 return false; 6529 6530 // Check if the argument is a string literal. 6531 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6532 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6533 << Arg->getSourceRange(); 6534 6535 // Check the type of special register given. 6536 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6537 SmallVector<StringRef, 6> Fields; 6538 Reg.split(Fields, ":"); 6539 6540 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6541 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6542 << Arg->getSourceRange(); 6543 6544 // If the string is the name of a register then we cannot check that it is 6545 // valid here but if the string is of one the forms described in ACLE then we 6546 // can check that the supplied fields are integers and within the valid 6547 // ranges. 6548 if (Fields.size() > 1) { 6549 bool FiveFields = Fields.size() == 5; 6550 6551 bool ValidString = true; 6552 if (IsARMBuiltin) { 6553 ValidString &= Fields[0].startswith_lower("cp") || 6554 Fields[0].startswith_lower("p"); 6555 if (ValidString) 6556 Fields[0] = 6557 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6558 6559 ValidString &= Fields[2].startswith_lower("c"); 6560 if (ValidString) 6561 Fields[2] = Fields[2].drop_front(1); 6562 6563 if (FiveFields) { 6564 ValidString &= Fields[3].startswith_lower("c"); 6565 if (ValidString) 6566 Fields[3] = Fields[3].drop_front(1); 6567 } 6568 } 6569 6570 SmallVector<int, 5> Ranges; 6571 if (FiveFields) 6572 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6573 else 6574 Ranges.append({15, 7, 15}); 6575 6576 for (unsigned i=0; i<Fields.size(); ++i) { 6577 int IntField; 6578 ValidString &= !Fields[i].getAsInteger(10, IntField); 6579 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6580 } 6581 6582 if (!ValidString) 6583 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6584 << Arg->getSourceRange(); 6585 } else if (IsAArch64Builtin && Fields.size() == 1) { 6586 // If the register name is one of those that appear in the condition below 6587 // and the special register builtin being used is one of the write builtins, 6588 // then we require that the argument provided for writing to the register 6589 // is an integer constant expression. This is because it will be lowered to 6590 // an MSR (immediate) instruction, so we need to know the immediate at 6591 // compile time. 6592 if (TheCall->getNumArgs() != 2) 6593 return false; 6594 6595 std::string RegLower = Reg.lower(); 6596 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6597 RegLower != "pan" && RegLower != "uao") 6598 return false; 6599 6600 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6601 } 6602 6603 return false; 6604 } 6605 6606 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6607 /// This checks that the target supports __builtin_longjmp and 6608 /// that val is a constant 1. 6609 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6610 if (!Context.getTargetInfo().hasSjLjLowering()) 6611 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6612 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6613 6614 Expr *Arg = TheCall->getArg(1); 6615 llvm::APSInt Result; 6616 6617 // TODO: This is less than ideal. Overload this to take a value. 6618 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6619 return true; 6620 6621 if (Result != 1) 6622 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6623 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6624 6625 return false; 6626 } 6627 6628 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6629 /// This checks that the target supports __builtin_setjmp. 6630 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6631 if (!Context.getTargetInfo().hasSjLjLowering()) 6632 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6633 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6634 return false; 6635 } 6636 6637 namespace { 6638 6639 class UncoveredArgHandler { 6640 enum { Unknown = -1, AllCovered = -2 }; 6641 6642 signed FirstUncoveredArg = Unknown; 6643 SmallVector<const Expr *, 4> DiagnosticExprs; 6644 6645 public: 6646 UncoveredArgHandler() = default; 6647 6648 bool hasUncoveredArg() const { 6649 return (FirstUncoveredArg >= 0); 6650 } 6651 6652 unsigned getUncoveredArg() const { 6653 assert(hasUncoveredArg() && "no uncovered argument"); 6654 return FirstUncoveredArg; 6655 } 6656 6657 void setAllCovered() { 6658 // A string has been found with all arguments covered, so clear out 6659 // the diagnostics. 6660 DiagnosticExprs.clear(); 6661 FirstUncoveredArg = AllCovered; 6662 } 6663 6664 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6665 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6666 6667 // Don't update if a previous string covers all arguments. 6668 if (FirstUncoveredArg == AllCovered) 6669 return; 6670 6671 // UncoveredArgHandler tracks the highest uncovered argument index 6672 // and with it all the strings that match this index. 6673 if (NewFirstUncoveredArg == FirstUncoveredArg) 6674 DiagnosticExprs.push_back(StrExpr); 6675 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6676 DiagnosticExprs.clear(); 6677 DiagnosticExprs.push_back(StrExpr); 6678 FirstUncoveredArg = NewFirstUncoveredArg; 6679 } 6680 } 6681 6682 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6683 }; 6684 6685 enum StringLiteralCheckType { 6686 SLCT_NotALiteral, 6687 SLCT_UncheckedLiteral, 6688 SLCT_CheckedLiteral 6689 }; 6690 6691 } // namespace 6692 6693 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6694 BinaryOperatorKind BinOpKind, 6695 bool AddendIsRight) { 6696 unsigned BitWidth = Offset.getBitWidth(); 6697 unsigned AddendBitWidth = Addend.getBitWidth(); 6698 // There might be negative interim results. 6699 if (Addend.isUnsigned()) { 6700 Addend = Addend.zext(++AddendBitWidth); 6701 Addend.setIsSigned(true); 6702 } 6703 // Adjust the bit width of the APSInts. 6704 if (AddendBitWidth > BitWidth) { 6705 Offset = Offset.sext(AddendBitWidth); 6706 BitWidth = AddendBitWidth; 6707 } else if (BitWidth > AddendBitWidth) { 6708 Addend = Addend.sext(BitWidth); 6709 } 6710 6711 bool Ov = false; 6712 llvm::APSInt ResOffset = Offset; 6713 if (BinOpKind == BO_Add) 6714 ResOffset = Offset.sadd_ov(Addend, Ov); 6715 else { 6716 assert(AddendIsRight && BinOpKind == BO_Sub && 6717 "operator must be add or sub with addend on the right"); 6718 ResOffset = Offset.ssub_ov(Addend, Ov); 6719 } 6720 6721 // We add an offset to a pointer here so we should support an offset as big as 6722 // possible. 6723 if (Ov) { 6724 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6725 "index (intermediate) result too big"); 6726 Offset = Offset.sext(2 * BitWidth); 6727 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6728 return; 6729 } 6730 6731 Offset = ResOffset; 6732 } 6733 6734 namespace { 6735 6736 // This is a wrapper class around StringLiteral to support offsetted string 6737 // literals as format strings. It takes the offset into account when returning 6738 // the string and its length or the source locations to display notes correctly. 6739 class FormatStringLiteral { 6740 const StringLiteral *FExpr; 6741 int64_t Offset; 6742 6743 public: 6744 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6745 : FExpr(fexpr), Offset(Offset) {} 6746 6747 StringRef getString() const { 6748 return FExpr->getString().drop_front(Offset); 6749 } 6750 6751 unsigned getByteLength() const { 6752 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6753 } 6754 6755 unsigned getLength() const { return FExpr->getLength() - Offset; } 6756 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6757 6758 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6759 6760 QualType getType() const { return FExpr->getType(); } 6761 6762 bool isAscii() const { return FExpr->isAscii(); } 6763 bool isWide() const { return FExpr->isWide(); } 6764 bool isUTF8() const { return FExpr->isUTF8(); } 6765 bool isUTF16() const { return FExpr->isUTF16(); } 6766 bool isUTF32() const { return FExpr->isUTF32(); } 6767 bool isPascal() const { return FExpr->isPascal(); } 6768 6769 SourceLocation getLocationOfByte( 6770 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6771 const TargetInfo &Target, unsigned *StartToken = nullptr, 6772 unsigned *StartTokenByteOffset = nullptr) const { 6773 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6774 StartToken, StartTokenByteOffset); 6775 } 6776 6777 SourceLocation getBeginLoc() const LLVM_READONLY { 6778 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6779 } 6780 6781 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6782 }; 6783 6784 } // namespace 6785 6786 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6787 const Expr *OrigFormatExpr, 6788 ArrayRef<const Expr *> Args, 6789 bool HasVAListArg, unsigned format_idx, 6790 unsigned firstDataArg, 6791 Sema::FormatStringType Type, 6792 bool inFunctionCall, 6793 Sema::VariadicCallType CallType, 6794 llvm::SmallBitVector &CheckedVarArgs, 6795 UncoveredArgHandler &UncoveredArg, 6796 bool IgnoreStringsWithoutSpecifiers); 6797 6798 // Determine if an expression is a string literal or constant string. 6799 // If this function returns false on the arguments to a function expecting a 6800 // format string, we will usually need to emit a warning. 6801 // True string literals are then checked by CheckFormatString. 6802 static StringLiteralCheckType 6803 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6804 bool HasVAListArg, unsigned format_idx, 6805 unsigned firstDataArg, Sema::FormatStringType Type, 6806 Sema::VariadicCallType CallType, bool InFunctionCall, 6807 llvm::SmallBitVector &CheckedVarArgs, 6808 UncoveredArgHandler &UncoveredArg, 6809 llvm::APSInt Offset, 6810 bool IgnoreStringsWithoutSpecifiers = false) { 6811 if (S.isConstantEvaluated()) 6812 return SLCT_NotALiteral; 6813 tryAgain: 6814 assert(Offset.isSigned() && "invalid offset"); 6815 6816 if (E->isTypeDependent() || E->isValueDependent()) 6817 return SLCT_NotALiteral; 6818 6819 E = E->IgnoreParenCasts(); 6820 6821 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6822 // Technically -Wformat-nonliteral does not warn about this case. 6823 // The behavior of printf and friends in this case is implementation 6824 // dependent. Ideally if the format string cannot be null then 6825 // it should have a 'nonnull' attribute in the function prototype. 6826 return SLCT_UncheckedLiteral; 6827 6828 switch (E->getStmtClass()) { 6829 case Stmt::BinaryConditionalOperatorClass: 6830 case Stmt::ConditionalOperatorClass: { 6831 // The expression is a literal if both sub-expressions were, and it was 6832 // completely checked only if both sub-expressions were checked. 6833 const AbstractConditionalOperator *C = 6834 cast<AbstractConditionalOperator>(E); 6835 6836 // Determine whether it is necessary to check both sub-expressions, for 6837 // example, because the condition expression is a constant that can be 6838 // evaluated at compile time. 6839 bool CheckLeft = true, CheckRight = true; 6840 6841 bool Cond; 6842 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6843 S.isConstantEvaluated())) { 6844 if (Cond) 6845 CheckRight = false; 6846 else 6847 CheckLeft = false; 6848 } 6849 6850 // We need to maintain the offsets for the right and the left hand side 6851 // separately to check if every possible indexed expression is a valid 6852 // string literal. They might have different offsets for different string 6853 // literals in the end. 6854 StringLiteralCheckType Left; 6855 if (!CheckLeft) 6856 Left = SLCT_UncheckedLiteral; 6857 else { 6858 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6859 HasVAListArg, format_idx, firstDataArg, 6860 Type, CallType, InFunctionCall, 6861 CheckedVarArgs, UncoveredArg, Offset, 6862 IgnoreStringsWithoutSpecifiers); 6863 if (Left == SLCT_NotALiteral || !CheckRight) { 6864 return Left; 6865 } 6866 } 6867 6868 StringLiteralCheckType Right = checkFormatStringExpr( 6869 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6870 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6871 IgnoreStringsWithoutSpecifiers); 6872 6873 return (CheckLeft && Left < Right) ? Left : Right; 6874 } 6875 6876 case Stmt::ImplicitCastExprClass: 6877 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6878 goto tryAgain; 6879 6880 case Stmt::OpaqueValueExprClass: 6881 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6882 E = src; 6883 goto tryAgain; 6884 } 6885 return SLCT_NotALiteral; 6886 6887 case Stmt::PredefinedExprClass: 6888 // While __func__, etc., are technically not string literals, they 6889 // cannot contain format specifiers and thus are not a security 6890 // liability. 6891 return SLCT_UncheckedLiteral; 6892 6893 case Stmt::DeclRefExprClass: { 6894 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6895 6896 // As an exception, do not flag errors for variables binding to 6897 // const string literals. 6898 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6899 bool isConstant = false; 6900 QualType T = DR->getType(); 6901 6902 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6903 isConstant = AT->getElementType().isConstant(S.Context); 6904 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6905 isConstant = T.isConstant(S.Context) && 6906 PT->getPointeeType().isConstant(S.Context); 6907 } else if (T->isObjCObjectPointerType()) { 6908 // In ObjC, there is usually no "const ObjectPointer" type, 6909 // so don't check if the pointee type is constant. 6910 isConstant = T.isConstant(S.Context); 6911 } 6912 6913 if (isConstant) { 6914 if (const Expr *Init = VD->getAnyInitializer()) { 6915 // Look through initializers like const char c[] = { "foo" } 6916 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6917 if (InitList->isStringLiteralInit()) 6918 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6919 } 6920 return checkFormatStringExpr(S, Init, Args, 6921 HasVAListArg, format_idx, 6922 firstDataArg, Type, CallType, 6923 /*InFunctionCall*/ false, CheckedVarArgs, 6924 UncoveredArg, Offset); 6925 } 6926 } 6927 6928 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6929 // special check to see if the format string is a function parameter 6930 // of the function calling the printf function. If the function 6931 // has an attribute indicating it is a printf-like function, then we 6932 // should suppress warnings concerning non-literals being used in a call 6933 // to a vprintf function. For example: 6934 // 6935 // void 6936 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6937 // va_list ap; 6938 // va_start(ap, fmt); 6939 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6940 // ... 6941 // } 6942 if (HasVAListArg) { 6943 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6944 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6945 int PVIndex = PV->getFunctionScopeIndex() + 1; 6946 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6947 // adjust for implicit parameter 6948 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6949 if (MD->isInstance()) 6950 ++PVIndex; 6951 // We also check if the formats are compatible. 6952 // We can't pass a 'scanf' string to a 'printf' function. 6953 if (PVIndex == PVFormat->getFormatIdx() && 6954 Type == S.GetFormatStringType(PVFormat)) 6955 return SLCT_UncheckedLiteral; 6956 } 6957 } 6958 } 6959 } 6960 } 6961 6962 return SLCT_NotALiteral; 6963 } 6964 6965 case Stmt::CallExprClass: 6966 case Stmt::CXXMemberCallExprClass: { 6967 const CallExpr *CE = cast<CallExpr>(E); 6968 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6969 bool IsFirst = true; 6970 StringLiteralCheckType CommonResult; 6971 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6972 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6973 StringLiteralCheckType Result = checkFormatStringExpr( 6974 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6975 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6976 IgnoreStringsWithoutSpecifiers); 6977 if (IsFirst) { 6978 CommonResult = Result; 6979 IsFirst = false; 6980 } 6981 } 6982 if (!IsFirst) 6983 return CommonResult; 6984 6985 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6986 unsigned BuiltinID = FD->getBuiltinID(); 6987 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6988 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6989 const Expr *Arg = CE->getArg(0); 6990 return checkFormatStringExpr(S, Arg, Args, 6991 HasVAListArg, format_idx, 6992 firstDataArg, Type, CallType, 6993 InFunctionCall, CheckedVarArgs, 6994 UncoveredArg, Offset, 6995 IgnoreStringsWithoutSpecifiers); 6996 } 6997 } 6998 } 6999 7000 return SLCT_NotALiteral; 7001 } 7002 case Stmt::ObjCMessageExprClass: { 7003 const auto *ME = cast<ObjCMessageExpr>(E); 7004 if (const auto *MD = ME->getMethodDecl()) { 7005 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7006 // As a special case heuristic, if we're using the method -[NSBundle 7007 // localizedStringForKey:value:table:], ignore any key strings that lack 7008 // format specifiers. The idea is that if the key doesn't have any 7009 // format specifiers then its probably just a key to map to the 7010 // localized strings. If it does have format specifiers though, then its 7011 // likely that the text of the key is the format string in the 7012 // programmer's language, and should be checked. 7013 const ObjCInterfaceDecl *IFace; 7014 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7015 IFace->getIdentifier()->isStr("NSBundle") && 7016 MD->getSelector().isKeywordSelector( 7017 {"localizedStringForKey", "value", "table"})) { 7018 IgnoreStringsWithoutSpecifiers = true; 7019 } 7020 7021 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7022 return checkFormatStringExpr( 7023 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7024 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7025 IgnoreStringsWithoutSpecifiers); 7026 } 7027 } 7028 7029 return SLCT_NotALiteral; 7030 } 7031 case Stmt::ObjCStringLiteralClass: 7032 case Stmt::StringLiteralClass: { 7033 const StringLiteral *StrE = nullptr; 7034 7035 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7036 StrE = ObjCFExpr->getString(); 7037 else 7038 StrE = cast<StringLiteral>(E); 7039 7040 if (StrE) { 7041 if (Offset.isNegative() || Offset > StrE->getLength()) { 7042 // TODO: It would be better to have an explicit warning for out of 7043 // bounds literals. 7044 return SLCT_NotALiteral; 7045 } 7046 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7047 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7048 firstDataArg, Type, InFunctionCall, CallType, 7049 CheckedVarArgs, UncoveredArg, 7050 IgnoreStringsWithoutSpecifiers); 7051 return SLCT_CheckedLiteral; 7052 } 7053 7054 return SLCT_NotALiteral; 7055 } 7056 case Stmt::BinaryOperatorClass: { 7057 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7058 7059 // A string literal + an int offset is still a string literal. 7060 if (BinOp->isAdditiveOp()) { 7061 Expr::EvalResult LResult, RResult; 7062 7063 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7064 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7065 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7066 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7067 7068 if (LIsInt != RIsInt) { 7069 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7070 7071 if (LIsInt) { 7072 if (BinOpKind == BO_Add) { 7073 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7074 E = BinOp->getRHS(); 7075 goto tryAgain; 7076 } 7077 } else { 7078 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7079 E = BinOp->getLHS(); 7080 goto tryAgain; 7081 } 7082 } 7083 } 7084 7085 return SLCT_NotALiteral; 7086 } 7087 case Stmt::UnaryOperatorClass: { 7088 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7089 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7090 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7091 Expr::EvalResult IndexResult; 7092 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7093 Expr::SE_NoSideEffects, 7094 S.isConstantEvaluated())) { 7095 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7096 /*RHS is int*/ true); 7097 E = ASE->getBase(); 7098 goto tryAgain; 7099 } 7100 } 7101 7102 return SLCT_NotALiteral; 7103 } 7104 7105 default: 7106 return SLCT_NotALiteral; 7107 } 7108 } 7109 7110 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7111 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7112 .Case("scanf", FST_Scanf) 7113 .Cases("printf", "printf0", FST_Printf) 7114 .Cases("NSString", "CFString", FST_NSString) 7115 .Case("strftime", FST_Strftime) 7116 .Case("strfmon", FST_Strfmon) 7117 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7118 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7119 .Case("os_trace", FST_OSLog) 7120 .Case("os_log", FST_OSLog) 7121 .Default(FST_Unknown); 7122 } 7123 7124 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7125 /// functions) for correct use of format strings. 7126 /// Returns true if a format string has been fully checked. 7127 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7128 ArrayRef<const Expr *> Args, 7129 bool IsCXXMember, 7130 VariadicCallType CallType, 7131 SourceLocation Loc, SourceRange Range, 7132 llvm::SmallBitVector &CheckedVarArgs) { 7133 FormatStringInfo FSI; 7134 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7135 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7136 FSI.FirstDataArg, GetFormatStringType(Format), 7137 CallType, Loc, Range, CheckedVarArgs); 7138 return false; 7139 } 7140 7141 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7142 bool HasVAListArg, unsigned format_idx, 7143 unsigned firstDataArg, FormatStringType Type, 7144 VariadicCallType CallType, 7145 SourceLocation Loc, SourceRange Range, 7146 llvm::SmallBitVector &CheckedVarArgs) { 7147 // CHECK: printf/scanf-like function is called with no format string. 7148 if (format_idx >= Args.size()) { 7149 Diag(Loc, diag::warn_missing_format_string) << Range; 7150 return false; 7151 } 7152 7153 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7154 7155 // CHECK: format string is not a string literal. 7156 // 7157 // Dynamically generated format strings are difficult to 7158 // automatically vet at compile time. Requiring that format strings 7159 // are string literals: (1) permits the checking of format strings by 7160 // the compiler and thereby (2) can practically remove the source of 7161 // many format string exploits. 7162 7163 // Format string can be either ObjC string (e.g. @"%d") or 7164 // C string (e.g. "%d") 7165 // ObjC string uses the same format specifiers as C string, so we can use 7166 // the same format string checking logic for both ObjC and C strings. 7167 UncoveredArgHandler UncoveredArg; 7168 StringLiteralCheckType CT = 7169 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7170 format_idx, firstDataArg, Type, CallType, 7171 /*IsFunctionCall*/ true, CheckedVarArgs, 7172 UncoveredArg, 7173 /*no string offset*/ llvm::APSInt(64, false) = 0); 7174 7175 // Generate a diagnostic where an uncovered argument is detected. 7176 if (UncoveredArg.hasUncoveredArg()) { 7177 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7178 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7179 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7180 } 7181 7182 if (CT != SLCT_NotALiteral) 7183 // Literal format string found, check done! 7184 return CT == SLCT_CheckedLiteral; 7185 7186 // Strftime is particular as it always uses a single 'time' argument, 7187 // so it is safe to pass a non-literal string. 7188 if (Type == FST_Strftime) 7189 return false; 7190 7191 // Do not emit diag when the string param is a macro expansion and the 7192 // format is either NSString or CFString. This is a hack to prevent 7193 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7194 // which are usually used in place of NS and CF string literals. 7195 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7196 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7197 return false; 7198 7199 // If there are no arguments specified, warn with -Wformat-security, otherwise 7200 // warn only with -Wformat-nonliteral. 7201 if (Args.size() == firstDataArg) { 7202 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7203 << OrigFormatExpr->getSourceRange(); 7204 switch (Type) { 7205 default: 7206 break; 7207 case FST_Kprintf: 7208 case FST_FreeBSDKPrintf: 7209 case FST_Printf: 7210 Diag(FormatLoc, diag::note_format_security_fixit) 7211 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7212 break; 7213 case FST_NSString: 7214 Diag(FormatLoc, diag::note_format_security_fixit) 7215 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7216 break; 7217 } 7218 } else { 7219 Diag(FormatLoc, diag::warn_format_nonliteral) 7220 << OrigFormatExpr->getSourceRange(); 7221 } 7222 return false; 7223 } 7224 7225 namespace { 7226 7227 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7228 protected: 7229 Sema &S; 7230 const FormatStringLiteral *FExpr; 7231 const Expr *OrigFormatExpr; 7232 const Sema::FormatStringType FSType; 7233 const unsigned FirstDataArg; 7234 const unsigned NumDataArgs; 7235 const char *Beg; // Start of format string. 7236 const bool HasVAListArg; 7237 ArrayRef<const Expr *> Args; 7238 unsigned FormatIdx; 7239 llvm::SmallBitVector CoveredArgs; 7240 bool usesPositionalArgs = false; 7241 bool atFirstArg = true; 7242 bool inFunctionCall; 7243 Sema::VariadicCallType CallType; 7244 llvm::SmallBitVector &CheckedVarArgs; 7245 UncoveredArgHandler &UncoveredArg; 7246 7247 public: 7248 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7249 const Expr *origFormatExpr, 7250 const Sema::FormatStringType type, unsigned firstDataArg, 7251 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7252 ArrayRef<const Expr *> Args, unsigned formatIdx, 7253 bool inFunctionCall, Sema::VariadicCallType callType, 7254 llvm::SmallBitVector &CheckedVarArgs, 7255 UncoveredArgHandler &UncoveredArg) 7256 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7257 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7258 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7259 inFunctionCall(inFunctionCall), CallType(callType), 7260 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7261 CoveredArgs.resize(numDataArgs); 7262 CoveredArgs.reset(); 7263 } 7264 7265 void DoneProcessing(); 7266 7267 void HandleIncompleteSpecifier(const char *startSpecifier, 7268 unsigned specifierLen) override; 7269 7270 void HandleInvalidLengthModifier( 7271 const analyze_format_string::FormatSpecifier &FS, 7272 const analyze_format_string::ConversionSpecifier &CS, 7273 const char *startSpecifier, unsigned specifierLen, 7274 unsigned DiagID); 7275 7276 void HandleNonStandardLengthModifier( 7277 const analyze_format_string::FormatSpecifier &FS, 7278 const char *startSpecifier, unsigned specifierLen); 7279 7280 void HandleNonStandardConversionSpecifier( 7281 const analyze_format_string::ConversionSpecifier &CS, 7282 const char *startSpecifier, unsigned specifierLen); 7283 7284 void HandlePosition(const char *startPos, unsigned posLen) override; 7285 7286 void HandleInvalidPosition(const char *startSpecifier, 7287 unsigned specifierLen, 7288 analyze_format_string::PositionContext p) override; 7289 7290 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7291 7292 void HandleNullChar(const char *nullCharacter) override; 7293 7294 template <typename Range> 7295 static void 7296 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7297 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7298 bool IsStringLocation, Range StringRange, 7299 ArrayRef<FixItHint> Fixit = None); 7300 7301 protected: 7302 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7303 const char *startSpec, 7304 unsigned specifierLen, 7305 const char *csStart, unsigned csLen); 7306 7307 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7308 const char *startSpec, 7309 unsigned specifierLen); 7310 7311 SourceRange getFormatStringRange(); 7312 CharSourceRange getSpecifierRange(const char *startSpecifier, 7313 unsigned specifierLen); 7314 SourceLocation getLocationOfByte(const char *x); 7315 7316 const Expr *getDataArg(unsigned i) const; 7317 7318 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7319 const analyze_format_string::ConversionSpecifier &CS, 7320 const char *startSpecifier, unsigned specifierLen, 7321 unsigned argIndex); 7322 7323 template <typename Range> 7324 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7325 bool IsStringLocation, Range StringRange, 7326 ArrayRef<FixItHint> Fixit = None); 7327 }; 7328 7329 } // namespace 7330 7331 SourceRange CheckFormatHandler::getFormatStringRange() { 7332 return OrigFormatExpr->getSourceRange(); 7333 } 7334 7335 CharSourceRange CheckFormatHandler:: 7336 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7337 SourceLocation Start = getLocationOfByte(startSpecifier); 7338 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7339 7340 // Advance the end SourceLocation by one due to half-open ranges. 7341 End = End.getLocWithOffset(1); 7342 7343 return CharSourceRange::getCharRange(Start, End); 7344 } 7345 7346 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7347 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7348 S.getLangOpts(), S.Context.getTargetInfo()); 7349 } 7350 7351 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7352 unsigned specifierLen){ 7353 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7354 getLocationOfByte(startSpecifier), 7355 /*IsStringLocation*/true, 7356 getSpecifierRange(startSpecifier, specifierLen)); 7357 } 7358 7359 void CheckFormatHandler::HandleInvalidLengthModifier( 7360 const analyze_format_string::FormatSpecifier &FS, 7361 const analyze_format_string::ConversionSpecifier &CS, 7362 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7363 using namespace analyze_format_string; 7364 7365 const LengthModifier &LM = FS.getLengthModifier(); 7366 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7367 7368 // See if we know how to fix this length modifier. 7369 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7370 if (FixedLM) { 7371 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7372 getLocationOfByte(LM.getStart()), 7373 /*IsStringLocation*/true, 7374 getSpecifierRange(startSpecifier, specifierLen)); 7375 7376 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7377 << FixedLM->toString() 7378 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7379 7380 } else { 7381 FixItHint Hint; 7382 if (DiagID == diag::warn_format_nonsensical_length) 7383 Hint = FixItHint::CreateRemoval(LMRange); 7384 7385 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7386 getLocationOfByte(LM.getStart()), 7387 /*IsStringLocation*/true, 7388 getSpecifierRange(startSpecifier, specifierLen), 7389 Hint); 7390 } 7391 } 7392 7393 void CheckFormatHandler::HandleNonStandardLengthModifier( 7394 const analyze_format_string::FormatSpecifier &FS, 7395 const char *startSpecifier, unsigned specifierLen) { 7396 using namespace analyze_format_string; 7397 7398 const LengthModifier &LM = FS.getLengthModifier(); 7399 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7400 7401 // See if we know how to fix this length modifier. 7402 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7403 if (FixedLM) { 7404 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7405 << LM.toString() << 0, 7406 getLocationOfByte(LM.getStart()), 7407 /*IsStringLocation*/true, 7408 getSpecifierRange(startSpecifier, specifierLen)); 7409 7410 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7411 << FixedLM->toString() 7412 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7413 7414 } else { 7415 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7416 << LM.toString() << 0, 7417 getLocationOfByte(LM.getStart()), 7418 /*IsStringLocation*/true, 7419 getSpecifierRange(startSpecifier, specifierLen)); 7420 } 7421 } 7422 7423 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7424 const analyze_format_string::ConversionSpecifier &CS, 7425 const char *startSpecifier, unsigned specifierLen) { 7426 using namespace analyze_format_string; 7427 7428 // See if we know how to fix this conversion specifier. 7429 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7430 if (FixedCS) { 7431 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7432 << CS.toString() << /*conversion specifier*/1, 7433 getLocationOfByte(CS.getStart()), 7434 /*IsStringLocation*/true, 7435 getSpecifierRange(startSpecifier, specifierLen)); 7436 7437 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7438 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7439 << FixedCS->toString() 7440 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7441 } else { 7442 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7443 << CS.toString() << /*conversion specifier*/1, 7444 getLocationOfByte(CS.getStart()), 7445 /*IsStringLocation*/true, 7446 getSpecifierRange(startSpecifier, specifierLen)); 7447 } 7448 } 7449 7450 void CheckFormatHandler::HandlePosition(const char *startPos, 7451 unsigned posLen) { 7452 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7453 getLocationOfByte(startPos), 7454 /*IsStringLocation*/true, 7455 getSpecifierRange(startPos, posLen)); 7456 } 7457 7458 void 7459 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7460 analyze_format_string::PositionContext p) { 7461 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7462 << (unsigned) p, 7463 getLocationOfByte(startPos), /*IsStringLocation*/true, 7464 getSpecifierRange(startPos, posLen)); 7465 } 7466 7467 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7468 unsigned posLen) { 7469 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7470 getLocationOfByte(startPos), 7471 /*IsStringLocation*/true, 7472 getSpecifierRange(startPos, posLen)); 7473 } 7474 7475 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7476 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7477 // The presence of a null character is likely an error. 7478 EmitFormatDiagnostic( 7479 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7480 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7481 getFormatStringRange()); 7482 } 7483 } 7484 7485 // Note that this may return NULL if there was an error parsing or building 7486 // one of the argument expressions. 7487 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7488 return Args[FirstDataArg + i]; 7489 } 7490 7491 void CheckFormatHandler::DoneProcessing() { 7492 // Does the number of data arguments exceed the number of 7493 // format conversions in the format string? 7494 if (!HasVAListArg) { 7495 // Find any arguments that weren't covered. 7496 CoveredArgs.flip(); 7497 signed notCoveredArg = CoveredArgs.find_first(); 7498 if (notCoveredArg >= 0) { 7499 assert((unsigned)notCoveredArg < NumDataArgs); 7500 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7501 } else { 7502 UncoveredArg.setAllCovered(); 7503 } 7504 } 7505 } 7506 7507 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7508 const Expr *ArgExpr) { 7509 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7510 "Invalid state"); 7511 7512 if (!ArgExpr) 7513 return; 7514 7515 SourceLocation Loc = ArgExpr->getBeginLoc(); 7516 7517 if (S.getSourceManager().isInSystemMacro(Loc)) 7518 return; 7519 7520 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7521 for (auto E : DiagnosticExprs) 7522 PDiag << E->getSourceRange(); 7523 7524 CheckFormatHandler::EmitFormatDiagnostic( 7525 S, IsFunctionCall, DiagnosticExprs[0], 7526 PDiag, Loc, /*IsStringLocation*/false, 7527 DiagnosticExprs[0]->getSourceRange()); 7528 } 7529 7530 bool 7531 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7532 SourceLocation Loc, 7533 const char *startSpec, 7534 unsigned specifierLen, 7535 const char *csStart, 7536 unsigned csLen) { 7537 bool keepGoing = true; 7538 if (argIndex < NumDataArgs) { 7539 // Consider the argument coverered, even though the specifier doesn't 7540 // make sense. 7541 CoveredArgs.set(argIndex); 7542 } 7543 else { 7544 // If argIndex exceeds the number of data arguments we 7545 // don't issue a warning because that is just a cascade of warnings (and 7546 // they may have intended '%%' anyway). We don't want to continue processing 7547 // the format string after this point, however, as we will like just get 7548 // gibberish when trying to match arguments. 7549 keepGoing = false; 7550 } 7551 7552 StringRef Specifier(csStart, csLen); 7553 7554 // If the specifier in non-printable, it could be the first byte of a UTF-8 7555 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7556 // hex value. 7557 std::string CodePointStr; 7558 if (!llvm::sys::locale::isPrint(*csStart)) { 7559 llvm::UTF32 CodePoint; 7560 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7561 const llvm::UTF8 *E = 7562 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7563 llvm::ConversionResult Result = 7564 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7565 7566 if (Result != llvm::conversionOK) { 7567 unsigned char FirstChar = *csStart; 7568 CodePoint = (llvm::UTF32)FirstChar; 7569 } 7570 7571 llvm::raw_string_ostream OS(CodePointStr); 7572 if (CodePoint < 256) 7573 OS << "\\x" << llvm::format("%02x", CodePoint); 7574 else if (CodePoint <= 0xFFFF) 7575 OS << "\\u" << llvm::format("%04x", CodePoint); 7576 else 7577 OS << "\\U" << llvm::format("%08x", CodePoint); 7578 OS.flush(); 7579 Specifier = CodePointStr; 7580 } 7581 7582 EmitFormatDiagnostic( 7583 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7584 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7585 7586 return keepGoing; 7587 } 7588 7589 void 7590 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7591 const char *startSpec, 7592 unsigned specifierLen) { 7593 EmitFormatDiagnostic( 7594 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7595 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7596 } 7597 7598 bool 7599 CheckFormatHandler::CheckNumArgs( 7600 const analyze_format_string::FormatSpecifier &FS, 7601 const analyze_format_string::ConversionSpecifier &CS, 7602 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7603 7604 if (argIndex >= NumDataArgs) { 7605 PartialDiagnostic PDiag = FS.usesPositionalArg() 7606 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7607 << (argIndex+1) << NumDataArgs) 7608 : S.PDiag(diag::warn_printf_insufficient_data_args); 7609 EmitFormatDiagnostic( 7610 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7611 getSpecifierRange(startSpecifier, specifierLen)); 7612 7613 // Since more arguments than conversion tokens are given, by extension 7614 // all arguments are covered, so mark this as so. 7615 UncoveredArg.setAllCovered(); 7616 return false; 7617 } 7618 return true; 7619 } 7620 7621 template<typename Range> 7622 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7623 SourceLocation Loc, 7624 bool IsStringLocation, 7625 Range StringRange, 7626 ArrayRef<FixItHint> FixIt) { 7627 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7628 Loc, IsStringLocation, StringRange, FixIt); 7629 } 7630 7631 /// If the format string is not within the function call, emit a note 7632 /// so that the function call and string are in diagnostic messages. 7633 /// 7634 /// \param InFunctionCall if true, the format string is within the function 7635 /// call and only one diagnostic message will be produced. Otherwise, an 7636 /// extra note will be emitted pointing to location of the format string. 7637 /// 7638 /// \param ArgumentExpr the expression that is passed as the format string 7639 /// argument in the function call. Used for getting locations when two 7640 /// diagnostics are emitted. 7641 /// 7642 /// \param PDiag the callee should already have provided any strings for the 7643 /// diagnostic message. This function only adds locations and fixits 7644 /// to diagnostics. 7645 /// 7646 /// \param Loc primary location for diagnostic. If two diagnostics are 7647 /// required, one will be at Loc and a new SourceLocation will be created for 7648 /// the other one. 7649 /// 7650 /// \param IsStringLocation if true, Loc points to the format string should be 7651 /// used for the note. Otherwise, Loc points to the argument list and will 7652 /// be used with PDiag. 7653 /// 7654 /// \param StringRange some or all of the string to highlight. This is 7655 /// templated so it can accept either a CharSourceRange or a SourceRange. 7656 /// 7657 /// \param FixIt optional fix it hint for the format string. 7658 template <typename Range> 7659 void CheckFormatHandler::EmitFormatDiagnostic( 7660 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7661 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7662 Range StringRange, ArrayRef<FixItHint> FixIt) { 7663 if (InFunctionCall) { 7664 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7665 D << StringRange; 7666 D << FixIt; 7667 } else { 7668 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7669 << ArgumentExpr->getSourceRange(); 7670 7671 const Sema::SemaDiagnosticBuilder &Note = 7672 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7673 diag::note_format_string_defined); 7674 7675 Note << StringRange; 7676 Note << FixIt; 7677 } 7678 } 7679 7680 //===--- CHECK: Printf format string checking ------------------------------===// 7681 7682 namespace { 7683 7684 class CheckPrintfHandler : public CheckFormatHandler { 7685 public: 7686 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7687 const Expr *origFormatExpr, 7688 const Sema::FormatStringType type, unsigned firstDataArg, 7689 unsigned numDataArgs, bool isObjC, const char *beg, 7690 bool hasVAListArg, ArrayRef<const Expr *> Args, 7691 unsigned formatIdx, bool inFunctionCall, 7692 Sema::VariadicCallType CallType, 7693 llvm::SmallBitVector &CheckedVarArgs, 7694 UncoveredArgHandler &UncoveredArg) 7695 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7696 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7697 inFunctionCall, CallType, CheckedVarArgs, 7698 UncoveredArg) {} 7699 7700 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7701 7702 /// Returns true if '%@' specifiers are allowed in the format string. 7703 bool allowsObjCArg() const { 7704 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7705 FSType == Sema::FST_OSTrace; 7706 } 7707 7708 bool HandleInvalidPrintfConversionSpecifier( 7709 const analyze_printf::PrintfSpecifier &FS, 7710 const char *startSpecifier, 7711 unsigned specifierLen) override; 7712 7713 void handleInvalidMaskType(StringRef MaskType) override; 7714 7715 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7716 const char *startSpecifier, 7717 unsigned specifierLen) override; 7718 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7719 const char *StartSpecifier, 7720 unsigned SpecifierLen, 7721 const Expr *E); 7722 7723 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7724 const char *startSpecifier, unsigned specifierLen); 7725 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7726 const analyze_printf::OptionalAmount &Amt, 7727 unsigned type, 7728 const char *startSpecifier, unsigned specifierLen); 7729 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7730 const analyze_printf::OptionalFlag &flag, 7731 const char *startSpecifier, unsigned specifierLen); 7732 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7733 const analyze_printf::OptionalFlag &ignoredFlag, 7734 const analyze_printf::OptionalFlag &flag, 7735 const char *startSpecifier, unsigned specifierLen); 7736 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7737 const Expr *E); 7738 7739 void HandleEmptyObjCModifierFlag(const char *startFlag, 7740 unsigned flagLen) override; 7741 7742 void HandleInvalidObjCModifierFlag(const char *startFlag, 7743 unsigned flagLen) override; 7744 7745 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7746 const char *flagsEnd, 7747 const char *conversionPosition) 7748 override; 7749 }; 7750 7751 } // namespace 7752 7753 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7754 const analyze_printf::PrintfSpecifier &FS, 7755 const char *startSpecifier, 7756 unsigned specifierLen) { 7757 const analyze_printf::PrintfConversionSpecifier &CS = 7758 FS.getConversionSpecifier(); 7759 7760 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7761 getLocationOfByte(CS.getStart()), 7762 startSpecifier, specifierLen, 7763 CS.getStart(), CS.getLength()); 7764 } 7765 7766 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7767 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7768 } 7769 7770 bool CheckPrintfHandler::HandleAmount( 7771 const analyze_format_string::OptionalAmount &Amt, 7772 unsigned k, const char *startSpecifier, 7773 unsigned specifierLen) { 7774 if (Amt.hasDataArgument()) { 7775 if (!HasVAListArg) { 7776 unsigned argIndex = Amt.getArgIndex(); 7777 if (argIndex >= NumDataArgs) { 7778 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7779 << k, 7780 getLocationOfByte(Amt.getStart()), 7781 /*IsStringLocation*/true, 7782 getSpecifierRange(startSpecifier, specifierLen)); 7783 // Don't do any more checking. We will just emit 7784 // spurious errors. 7785 return false; 7786 } 7787 7788 // Type check the data argument. It should be an 'int'. 7789 // Although not in conformance with C99, we also allow the argument to be 7790 // an 'unsigned int' as that is a reasonably safe case. GCC also 7791 // doesn't emit a warning for that case. 7792 CoveredArgs.set(argIndex); 7793 const Expr *Arg = getDataArg(argIndex); 7794 if (!Arg) 7795 return false; 7796 7797 QualType T = Arg->getType(); 7798 7799 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7800 assert(AT.isValid()); 7801 7802 if (!AT.matchesType(S.Context, T)) { 7803 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7804 << k << AT.getRepresentativeTypeName(S.Context) 7805 << T << Arg->getSourceRange(), 7806 getLocationOfByte(Amt.getStart()), 7807 /*IsStringLocation*/true, 7808 getSpecifierRange(startSpecifier, specifierLen)); 7809 // Don't do any more checking. We will just emit 7810 // spurious errors. 7811 return false; 7812 } 7813 } 7814 } 7815 return true; 7816 } 7817 7818 void CheckPrintfHandler::HandleInvalidAmount( 7819 const analyze_printf::PrintfSpecifier &FS, 7820 const analyze_printf::OptionalAmount &Amt, 7821 unsigned type, 7822 const char *startSpecifier, 7823 unsigned specifierLen) { 7824 const analyze_printf::PrintfConversionSpecifier &CS = 7825 FS.getConversionSpecifier(); 7826 7827 FixItHint fixit = 7828 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7829 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7830 Amt.getConstantLength())) 7831 : FixItHint(); 7832 7833 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7834 << type << CS.toString(), 7835 getLocationOfByte(Amt.getStart()), 7836 /*IsStringLocation*/true, 7837 getSpecifierRange(startSpecifier, specifierLen), 7838 fixit); 7839 } 7840 7841 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7842 const analyze_printf::OptionalFlag &flag, 7843 const char *startSpecifier, 7844 unsigned specifierLen) { 7845 // Warn about pointless flag with a fixit removal. 7846 const analyze_printf::PrintfConversionSpecifier &CS = 7847 FS.getConversionSpecifier(); 7848 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7849 << flag.toString() << CS.toString(), 7850 getLocationOfByte(flag.getPosition()), 7851 /*IsStringLocation*/true, 7852 getSpecifierRange(startSpecifier, specifierLen), 7853 FixItHint::CreateRemoval( 7854 getSpecifierRange(flag.getPosition(), 1))); 7855 } 7856 7857 void CheckPrintfHandler::HandleIgnoredFlag( 7858 const analyze_printf::PrintfSpecifier &FS, 7859 const analyze_printf::OptionalFlag &ignoredFlag, 7860 const analyze_printf::OptionalFlag &flag, 7861 const char *startSpecifier, 7862 unsigned specifierLen) { 7863 // Warn about ignored flag with a fixit removal. 7864 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7865 << ignoredFlag.toString() << flag.toString(), 7866 getLocationOfByte(ignoredFlag.getPosition()), 7867 /*IsStringLocation*/true, 7868 getSpecifierRange(startSpecifier, specifierLen), 7869 FixItHint::CreateRemoval( 7870 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7871 } 7872 7873 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7874 unsigned flagLen) { 7875 // Warn about an empty flag. 7876 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7877 getLocationOfByte(startFlag), 7878 /*IsStringLocation*/true, 7879 getSpecifierRange(startFlag, flagLen)); 7880 } 7881 7882 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7883 unsigned flagLen) { 7884 // Warn about an invalid flag. 7885 auto Range = getSpecifierRange(startFlag, flagLen); 7886 StringRef flag(startFlag, flagLen); 7887 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7888 getLocationOfByte(startFlag), 7889 /*IsStringLocation*/true, 7890 Range, FixItHint::CreateRemoval(Range)); 7891 } 7892 7893 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7894 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7895 // Warn about using '[...]' without a '@' conversion. 7896 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7897 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7898 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7899 getLocationOfByte(conversionPosition), 7900 /*IsStringLocation*/true, 7901 Range, FixItHint::CreateRemoval(Range)); 7902 } 7903 7904 // Determines if the specified is a C++ class or struct containing 7905 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7906 // "c_str()"). 7907 template<typename MemberKind> 7908 static llvm::SmallPtrSet<MemberKind*, 1> 7909 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7910 const RecordType *RT = Ty->getAs<RecordType>(); 7911 llvm::SmallPtrSet<MemberKind*, 1> Results; 7912 7913 if (!RT) 7914 return Results; 7915 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7916 if (!RD || !RD->getDefinition()) 7917 return Results; 7918 7919 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7920 Sema::LookupMemberName); 7921 R.suppressDiagnostics(); 7922 7923 // We just need to include all members of the right kind turned up by the 7924 // filter, at this point. 7925 if (S.LookupQualifiedName(R, RT->getDecl())) 7926 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7927 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7928 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7929 Results.insert(FK); 7930 } 7931 return Results; 7932 } 7933 7934 /// Check if we could call '.c_str()' on an object. 7935 /// 7936 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7937 /// allow the call, or if it would be ambiguous). 7938 bool Sema::hasCStrMethod(const Expr *E) { 7939 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7940 7941 MethodSet Results = 7942 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7943 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7944 MI != ME; ++MI) 7945 if ((*MI)->getMinRequiredArguments() == 0) 7946 return true; 7947 return false; 7948 } 7949 7950 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7951 // better diagnostic if so. AT is assumed to be valid. 7952 // Returns true when a c_str() conversion method is found. 7953 bool CheckPrintfHandler::checkForCStrMembers( 7954 const analyze_printf::ArgType &AT, const Expr *E) { 7955 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7956 7957 MethodSet Results = 7958 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7959 7960 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7961 MI != ME; ++MI) { 7962 const CXXMethodDecl *Method = *MI; 7963 if (Method->getMinRequiredArguments() == 0 && 7964 AT.matchesType(S.Context, Method->getReturnType())) { 7965 // FIXME: Suggest parens if the expression needs them. 7966 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7967 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7968 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7969 return true; 7970 } 7971 } 7972 7973 return false; 7974 } 7975 7976 bool 7977 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7978 &FS, 7979 const char *startSpecifier, 7980 unsigned specifierLen) { 7981 using namespace analyze_format_string; 7982 using namespace analyze_printf; 7983 7984 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7985 7986 if (FS.consumesDataArgument()) { 7987 if (atFirstArg) { 7988 atFirstArg = false; 7989 usesPositionalArgs = FS.usesPositionalArg(); 7990 } 7991 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7992 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7993 startSpecifier, specifierLen); 7994 return false; 7995 } 7996 } 7997 7998 // First check if the field width, precision, and conversion specifier 7999 // have matching data arguments. 8000 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8001 startSpecifier, specifierLen)) { 8002 return false; 8003 } 8004 8005 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8006 startSpecifier, specifierLen)) { 8007 return false; 8008 } 8009 8010 if (!CS.consumesDataArgument()) { 8011 // FIXME: Technically specifying a precision or field width here 8012 // makes no sense. Worth issuing a warning at some point. 8013 return true; 8014 } 8015 8016 // Consume the argument. 8017 unsigned argIndex = FS.getArgIndex(); 8018 if (argIndex < NumDataArgs) { 8019 // The check to see if the argIndex is valid will come later. 8020 // We set the bit here because we may exit early from this 8021 // function if we encounter some other error. 8022 CoveredArgs.set(argIndex); 8023 } 8024 8025 // FreeBSD kernel extensions. 8026 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8027 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8028 // We need at least two arguments. 8029 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8030 return false; 8031 8032 // Claim the second argument. 8033 CoveredArgs.set(argIndex + 1); 8034 8035 // Type check the first argument (int for %b, pointer for %D) 8036 const Expr *Ex = getDataArg(argIndex); 8037 const analyze_printf::ArgType &AT = 8038 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8039 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8040 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8041 EmitFormatDiagnostic( 8042 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8043 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8044 << false << Ex->getSourceRange(), 8045 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8046 getSpecifierRange(startSpecifier, specifierLen)); 8047 8048 // Type check the second argument (char * for both %b and %D) 8049 Ex = getDataArg(argIndex + 1); 8050 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8051 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8052 EmitFormatDiagnostic( 8053 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8054 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8055 << false << Ex->getSourceRange(), 8056 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8057 getSpecifierRange(startSpecifier, specifierLen)); 8058 8059 return true; 8060 } 8061 8062 // Check for using an Objective-C specific conversion specifier 8063 // in a non-ObjC literal. 8064 if (!allowsObjCArg() && CS.isObjCArg()) { 8065 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8066 specifierLen); 8067 } 8068 8069 // %P can only be used with os_log. 8070 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8071 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8072 specifierLen); 8073 } 8074 8075 // %n is not allowed with os_log. 8076 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8077 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8078 getLocationOfByte(CS.getStart()), 8079 /*IsStringLocation*/ false, 8080 getSpecifierRange(startSpecifier, specifierLen)); 8081 8082 return true; 8083 } 8084 8085 // Only scalars are allowed for os_trace. 8086 if (FSType == Sema::FST_OSTrace && 8087 (CS.getKind() == ConversionSpecifier::PArg || 8088 CS.getKind() == ConversionSpecifier::sArg || 8089 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8090 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8091 specifierLen); 8092 } 8093 8094 // Check for use of public/private annotation outside of os_log(). 8095 if (FSType != Sema::FST_OSLog) { 8096 if (FS.isPublic().isSet()) { 8097 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8098 << "public", 8099 getLocationOfByte(FS.isPublic().getPosition()), 8100 /*IsStringLocation*/ false, 8101 getSpecifierRange(startSpecifier, specifierLen)); 8102 } 8103 if (FS.isPrivate().isSet()) { 8104 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8105 << "private", 8106 getLocationOfByte(FS.isPrivate().getPosition()), 8107 /*IsStringLocation*/ false, 8108 getSpecifierRange(startSpecifier, specifierLen)); 8109 } 8110 } 8111 8112 // Check for invalid use of field width 8113 if (!FS.hasValidFieldWidth()) { 8114 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8115 startSpecifier, specifierLen); 8116 } 8117 8118 // Check for invalid use of precision 8119 if (!FS.hasValidPrecision()) { 8120 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8121 startSpecifier, specifierLen); 8122 } 8123 8124 // Precision is mandatory for %P specifier. 8125 if (CS.getKind() == ConversionSpecifier::PArg && 8126 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8127 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8128 getLocationOfByte(startSpecifier), 8129 /*IsStringLocation*/ false, 8130 getSpecifierRange(startSpecifier, specifierLen)); 8131 } 8132 8133 // Check each flag does not conflict with any other component. 8134 if (!FS.hasValidThousandsGroupingPrefix()) 8135 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8136 if (!FS.hasValidLeadingZeros()) 8137 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8138 if (!FS.hasValidPlusPrefix()) 8139 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8140 if (!FS.hasValidSpacePrefix()) 8141 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8142 if (!FS.hasValidAlternativeForm()) 8143 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8144 if (!FS.hasValidLeftJustified()) 8145 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8146 8147 // Check that flags are not ignored by another flag 8148 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8149 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8150 startSpecifier, specifierLen); 8151 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8152 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8153 startSpecifier, specifierLen); 8154 8155 // Check the length modifier is valid with the given conversion specifier. 8156 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8157 S.getLangOpts())) 8158 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8159 diag::warn_format_nonsensical_length); 8160 else if (!FS.hasStandardLengthModifier()) 8161 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8162 else if (!FS.hasStandardLengthConversionCombination()) 8163 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8164 diag::warn_format_non_standard_conversion_spec); 8165 8166 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8167 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8168 8169 // The remaining checks depend on the data arguments. 8170 if (HasVAListArg) 8171 return true; 8172 8173 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8174 return false; 8175 8176 const Expr *Arg = getDataArg(argIndex); 8177 if (!Arg) 8178 return true; 8179 8180 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8181 } 8182 8183 static bool requiresParensToAddCast(const Expr *E) { 8184 // FIXME: We should have a general way to reason about operator 8185 // precedence and whether parens are actually needed here. 8186 // Take care of a few common cases where they aren't. 8187 const Expr *Inside = E->IgnoreImpCasts(); 8188 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8189 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8190 8191 switch (Inside->getStmtClass()) { 8192 case Stmt::ArraySubscriptExprClass: 8193 case Stmt::CallExprClass: 8194 case Stmt::CharacterLiteralClass: 8195 case Stmt::CXXBoolLiteralExprClass: 8196 case Stmt::DeclRefExprClass: 8197 case Stmt::FloatingLiteralClass: 8198 case Stmt::IntegerLiteralClass: 8199 case Stmt::MemberExprClass: 8200 case Stmt::ObjCArrayLiteralClass: 8201 case Stmt::ObjCBoolLiteralExprClass: 8202 case Stmt::ObjCBoxedExprClass: 8203 case Stmt::ObjCDictionaryLiteralClass: 8204 case Stmt::ObjCEncodeExprClass: 8205 case Stmt::ObjCIvarRefExprClass: 8206 case Stmt::ObjCMessageExprClass: 8207 case Stmt::ObjCPropertyRefExprClass: 8208 case Stmt::ObjCStringLiteralClass: 8209 case Stmt::ObjCSubscriptRefExprClass: 8210 case Stmt::ParenExprClass: 8211 case Stmt::StringLiteralClass: 8212 case Stmt::UnaryOperatorClass: 8213 return false; 8214 default: 8215 return true; 8216 } 8217 } 8218 8219 static std::pair<QualType, StringRef> 8220 shouldNotPrintDirectly(const ASTContext &Context, 8221 QualType IntendedTy, 8222 const Expr *E) { 8223 // Use a 'while' to peel off layers of typedefs. 8224 QualType TyTy = IntendedTy; 8225 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8226 StringRef Name = UserTy->getDecl()->getName(); 8227 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8228 .Case("CFIndex", Context.getNSIntegerType()) 8229 .Case("NSInteger", Context.getNSIntegerType()) 8230 .Case("NSUInteger", Context.getNSUIntegerType()) 8231 .Case("SInt32", Context.IntTy) 8232 .Case("UInt32", Context.UnsignedIntTy) 8233 .Default(QualType()); 8234 8235 if (!CastTy.isNull()) 8236 return std::make_pair(CastTy, Name); 8237 8238 TyTy = UserTy->desugar(); 8239 } 8240 8241 // Strip parens if necessary. 8242 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8243 return shouldNotPrintDirectly(Context, 8244 PE->getSubExpr()->getType(), 8245 PE->getSubExpr()); 8246 8247 // If this is a conditional expression, then its result type is constructed 8248 // via usual arithmetic conversions and thus there might be no necessary 8249 // typedef sugar there. Recurse to operands to check for NSInteger & 8250 // Co. usage condition. 8251 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8252 QualType TrueTy, FalseTy; 8253 StringRef TrueName, FalseName; 8254 8255 std::tie(TrueTy, TrueName) = 8256 shouldNotPrintDirectly(Context, 8257 CO->getTrueExpr()->getType(), 8258 CO->getTrueExpr()); 8259 std::tie(FalseTy, FalseName) = 8260 shouldNotPrintDirectly(Context, 8261 CO->getFalseExpr()->getType(), 8262 CO->getFalseExpr()); 8263 8264 if (TrueTy == FalseTy) 8265 return std::make_pair(TrueTy, TrueName); 8266 else if (TrueTy.isNull()) 8267 return std::make_pair(FalseTy, FalseName); 8268 else if (FalseTy.isNull()) 8269 return std::make_pair(TrueTy, TrueName); 8270 } 8271 8272 return std::make_pair(QualType(), StringRef()); 8273 } 8274 8275 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8276 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8277 /// type do not count. 8278 static bool 8279 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8280 QualType From = ICE->getSubExpr()->getType(); 8281 QualType To = ICE->getType(); 8282 // It's an integer promotion if the destination type is the promoted 8283 // source type. 8284 if (ICE->getCastKind() == CK_IntegralCast && 8285 From->isPromotableIntegerType() && 8286 S.Context.getPromotedIntegerType(From) == To) 8287 return true; 8288 // Look through vector types, since we do default argument promotion for 8289 // those in OpenCL. 8290 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8291 From = VecTy->getElementType(); 8292 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8293 To = VecTy->getElementType(); 8294 // It's a floating promotion if the source type is a lower rank. 8295 return ICE->getCastKind() == CK_FloatingCast && 8296 S.Context.getFloatingTypeOrder(From, To) < 0; 8297 } 8298 8299 bool 8300 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8301 const char *StartSpecifier, 8302 unsigned SpecifierLen, 8303 const Expr *E) { 8304 using namespace analyze_format_string; 8305 using namespace analyze_printf; 8306 8307 // Now type check the data expression that matches the 8308 // format specifier. 8309 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8310 if (!AT.isValid()) 8311 return true; 8312 8313 QualType ExprTy = E->getType(); 8314 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8315 ExprTy = TET->getUnderlyingExpr()->getType(); 8316 } 8317 8318 // Diagnose attempts to print a boolean value as a character. Unlike other 8319 // -Wformat diagnostics, this is fine from a type perspective, but it still 8320 // doesn't make sense. 8321 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8322 E->isKnownToHaveBooleanValue()) { 8323 const CharSourceRange &CSR = 8324 getSpecifierRange(StartSpecifier, SpecifierLen); 8325 SmallString<4> FSString; 8326 llvm::raw_svector_ostream os(FSString); 8327 FS.toString(os); 8328 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8329 << FSString, 8330 E->getExprLoc(), false, CSR); 8331 return true; 8332 } 8333 8334 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8335 if (Match == analyze_printf::ArgType::Match) 8336 return true; 8337 8338 // Look through argument promotions for our error message's reported type. 8339 // This includes the integral and floating promotions, but excludes array 8340 // and function pointer decay (seeing that an argument intended to be a 8341 // string has type 'char [6]' is probably more confusing than 'char *') and 8342 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8343 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8344 if (isArithmeticArgumentPromotion(S, ICE)) { 8345 E = ICE->getSubExpr(); 8346 ExprTy = E->getType(); 8347 8348 // Check if we didn't match because of an implicit cast from a 'char' 8349 // or 'short' to an 'int'. This is done because printf is a varargs 8350 // function. 8351 if (ICE->getType() == S.Context.IntTy || 8352 ICE->getType() == S.Context.UnsignedIntTy) { 8353 // All further checking is done on the subexpression 8354 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8355 AT.matchesType(S.Context, ExprTy); 8356 if (ImplicitMatch == analyze_printf::ArgType::Match) 8357 return true; 8358 if (ImplicitMatch == ArgType::NoMatchPedantic || 8359 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8360 Match = ImplicitMatch; 8361 } 8362 } 8363 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8364 // Special case for 'a', which has type 'int' in C. 8365 // Note, however, that we do /not/ want to treat multibyte constants like 8366 // 'MooV' as characters! This form is deprecated but still exists. 8367 if (ExprTy == S.Context.IntTy) 8368 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8369 ExprTy = S.Context.CharTy; 8370 } 8371 8372 // Look through enums to their underlying type. 8373 bool IsEnum = false; 8374 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8375 ExprTy = EnumTy->getDecl()->getIntegerType(); 8376 IsEnum = true; 8377 } 8378 8379 // %C in an Objective-C context prints a unichar, not a wchar_t. 8380 // If the argument is an integer of some kind, believe the %C and suggest 8381 // a cast instead of changing the conversion specifier. 8382 QualType IntendedTy = ExprTy; 8383 if (isObjCContext() && 8384 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8385 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8386 !ExprTy->isCharType()) { 8387 // 'unichar' is defined as a typedef of unsigned short, but we should 8388 // prefer using the typedef if it is visible. 8389 IntendedTy = S.Context.UnsignedShortTy; 8390 8391 // While we are here, check if the value is an IntegerLiteral that happens 8392 // to be within the valid range. 8393 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8394 const llvm::APInt &V = IL->getValue(); 8395 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8396 return true; 8397 } 8398 8399 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8400 Sema::LookupOrdinaryName); 8401 if (S.LookupName(Result, S.getCurScope())) { 8402 NamedDecl *ND = Result.getFoundDecl(); 8403 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8404 if (TD->getUnderlyingType() == IntendedTy) 8405 IntendedTy = S.Context.getTypedefType(TD); 8406 } 8407 } 8408 } 8409 8410 // Special-case some of Darwin's platform-independence types by suggesting 8411 // casts to primitive types that are known to be large enough. 8412 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8413 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8414 QualType CastTy; 8415 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8416 if (!CastTy.isNull()) { 8417 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8418 // (long in ASTContext). Only complain to pedants. 8419 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8420 (AT.isSizeT() || AT.isPtrdiffT()) && 8421 AT.matchesType(S.Context, CastTy)) 8422 Match = ArgType::NoMatchPedantic; 8423 IntendedTy = CastTy; 8424 ShouldNotPrintDirectly = true; 8425 } 8426 } 8427 8428 // We may be able to offer a FixItHint if it is a supported type. 8429 PrintfSpecifier fixedFS = FS; 8430 bool Success = 8431 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8432 8433 if (Success) { 8434 // Get the fix string from the fixed format specifier 8435 SmallString<16> buf; 8436 llvm::raw_svector_ostream os(buf); 8437 fixedFS.toString(os); 8438 8439 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8440 8441 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8442 unsigned Diag; 8443 switch (Match) { 8444 case ArgType::Match: llvm_unreachable("expected non-matching"); 8445 case ArgType::NoMatchPedantic: 8446 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8447 break; 8448 case ArgType::NoMatchTypeConfusion: 8449 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8450 break; 8451 case ArgType::NoMatch: 8452 Diag = diag::warn_format_conversion_argument_type_mismatch; 8453 break; 8454 } 8455 8456 // In this case, the specifier is wrong and should be changed to match 8457 // the argument. 8458 EmitFormatDiagnostic(S.PDiag(Diag) 8459 << AT.getRepresentativeTypeName(S.Context) 8460 << IntendedTy << IsEnum << E->getSourceRange(), 8461 E->getBeginLoc(), 8462 /*IsStringLocation*/ false, SpecRange, 8463 FixItHint::CreateReplacement(SpecRange, os.str())); 8464 } else { 8465 // The canonical type for formatting this value is different from the 8466 // actual type of the expression. (This occurs, for example, with Darwin's 8467 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8468 // should be printed as 'long' for 64-bit compatibility.) 8469 // Rather than emitting a normal format/argument mismatch, we want to 8470 // add a cast to the recommended type (and correct the format string 8471 // if necessary). 8472 SmallString<16> CastBuf; 8473 llvm::raw_svector_ostream CastFix(CastBuf); 8474 CastFix << "("; 8475 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8476 CastFix << ")"; 8477 8478 SmallVector<FixItHint,4> Hints; 8479 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8480 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8481 8482 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8483 // If there's already a cast present, just replace it. 8484 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8485 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8486 8487 } else if (!requiresParensToAddCast(E)) { 8488 // If the expression has high enough precedence, 8489 // just write the C-style cast. 8490 Hints.push_back( 8491 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8492 } else { 8493 // Otherwise, add parens around the expression as well as the cast. 8494 CastFix << "("; 8495 Hints.push_back( 8496 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8497 8498 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8499 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8500 } 8501 8502 if (ShouldNotPrintDirectly) { 8503 // The expression has a type that should not be printed directly. 8504 // We extract the name from the typedef because we don't want to show 8505 // the underlying type in the diagnostic. 8506 StringRef Name; 8507 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8508 Name = TypedefTy->getDecl()->getName(); 8509 else 8510 Name = CastTyName; 8511 unsigned Diag = Match == ArgType::NoMatchPedantic 8512 ? diag::warn_format_argument_needs_cast_pedantic 8513 : diag::warn_format_argument_needs_cast; 8514 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8515 << E->getSourceRange(), 8516 E->getBeginLoc(), /*IsStringLocation=*/false, 8517 SpecRange, Hints); 8518 } else { 8519 // In this case, the expression could be printed using a different 8520 // specifier, but we've decided that the specifier is probably correct 8521 // and we should cast instead. Just use the normal warning message. 8522 EmitFormatDiagnostic( 8523 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8524 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8525 << E->getSourceRange(), 8526 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8527 } 8528 } 8529 } else { 8530 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8531 SpecifierLen); 8532 // Since the warning for passing non-POD types to variadic functions 8533 // was deferred until now, we emit a warning for non-POD 8534 // arguments here. 8535 switch (S.isValidVarArgType(ExprTy)) { 8536 case Sema::VAK_Valid: 8537 case Sema::VAK_ValidInCXX11: { 8538 unsigned Diag; 8539 switch (Match) { 8540 case ArgType::Match: llvm_unreachable("expected non-matching"); 8541 case ArgType::NoMatchPedantic: 8542 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8543 break; 8544 case ArgType::NoMatchTypeConfusion: 8545 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8546 break; 8547 case ArgType::NoMatch: 8548 Diag = diag::warn_format_conversion_argument_type_mismatch; 8549 break; 8550 } 8551 8552 EmitFormatDiagnostic( 8553 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8554 << IsEnum << CSR << E->getSourceRange(), 8555 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8556 break; 8557 } 8558 case Sema::VAK_Undefined: 8559 case Sema::VAK_MSVCUndefined: 8560 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8561 << S.getLangOpts().CPlusPlus11 << ExprTy 8562 << CallType 8563 << AT.getRepresentativeTypeName(S.Context) << CSR 8564 << E->getSourceRange(), 8565 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8566 checkForCStrMembers(AT, E); 8567 break; 8568 8569 case Sema::VAK_Invalid: 8570 if (ExprTy->isObjCObjectType()) 8571 EmitFormatDiagnostic( 8572 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8573 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8574 << AT.getRepresentativeTypeName(S.Context) << CSR 8575 << E->getSourceRange(), 8576 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8577 else 8578 // FIXME: If this is an initializer list, suggest removing the braces 8579 // or inserting a cast to the target type. 8580 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8581 << isa<InitListExpr>(E) << ExprTy << CallType 8582 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8583 break; 8584 } 8585 8586 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8587 "format string specifier index out of range"); 8588 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8589 } 8590 8591 return true; 8592 } 8593 8594 //===--- CHECK: Scanf format string checking ------------------------------===// 8595 8596 namespace { 8597 8598 class CheckScanfHandler : public CheckFormatHandler { 8599 public: 8600 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8601 const Expr *origFormatExpr, Sema::FormatStringType type, 8602 unsigned firstDataArg, unsigned numDataArgs, 8603 const char *beg, bool hasVAListArg, 8604 ArrayRef<const Expr *> Args, unsigned formatIdx, 8605 bool inFunctionCall, Sema::VariadicCallType CallType, 8606 llvm::SmallBitVector &CheckedVarArgs, 8607 UncoveredArgHandler &UncoveredArg) 8608 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8609 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8610 inFunctionCall, CallType, CheckedVarArgs, 8611 UncoveredArg) {} 8612 8613 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8614 const char *startSpecifier, 8615 unsigned specifierLen) override; 8616 8617 bool HandleInvalidScanfConversionSpecifier( 8618 const analyze_scanf::ScanfSpecifier &FS, 8619 const char *startSpecifier, 8620 unsigned specifierLen) override; 8621 8622 void HandleIncompleteScanList(const char *start, const char *end) override; 8623 }; 8624 8625 } // namespace 8626 8627 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8628 const char *end) { 8629 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8630 getLocationOfByte(end), /*IsStringLocation*/true, 8631 getSpecifierRange(start, end - start)); 8632 } 8633 8634 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8635 const analyze_scanf::ScanfSpecifier &FS, 8636 const char *startSpecifier, 8637 unsigned specifierLen) { 8638 const analyze_scanf::ScanfConversionSpecifier &CS = 8639 FS.getConversionSpecifier(); 8640 8641 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8642 getLocationOfByte(CS.getStart()), 8643 startSpecifier, specifierLen, 8644 CS.getStart(), CS.getLength()); 8645 } 8646 8647 bool CheckScanfHandler::HandleScanfSpecifier( 8648 const analyze_scanf::ScanfSpecifier &FS, 8649 const char *startSpecifier, 8650 unsigned specifierLen) { 8651 using namespace analyze_scanf; 8652 using namespace analyze_format_string; 8653 8654 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8655 8656 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8657 // be used to decide if we are using positional arguments consistently. 8658 if (FS.consumesDataArgument()) { 8659 if (atFirstArg) { 8660 atFirstArg = false; 8661 usesPositionalArgs = FS.usesPositionalArg(); 8662 } 8663 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8664 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8665 startSpecifier, specifierLen); 8666 return false; 8667 } 8668 } 8669 8670 // Check if the field with is non-zero. 8671 const OptionalAmount &Amt = FS.getFieldWidth(); 8672 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8673 if (Amt.getConstantAmount() == 0) { 8674 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8675 Amt.getConstantLength()); 8676 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8677 getLocationOfByte(Amt.getStart()), 8678 /*IsStringLocation*/true, R, 8679 FixItHint::CreateRemoval(R)); 8680 } 8681 } 8682 8683 if (!FS.consumesDataArgument()) { 8684 // FIXME: Technically specifying a precision or field width here 8685 // makes no sense. Worth issuing a warning at some point. 8686 return true; 8687 } 8688 8689 // Consume the argument. 8690 unsigned argIndex = FS.getArgIndex(); 8691 if (argIndex < NumDataArgs) { 8692 // The check to see if the argIndex is valid will come later. 8693 // We set the bit here because we may exit early from this 8694 // function if we encounter some other error. 8695 CoveredArgs.set(argIndex); 8696 } 8697 8698 // Check the length modifier is valid with the given conversion specifier. 8699 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8700 S.getLangOpts())) 8701 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8702 diag::warn_format_nonsensical_length); 8703 else if (!FS.hasStandardLengthModifier()) 8704 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8705 else if (!FS.hasStandardLengthConversionCombination()) 8706 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8707 diag::warn_format_non_standard_conversion_spec); 8708 8709 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8710 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8711 8712 // The remaining checks depend on the data arguments. 8713 if (HasVAListArg) 8714 return true; 8715 8716 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8717 return false; 8718 8719 // Check that the argument type matches the format specifier. 8720 const Expr *Ex = getDataArg(argIndex); 8721 if (!Ex) 8722 return true; 8723 8724 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8725 8726 if (!AT.isValid()) { 8727 return true; 8728 } 8729 8730 analyze_format_string::ArgType::MatchKind Match = 8731 AT.matchesType(S.Context, Ex->getType()); 8732 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8733 if (Match == analyze_format_string::ArgType::Match) 8734 return true; 8735 8736 ScanfSpecifier fixedFS = FS; 8737 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8738 S.getLangOpts(), S.Context); 8739 8740 unsigned Diag = 8741 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8742 : diag::warn_format_conversion_argument_type_mismatch; 8743 8744 if (Success) { 8745 // Get the fix string from the fixed format specifier. 8746 SmallString<128> buf; 8747 llvm::raw_svector_ostream os(buf); 8748 fixedFS.toString(os); 8749 8750 EmitFormatDiagnostic( 8751 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8752 << Ex->getType() << false << Ex->getSourceRange(), 8753 Ex->getBeginLoc(), 8754 /*IsStringLocation*/ false, 8755 getSpecifierRange(startSpecifier, specifierLen), 8756 FixItHint::CreateReplacement( 8757 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8758 } else { 8759 EmitFormatDiagnostic(S.PDiag(Diag) 8760 << AT.getRepresentativeTypeName(S.Context) 8761 << Ex->getType() << false << Ex->getSourceRange(), 8762 Ex->getBeginLoc(), 8763 /*IsStringLocation*/ false, 8764 getSpecifierRange(startSpecifier, specifierLen)); 8765 } 8766 8767 return true; 8768 } 8769 8770 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8771 const Expr *OrigFormatExpr, 8772 ArrayRef<const Expr *> Args, 8773 bool HasVAListArg, unsigned format_idx, 8774 unsigned firstDataArg, 8775 Sema::FormatStringType Type, 8776 bool inFunctionCall, 8777 Sema::VariadicCallType CallType, 8778 llvm::SmallBitVector &CheckedVarArgs, 8779 UncoveredArgHandler &UncoveredArg, 8780 bool IgnoreStringsWithoutSpecifiers) { 8781 // CHECK: is the format string a wide literal? 8782 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8783 CheckFormatHandler::EmitFormatDiagnostic( 8784 S, inFunctionCall, Args[format_idx], 8785 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8786 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8787 return; 8788 } 8789 8790 // Str - The format string. NOTE: this is NOT null-terminated! 8791 StringRef StrRef = FExpr->getString(); 8792 const char *Str = StrRef.data(); 8793 // Account for cases where the string literal is truncated in a declaration. 8794 const ConstantArrayType *T = 8795 S.Context.getAsConstantArrayType(FExpr->getType()); 8796 assert(T && "String literal not of constant array type!"); 8797 size_t TypeSize = T->getSize().getZExtValue(); 8798 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8799 const unsigned numDataArgs = Args.size() - firstDataArg; 8800 8801 if (IgnoreStringsWithoutSpecifiers && 8802 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8803 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8804 return; 8805 8806 // Emit a warning if the string literal is truncated and does not contain an 8807 // embedded null character. 8808 if (TypeSize <= StrRef.size() && 8809 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8810 CheckFormatHandler::EmitFormatDiagnostic( 8811 S, inFunctionCall, Args[format_idx], 8812 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8813 FExpr->getBeginLoc(), 8814 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8815 return; 8816 } 8817 8818 // CHECK: empty format string? 8819 if (StrLen == 0 && numDataArgs > 0) { 8820 CheckFormatHandler::EmitFormatDiagnostic( 8821 S, inFunctionCall, Args[format_idx], 8822 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8823 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8824 return; 8825 } 8826 8827 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8828 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8829 Type == Sema::FST_OSTrace) { 8830 CheckPrintfHandler H( 8831 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8832 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8833 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8834 CheckedVarArgs, UncoveredArg); 8835 8836 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8837 S.getLangOpts(), 8838 S.Context.getTargetInfo(), 8839 Type == Sema::FST_FreeBSDKPrintf)) 8840 H.DoneProcessing(); 8841 } else if (Type == Sema::FST_Scanf) { 8842 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8843 numDataArgs, Str, HasVAListArg, Args, format_idx, 8844 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8845 8846 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8847 S.getLangOpts(), 8848 S.Context.getTargetInfo())) 8849 H.DoneProcessing(); 8850 } // TODO: handle other formats 8851 } 8852 8853 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8854 // Str - The format string. NOTE: this is NOT null-terminated! 8855 StringRef StrRef = FExpr->getString(); 8856 const char *Str = StrRef.data(); 8857 // Account for cases where the string literal is truncated in a declaration. 8858 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8859 assert(T && "String literal not of constant array type!"); 8860 size_t TypeSize = T->getSize().getZExtValue(); 8861 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8862 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8863 getLangOpts(), 8864 Context.getTargetInfo()); 8865 } 8866 8867 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8868 8869 // Returns the related absolute value function that is larger, of 0 if one 8870 // does not exist. 8871 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8872 switch (AbsFunction) { 8873 default: 8874 return 0; 8875 8876 case Builtin::BI__builtin_abs: 8877 return Builtin::BI__builtin_labs; 8878 case Builtin::BI__builtin_labs: 8879 return Builtin::BI__builtin_llabs; 8880 case Builtin::BI__builtin_llabs: 8881 return 0; 8882 8883 case Builtin::BI__builtin_fabsf: 8884 return Builtin::BI__builtin_fabs; 8885 case Builtin::BI__builtin_fabs: 8886 return Builtin::BI__builtin_fabsl; 8887 case Builtin::BI__builtin_fabsl: 8888 return 0; 8889 8890 case Builtin::BI__builtin_cabsf: 8891 return Builtin::BI__builtin_cabs; 8892 case Builtin::BI__builtin_cabs: 8893 return Builtin::BI__builtin_cabsl; 8894 case Builtin::BI__builtin_cabsl: 8895 return 0; 8896 8897 case Builtin::BIabs: 8898 return Builtin::BIlabs; 8899 case Builtin::BIlabs: 8900 return Builtin::BIllabs; 8901 case Builtin::BIllabs: 8902 return 0; 8903 8904 case Builtin::BIfabsf: 8905 return Builtin::BIfabs; 8906 case Builtin::BIfabs: 8907 return Builtin::BIfabsl; 8908 case Builtin::BIfabsl: 8909 return 0; 8910 8911 case Builtin::BIcabsf: 8912 return Builtin::BIcabs; 8913 case Builtin::BIcabs: 8914 return Builtin::BIcabsl; 8915 case Builtin::BIcabsl: 8916 return 0; 8917 } 8918 } 8919 8920 // Returns the argument type of the absolute value function. 8921 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8922 unsigned AbsType) { 8923 if (AbsType == 0) 8924 return QualType(); 8925 8926 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8927 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8928 if (Error != ASTContext::GE_None) 8929 return QualType(); 8930 8931 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8932 if (!FT) 8933 return QualType(); 8934 8935 if (FT->getNumParams() != 1) 8936 return QualType(); 8937 8938 return FT->getParamType(0); 8939 } 8940 8941 // Returns the best absolute value function, or zero, based on type and 8942 // current absolute value function. 8943 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8944 unsigned AbsFunctionKind) { 8945 unsigned BestKind = 0; 8946 uint64_t ArgSize = Context.getTypeSize(ArgType); 8947 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8948 Kind = getLargerAbsoluteValueFunction(Kind)) { 8949 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8950 if (Context.getTypeSize(ParamType) >= ArgSize) { 8951 if (BestKind == 0) 8952 BestKind = Kind; 8953 else if (Context.hasSameType(ParamType, ArgType)) { 8954 BestKind = Kind; 8955 break; 8956 } 8957 } 8958 } 8959 return BestKind; 8960 } 8961 8962 enum AbsoluteValueKind { 8963 AVK_Integer, 8964 AVK_Floating, 8965 AVK_Complex 8966 }; 8967 8968 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8969 if (T->isIntegralOrEnumerationType()) 8970 return AVK_Integer; 8971 if (T->isRealFloatingType()) 8972 return AVK_Floating; 8973 if (T->isAnyComplexType()) 8974 return AVK_Complex; 8975 8976 llvm_unreachable("Type not integer, floating, or complex"); 8977 } 8978 8979 // Changes the absolute value function to a different type. Preserves whether 8980 // the function is a builtin. 8981 static unsigned changeAbsFunction(unsigned AbsKind, 8982 AbsoluteValueKind ValueKind) { 8983 switch (ValueKind) { 8984 case AVK_Integer: 8985 switch (AbsKind) { 8986 default: 8987 return 0; 8988 case Builtin::BI__builtin_fabsf: 8989 case Builtin::BI__builtin_fabs: 8990 case Builtin::BI__builtin_fabsl: 8991 case Builtin::BI__builtin_cabsf: 8992 case Builtin::BI__builtin_cabs: 8993 case Builtin::BI__builtin_cabsl: 8994 return Builtin::BI__builtin_abs; 8995 case Builtin::BIfabsf: 8996 case Builtin::BIfabs: 8997 case Builtin::BIfabsl: 8998 case Builtin::BIcabsf: 8999 case Builtin::BIcabs: 9000 case Builtin::BIcabsl: 9001 return Builtin::BIabs; 9002 } 9003 case AVK_Floating: 9004 switch (AbsKind) { 9005 default: 9006 return 0; 9007 case Builtin::BI__builtin_abs: 9008 case Builtin::BI__builtin_labs: 9009 case Builtin::BI__builtin_llabs: 9010 case Builtin::BI__builtin_cabsf: 9011 case Builtin::BI__builtin_cabs: 9012 case Builtin::BI__builtin_cabsl: 9013 return Builtin::BI__builtin_fabsf; 9014 case Builtin::BIabs: 9015 case Builtin::BIlabs: 9016 case Builtin::BIllabs: 9017 case Builtin::BIcabsf: 9018 case Builtin::BIcabs: 9019 case Builtin::BIcabsl: 9020 return Builtin::BIfabsf; 9021 } 9022 case AVK_Complex: 9023 switch (AbsKind) { 9024 default: 9025 return 0; 9026 case Builtin::BI__builtin_abs: 9027 case Builtin::BI__builtin_labs: 9028 case Builtin::BI__builtin_llabs: 9029 case Builtin::BI__builtin_fabsf: 9030 case Builtin::BI__builtin_fabs: 9031 case Builtin::BI__builtin_fabsl: 9032 return Builtin::BI__builtin_cabsf; 9033 case Builtin::BIabs: 9034 case Builtin::BIlabs: 9035 case Builtin::BIllabs: 9036 case Builtin::BIfabsf: 9037 case Builtin::BIfabs: 9038 case Builtin::BIfabsl: 9039 return Builtin::BIcabsf; 9040 } 9041 } 9042 llvm_unreachable("Unable to convert function"); 9043 } 9044 9045 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9046 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9047 if (!FnInfo) 9048 return 0; 9049 9050 switch (FDecl->getBuiltinID()) { 9051 default: 9052 return 0; 9053 case Builtin::BI__builtin_abs: 9054 case Builtin::BI__builtin_fabs: 9055 case Builtin::BI__builtin_fabsf: 9056 case Builtin::BI__builtin_fabsl: 9057 case Builtin::BI__builtin_labs: 9058 case Builtin::BI__builtin_llabs: 9059 case Builtin::BI__builtin_cabs: 9060 case Builtin::BI__builtin_cabsf: 9061 case Builtin::BI__builtin_cabsl: 9062 case Builtin::BIabs: 9063 case Builtin::BIlabs: 9064 case Builtin::BIllabs: 9065 case Builtin::BIfabs: 9066 case Builtin::BIfabsf: 9067 case Builtin::BIfabsl: 9068 case Builtin::BIcabs: 9069 case Builtin::BIcabsf: 9070 case Builtin::BIcabsl: 9071 return FDecl->getBuiltinID(); 9072 } 9073 llvm_unreachable("Unknown Builtin type"); 9074 } 9075 9076 // If the replacement is valid, emit a note with replacement function. 9077 // Additionally, suggest including the proper header if not already included. 9078 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9079 unsigned AbsKind, QualType ArgType) { 9080 bool EmitHeaderHint = true; 9081 const char *HeaderName = nullptr; 9082 const char *FunctionName = nullptr; 9083 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9084 FunctionName = "std::abs"; 9085 if (ArgType->isIntegralOrEnumerationType()) { 9086 HeaderName = "cstdlib"; 9087 } else if (ArgType->isRealFloatingType()) { 9088 HeaderName = "cmath"; 9089 } else { 9090 llvm_unreachable("Invalid Type"); 9091 } 9092 9093 // Lookup all std::abs 9094 if (NamespaceDecl *Std = S.getStdNamespace()) { 9095 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9096 R.suppressDiagnostics(); 9097 S.LookupQualifiedName(R, Std); 9098 9099 for (const auto *I : R) { 9100 const FunctionDecl *FDecl = nullptr; 9101 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9102 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9103 } else { 9104 FDecl = dyn_cast<FunctionDecl>(I); 9105 } 9106 if (!FDecl) 9107 continue; 9108 9109 // Found std::abs(), check that they are the right ones. 9110 if (FDecl->getNumParams() != 1) 9111 continue; 9112 9113 // Check that the parameter type can handle the argument. 9114 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9115 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9116 S.Context.getTypeSize(ArgType) <= 9117 S.Context.getTypeSize(ParamType)) { 9118 // Found a function, don't need the header hint. 9119 EmitHeaderHint = false; 9120 break; 9121 } 9122 } 9123 } 9124 } else { 9125 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9126 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9127 9128 if (HeaderName) { 9129 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9130 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9131 R.suppressDiagnostics(); 9132 S.LookupName(R, S.getCurScope()); 9133 9134 if (R.isSingleResult()) { 9135 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9136 if (FD && FD->getBuiltinID() == AbsKind) { 9137 EmitHeaderHint = false; 9138 } else { 9139 return; 9140 } 9141 } else if (!R.empty()) { 9142 return; 9143 } 9144 } 9145 } 9146 9147 S.Diag(Loc, diag::note_replace_abs_function) 9148 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9149 9150 if (!HeaderName) 9151 return; 9152 9153 if (!EmitHeaderHint) 9154 return; 9155 9156 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9157 << FunctionName; 9158 } 9159 9160 template <std::size_t StrLen> 9161 static bool IsStdFunction(const FunctionDecl *FDecl, 9162 const char (&Str)[StrLen]) { 9163 if (!FDecl) 9164 return false; 9165 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9166 return false; 9167 if (!FDecl->isInStdNamespace()) 9168 return false; 9169 9170 return true; 9171 } 9172 9173 // Warn when using the wrong abs() function. 9174 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9175 const FunctionDecl *FDecl) { 9176 if (Call->getNumArgs() != 1) 9177 return; 9178 9179 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9180 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9181 if (AbsKind == 0 && !IsStdAbs) 9182 return; 9183 9184 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9185 QualType ParamType = Call->getArg(0)->getType(); 9186 9187 // Unsigned types cannot be negative. Suggest removing the absolute value 9188 // function call. 9189 if (ArgType->isUnsignedIntegerType()) { 9190 const char *FunctionName = 9191 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9192 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9193 Diag(Call->getExprLoc(), diag::note_remove_abs) 9194 << FunctionName 9195 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9196 return; 9197 } 9198 9199 // Taking the absolute value of a pointer is very suspicious, they probably 9200 // wanted to index into an array, dereference a pointer, call a function, etc. 9201 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9202 unsigned DiagType = 0; 9203 if (ArgType->isFunctionType()) 9204 DiagType = 1; 9205 else if (ArgType->isArrayType()) 9206 DiagType = 2; 9207 9208 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9209 return; 9210 } 9211 9212 // std::abs has overloads which prevent most of the absolute value problems 9213 // from occurring. 9214 if (IsStdAbs) 9215 return; 9216 9217 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9218 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9219 9220 // The argument and parameter are the same kind. Check if they are the right 9221 // size. 9222 if (ArgValueKind == ParamValueKind) { 9223 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9224 return; 9225 9226 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9227 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9228 << FDecl << ArgType << ParamType; 9229 9230 if (NewAbsKind == 0) 9231 return; 9232 9233 emitReplacement(*this, Call->getExprLoc(), 9234 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9235 return; 9236 } 9237 9238 // ArgValueKind != ParamValueKind 9239 // The wrong type of absolute value function was used. Attempt to find the 9240 // proper one. 9241 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9242 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9243 if (NewAbsKind == 0) 9244 return; 9245 9246 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9247 << FDecl << ParamValueKind << ArgValueKind; 9248 9249 emitReplacement(*this, Call->getExprLoc(), 9250 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9251 } 9252 9253 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9254 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9255 const FunctionDecl *FDecl) { 9256 if (!Call || !FDecl) return; 9257 9258 // Ignore template specializations and macros. 9259 if (inTemplateInstantiation()) return; 9260 if (Call->getExprLoc().isMacroID()) return; 9261 9262 // Only care about the one template argument, two function parameter std::max 9263 if (Call->getNumArgs() != 2) return; 9264 if (!IsStdFunction(FDecl, "max")) return; 9265 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9266 if (!ArgList) return; 9267 if (ArgList->size() != 1) return; 9268 9269 // Check that template type argument is unsigned integer. 9270 const auto& TA = ArgList->get(0); 9271 if (TA.getKind() != TemplateArgument::Type) return; 9272 QualType ArgType = TA.getAsType(); 9273 if (!ArgType->isUnsignedIntegerType()) return; 9274 9275 // See if either argument is a literal zero. 9276 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9277 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9278 if (!MTE) return false; 9279 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9280 if (!Num) return false; 9281 if (Num->getValue() != 0) return false; 9282 return true; 9283 }; 9284 9285 const Expr *FirstArg = Call->getArg(0); 9286 const Expr *SecondArg = Call->getArg(1); 9287 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9288 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9289 9290 // Only warn when exactly one argument is zero. 9291 if (IsFirstArgZero == IsSecondArgZero) return; 9292 9293 SourceRange FirstRange = FirstArg->getSourceRange(); 9294 SourceRange SecondRange = SecondArg->getSourceRange(); 9295 9296 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9297 9298 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9299 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9300 9301 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9302 SourceRange RemovalRange; 9303 if (IsFirstArgZero) { 9304 RemovalRange = SourceRange(FirstRange.getBegin(), 9305 SecondRange.getBegin().getLocWithOffset(-1)); 9306 } else { 9307 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9308 SecondRange.getEnd()); 9309 } 9310 9311 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9312 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9313 << FixItHint::CreateRemoval(RemovalRange); 9314 } 9315 9316 //===--- CHECK: Standard memory functions ---------------------------------===// 9317 9318 /// Takes the expression passed to the size_t parameter of functions 9319 /// such as memcmp, strncat, etc and warns if it's a comparison. 9320 /// 9321 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9322 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9323 IdentifierInfo *FnName, 9324 SourceLocation FnLoc, 9325 SourceLocation RParenLoc) { 9326 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9327 if (!Size) 9328 return false; 9329 9330 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9331 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9332 return false; 9333 9334 SourceRange SizeRange = Size->getSourceRange(); 9335 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9336 << SizeRange << FnName; 9337 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9338 << FnName 9339 << FixItHint::CreateInsertion( 9340 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9341 << FixItHint::CreateRemoval(RParenLoc); 9342 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9343 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9344 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9345 ")"); 9346 9347 return true; 9348 } 9349 9350 /// Determine whether the given type is or contains a dynamic class type 9351 /// (e.g., whether it has a vtable). 9352 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9353 bool &IsContained) { 9354 // Look through array types while ignoring qualifiers. 9355 const Type *Ty = T->getBaseElementTypeUnsafe(); 9356 IsContained = false; 9357 9358 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9359 RD = RD ? RD->getDefinition() : nullptr; 9360 if (!RD || RD->isInvalidDecl()) 9361 return nullptr; 9362 9363 if (RD->isDynamicClass()) 9364 return RD; 9365 9366 // Check all the fields. If any bases were dynamic, the class is dynamic. 9367 // It's impossible for a class to transitively contain itself by value, so 9368 // infinite recursion is impossible. 9369 for (auto *FD : RD->fields()) { 9370 bool SubContained; 9371 if (const CXXRecordDecl *ContainedRD = 9372 getContainedDynamicClass(FD->getType(), SubContained)) { 9373 IsContained = true; 9374 return ContainedRD; 9375 } 9376 } 9377 9378 return nullptr; 9379 } 9380 9381 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9382 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9383 if (Unary->getKind() == UETT_SizeOf) 9384 return Unary; 9385 return nullptr; 9386 } 9387 9388 /// If E is a sizeof expression, returns its argument expression, 9389 /// otherwise returns NULL. 9390 static const Expr *getSizeOfExprArg(const Expr *E) { 9391 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9392 if (!SizeOf->isArgumentType()) 9393 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9394 return nullptr; 9395 } 9396 9397 /// If E is a sizeof expression, returns its argument type. 9398 static QualType getSizeOfArgType(const Expr *E) { 9399 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9400 return SizeOf->getTypeOfArgument(); 9401 return QualType(); 9402 } 9403 9404 namespace { 9405 9406 struct SearchNonTrivialToInitializeField 9407 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9408 using Super = 9409 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9410 9411 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9412 9413 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9414 SourceLocation SL) { 9415 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9416 asDerived().visitArray(PDIK, AT, SL); 9417 return; 9418 } 9419 9420 Super::visitWithKind(PDIK, FT, SL); 9421 } 9422 9423 void visitARCStrong(QualType FT, SourceLocation SL) { 9424 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9425 } 9426 void visitARCWeak(QualType FT, SourceLocation SL) { 9427 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9428 } 9429 void visitStruct(QualType FT, SourceLocation SL) { 9430 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9431 visit(FD->getType(), FD->getLocation()); 9432 } 9433 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9434 const ArrayType *AT, SourceLocation SL) { 9435 visit(getContext().getBaseElementType(AT), SL); 9436 } 9437 void visitTrivial(QualType FT, SourceLocation SL) {} 9438 9439 static void diag(QualType RT, const Expr *E, Sema &S) { 9440 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9441 } 9442 9443 ASTContext &getContext() { return S.getASTContext(); } 9444 9445 const Expr *E; 9446 Sema &S; 9447 }; 9448 9449 struct SearchNonTrivialToCopyField 9450 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9451 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9452 9453 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9454 9455 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9456 SourceLocation SL) { 9457 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9458 asDerived().visitArray(PCK, AT, SL); 9459 return; 9460 } 9461 9462 Super::visitWithKind(PCK, FT, SL); 9463 } 9464 9465 void visitARCStrong(QualType FT, SourceLocation SL) { 9466 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9467 } 9468 void visitARCWeak(QualType FT, SourceLocation SL) { 9469 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9470 } 9471 void visitStruct(QualType FT, SourceLocation SL) { 9472 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9473 visit(FD->getType(), FD->getLocation()); 9474 } 9475 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9476 SourceLocation SL) { 9477 visit(getContext().getBaseElementType(AT), SL); 9478 } 9479 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9480 SourceLocation SL) {} 9481 void visitTrivial(QualType FT, SourceLocation SL) {} 9482 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9483 9484 static void diag(QualType RT, const Expr *E, Sema &S) { 9485 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9486 } 9487 9488 ASTContext &getContext() { return S.getASTContext(); } 9489 9490 const Expr *E; 9491 Sema &S; 9492 }; 9493 9494 } 9495 9496 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9497 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9498 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9499 9500 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9501 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9502 return false; 9503 9504 return doesExprLikelyComputeSize(BO->getLHS()) || 9505 doesExprLikelyComputeSize(BO->getRHS()); 9506 } 9507 9508 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9509 } 9510 9511 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9512 /// 9513 /// \code 9514 /// #define MACRO 0 9515 /// foo(MACRO); 9516 /// foo(0); 9517 /// \endcode 9518 /// 9519 /// This should return true for the first call to foo, but not for the second 9520 /// (regardless of whether foo is a macro or function). 9521 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9522 SourceLocation CallLoc, 9523 SourceLocation ArgLoc) { 9524 if (!CallLoc.isMacroID()) 9525 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9526 9527 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9528 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9529 } 9530 9531 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9532 /// last two arguments transposed. 9533 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9534 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9535 return; 9536 9537 const Expr *SizeArg = 9538 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9539 9540 auto isLiteralZero = [](const Expr *E) { 9541 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9542 }; 9543 9544 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9545 SourceLocation CallLoc = Call->getRParenLoc(); 9546 SourceManager &SM = S.getSourceManager(); 9547 if (isLiteralZero(SizeArg) && 9548 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9549 9550 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9551 9552 // Some platforms #define bzero to __builtin_memset. See if this is the 9553 // case, and if so, emit a better diagnostic. 9554 if (BId == Builtin::BIbzero || 9555 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9556 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9557 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9558 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9559 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9560 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9561 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9562 } 9563 return; 9564 } 9565 9566 // If the second argument to a memset is a sizeof expression and the third 9567 // isn't, this is also likely an error. This should catch 9568 // 'memset(buf, sizeof(buf), 0xff)'. 9569 if (BId == Builtin::BImemset && 9570 doesExprLikelyComputeSize(Call->getArg(1)) && 9571 !doesExprLikelyComputeSize(Call->getArg(2))) { 9572 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9573 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9574 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9575 return; 9576 } 9577 } 9578 9579 /// Check for dangerous or invalid arguments to memset(). 9580 /// 9581 /// This issues warnings on known problematic, dangerous or unspecified 9582 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9583 /// function calls. 9584 /// 9585 /// \param Call The call expression to diagnose. 9586 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9587 unsigned BId, 9588 IdentifierInfo *FnName) { 9589 assert(BId != 0); 9590 9591 // It is possible to have a non-standard definition of memset. Validate 9592 // we have enough arguments, and if not, abort further checking. 9593 unsigned ExpectedNumArgs = 9594 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9595 if (Call->getNumArgs() < ExpectedNumArgs) 9596 return; 9597 9598 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9599 BId == Builtin::BIstrndup ? 1 : 2); 9600 unsigned LenArg = 9601 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9602 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9603 9604 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9605 Call->getBeginLoc(), Call->getRParenLoc())) 9606 return; 9607 9608 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9609 CheckMemaccessSize(*this, BId, Call); 9610 9611 // We have special checking when the length is a sizeof expression. 9612 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9613 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9614 llvm::FoldingSetNodeID SizeOfArgID; 9615 9616 // Although widely used, 'bzero' is not a standard function. Be more strict 9617 // with the argument types before allowing diagnostics and only allow the 9618 // form bzero(ptr, sizeof(...)). 9619 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9620 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9621 return; 9622 9623 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9624 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9625 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9626 9627 QualType DestTy = Dest->getType(); 9628 QualType PointeeTy; 9629 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9630 PointeeTy = DestPtrTy->getPointeeType(); 9631 9632 // Never warn about void type pointers. This can be used to suppress 9633 // false positives. 9634 if (PointeeTy->isVoidType()) 9635 continue; 9636 9637 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9638 // actually comparing the expressions for equality. Because computing the 9639 // expression IDs can be expensive, we only do this if the diagnostic is 9640 // enabled. 9641 if (SizeOfArg && 9642 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9643 SizeOfArg->getExprLoc())) { 9644 // We only compute IDs for expressions if the warning is enabled, and 9645 // cache the sizeof arg's ID. 9646 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9647 SizeOfArg->Profile(SizeOfArgID, Context, true); 9648 llvm::FoldingSetNodeID DestID; 9649 Dest->Profile(DestID, Context, true); 9650 if (DestID == SizeOfArgID) { 9651 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9652 // over sizeof(src) as well. 9653 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9654 StringRef ReadableName = FnName->getName(); 9655 9656 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9657 if (UnaryOp->getOpcode() == UO_AddrOf) 9658 ActionIdx = 1; // If its an address-of operator, just remove it. 9659 if (!PointeeTy->isIncompleteType() && 9660 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9661 ActionIdx = 2; // If the pointee's size is sizeof(char), 9662 // suggest an explicit length. 9663 9664 // If the function is defined as a builtin macro, do not show macro 9665 // expansion. 9666 SourceLocation SL = SizeOfArg->getExprLoc(); 9667 SourceRange DSR = Dest->getSourceRange(); 9668 SourceRange SSR = SizeOfArg->getSourceRange(); 9669 SourceManager &SM = getSourceManager(); 9670 9671 if (SM.isMacroArgExpansion(SL)) { 9672 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9673 SL = SM.getSpellingLoc(SL); 9674 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9675 SM.getSpellingLoc(DSR.getEnd())); 9676 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9677 SM.getSpellingLoc(SSR.getEnd())); 9678 } 9679 9680 DiagRuntimeBehavior(SL, SizeOfArg, 9681 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9682 << ReadableName 9683 << PointeeTy 9684 << DestTy 9685 << DSR 9686 << SSR); 9687 DiagRuntimeBehavior(SL, SizeOfArg, 9688 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9689 << ActionIdx 9690 << SSR); 9691 9692 break; 9693 } 9694 } 9695 9696 // Also check for cases where the sizeof argument is the exact same 9697 // type as the memory argument, and where it points to a user-defined 9698 // record type. 9699 if (SizeOfArgTy != QualType()) { 9700 if (PointeeTy->isRecordType() && 9701 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9702 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9703 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9704 << FnName << SizeOfArgTy << ArgIdx 9705 << PointeeTy << Dest->getSourceRange() 9706 << LenExpr->getSourceRange()); 9707 break; 9708 } 9709 } 9710 } else if (DestTy->isArrayType()) { 9711 PointeeTy = DestTy; 9712 } 9713 9714 if (PointeeTy == QualType()) 9715 continue; 9716 9717 // Always complain about dynamic classes. 9718 bool IsContained; 9719 if (const CXXRecordDecl *ContainedRD = 9720 getContainedDynamicClass(PointeeTy, IsContained)) { 9721 9722 unsigned OperationType = 0; 9723 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9724 // "overwritten" if we're warning about the destination for any call 9725 // but memcmp; otherwise a verb appropriate to the call. 9726 if (ArgIdx != 0 || IsCmp) { 9727 if (BId == Builtin::BImemcpy) 9728 OperationType = 1; 9729 else if(BId == Builtin::BImemmove) 9730 OperationType = 2; 9731 else if (IsCmp) 9732 OperationType = 3; 9733 } 9734 9735 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9736 PDiag(diag::warn_dyn_class_memaccess) 9737 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9738 << IsContained << ContainedRD << OperationType 9739 << Call->getCallee()->getSourceRange()); 9740 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9741 BId != Builtin::BImemset) 9742 DiagRuntimeBehavior( 9743 Dest->getExprLoc(), Dest, 9744 PDiag(diag::warn_arc_object_memaccess) 9745 << ArgIdx << FnName << PointeeTy 9746 << Call->getCallee()->getSourceRange()); 9747 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9748 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9749 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9750 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9751 PDiag(diag::warn_cstruct_memaccess) 9752 << ArgIdx << FnName << PointeeTy << 0); 9753 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9754 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9755 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9756 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9757 PDiag(diag::warn_cstruct_memaccess) 9758 << ArgIdx << FnName << PointeeTy << 1); 9759 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9760 } else { 9761 continue; 9762 } 9763 } else 9764 continue; 9765 9766 DiagRuntimeBehavior( 9767 Dest->getExprLoc(), Dest, 9768 PDiag(diag::note_bad_memaccess_silence) 9769 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9770 break; 9771 } 9772 } 9773 9774 // A little helper routine: ignore addition and subtraction of integer literals. 9775 // This intentionally does not ignore all integer constant expressions because 9776 // we don't want to remove sizeof(). 9777 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9778 Ex = Ex->IgnoreParenCasts(); 9779 9780 while (true) { 9781 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9782 if (!BO || !BO->isAdditiveOp()) 9783 break; 9784 9785 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9786 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9787 9788 if (isa<IntegerLiteral>(RHS)) 9789 Ex = LHS; 9790 else if (isa<IntegerLiteral>(LHS)) 9791 Ex = RHS; 9792 else 9793 break; 9794 } 9795 9796 return Ex; 9797 } 9798 9799 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9800 ASTContext &Context) { 9801 // Only handle constant-sized or VLAs, but not flexible members. 9802 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9803 // Only issue the FIXIT for arrays of size > 1. 9804 if (CAT->getSize().getSExtValue() <= 1) 9805 return false; 9806 } else if (!Ty->isVariableArrayType()) { 9807 return false; 9808 } 9809 return true; 9810 } 9811 9812 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9813 // be the size of the source, instead of the destination. 9814 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9815 IdentifierInfo *FnName) { 9816 9817 // Don't crash if the user has the wrong number of arguments 9818 unsigned NumArgs = Call->getNumArgs(); 9819 if ((NumArgs != 3) && (NumArgs != 4)) 9820 return; 9821 9822 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9823 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9824 const Expr *CompareWithSrc = nullptr; 9825 9826 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9827 Call->getBeginLoc(), Call->getRParenLoc())) 9828 return; 9829 9830 // Look for 'strlcpy(dst, x, sizeof(x))' 9831 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9832 CompareWithSrc = Ex; 9833 else { 9834 // Look for 'strlcpy(dst, x, strlen(x))' 9835 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9836 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9837 SizeCall->getNumArgs() == 1) 9838 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9839 } 9840 } 9841 9842 if (!CompareWithSrc) 9843 return; 9844 9845 // Determine if the argument to sizeof/strlen is equal to the source 9846 // argument. In principle there's all kinds of things you could do 9847 // here, for instance creating an == expression and evaluating it with 9848 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9849 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9850 if (!SrcArgDRE) 9851 return; 9852 9853 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9854 if (!CompareWithSrcDRE || 9855 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9856 return; 9857 9858 const Expr *OriginalSizeArg = Call->getArg(2); 9859 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9860 << OriginalSizeArg->getSourceRange() << FnName; 9861 9862 // Output a FIXIT hint if the destination is an array (rather than a 9863 // pointer to an array). This could be enhanced to handle some 9864 // pointers if we know the actual size, like if DstArg is 'array+2' 9865 // we could say 'sizeof(array)-2'. 9866 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9867 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9868 return; 9869 9870 SmallString<128> sizeString; 9871 llvm::raw_svector_ostream OS(sizeString); 9872 OS << "sizeof("; 9873 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9874 OS << ")"; 9875 9876 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9877 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9878 OS.str()); 9879 } 9880 9881 /// Check if two expressions refer to the same declaration. 9882 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9883 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9884 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9885 return D1->getDecl() == D2->getDecl(); 9886 return false; 9887 } 9888 9889 static const Expr *getStrlenExprArg(const Expr *E) { 9890 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9891 const FunctionDecl *FD = CE->getDirectCallee(); 9892 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9893 return nullptr; 9894 return CE->getArg(0)->IgnoreParenCasts(); 9895 } 9896 return nullptr; 9897 } 9898 9899 // Warn on anti-patterns as the 'size' argument to strncat. 9900 // The correct size argument should look like following: 9901 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9902 void Sema::CheckStrncatArguments(const CallExpr *CE, 9903 IdentifierInfo *FnName) { 9904 // Don't crash if the user has the wrong number of arguments. 9905 if (CE->getNumArgs() < 3) 9906 return; 9907 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9908 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9909 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9910 9911 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9912 CE->getRParenLoc())) 9913 return; 9914 9915 // Identify common expressions, which are wrongly used as the size argument 9916 // to strncat and may lead to buffer overflows. 9917 unsigned PatternType = 0; 9918 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9919 // - sizeof(dst) 9920 if (referToTheSameDecl(SizeOfArg, DstArg)) 9921 PatternType = 1; 9922 // - sizeof(src) 9923 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9924 PatternType = 2; 9925 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9926 if (BE->getOpcode() == BO_Sub) { 9927 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9928 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9929 // - sizeof(dst) - strlen(dst) 9930 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9931 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9932 PatternType = 1; 9933 // - sizeof(src) - (anything) 9934 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9935 PatternType = 2; 9936 } 9937 } 9938 9939 if (PatternType == 0) 9940 return; 9941 9942 // Generate the diagnostic. 9943 SourceLocation SL = LenArg->getBeginLoc(); 9944 SourceRange SR = LenArg->getSourceRange(); 9945 SourceManager &SM = getSourceManager(); 9946 9947 // If the function is defined as a builtin macro, do not show macro expansion. 9948 if (SM.isMacroArgExpansion(SL)) { 9949 SL = SM.getSpellingLoc(SL); 9950 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9951 SM.getSpellingLoc(SR.getEnd())); 9952 } 9953 9954 // Check if the destination is an array (rather than a pointer to an array). 9955 QualType DstTy = DstArg->getType(); 9956 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9957 Context); 9958 if (!isKnownSizeArray) { 9959 if (PatternType == 1) 9960 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9961 else 9962 Diag(SL, diag::warn_strncat_src_size) << SR; 9963 return; 9964 } 9965 9966 if (PatternType == 1) 9967 Diag(SL, diag::warn_strncat_large_size) << SR; 9968 else 9969 Diag(SL, diag::warn_strncat_src_size) << SR; 9970 9971 SmallString<128> sizeString; 9972 llvm::raw_svector_ostream OS(sizeString); 9973 OS << "sizeof("; 9974 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9975 OS << ") - "; 9976 OS << "strlen("; 9977 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9978 OS << ") - 1"; 9979 9980 Diag(SL, diag::note_strncat_wrong_size) 9981 << FixItHint::CreateReplacement(SR, OS.str()); 9982 } 9983 9984 void 9985 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9986 SourceLocation ReturnLoc, 9987 bool isObjCMethod, 9988 const AttrVec *Attrs, 9989 const FunctionDecl *FD) { 9990 // Check if the return value is null but should not be. 9991 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9992 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9993 CheckNonNullExpr(*this, RetValExp)) 9994 Diag(ReturnLoc, diag::warn_null_ret) 9995 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9996 9997 // C++11 [basic.stc.dynamic.allocation]p4: 9998 // If an allocation function declared with a non-throwing 9999 // exception-specification fails to allocate storage, it shall return 10000 // a null pointer. Any other allocation function that fails to allocate 10001 // storage shall indicate failure only by throwing an exception [...] 10002 if (FD) { 10003 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10004 if (Op == OO_New || Op == OO_Array_New) { 10005 const FunctionProtoType *Proto 10006 = FD->getType()->castAs<FunctionProtoType>(); 10007 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10008 CheckNonNullExpr(*this, RetValExp)) 10009 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10010 << FD << getLangOpts().CPlusPlus11; 10011 } 10012 } 10013 } 10014 10015 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10016 10017 /// Check for comparisons of floating point operands using != and ==. 10018 /// Issue a warning if these are no self-comparisons, as they are not likely 10019 /// to do what the programmer intended. 10020 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10021 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10022 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10023 10024 // Special case: check for x == x (which is OK). 10025 // Do not emit warnings for such cases. 10026 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10027 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10028 if (DRL->getDecl() == DRR->getDecl()) 10029 return; 10030 10031 // Special case: check for comparisons against literals that can be exactly 10032 // represented by APFloat. In such cases, do not emit a warning. This 10033 // is a heuristic: often comparison against such literals are used to 10034 // detect if a value in a variable has not changed. This clearly can 10035 // lead to false negatives. 10036 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10037 if (FLL->isExact()) 10038 return; 10039 } else 10040 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10041 if (FLR->isExact()) 10042 return; 10043 10044 // Check for comparisons with builtin types. 10045 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10046 if (CL->getBuiltinCallee()) 10047 return; 10048 10049 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10050 if (CR->getBuiltinCallee()) 10051 return; 10052 10053 // Emit the diagnostic. 10054 Diag(Loc, diag::warn_floatingpoint_eq) 10055 << LHS->getSourceRange() << RHS->getSourceRange(); 10056 } 10057 10058 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10059 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10060 10061 namespace { 10062 10063 /// Structure recording the 'active' range of an integer-valued 10064 /// expression. 10065 struct IntRange { 10066 /// The number of bits active in the int. 10067 unsigned Width; 10068 10069 /// True if the int is known not to have negative values. 10070 bool NonNegative; 10071 10072 IntRange(unsigned Width, bool NonNegative) 10073 : Width(Width), NonNegative(NonNegative) {} 10074 10075 /// Returns the range of the bool type. 10076 static IntRange forBoolType() { 10077 return IntRange(1, true); 10078 } 10079 10080 /// Returns the range of an opaque value of the given integral type. 10081 static IntRange forValueOfType(ASTContext &C, QualType T) { 10082 return forValueOfCanonicalType(C, 10083 T->getCanonicalTypeInternal().getTypePtr()); 10084 } 10085 10086 /// Returns the range of an opaque value of a canonical integral type. 10087 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10088 assert(T->isCanonicalUnqualified()); 10089 10090 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10091 T = VT->getElementType().getTypePtr(); 10092 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10093 T = CT->getElementType().getTypePtr(); 10094 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10095 T = AT->getValueType().getTypePtr(); 10096 10097 if (!C.getLangOpts().CPlusPlus) { 10098 // For enum types in C code, use the underlying datatype. 10099 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10100 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10101 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10102 // For enum types in C++, use the known bit width of the enumerators. 10103 EnumDecl *Enum = ET->getDecl(); 10104 // In C++11, enums can have a fixed underlying type. Use this type to 10105 // compute the range. 10106 if (Enum->isFixed()) { 10107 return IntRange(C.getIntWidth(QualType(T, 0)), 10108 !ET->isSignedIntegerOrEnumerationType()); 10109 } 10110 10111 unsigned NumPositive = Enum->getNumPositiveBits(); 10112 unsigned NumNegative = Enum->getNumNegativeBits(); 10113 10114 if (NumNegative == 0) 10115 return IntRange(NumPositive, true/*NonNegative*/); 10116 else 10117 return IntRange(std::max(NumPositive + 1, NumNegative), 10118 false/*NonNegative*/); 10119 } 10120 10121 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10122 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10123 10124 const BuiltinType *BT = cast<BuiltinType>(T); 10125 assert(BT->isInteger()); 10126 10127 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10128 } 10129 10130 /// Returns the "target" range of a canonical integral type, i.e. 10131 /// the range of values expressible in the type. 10132 /// 10133 /// This matches forValueOfCanonicalType except that enums have the 10134 /// full range of their type, not the range of their enumerators. 10135 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10136 assert(T->isCanonicalUnqualified()); 10137 10138 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10139 T = VT->getElementType().getTypePtr(); 10140 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10141 T = CT->getElementType().getTypePtr(); 10142 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10143 T = AT->getValueType().getTypePtr(); 10144 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10145 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10146 10147 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10148 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10149 10150 const BuiltinType *BT = cast<BuiltinType>(T); 10151 assert(BT->isInteger()); 10152 10153 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10154 } 10155 10156 /// Returns the supremum of two ranges: i.e. their conservative merge. 10157 static IntRange join(IntRange L, IntRange R) { 10158 return IntRange(std::max(L.Width, R.Width), 10159 L.NonNegative && R.NonNegative); 10160 } 10161 10162 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10163 static IntRange meet(IntRange L, IntRange R) { 10164 return IntRange(std::min(L.Width, R.Width), 10165 L.NonNegative || R.NonNegative); 10166 } 10167 }; 10168 10169 } // namespace 10170 10171 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10172 unsigned MaxWidth) { 10173 if (value.isSigned() && value.isNegative()) 10174 return IntRange(value.getMinSignedBits(), false); 10175 10176 if (value.getBitWidth() > MaxWidth) 10177 value = value.trunc(MaxWidth); 10178 10179 // isNonNegative() just checks the sign bit without considering 10180 // signedness. 10181 return IntRange(value.getActiveBits(), true); 10182 } 10183 10184 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10185 unsigned MaxWidth) { 10186 if (result.isInt()) 10187 return GetValueRange(C, result.getInt(), MaxWidth); 10188 10189 if (result.isVector()) { 10190 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10191 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10192 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10193 R = IntRange::join(R, El); 10194 } 10195 return R; 10196 } 10197 10198 if (result.isComplexInt()) { 10199 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10200 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10201 return IntRange::join(R, I); 10202 } 10203 10204 // This can happen with lossless casts to intptr_t of "based" lvalues. 10205 // Assume it might use arbitrary bits. 10206 // FIXME: The only reason we need to pass the type in here is to get 10207 // the sign right on this one case. It would be nice if APValue 10208 // preserved this. 10209 assert(result.isLValue() || result.isAddrLabelDiff()); 10210 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10211 } 10212 10213 static QualType GetExprType(const Expr *E) { 10214 QualType Ty = E->getType(); 10215 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10216 Ty = AtomicRHS->getValueType(); 10217 return Ty; 10218 } 10219 10220 /// Pseudo-evaluate the given integer expression, estimating the 10221 /// range of values it might take. 10222 /// 10223 /// \param MaxWidth - the width to which the value will be truncated 10224 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10225 bool InConstantContext) { 10226 E = E->IgnoreParens(); 10227 10228 // Try a full evaluation first. 10229 Expr::EvalResult result; 10230 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10231 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10232 10233 // I think we only want to look through implicit casts here; if the 10234 // user has an explicit widening cast, we should treat the value as 10235 // being of the new, wider type. 10236 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10237 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10238 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10239 10240 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10241 10242 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10243 CE->getCastKind() == CK_BooleanToSignedIntegral; 10244 10245 // Assume that non-integer casts can span the full range of the type. 10246 if (!isIntegerCast) 10247 return OutputTypeRange; 10248 10249 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10250 std::min(MaxWidth, OutputTypeRange.Width), 10251 InConstantContext); 10252 10253 // Bail out if the subexpr's range is as wide as the cast type. 10254 if (SubRange.Width >= OutputTypeRange.Width) 10255 return OutputTypeRange; 10256 10257 // Otherwise, we take the smaller width, and we're non-negative if 10258 // either the output type or the subexpr is. 10259 return IntRange(SubRange.Width, 10260 SubRange.NonNegative || OutputTypeRange.NonNegative); 10261 } 10262 10263 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10264 // If we can fold the condition, just take that operand. 10265 bool CondResult; 10266 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10267 return GetExprRange(C, 10268 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10269 MaxWidth, InConstantContext); 10270 10271 // Otherwise, conservatively merge. 10272 IntRange L = 10273 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10274 IntRange R = 10275 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10276 return IntRange::join(L, R); 10277 } 10278 10279 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10280 switch (BO->getOpcode()) { 10281 case BO_Cmp: 10282 llvm_unreachable("builtin <=> should have class type"); 10283 10284 // Boolean-valued operations are single-bit and positive. 10285 case BO_LAnd: 10286 case BO_LOr: 10287 case BO_LT: 10288 case BO_GT: 10289 case BO_LE: 10290 case BO_GE: 10291 case BO_EQ: 10292 case BO_NE: 10293 return IntRange::forBoolType(); 10294 10295 // The type of the assignments is the type of the LHS, so the RHS 10296 // is not necessarily the same type. 10297 case BO_MulAssign: 10298 case BO_DivAssign: 10299 case BO_RemAssign: 10300 case BO_AddAssign: 10301 case BO_SubAssign: 10302 case BO_XorAssign: 10303 case BO_OrAssign: 10304 // TODO: bitfields? 10305 return IntRange::forValueOfType(C, GetExprType(E)); 10306 10307 // Simple assignments just pass through the RHS, which will have 10308 // been coerced to the LHS type. 10309 case BO_Assign: 10310 // TODO: bitfields? 10311 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10312 10313 // Operations with opaque sources are black-listed. 10314 case BO_PtrMemD: 10315 case BO_PtrMemI: 10316 return IntRange::forValueOfType(C, GetExprType(E)); 10317 10318 // Bitwise-and uses the *infinum* of the two source ranges. 10319 case BO_And: 10320 case BO_AndAssign: 10321 return IntRange::meet( 10322 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10323 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10324 10325 // Left shift gets black-listed based on a judgement call. 10326 case BO_Shl: 10327 // ...except that we want to treat '1 << (blah)' as logically 10328 // positive. It's an important idiom. 10329 if (IntegerLiteral *I 10330 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10331 if (I->getValue() == 1) { 10332 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10333 return IntRange(R.Width, /*NonNegative*/ true); 10334 } 10335 } 10336 LLVM_FALLTHROUGH; 10337 10338 case BO_ShlAssign: 10339 return IntRange::forValueOfType(C, GetExprType(E)); 10340 10341 // Right shift by a constant can narrow its left argument. 10342 case BO_Shr: 10343 case BO_ShrAssign: { 10344 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10345 10346 // If the shift amount is a positive constant, drop the width by 10347 // that much. 10348 if (Optional<llvm::APSInt> shift = 10349 BO->getRHS()->getIntegerConstantExpr(C)) { 10350 if (shift->isNonNegative()) { 10351 unsigned zext = shift->getZExtValue(); 10352 if (zext >= L.Width) 10353 L.Width = (L.NonNegative ? 0 : 1); 10354 else 10355 L.Width -= zext; 10356 } 10357 } 10358 10359 return L; 10360 } 10361 10362 // Comma acts as its right operand. 10363 case BO_Comma: 10364 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10365 10366 // Black-list pointer subtractions. 10367 case BO_Sub: 10368 if (BO->getLHS()->getType()->isPointerType()) 10369 return IntRange::forValueOfType(C, GetExprType(E)); 10370 break; 10371 10372 // The width of a division result is mostly determined by the size 10373 // of the LHS. 10374 case BO_Div: { 10375 // Don't 'pre-truncate' the operands. 10376 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10377 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10378 10379 // If the divisor is constant, use that. 10380 if (Optional<llvm::APSInt> divisor = 10381 BO->getRHS()->getIntegerConstantExpr(C)) { 10382 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10383 if (log2 >= L.Width) 10384 L.Width = (L.NonNegative ? 0 : 1); 10385 else 10386 L.Width = std::min(L.Width - log2, MaxWidth); 10387 return L; 10388 } 10389 10390 // Otherwise, just use the LHS's width. 10391 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10392 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10393 } 10394 10395 // The result of a remainder can't be larger than the result of 10396 // either side. 10397 case BO_Rem: { 10398 // Don't 'pre-truncate' the operands. 10399 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10400 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10401 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10402 10403 IntRange meet = IntRange::meet(L, R); 10404 meet.Width = std::min(meet.Width, MaxWidth); 10405 return meet; 10406 } 10407 10408 // The default behavior is okay for these. 10409 case BO_Mul: 10410 case BO_Add: 10411 case BO_Xor: 10412 case BO_Or: 10413 break; 10414 } 10415 10416 // The default case is to treat the operation as if it were closed 10417 // on the narrowest type that encompasses both operands. 10418 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10419 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10420 return IntRange::join(L, R); 10421 } 10422 10423 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10424 switch (UO->getOpcode()) { 10425 // Boolean-valued operations are white-listed. 10426 case UO_LNot: 10427 return IntRange::forBoolType(); 10428 10429 // Operations with opaque sources are black-listed. 10430 case UO_Deref: 10431 case UO_AddrOf: // should be impossible 10432 return IntRange::forValueOfType(C, GetExprType(E)); 10433 10434 default: 10435 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10436 } 10437 } 10438 10439 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10440 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10441 10442 if (const auto *BitField = E->getSourceBitField()) 10443 return IntRange(BitField->getBitWidthValue(C), 10444 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10445 10446 return IntRange::forValueOfType(C, GetExprType(E)); 10447 } 10448 10449 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10450 bool InConstantContext) { 10451 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10452 } 10453 10454 /// Checks whether the given value, which currently has the given 10455 /// source semantics, has the same value when coerced through the 10456 /// target semantics. 10457 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10458 const llvm::fltSemantics &Src, 10459 const llvm::fltSemantics &Tgt) { 10460 llvm::APFloat truncated = value; 10461 10462 bool ignored; 10463 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10464 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10465 10466 return truncated.bitwiseIsEqual(value); 10467 } 10468 10469 /// Checks whether the given value, which currently has the given 10470 /// source semantics, has the same value when coerced through the 10471 /// target semantics. 10472 /// 10473 /// The value might be a vector of floats (or a complex number). 10474 static bool IsSameFloatAfterCast(const APValue &value, 10475 const llvm::fltSemantics &Src, 10476 const llvm::fltSemantics &Tgt) { 10477 if (value.isFloat()) 10478 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10479 10480 if (value.isVector()) { 10481 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10482 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10483 return false; 10484 return true; 10485 } 10486 10487 assert(value.isComplexFloat()); 10488 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10489 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10490 } 10491 10492 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10493 bool IsListInit = false); 10494 10495 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10496 // Suppress cases where we are comparing against an enum constant. 10497 if (const DeclRefExpr *DR = 10498 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10499 if (isa<EnumConstantDecl>(DR->getDecl())) 10500 return true; 10501 10502 // Suppress cases where the value is expanded from a macro, unless that macro 10503 // is how a language represents a boolean literal. This is the case in both C 10504 // and Objective-C. 10505 SourceLocation BeginLoc = E->getBeginLoc(); 10506 if (BeginLoc.isMacroID()) { 10507 StringRef MacroName = Lexer::getImmediateMacroName( 10508 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10509 return MacroName != "YES" && MacroName != "NO" && 10510 MacroName != "true" && MacroName != "false"; 10511 } 10512 10513 return false; 10514 } 10515 10516 static bool isKnownToHaveUnsignedValue(Expr *E) { 10517 return E->getType()->isIntegerType() && 10518 (!E->getType()->isSignedIntegerType() || 10519 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10520 } 10521 10522 namespace { 10523 /// The promoted range of values of a type. In general this has the 10524 /// following structure: 10525 /// 10526 /// |-----------| . . . |-----------| 10527 /// ^ ^ ^ ^ 10528 /// Min HoleMin HoleMax Max 10529 /// 10530 /// ... where there is only a hole if a signed type is promoted to unsigned 10531 /// (in which case Min and Max are the smallest and largest representable 10532 /// values). 10533 struct PromotedRange { 10534 // Min, or HoleMax if there is a hole. 10535 llvm::APSInt PromotedMin; 10536 // Max, or HoleMin if there is a hole. 10537 llvm::APSInt PromotedMax; 10538 10539 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10540 if (R.Width == 0) 10541 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10542 else if (R.Width >= BitWidth && !Unsigned) { 10543 // Promotion made the type *narrower*. This happens when promoting 10544 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10545 // Treat all values of 'signed int' as being in range for now. 10546 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10547 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10548 } else { 10549 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10550 .extOrTrunc(BitWidth); 10551 PromotedMin.setIsUnsigned(Unsigned); 10552 10553 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10554 .extOrTrunc(BitWidth); 10555 PromotedMax.setIsUnsigned(Unsigned); 10556 } 10557 } 10558 10559 // Determine whether this range is contiguous (has no hole). 10560 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10561 10562 // Where a constant value is within the range. 10563 enum ComparisonResult { 10564 LT = 0x1, 10565 LE = 0x2, 10566 GT = 0x4, 10567 GE = 0x8, 10568 EQ = 0x10, 10569 NE = 0x20, 10570 InRangeFlag = 0x40, 10571 10572 Less = LE | LT | NE, 10573 Min = LE | InRangeFlag, 10574 InRange = InRangeFlag, 10575 Max = GE | InRangeFlag, 10576 Greater = GE | GT | NE, 10577 10578 OnlyValue = LE | GE | EQ | InRangeFlag, 10579 InHole = NE 10580 }; 10581 10582 ComparisonResult compare(const llvm::APSInt &Value) const { 10583 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10584 Value.isUnsigned() == PromotedMin.isUnsigned()); 10585 if (!isContiguous()) { 10586 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10587 if (Value.isMinValue()) return Min; 10588 if (Value.isMaxValue()) return Max; 10589 if (Value >= PromotedMin) return InRange; 10590 if (Value <= PromotedMax) return InRange; 10591 return InHole; 10592 } 10593 10594 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10595 case -1: return Less; 10596 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10597 case 1: 10598 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10599 case -1: return InRange; 10600 case 0: return Max; 10601 case 1: return Greater; 10602 } 10603 } 10604 10605 llvm_unreachable("impossible compare result"); 10606 } 10607 10608 static llvm::Optional<StringRef> 10609 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10610 if (Op == BO_Cmp) { 10611 ComparisonResult LTFlag = LT, GTFlag = GT; 10612 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10613 10614 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10615 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10616 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10617 return llvm::None; 10618 } 10619 10620 ComparisonResult TrueFlag, FalseFlag; 10621 if (Op == BO_EQ) { 10622 TrueFlag = EQ; 10623 FalseFlag = NE; 10624 } else if (Op == BO_NE) { 10625 TrueFlag = NE; 10626 FalseFlag = EQ; 10627 } else { 10628 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10629 TrueFlag = LT; 10630 FalseFlag = GE; 10631 } else { 10632 TrueFlag = GT; 10633 FalseFlag = LE; 10634 } 10635 if (Op == BO_GE || Op == BO_LE) 10636 std::swap(TrueFlag, FalseFlag); 10637 } 10638 if (R & TrueFlag) 10639 return StringRef("true"); 10640 if (R & FalseFlag) 10641 return StringRef("false"); 10642 return llvm::None; 10643 } 10644 }; 10645 } 10646 10647 static bool HasEnumType(Expr *E) { 10648 // Strip off implicit integral promotions. 10649 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10650 if (ICE->getCastKind() != CK_IntegralCast && 10651 ICE->getCastKind() != CK_NoOp) 10652 break; 10653 E = ICE->getSubExpr(); 10654 } 10655 10656 return E->getType()->isEnumeralType(); 10657 } 10658 10659 static int classifyConstantValue(Expr *Constant) { 10660 // The values of this enumeration are used in the diagnostics 10661 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10662 enum ConstantValueKind { 10663 Miscellaneous = 0, 10664 LiteralTrue, 10665 LiteralFalse 10666 }; 10667 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10668 return BL->getValue() ? ConstantValueKind::LiteralTrue 10669 : ConstantValueKind::LiteralFalse; 10670 return ConstantValueKind::Miscellaneous; 10671 } 10672 10673 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10674 Expr *Constant, Expr *Other, 10675 const llvm::APSInt &Value, 10676 bool RhsConstant) { 10677 if (S.inTemplateInstantiation()) 10678 return false; 10679 10680 Expr *OriginalOther = Other; 10681 10682 Constant = Constant->IgnoreParenImpCasts(); 10683 Other = Other->IgnoreParenImpCasts(); 10684 10685 // Suppress warnings on tautological comparisons between values of the same 10686 // enumeration type. There are only two ways we could warn on this: 10687 // - If the constant is outside the range of representable values of 10688 // the enumeration. In such a case, we should warn about the cast 10689 // to enumeration type, not about the comparison. 10690 // - If the constant is the maximum / minimum in-range value. For an 10691 // enumeratin type, such comparisons can be meaningful and useful. 10692 if (Constant->getType()->isEnumeralType() && 10693 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10694 return false; 10695 10696 // TODO: Investigate using GetExprRange() to get tighter bounds 10697 // on the bit ranges. 10698 QualType OtherT = Other->getType(); 10699 if (const auto *AT = OtherT->getAs<AtomicType>()) 10700 OtherT = AT->getValueType(); 10701 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10702 10703 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10704 // (Namely, macOS). 10705 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10706 S.NSAPIObj->isObjCBOOLType(OtherT) && 10707 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10708 10709 // Whether we're treating Other as being a bool because of the form of 10710 // expression despite it having another type (typically 'int' in C). 10711 bool OtherIsBooleanDespiteType = 10712 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10713 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10714 OtherRange = IntRange::forBoolType(); 10715 10716 // Determine the promoted range of the other type and see if a comparison of 10717 // the constant against that range is tautological. 10718 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10719 Value.isUnsigned()); 10720 auto Cmp = OtherPromotedRange.compare(Value); 10721 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10722 if (!Result) 10723 return false; 10724 10725 // Suppress the diagnostic for an in-range comparison if the constant comes 10726 // from a macro or enumerator. We don't want to diagnose 10727 // 10728 // some_long_value <= INT_MAX 10729 // 10730 // when sizeof(int) == sizeof(long). 10731 bool InRange = Cmp & PromotedRange::InRangeFlag; 10732 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10733 return false; 10734 10735 // If this is a comparison to an enum constant, include that 10736 // constant in the diagnostic. 10737 const EnumConstantDecl *ED = nullptr; 10738 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10739 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10740 10741 // Should be enough for uint128 (39 decimal digits) 10742 SmallString<64> PrettySourceValue; 10743 llvm::raw_svector_ostream OS(PrettySourceValue); 10744 if (ED) { 10745 OS << '\'' << *ED << "' (" << Value << ")"; 10746 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10747 Constant->IgnoreParenImpCasts())) { 10748 OS << (BL->getValue() ? "YES" : "NO"); 10749 } else { 10750 OS << Value; 10751 } 10752 10753 if (IsObjCSignedCharBool) { 10754 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10755 S.PDiag(diag::warn_tautological_compare_objc_bool) 10756 << OS.str() << *Result); 10757 return true; 10758 } 10759 10760 // FIXME: We use a somewhat different formatting for the in-range cases and 10761 // cases involving boolean values for historical reasons. We should pick a 10762 // consistent way of presenting these diagnostics. 10763 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10764 10765 S.DiagRuntimeBehavior( 10766 E->getOperatorLoc(), E, 10767 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10768 : diag::warn_tautological_bool_compare) 10769 << OS.str() << classifyConstantValue(Constant) << OtherT 10770 << OtherIsBooleanDespiteType << *Result 10771 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10772 } else { 10773 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10774 ? (HasEnumType(OriginalOther) 10775 ? diag::warn_unsigned_enum_always_true_comparison 10776 : diag::warn_unsigned_always_true_comparison) 10777 : diag::warn_tautological_constant_compare; 10778 10779 S.Diag(E->getOperatorLoc(), Diag) 10780 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10781 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10782 } 10783 10784 return true; 10785 } 10786 10787 /// Analyze the operands of the given comparison. Implements the 10788 /// fallback case from AnalyzeComparison. 10789 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10790 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10791 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10792 } 10793 10794 /// Implements -Wsign-compare. 10795 /// 10796 /// \param E the binary operator to check for warnings 10797 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10798 // The type the comparison is being performed in. 10799 QualType T = E->getLHS()->getType(); 10800 10801 // Only analyze comparison operators where both sides have been converted to 10802 // the same type. 10803 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10804 return AnalyzeImpConvsInComparison(S, E); 10805 10806 // Don't analyze value-dependent comparisons directly. 10807 if (E->isValueDependent()) 10808 return AnalyzeImpConvsInComparison(S, E); 10809 10810 Expr *LHS = E->getLHS(); 10811 Expr *RHS = E->getRHS(); 10812 10813 if (T->isIntegralType(S.Context)) { 10814 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 10815 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 10816 10817 // We don't care about expressions whose result is a constant. 10818 if (RHSValue && LHSValue) 10819 return AnalyzeImpConvsInComparison(S, E); 10820 10821 // We only care about expressions where just one side is literal 10822 if ((bool)RHSValue ^ (bool)LHSValue) { 10823 // Is the constant on the RHS or LHS? 10824 const bool RhsConstant = (bool)RHSValue; 10825 Expr *Const = RhsConstant ? RHS : LHS; 10826 Expr *Other = RhsConstant ? LHS : RHS; 10827 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 10828 10829 // Check whether an integer constant comparison results in a value 10830 // of 'true' or 'false'. 10831 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10832 return AnalyzeImpConvsInComparison(S, E); 10833 } 10834 } 10835 10836 if (!T->hasUnsignedIntegerRepresentation()) { 10837 // We don't do anything special if this isn't an unsigned integral 10838 // comparison: we're only interested in integral comparisons, and 10839 // signed comparisons only happen in cases we don't care to warn about. 10840 return AnalyzeImpConvsInComparison(S, E); 10841 } 10842 10843 LHS = LHS->IgnoreParenImpCasts(); 10844 RHS = RHS->IgnoreParenImpCasts(); 10845 10846 if (!S.getLangOpts().CPlusPlus) { 10847 // Avoid warning about comparison of integers with different signs when 10848 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10849 // the type of `E`. 10850 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10851 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10852 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10853 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10854 } 10855 10856 // Check to see if one of the (unmodified) operands is of different 10857 // signedness. 10858 Expr *signedOperand, *unsignedOperand; 10859 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10860 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10861 "unsigned comparison between two signed integer expressions?"); 10862 signedOperand = LHS; 10863 unsignedOperand = RHS; 10864 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10865 signedOperand = RHS; 10866 unsignedOperand = LHS; 10867 } else { 10868 return AnalyzeImpConvsInComparison(S, E); 10869 } 10870 10871 // Otherwise, calculate the effective range of the signed operand. 10872 IntRange signedRange = 10873 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10874 10875 // Go ahead and analyze implicit conversions in the operands. Note 10876 // that we skip the implicit conversions on both sides. 10877 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10878 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10879 10880 // If the signed range is non-negative, -Wsign-compare won't fire. 10881 if (signedRange.NonNegative) 10882 return; 10883 10884 // For (in)equality comparisons, if the unsigned operand is a 10885 // constant which cannot collide with a overflowed signed operand, 10886 // then reinterpreting the signed operand as unsigned will not 10887 // change the result of the comparison. 10888 if (E->isEqualityOp()) { 10889 unsigned comparisonWidth = S.Context.getIntWidth(T); 10890 IntRange unsignedRange = 10891 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10892 10893 // We should never be unable to prove that the unsigned operand is 10894 // non-negative. 10895 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10896 10897 if (unsignedRange.Width < comparisonWidth) 10898 return; 10899 } 10900 10901 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10902 S.PDiag(diag::warn_mixed_sign_comparison) 10903 << LHS->getType() << RHS->getType() 10904 << LHS->getSourceRange() << RHS->getSourceRange()); 10905 } 10906 10907 /// Analyzes an attempt to assign the given value to a bitfield. 10908 /// 10909 /// Returns true if there was something fishy about the attempt. 10910 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10911 SourceLocation InitLoc) { 10912 assert(Bitfield->isBitField()); 10913 if (Bitfield->isInvalidDecl()) 10914 return false; 10915 10916 // White-list bool bitfields. 10917 QualType BitfieldType = Bitfield->getType(); 10918 if (BitfieldType->isBooleanType()) 10919 return false; 10920 10921 if (BitfieldType->isEnumeralType()) { 10922 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10923 // If the underlying enum type was not explicitly specified as an unsigned 10924 // type and the enum contain only positive values, MSVC++ will cause an 10925 // inconsistency by storing this as a signed type. 10926 if (S.getLangOpts().CPlusPlus11 && 10927 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10928 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10929 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10930 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10931 << BitfieldEnumDecl->getNameAsString(); 10932 } 10933 } 10934 10935 if (Bitfield->getType()->isBooleanType()) 10936 return false; 10937 10938 // Ignore value- or type-dependent expressions. 10939 if (Bitfield->getBitWidth()->isValueDependent() || 10940 Bitfield->getBitWidth()->isTypeDependent() || 10941 Init->isValueDependent() || 10942 Init->isTypeDependent()) 10943 return false; 10944 10945 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10946 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10947 10948 Expr::EvalResult Result; 10949 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10950 Expr::SE_AllowSideEffects)) { 10951 // The RHS is not constant. If the RHS has an enum type, make sure the 10952 // bitfield is wide enough to hold all the values of the enum without 10953 // truncation. 10954 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10955 EnumDecl *ED = EnumTy->getDecl(); 10956 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10957 10958 // Enum types are implicitly signed on Windows, so check if there are any 10959 // negative enumerators to see if the enum was intended to be signed or 10960 // not. 10961 bool SignedEnum = ED->getNumNegativeBits() > 0; 10962 10963 // Check for surprising sign changes when assigning enum values to a 10964 // bitfield of different signedness. If the bitfield is signed and we 10965 // have exactly the right number of bits to store this unsigned enum, 10966 // suggest changing the enum to an unsigned type. This typically happens 10967 // on Windows where unfixed enums always use an underlying type of 'int'. 10968 unsigned DiagID = 0; 10969 if (SignedEnum && !SignedBitfield) { 10970 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10971 } else if (SignedBitfield && !SignedEnum && 10972 ED->getNumPositiveBits() == FieldWidth) { 10973 DiagID = diag::warn_signed_bitfield_enum_conversion; 10974 } 10975 10976 if (DiagID) { 10977 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10978 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10979 SourceRange TypeRange = 10980 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10981 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10982 << SignedEnum << TypeRange; 10983 } 10984 10985 // Compute the required bitwidth. If the enum has negative values, we need 10986 // one more bit than the normal number of positive bits to represent the 10987 // sign bit. 10988 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10989 ED->getNumNegativeBits()) 10990 : ED->getNumPositiveBits(); 10991 10992 // Check the bitwidth. 10993 if (BitsNeeded > FieldWidth) { 10994 Expr *WidthExpr = Bitfield->getBitWidth(); 10995 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10996 << Bitfield << ED; 10997 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10998 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10999 } 11000 } 11001 11002 return false; 11003 } 11004 11005 llvm::APSInt Value = Result.Val.getInt(); 11006 11007 unsigned OriginalWidth = Value.getBitWidth(); 11008 11009 if (!Value.isSigned() || Value.isNegative()) 11010 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11011 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11012 OriginalWidth = Value.getMinSignedBits(); 11013 11014 if (OriginalWidth <= FieldWidth) 11015 return false; 11016 11017 // Compute the value which the bitfield will contain. 11018 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11019 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11020 11021 // Check whether the stored value is equal to the original value. 11022 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11023 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11024 return false; 11025 11026 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11027 // therefore don't strictly fit into a signed bitfield of width 1. 11028 if (FieldWidth == 1 && Value == 1) 11029 return false; 11030 11031 std::string PrettyValue = Value.toString(10); 11032 std::string PrettyTrunc = TruncatedValue.toString(10); 11033 11034 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11035 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11036 << Init->getSourceRange(); 11037 11038 return true; 11039 } 11040 11041 /// Analyze the given simple or compound assignment for warning-worthy 11042 /// operations. 11043 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11044 // Just recurse on the LHS. 11045 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11046 11047 // We want to recurse on the RHS as normal unless we're assigning to 11048 // a bitfield. 11049 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11050 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11051 E->getOperatorLoc())) { 11052 // Recurse, ignoring any implicit conversions on the RHS. 11053 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11054 E->getOperatorLoc()); 11055 } 11056 } 11057 11058 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11059 11060 // Diagnose implicitly sequentially-consistent atomic assignment. 11061 if (E->getLHS()->getType()->isAtomicType()) 11062 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11063 } 11064 11065 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11066 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11067 SourceLocation CContext, unsigned diag, 11068 bool pruneControlFlow = false) { 11069 if (pruneControlFlow) { 11070 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11071 S.PDiag(diag) 11072 << SourceType << T << E->getSourceRange() 11073 << SourceRange(CContext)); 11074 return; 11075 } 11076 S.Diag(E->getExprLoc(), diag) 11077 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11078 } 11079 11080 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11081 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11082 SourceLocation CContext, 11083 unsigned diag, bool pruneControlFlow = false) { 11084 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11085 } 11086 11087 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11088 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11089 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11090 } 11091 11092 static void adornObjCBoolConversionDiagWithTernaryFixit( 11093 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11094 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11095 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11096 Ignored = OVE->getSourceExpr(); 11097 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11098 isa<BinaryOperator>(Ignored) || 11099 isa<CXXOperatorCallExpr>(Ignored); 11100 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11101 if (NeedsParens) 11102 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11103 << FixItHint::CreateInsertion(EndLoc, ")"); 11104 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11105 } 11106 11107 /// Diagnose an implicit cast from a floating point value to an integer value. 11108 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11109 SourceLocation CContext) { 11110 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11111 const bool PruneWarnings = S.inTemplateInstantiation(); 11112 11113 Expr *InnerE = E->IgnoreParenImpCasts(); 11114 // We also want to warn on, e.g., "int i = -1.234" 11115 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11116 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11117 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11118 11119 const bool IsLiteral = 11120 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11121 11122 llvm::APFloat Value(0.0); 11123 bool IsConstant = 11124 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11125 if (!IsConstant) { 11126 if (isObjCSignedCharBool(S, T)) { 11127 return adornObjCBoolConversionDiagWithTernaryFixit( 11128 S, E, 11129 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11130 << E->getType()); 11131 } 11132 11133 return DiagnoseImpCast(S, E, T, CContext, 11134 diag::warn_impcast_float_integer, PruneWarnings); 11135 } 11136 11137 bool isExact = false; 11138 11139 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11140 T->hasUnsignedIntegerRepresentation()); 11141 llvm::APFloat::opStatus Result = Value.convertToInteger( 11142 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11143 11144 // FIXME: Force the precision of the source value down so we don't print 11145 // digits which are usually useless (we don't really care here if we 11146 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11147 // would automatically print the shortest representation, but it's a bit 11148 // tricky to implement. 11149 SmallString<16> PrettySourceValue; 11150 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11151 precision = (precision * 59 + 195) / 196; 11152 Value.toString(PrettySourceValue, precision); 11153 11154 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11155 return adornObjCBoolConversionDiagWithTernaryFixit( 11156 S, E, 11157 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11158 << PrettySourceValue); 11159 } 11160 11161 if (Result == llvm::APFloat::opOK && isExact) { 11162 if (IsLiteral) return; 11163 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11164 PruneWarnings); 11165 } 11166 11167 // Conversion of a floating-point value to a non-bool integer where the 11168 // integral part cannot be represented by the integer type is undefined. 11169 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11170 return DiagnoseImpCast( 11171 S, E, T, CContext, 11172 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11173 : diag::warn_impcast_float_to_integer_out_of_range, 11174 PruneWarnings); 11175 11176 unsigned DiagID = 0; 11177 if (IsLiteral) { 11178 // Warn on floating point literal to integer. 11179 DiagID = diag::warn_impcast_literal_float_to_integer; 11180 } else if (IntegerValue == 0) { 11181 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11182 return DiagnoseImpCast(S, E, T, CContext, 11183 diag::warn_impcast_float_integer, PruneWarnings); 11184 } 11185 // Warn on non-zero to zero conversion. 11186 DiagID = diag::warn_impcast_float_to_integer_zero; 11187 } else { 11188 if (IntegerValue.isUnsigned()) { 11189 if (!IntegerValue.isMaxValue()) { 11190 return DiagnoseImpCast(S, E, T, CContext, 11191 diag::warn_impcast_float_integer, PruneWarnings); 11192 } 11193 } else { // IntegerValue.isSigned() 11194 if (!IntegerValue.isMaxSignedValue() && 11195 !IntegerValue.isMinSignedValue()) { 11196 return DiagnoseImpCast(S, E, T, CContext, 11197 diag::warn_impcast_float_integer, PruneWarnings); 11198 } 11199 } 11200 // Warn on evaluatable floating point expression to integer conversion. 11201 DiagID = diag::warn_impcast_float_to_integer; 11202 } 11203 11204 SmallString<16> PrettyTargetValue; 11205 if (IsBool) 11206 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11207 else 11208 IntegerValue.toString(PrettyTargetValue); 11209 11210 if (PruneWarnings) { 11211 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11212 S.PDiag(DiagID) 11213 << E->getType() << T.getUnqualifiedType() 11214 << PrettySourceValue << PrettyTargetValue 11215 << E->getSourceRange() << SourceRange(CContext)); 11216 } else { 11217 S.Diag(E->getExprLoc(), DiagID) 11218 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11219 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11220 } 11221 } 11222 11223 /// Analyze the given compound assignment for the possible losing of 11224 /// floating-point precision. 11225 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11226 assert(isa<CompoundAssignOperator>(E) && 11227 "Must be compound assignment operation"); 11228 // Recurse on the LHS and RHS in here 11229 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11230 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11231 11232 if (E->getLHS()->getType()->isAtomicType()) 11233 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11234 11235 // Now check the outermost expression 11236 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11237 const auto *RBT = cast<CompoundAssignOperator>(E) 11238 ->getComputationResultType() 11239 ->getAs<BuiltinType>(); 11240 11241 // The below checks assume source is floating point. 11242 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11243 11244 // If source is floating point but target is an integer. 11245 if (ResultBT->isInteger()) 11246 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11247 E->getExprLoc(), diag::warn_impcast_float_integer); 11248 11249 if (!ResultBT->isFloatingPoint()) 11250 return; 11251 11252 // If both source and target are floating points, warn about losing precision. 11253 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11254 QualType(ResultBT, 0), QualType(RBT, 0)); 11255 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11256 // warn about dropping FP rank. 11257 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11258 diag::warn_impcast_float_result_precision); 11259 } 11260 11261 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11262 IntRange Range) { 11263 if (!Range.Width) return "0"; 11264 11265 llvm::APSInt ValueInRange = Value; 11266 ValueInRange.setIsSigned(!Range.NonNegative); 11267 ValueInRange = ValueInRange.trunc(Range.Width); 11268 return ValueInRange.toString(10); 11269 } 11270 11271 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11272 if (!isa<ImplicitCastExpr>(Ex)) 11273 return false; 11274 11275 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11276 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11277 const Type *Source = 11278 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11279 if (Target->isDependentType()) 11280 return false; 11281 11282 const BuiltinType *FloatCandidateBT = 11283 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11284 const Type *BoolCandidateType = ToBool ? Target : Source; 11285 11286 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11287 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11288 } 11289 11290 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11291 SourceLocation CC) { 11292 unsigned NumArgs = TheCall->getNumArgs(); 11293 for (unsigned i = 0; i < NumArgs; ++i) { 11294 Expr *CurrA = TheCall->getArg(i); 11295 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11296 continue; 11297 11298 bool IsSwapped = ((i > 0) && 11299 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11300 IsSwapped |= ((i < (NumArgs - 1)) && 11301 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11302 if (IsSwapped) { 11303 // Warn on this floating-point to bool conversion. 11304 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11305 CurrA->getType(), CC, 11306 diag::warn_impcast_floating_point_to_bool); 11307 } 11308 } 11309 } 11310 11311 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11312 SourceLocation CC) { 11313 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11314 E->getExprLoc())) 11315 return; 11316 11317 // Don't warn on functions which have return type nullptr_t. 11318 if (isa<CallExpr>(E)) 11319 return; 11320 11321 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11322 const Expr::NullPointerConstantKind NullKind = 11323 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11324 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11325 return; 11326 11327 // Return if target type is a safe conversion. 11328 if (T->isAnyPointerType() || T->isBlockPointerType() || 11329 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11330 return; 11331 11332 SourceLocation Loc = E->getSourceRange().getBegin(); 11333 11334 // Venture through the macro stacks to get to the source of macro arguments. 11335 // The new location is a better location than the complete location that was 11336 // passed in. 11337 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11338 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11339 11340 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11341 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11342 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11343 Loc, S.SourceMgr, S.getLangOpts()); 11344 if (MacroName == "NULL") 11345 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11346 } 11347 11348 // Only warn if the null and context location are in the same macro expansion. 11349 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11350 return; 11351 11352 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11353 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11354 << FixItHint::CreateReplacement(Loc, 11355 S.getFixItZeroLiteralForType(T, Loc)); 11356 } 11357 11358 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11359 ObjCArrayLiteral *ArrayLiteral); 11360 11361 static void 11362 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11363 ObjCDictionaryLiteral *DictionaryLiteral); 11364 11365 /// Check a single element within a collection literal against the 11366 /// target element type. 11367 static void checkObjCCollectionLiteralElement(Sema &S, 11368 QualType TargetElementType, 11369 Expr *Element, 11370 unsigned ElementKind) { 11371 // Skip a bitcast to 'id' or qualified 'id'. 11372 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11373 if (ICE->getCastKind() == CK_BitCast && 11374 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11375 Element = ICE->getSubExpr(); 11376 } 11377 11378 QualType ElementType = Element->getType(); 11379 ExprResult ElementResult(Element); 11380 if (ElementType->getAs<ObjCObjectPointerType>() && 11381 S.CheckSingleAssignmentConstraints(TargetElementType, 11382 ElementResult, 11383 false, false) 11384 != Sema::Compatible) { 11385 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11386 << ElementType << ElementKind << TargetElementType 11387 << Element->getSourceRange(); 11388 } 11389 11390 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11391 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11392 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11393 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11394 } 11395 11396 /// Check an Objective-C array literal being converted to the given 11397 /// target type. 11398 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11399 ObjCArrayLiteral *ArrayLiteral) { 11400 if (!S.NSArrayDecl) 11401 return; 11402 11403 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11404 if (!TargetObjCPtr) 11405 return; 11406 11407 if (TargetObjCPtr->isUnspecialized() || 11408 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11409 != S.NSArrayDecl->getCanonicalDecl()) 11410 return; 11411 11412 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11413 if (TypeArgs.size() != 1) 11414 return; 11415 11416 QualType TargetElementType = TypeArgs[0]; 11417 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11418 checkObjCCollectionLiteralElement(S, TargetElementType, 11419 ArrayLiteral->getElement(I), 11420 0); 11421 } 11422 } 11423 11424 /// Check an Objective-C dictionary literal being converted to the given 11425 /// target type. 11426 static void 11427 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11428 ObjCDictionaryLiteral *DictionaryLiteral) { 11429 if (!S.NSDictionaryDecl) 11430 return; 11431 11432 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11433 if (!TargetObjCPtr) 11434 return; 11435 11436 if (TargetObjCPtr->isUnspecialized() || 11437 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11438 != S.NSDictionaryDecl->getCanonicalDecl()) 11439 return; 11440 11441 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11442 if (TypeArgs.size() != 2) 11443 return; 11444 11445 QualType TargetKeyType = TypeArgs[0]; 11446 QualType TargetObjectType = TypeArgs[1]; 11447 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11448 auto Element = DictionaryLiteral->getKeyValueElement(I); 11449 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11450 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11451 } 11452 } 11453 11454 // Helper function to filter out cases for constant width constant conversion. 11455 // Don't warn on char array initialization or for non-decimal values. 11456 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11457 SourceLocation CC) { 11458 // If initializing from a constant, and the constant starts with '0', 11459 // then it is a binary, octal, or hexadecimal. Allow these constants 11460 // to fill all the bits, even if there is a sign change. 11461 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11462 const char FirstLiteralCharacter = 11463 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11464 if (FirstLiteralCharacter == '0') 11465 return false; 11466 } 11467 11468 // If the CC location points to a '{', and the type is char, then assume 11469 // assume it is an array initialization. 11470 if (CC.isValid() && T->isCharType()) { 11471 const char FirstContextCharacter = 11472 S.getSourceManager().getCharacterData(CC)[0]; 11473 if (FirstContextCharacter == '{') 11474 return false; 11475 } 11476 11477 return true; 11478 } 11479 11480 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11481 const auto *IL = dyn_cast<IntegerLiteral>(E); 11482 if (!IL) { 11483 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11484 if (UO->getOpcode() == UO_Minus) 11485 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11486 } 11487 } 11488 11489 return IL; 11490 } 11491 11492 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11493 E = E->IgnoreParenImpCasts(); 11494 SourceLocation ExprLoc = E->getExprLoc(); 11495 11496 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11497 BinaryOperator::Opcode Opc = BO->getOpcode(); 11498 Expr::EvalResult Result; 11499 // Do not diagnose unsigned shifts. 11500 if (Opc == BO_Shl) { 11501 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11502 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11503 if (LHS && LHS->getValue() == 0) 11504 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11505 else if (!E->isValueDependent() && LHS && RHS && 11506 RHS->getValue().isNonNegative() && 11507 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11508 S.Diag(ExprLoc, diag::warn_left_shift_always) 11509 << (Result.Val.getInt() != 0); 11510 else if (E->getType()->isSignedIntegerType()) 11511 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11512 } 11513 } 11514 11515 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11516 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11517 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11518 if (!LHS || !RHS) 11519 return; 11520 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11521 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11522 // Do not diagnose common idioms. 11523 return; 11524 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11525 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11526 } 11527 } 11528 11529 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11530 SourceLocation CC, 11531 bool *ICContext = nullptr, 11532 bool IsListInit = false) { 11533 if (E->isTypeDependent() || E->isValueDependent()) return; 11534 11535 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11536 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11537 if (Source == Target) return; 11538 if (Target->isDependentType()) return; 11539 11540 // If the conversion context location is invalid don't complain. We also 11541 // don't want to emit a warning if the issue occurs from the expansion of 11542 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11543 // delay this check as long as possible. Once we detect we are in that 11544 // scenario, we just return. 11545 if (CC.isInvalid()) 11546 return; 11547 11548 if (Source->isAtomicType()) 11549 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11550 11551 // Diagnose implicit casts to bool. 11552 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11553 if (isa<StringLiteral>(E)) 11554 // Warn on string literal to bool. Checks for string literals in logical 11555 // and expressions, for instance, assert(0 && "error here"), are 11556 // prevented by a check in AnalyzeImplicitConversions(). 11557 return DiagnoseImpCast(S, E, T, CC, 11558 diag::warn_impcast_string_literal_to_bool); 11559 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11560 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11561 // This covers the literal expressions that evaluate to Objective-C 11562 // objects. 11563 return DiagnoseImpCast(S, E, T, CC, 11564 diag::warn_impcast_objective_c_literal_to_bool); 11565 } 11566 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11567 // Warn on pointer to bool conversion that is always true. 11568 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11569 SourceRange(CC)); 11570 } 11571 } 11572 11573 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11574 // is a typedef for signed char (macOS), then that constant value has to be 1 11575 // or 0. 11576 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11577 Expr::EvalResult Result; 11578 if (E->EvaluateAsInt(Result, S.getASTContext(), 11579 Expr::SE_AllowSideEffects)) { 11580 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11581 adornObjCBoolConversionDiagWithTernaryFixit( 11582 S, E, 11583 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11584 << Result.Val.getInt().toString(10)); 11585 } 11586 return; 11587 } 11588 } 11589 11590 // Check implicit casts from Objective-C collection literals to specialized 11591 // collection types, e.g., NSArray<NSString *> *. 11592 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11593 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11594 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11595 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11596 11597 // Strip vector types. 11598 if (isa<VectorType>(Source)) { 11599 if (!isa<VectorType>(Target)) { 11600 if (S.SourceMgr.isInSystemMacro(CC)) 11601 return; 11602 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11603 } 11604 11605 // If the vector cast is cast between two vectors of the same size, it is 11606 // a bitcast, not a conversion. 11607 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11608 return; 11609 11610 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11611 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11612 } 11613 if (auto VecTy = dyn_cast<VectorType>(Target)) 11614 Target = VecTy->getElementType().getTypePtr(); 11615 11616 // Strip complex types. 11617 if (isa<ComplexType>(Source)) { 11618 if (!isa<ComplexType>(Target)) { 11619 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11620 return; 11621 11622 return DiagnoseImpCast(S, E, T, CC, 11623 S.getLangOpts().CPlusPlus 11624 ? diag::err_impcast_complex_scalar 11625 : diag::warn_impcast_complex_scalar); 11626 } 11627 11628 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11629 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11630 } 11631 11632 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11633 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11634 11635 // If the source is floating point... 11636 if (SourceBT && SourceBT->isFloatingPoint()) { 11637 // ...and the target is floating point... 11638 if (TargetBT && TargetBT->isFloatingPoint()) { 11639 // ...then warn if we're dropping FP rank. 11640 11641 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11642 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11643 if (Order > 0) { 11644 // Don't warn about float constants that are precisely 11645 // representable in the target type. 11646 Expr::EvalResult result; 11647 if (E->EvaluateAsRValue(result, S.Context)) { 11648 // Value might be a float, a float vector, or a float complex. 11649 if (IsSameFloatAfterCast(result.Val, 11650 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11651 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11652 return; 11653 } 11654 11655 if (S.SourceMgr.isInSystemMacro(CC)) 11656 return; 11657 11658 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11659 } 11660 // ... or possibly if we're increasing rank, too 11661 else if (Order < 0) { 11662 if (S.SourceMgr.isInSystemMacro(CC)) 11663 return; 11664 11665 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11666 } 11667 return; 11668 } 11669 11670 // If the target is integral, always warn. 11671 if (TargetBT && TargetBT->isInteger()) { 11672 if (S.SourceMgr.isInSystemMacro(CC)) 11673 return; 11674 11675 DiagnoseFloatingImpCast(S, E, T, CC); 11676 } 11677 11678 // Detect the case where a call result is converted from floating-point to 11679 // to bool, and the final argument to the call is converted from bool, to 11680 // discover this typo: 11681 // 11682 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11683 // 11684 // FIXME: This is an incredibly special case; is there some more general 11685 // way to detect this class of misplaced-parentheses bug? 11686 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11687 // Check last argument of function call to see if it is an 11688 // implicit cast from a type matching the type the result 11689 // is being cast to. 11690 CallExpr *CEx = cast<CallExpr>(E); 11691 if (unsigned NumArgs = CEx->getNumArgs()) { 11692 Expr *LastA = CEx->getArg(NumArgs - 1); 11693 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11694 if (isa<ImplicitCastExpr>(LastA) && 11695 InnerE->getType()->isBooleanType()) { 11696 // Warn on this floating-point to bool conversion 11697 DiagnoseImpCast(S, E, T, CC, 11698 diag::warn_impcast_floating_point_to_bool); 11699 } 11700 } 11701 } 11702 return; 11703 } 11704 11705 // Valid casts involving fixed point types should be accounted for here. 11706 if (Source->isFixedPointType()) { 11707 if (Target->isUnsaturatedFixedPointType()) { 11708 Expr::EvalResult Result; 11709 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11710 S.isConstantEvaluated())) { 11711 APFixedPoint Value = Result.Val.getFixedPoint(); 11712 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11713 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11714 if (Value > MaxVal || Value < MinVal) { 11715 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11716 S.PDiag(diag::warn_impcast_fixed_point_range) 11717 << Value.toString() << T 11718 << E->getSourceRange() 11719 << clang::SourceRange(CC)); 11720 return; 11721 } 11722 } 11723 } else if (Target->isIntegerType()) { 11724 Expr::EvalResult Result; 11725 if (!S.isConstantEvaluated() && 11726 E->EvaluateAsFixedPoint(Result, S.Context, 11727 Expr::SE_AllowSideEffects)) { 11728 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11729 11730 bool Overflowed; 11731 llvm::APSInt IntResult = FXResult.convertToInt( 11732 S.Context.getIntWidth(T), 11733 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11734 11735 if (Overflowed) { 11736 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11737 S.PDiag(diag::warn_impcast_fixed_point_range) 11738 << FXResult.toString() << T 11739 << E->getSourceRange() 11740 << clang::SourceRange(CC)); 11741 return; 11742 } 11743 } 11744 } 11745 } else if (Target->isUnsaturatedFixedPointType()) { 11746 if (Source->isIntegerType()) { 11747 Expr::EvalResult Result; 11748 if (!S.isConstantEvaluated() && 11749 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11750 llvm::APSInt Value = Result.Val.getInt(); 11751 11752 bool Overflowed; 11753 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11754 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11755 11756 if (Overflowed) { 11757 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11758 S.PDiag(diag::warn_impcast_fixed_point_range) 11759 << Value.toString(/*Radix=*/10) << T 11760 << E->getSourceRange() 11761 << clang::SourceRange(CC)); 11762 return; 11763 } 11764 } 11765 } 11766 } 11767 11768 // If we are casting an integer type to a floating point type without 11769 // initialization-list syntax, we might lose accuracy if the floating 11770 // point type has a narrower significand than the integer type. 11771 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11772 TargetBT->isFloatingType() && !IsListInit) { 11773 // Determine the number of precision bits in the source integer type. 11774 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11775 unsigned int SourcePrecision = SourceRange.Width; 11776 11777 // Determine the number of precision bits in the 11778 // target floating point type. 11779 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11780 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11781 11782 if (SourcePrecision > 0 && TargetPrecision > 0 && 11783 SourcePrecision > TargetPrecision) { 11784 11785 if (Optional<llvm::APSInt> SourceInt = 11786 E->getIntegerConstantExpr(S.Context)) { 11787 // If the source integer is a constant, convert it to the target 11788 // floating point type. Issue a warning if the value changes 11789 // during the whole conversion. 11790 llvm::APFloat TargetFloatValue( 11791 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11792 llvm::APFloat::opStatus ConversionStatus = 11793 TargetFloatValue.convertFromAPInt( 11794 *SourceInt, SourceBT->isSignedInteger(), 11795 llvm::APFloat::rmNearestTiesToEven); 11796 11797 if (ConversionStatus != llvm::APFloat::opOK) { 11798 std::string PrettySourceValue = SourceInt->toString(10); 11799 SmallString<32> PrettyTargetValue; 11800 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11801 11802 S.DiagRuntimeBehavior( 11803 E->getExprLoc(), E, 11804 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11805 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11806 << E->getSourceRange() << clang::SourceRange(CC)); 11807 } 11808 } else { 11809 // Otherwise, the implicit conversion may lose precision. 11810 DiagnoseImpCast(S, E, T, CC, 11811 diag::warn_impcast_integer_float_precision); 11812 } 11813 } 11814 } 11815 11816 DiagnoseNullConversion(S, E, T, CC); 11817 11818 S.DiscardMisalignedMemberAddress(Target, E); 11819 11820 if (Target->isBooleanType()) 11821 DiagnoseIntInBoolContext(S, E); 11822 11823 if (!Source->isIntegerType() || !Target->isIntegerType()) 11824 return; 11825 11826 // TODO: remove this early return once the false positives for constant->bool 11827 // in templates, macros, etc, are reduced or removed. 11828 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11829 return; 11830 11831 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11832 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11833 return adornObjCBoolConversionDiagWithTernaryFixit( 11834 S, E, 11835 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11836 << E->getType()); 11837 } 11838 11839 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11840 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11841 11842 if (SourceRange.Width > TargetRange.Width) { 11843 // If the source is a constant, use a default-on diagnostic. 11844 // TODO: this should happen for bitfield stores, too. 11845 Expr::EvalResult Result; 11846 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11847 S.isConstantEvaluated())) { 11848 llvm::APSInt Value(32); 11849 Value = Result.Val.getInt(); 11850 11851 if (S.SourceMgr.isInSystemMacro(CC)) 11852 return; 11853 11854 std::string PrettySourceValue = Value.toString(10); 11855 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11856 11857 S.DiagRuntimeBehavior( 11858 E->getExprLoc(), E, 11859 S.PDiag(diag::warn_impcast_integer_precision_constant) 11860 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11861 << E->getSourceRange() << clang::SourceRange(CC)); 11862 return; 11863 } 11864 11865 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11866 if (S.SourceMgr.isInSystemMacro(CC)) 11867 return; 11868 11869 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11870 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11871 /* pruneControlFlow */ true); 11872 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11873 } 11874 11875 if (TargetRange.Width > SourceRange.Width) { 11876 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11877 if (UO->getOpcode() == UO_Minus) 11878 if (Source->isUnsignedIntegerType()) { 11879 if (Target->isUnsignedIntegerType()) 11880 return DiagnoseImpCast(S, E, T, CC, 11881 diag::warn_impcast_high_order_zero_bits); 11882 if (Target->isSignedIntegerType()) 11883 return DiagnoseImpCast(S, E, T, CC, 11884 diag::warn_impcast_nonnegative_result); 11885 } 11886 } 11887 11888 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11889 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11890 // Warn when doing a signed to signed conversion, warn if the positive 11891 // source value is exactly the width of the target type, which will 11892 // cause a negative value to be stored. 11893 11894 Expr::EvalResult Result; 11895 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11896 !S.SourceMgr.isInSystemMacro(CC)) { 11897 llvm::APSInt Value = Result.Val.getInt(); 11898 if (isSameWidthConstantConversion(S, E, T, CC)) { 11899 std::string PrettySourceValue = Value.toString(10); 11900 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11901 11902 S.DiagRuntimeBehavior( 11903 E->getExprLoc(), E, 11904 S.PDiag(diag::warn_impcast_integer_precision_constant) 11905 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11906 << E->getSourceRange() << clang::SourceRange(CC)); 11907 return; 11908 } 11909 } 11910 11911 // Fall through for non-constants to give a sign conversion warning. 11912 } 11913 11914 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11915 (!TargetRange.NonNegative && SourceRange.NonNegative && 11916 SourceRange.Width == TargetRange.Width)) { 11917 if (S.SourceMgr.isInSystemMacro(CC)) 11918 return; 11919 11920 unsigned DiagID = diag::warn_impcast_integer_sign; 11921 11922 // Traditionally, gcc has warned about this under -Wsign-compare. 11923 // We also want to warn about it in -Wconversion. 11924 // So if -Wconversion is off, use a completely identical diagnostic 11925 // in the sign-compare group. 11926 // The conditional-checking code will 11927 if (ICContext) { 11928 DiagID = diag::warn_impcast_integer_sign_conditional; 11929 *ICContext = true; 11930 } 11931 11932 return DiagnoseImpCast(S, E, T, CC, DiagID); 11933 } 11934 11935 // Diagnose conversions between different enumeration types. 11936 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11937 // type, to give us better diagnostics. 11938 QualType SourceType = E->getType(); 11939 if (!S.getLangOpts().CPlusPlus) { 11940 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11941 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11942 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11943 SourceType = S.Context.getTypeDeclType(Enum); 11944 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11945 } 11946 } 11947 11948 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11949 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11950 if (SourceEnum->getDecl()->hasNameForLinkage() && 11951 TargetEnum->getDecl()->hasNameForLinkage() && 11952 SourceEnum != TargetEnum) { 11953 if (S.SourceMgr.isInSystemMacro(CC)) 11954 return; 11955 11956 return DiagnoseImpCast(S, E, SourceType, T, CC, 11957 diag::warn_impcast_different_enum_types); 11958 } 11959 } 11960 11961 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 11962 SourceLocation CC, QualType T); 11963 11964 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11965 SourceLocation CC, bool &ICContext) { 11966 E = E->IgnoreParenImpCasts(); 11967 11968 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 11969 return CheckConditionalOperator(S, CO, CC, T); 11970 11971 AnalyzeImplicitConversions(S, E, CC); 11972 if (E->getType() != T) 11973 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11974 } 11975 11976 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 11977 SourceLocation CC, QualType T) { 11978 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11979 11980 Expr *TrueExpr = E->getTrueExpr(); 11981 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 11982 TrueExpr = BCO->getCommon(); 11983 11984 bool Suspicious = false; 11985 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 11986 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11987 11988 if (T->isBooleanType()) 11989 DiagnoseIntInBoolContext(S, E); 11990 11991 // If -Wconversion would have warned about either of the candidates 11992 // for a signedness conversion to the context type... 11993 if (!Suspicious) return; 11994 11995 // ...but it's currently ignored... 11996 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11997 return; 11998 11999 // ...then check whether it would have warned about either of the 12000 // candidates for a signedness conversion to the condition type. 12001 if (E->getType() == T) return; 12002 12003 Suspicious = false; 12004 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12005 E->getType(), CC, &Suspicious); 12006 if (!Suspicious) 12007 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12008 E->getType(), CC, &Suspicious); 12009 } 12010 12011 /// Check conversion of given expression to boolean. 12012 /// Input argument E is a logical expression. 12013 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12014 if (S.getLangOpts().Bool) 12015 return; 12016 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12017 return; 12018 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12019 } 12020 12021 namespace { 12022 struct AnalyzeImplicitConversionsWorkItem { 12023 Expr *E; 12024 SourceLocation CC; 12025 bool IsListInit; 12026 }; 12027 } 12028 12029 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12030 /// that should be visited are added to WorkList. 12031 static void AnalyzeImplicitConversions( 12032 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12033 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12034 Expr *OrigE = Item.E; 12035 SourceLocation CC = Item.CC; 12036 12037 QualType T = OrigE->getType(); 12038 Expr *E = OrigE->IgnoreParenImpCasts(); 12039 12040 // Propagate whether we are in a C++ list initialization expression. 12041 // If so, we do not issue warnings for implicit int-float conversion 12042 // precision loss, because C++11 narrowing already handles it. 12043 bool IsListInit = Item.IsListInit || 12044 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12045 12046 if (E->isTypeDependent() || E->isValueDependent()) 12047 return; 12048 12049 Expr *SourceExpr = E; 12050 // Examine, but don't traverse into the source expression of an 12051 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12052 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12053 // evaluate it in the context of checking the specific conversion to T though. 12054 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12055 if (auto *Src = OVE->getSourceExpr()) 12056 SourceExpr = Src; 12057 12058 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12059 if (UO->getOpcode() == UO_Not && 12060 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12061 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12062 << OrigE->getSourceRange() << T->isBooleanType() 12063 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12064 12065 // For conditional operators, we analyze the arguments as if they 12066 // were being fed directly into the output. 12067 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12068 CheckConditionalOperator(S, CO, CC, T); 12069 return; 12070 } 12071 12072 // Check implicit argument conversions for function calls. 12073 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12074 CheckImplicitArgumentConversions(S, Call, CC); 12075 12076 // Go ahead and check any implicit conversions we might have skipped. 12077 // The non-canonical typecheck is just an optimization; 12078 // CheckImplicitConversion will filter out dead implicit conversions. 12079 if (SourceExpr->getType() != T) 12080 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12081 12082 // Now continue drilling into this expression. 12083 12084 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12085 // The bound subexpressions in a PseudoObjectExpr are not reachable 12086 // as transitive children. 12087 // FIXME: Use a more uniform representation for this. 12088 for (auto *SE : POE->semantics()) 12089 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12090 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12091 } 12092 12093 // Skip past explicit casts. 12094 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12095 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12096 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12097 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12098 WorkList.push_back({E, CC, IsListInit}); 12099 return; 12100 } 12101 12102 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12103 // Do a somewhat different check with comparison operators. 12104 if (BO->isComparisonOp()) 12105 return AnalyzeComparison(S, BO); 12106 12107 // And with simple assignments. 12108 if (BO->getOpcode() == BO_Assign) 12109 return AnalyzeAssignment(S, BO); 12110 // And with compound assignments. 12111 if (BO->isAssignmentOp()) 12112 return AnalyzeCompoundAssignment(S, BO); 12113 } 12114 12115 // These break the otherwise-useful invariant below. Fortunately, 12116 // we don't really need to recurse into them, because any internal 12117 // expressions should have been analyzed already when they were 12118 // built into statements. 12119 if (isa<StmtExpr>(E)) return; 12120 12121 // Don't descend into unevaluated contexts. 12122 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12123 12124 // Now just recurse over the expression's children. 12125 CC = E->getExprLoc(); 12126 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12127 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12128 for (Stmt *SubStmt : E->children()) { 12129 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12130 if (!ChildExpr) 12131 continue; 12132 12133 if (IsLogicalAndOperator && 12134 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12135 // Ignore checking string literals that are in logical and operators. 12136 // This is a common pattern for asserts. 12137 continue; 12138 WorkList.push_back({ChildExpr, CC, IsListInit}); 12139 } 12140 12141 if (BO && BO->isLogicalOp()) { 12142 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12143 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12144 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12145 12146 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12147 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12148 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12149 } 12150 12151 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12152 if (U->getOpcode() == UO_LNot) { 12153 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12154 } else if (U->getOpcode() != UO_AddrOf) { 12155 if (U->getSubExpr()->getType()->isAtomicType()) 12156 S.Diag(U->getSubExpr()->getBeginLoc(), 12157 diag::warn_atomic_implicit_seq_cst); 12158 } 12159 } 12160 } 12161 12162 /// AnalyzeImplicitConversions - Find and report any interesting 12163 /// implicit conversions in the given expression. There are a couple 12164 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12165 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12166 bool IsListInit/*= false*/) { 12167 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12168 WorkList.push_back({OrigE, CC, IsListInit}); 12169 while (!WorkList.empty()) 12170 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12171 } 12172 12173 /// Diagnose integer type and any valid implicit conversion to it. 12174 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12175 // Taking into account implicit conversions, 12176 // allow any integer. 12177 if (!E->getType()->isIntegerType()) { 12178 S.Diag(E->getBeginLoc(), 12179 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12180 return true; 12181 } 12182 // Potentially emit standard warnings for implicit conversions if enabled 12183 // using -Wconversion. 12184 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12185 return false; 12186 } 12187 12188 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12189 // Returns true when emitting a warning about taking the address of a reference. 12190 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12191 const PartialDiagnostic &PD) { 12192 E = E->IgnoreParenImpCasts(); 12193 12194 const FunctionDecl *FD = nullptr; 12195 12196 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12197 if (!DRE->getDecl()->getType()->isReferenceType()) 12198 return false; 12199 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12200 if (!M->getMemberDecl()->getType()->isReferenceType()) 12201 return false; 12202 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12203 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12204 return false; 12205 FD = Call->getDirectCallee(); 12206 } else { 12207 return false; 12208 } 12209 12210 SemaRef.Diag(E->getExprLoc(), PD); 12211 12212 // If possible, point to location of function. 12213 if (FD) { 12214 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12215 } 12216 12217 return true; 12218 } 12219 12220 // Returns true if the SourceLocation is expanded from any macro body. 12221 // Returns false if the SourceLocation is invalid, is from not in a macro 12222 // expansion, or is from expanded from a top-level macro argument. 12223 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12224 if (Loc.isInvalid()) 12225 return false; 12226 12227 while (Loc.isMacroID()) { 12228 if (SM.isMacroBodyExpansion(Loc)) 12229 return true; 12230 Loc = SM.getImmediateMacroCallerLoc(Loc); 12231 } 12232 12233 return false; 12234 } 12235 12236 /// Diagnose pointers that are always non-null. 12237 /// \param E the expression containing the pointer 12238 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12239 /// compared to a null pointer 12240 /// \param IsEqual True when the comparison is equal to a null pointer 12241 /// \param Range Extra SourceRange to highlight in the diagnostic 12242 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12243 Expr::NullPointerConstantKind NullKind, 12244 bool IsEqual, SourceRange Range) { 12245 if (!E) 12246 return; 12247 12248 // Don't warn inside macros. 12249 if (E->getExprLoc().isMacroID()) { 12250 const SourceManager &SM = getSourceManager(); 12251 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12252 IsInAnyMacroBody(SM, Range.getBegin())) 12253 return; 12254 } 12255 E = E->IgnoreImpCasts(); 12256 12257 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12258 12259 if (isa<CXXThisExpr>(E)) { 12260 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12261 : diag::warn_this_bool_conversion; 12262 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12263 return; 12264 } 12265 12266 bool IsAddressOf = false; 12267 12268 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12269 if (UO->getOpcode() != UO_AddrOf) 12270 return; 12271 IsAddressOf = true; 12272 E = UO->getSubExpr(); 12273 } 12274 12275 if (IsAddressOf) { 12276 unsigned DiagID = IsCompare 12277 ? diag::warn_address_of_reference_null_compare 12278 : diag::warn_address_of_reference_bool_conversion; 12279 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12280 << IsEqual; 12281 if (CheckForReference(*this, E, PD)) { 12282 return; 12283 } 12284 } 12285 12286 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12287 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12288 std::string Str; 12289 llvm::raw_string_ostream S(Str); 12290 E->printPretty(S, nullptr, getPrintingPolicy()); 12291 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12292 : diag::warn_cast_nonnull_to_bool; 12293 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12294 << E->getSourceRange() << Range << IsEqual; 12295 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12296 }; 12297 12298 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12299 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12300 if (auto *Callee = Call->getDirectCallee()) { 12301 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12302 ComplainAboutNonnullParamOrCall(A); 12303 return; 12304 } 12305 } 12306 } 12307 12308 // Expect to find a single Decl. Skip anything more complicated. 12309 ValueDecl *D = nullptr; 12310 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12311 D = R->getDecl(); 12312 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12313 D = M->getMemberDecl(); 12314 } 12315 12316 // Weak Decls can be null. 12317 if (!D || D->isWeak()) 12318 return; 12319 12320 // Check for parameter decl with nonnull attribute 12321 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12322 if (getCurFunction() && 12323 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12324 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12325 ComplainAboutNonnullParamOrCall(A); 12326 return; 12327 } 12328 12329 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12330 // Skip function template not specialized yet. 12331 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12332 return; 12333 auto ParamIter = llvm::find(FD->parameters(), PV); 12334 assert(ParamIter != FD->param_end()); 12335 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12336 12337 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12338 if (!NonNull->args_size()) { 12339 ComplainAboutNonnullParamOrCall(NonNull); 12340 return; 12341 } 12342 12343 for (const ParamIdx &ArgNo : NonNull->args()) { 12344 if (ArgNo.getASTIndex() == ParamNo) { 12345 ComplainAboutNonnullParamOrCall(NonNull); 12346 return; 12347 } 12348 } 12349 } 12350 } 12351 } 12352 } 12353 12354 QualType T = D->getType(); 12355 const bool IsArray = T->isArrayType(); 12356 const bool IsFunction = T->isFunctionType(); 12357 12358 // Address of function is used to silence the function warning. 12359 if (IsAddressOf && IsFunction) { 12360 return; 12361 } 12362 12363 // Found nothing. 12364 if (!IsAddressOf && !IsFunction && !IsArray) 12365 return; 12366 12367 // Pretty print the expression for the diagnostic. 12368 std::string Str; 12369 llvm::raw_string_ostream S(Str); 12370 E->printPretty(S, nullptr, getPrintingPolicy()); 12371 12372 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12373 : diag::warn_impcast_pointer_to_bool; 12374 enum { 12375 AddressOf, 12376 FunctionPointer, 12377 ArrayPointer 12378 } DiagType; 12379 if (IsAddressOf) 12380 DiagType = AddressOf; 12381 else if (IsFunction) 12382 DiagType = FunctionPointer; 12383 else if (IsArray) 12384 DiagType = ArrayPointer; 12385 else 12386 llvm_unreachable("Could not determine diagnostic."); 12387 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12388 << Range << IsEqual; 12389 12390 if (!IsFunction) 12391 return; 12392 12393 // Suggest '&' to silence the function warning. 12394 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12395 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12396 12397 // Check to see if '()' fixit should be emitted. 12398 QualType ReturnType; 12399 UnresolvedSet<4> NonTemplateOverloads; 12400 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12401 if (ReturnType.isNull()) 12402 return; 12403 12404 if (IsCompare) { 12405 // There are two cases here. If there is null constant, the only suggest 12406 // for a pointer return type. If the null is 0, then suggest if the return 12407 // type is a pointer or an integer type. 12408 if (!ReturnType->isPointerType()) { 12409 if (NullKind == Expr::NPCK_ZeroExpression || 12410 NullKind == Expr::NPCK_ZeroLiteral) { 12411 if (!ReturnType->isIntegerType()) 12412 return; 12413 } else { 12414 return; 12415 } 12416 } 12417 } else { // !IsCompare 12418 // For function to bool, only suggest if the function pointer has bool 12419 // return type. 12420 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12421 return; 12422 } 12423 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12424 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12425 } 12426 12427 /// Diagnoses "dangerous" implicit conversions within the given 12428 /// expression (which is a full expression). Implements -Wconversion 12429 /// and -Wsign-compare. 12430 /// 12431 /// \param CC the "context" location of the implicit conversion, i.e. 12432 /// the most location of the syntactic entity requiring the implicit 12433 /// conversion 12434 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12435 // Don't diagnose in unevaluated contexts. 12436 if (isUnevaluatedContext()) 12437 return; 12438 12439 // Don't diagnose for value- or type-dependent expressions. 12440 if (E->isTypeDependent() || E->isValueDependent()) 12441 return; 12442 12443 // Check for array bounds violations in cases where the check isn't triggered 12444 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12445 // ArraySubscriptExpr is on the RHS of a variable initialization. 12446 CheckArrayAccess(E); 12447 12448 // This is not the right CC for (e.g.) a variable initialization. 12449 AnalyzeImplicitConversions(*this, E, CC); 12450 } 12451 12452 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12453 /// Input argument E is a logical expression. 12454 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12455 ::CheckBoolLikeConversion(*this, E, CC); 12456 } 12457 12458 /// Diagnose when expression is an integer constant expression and its evaluation 12459 /// results in integer overflow 12460 void Sema::CheckForIntOverflow (Expr *E) { 12461 // Use a work list to deal with nested struct initializers. 12462 SmallVector<Expr *, 2> Exprs(1, E); 12463 12464 do { 12465 Expr *OriginalE = Exprs.pop_back_val(); 12466 Expr *E = OriginalE->IgnoreParenCasts(); 12467 12468 if (isa<BinaryOperator>(E)) { 12469 E->EvaluateForOverflow(Context); 12470 continue; 12471 } 12472 12473 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12474 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12475 else if (isa<ObjCBoxedExpr>(OriginalE)) 12476 E->EvaluateForOverflow(Context); 12477 else if (auto Call = dyn_cast<CallExpr>(E)) 12478 Exprs.append(Call->arg_begin(), Call->arg_end()); 12479 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12480 Exprs.append(Message->arg_begin(), Message->arg_end()); 12481 } while (!Exprs.empty()); 12482 } 12483 12484 namespace { 12485 12486 /// Visitor for expressions which looks for unsequenced operations on the 12487 /// same object. 12488 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12489 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12490 12491 /// A tree of sequenced regions within an expression. Two regions are 12492 /// unsequenced if one is an ancestor or a descendent of the other. When we 12493 /// finish processing an expression with sequencing, such as a comma 12494 /// expression, we fold its tree nodes into its parent, since they are 12495 /// unsequenced with respect to nodes we will visit later. 12496 class SequenceTree { 12497 struct Value { 12498 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12499 unsigned Parent : 31; 12500 unsigned Merged : 1; 12501 }; 12502 SmallVector<Value, 8> Values; 12503 12504 public: 12505 /// A region within an expression which may be sequenced with respect 12506 /// to some other region. 12507 class Seq { 12508 friend class SequenceTree; 12509 12510 unsigned Index; 12511 12512 explicit Seq(unsigned N) : Index(N) {} 12513 12514 public: 12515 Seq() : Index(0) {} 12516 }; 12517 12518 SequenceTree() { Values.push_back(Value(0)); } 12519 Seq root() const { return Seq(0); } 12520 12521 /// Create a new sequence of operations, which is an unsequenced 12522 /// subset of \p Parent. This sequence of operations is sequenced with 12523 /// respect to other children of \p Parent. 12524 Seq allocate(Seq Parent) { 12525 Values.push_back(Value(Parent.Index)); 12526 return Seq(Values.size() - 1); 12527 } 12528 12529 /// Merge a sequence of operations into its parent. 12530 void merge(Seq S) { 12531 Values[S.Index].Merged = true; 12532 } 12533 12534 /// Determine whether two operations are unsequenced. This operation 12535 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12536 /// should have been merged into its parent as appropriate. 12537 bool isUnsequenced(Seq Cur, Seq Old) { 12538 unsigned C = representative(Cur.Index); 12539 unsigned Target = representative(Old.Index); 12540 while (C >= Target) { 12541 if (C == Target) 12542 return true; 12543 C = Values[C].Parent; 12544 } 12545 return false; 12546 } 12547 12548 private: 12549 /// Pick a representative for a sequence. 12550 unsigned representative(unsigned K) { 12551 if (Values[K].Merged) 12552 // Perform path compression as we go. 12553 return Values[K].Parent = representative(Values[K].Parent); 12554 return K; 12555 } 12556 }; 12557 12558 /// An object for which we can track unsequenced uses. 12559 using Object = const NamedDecl *; 12560 12561 /// Different flavors of object usage which we track. We only track the 12562 /// least-sequenced usage of each kind. 12563 enum UsageKind { 12564 /// A read of an object. Multiple unsequenced reads are OK. 12565 UK_Use, 12566 12567 /// A modification of an object which is sequenced before the value 12568 /// computation of the expression, such as ++n in C++. 12569 UK_ModAsValue, 12570 12571 /// A modification of an object which is not sequenced before the value 12572 /// computation of the expression, such as n++. 12573 UK_ModAsSideEffect, 12574 12575 UK_Count = UK_ModAsSideEffect + 1 12576 }; 12577 12578 /// Bundle together a sequencing region and the expression corresponding 12579 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12580 struct Usage { 12581 const Expr *UsageExpr; 12582 SequenceTree::Seq Seq; 12583 12584 Usage() : UsageExpr(nullptr), Seq() {} 12585 }; 12586 12587 struct UsageInfo { 12588 Usage Uses[UK_Count]; 12589 12590 /// Have we issued a diagnostic for this object already? 12591 bool Diagnosed; 12592 12593 UsageInfo() : Uses(), Diagnosed(false) {} 12594 }; 12595 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12596 12597 Sema &SemaRef; 12598 12599 /// Sequenced regions within the expression. 12600 SequenceTree Tree; 12601 12602 /// Declaration modifications and references which we have seen. 12603 UsageInfoMap UsageMap; 12604 12605 /// The region we are currently within. 12606 SequenceTree::Seq Region; 12607 12608 /// Filled in with declarations which were modified as a side-effect 12609 /// (that is, post-increment operations). 12610 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12611 12612 /// Expressions to check later. We defer checking these to reduce 12613 /// stack usage. 12614 SmallVectorImpl<const Expr *> &WorkList; 12615 12616 /// RAII object wrapping the visitation of a sequenced subexpression of an 12617 /// expression. At the end of this process, the side-effects of the evaluation 12618 /// become sequenced with respect to the value computation of the result, so 12619 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12620 /// UK_ModAsValue. 12621 struct SequencedSubexpression { 12622 SequencedSubexpression(SequenceChecker &Self) 12623 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12624 Self.ModAsSideEffect = &ModAsSideEffect; 12625 } 12626 12627 ~SequencedSubexpression() { 12628 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12629 // Add a new usage with usage kind UK_ModAsValue, and then restore 12630 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12631 // the previous one was empty). 12632 UsageInfo &UI = Self.UsageMap[M.first]; 12633 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12634 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12635 SideEffectUsage = M.second; 12636 } 12637 Self.ModAsSideEffect = OldModAsSideEffect; 12638 } 12639 12640 SequenceChecker &Self; 12641 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12642 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12643 }; 12644 12645 /// RAII object wrapping the visitation of a subexpression which we might 12646 /// choose to evaluate as a constant. If any subexpression is evaluated and 12647 /// found to be non-constant, this allows us to suppress the evaluation of 12648 /// the outer expression. 12649 class EvaluationTracker { 12650 public: 12651 EvaluationTracker(SequenceChecker &Self) 12652 : Self(Self), Prev(Self.EvalTracker) { 12653 Self.EvalTracker = this; 12654 } 12655 12656 ~EvaluationTracker() { 12657 Self.EvalTracker = Prev; 12658 if (Prev) 12659 Prev->EvalOK &= EvalOK; 12660 } 12661 12662 bool evaluate(const Expr *E, bool &Result) { 12663 if (!EvalOK || E->isValueDependent()) 12664 return false; 12665 EvalOK = E->EvaluateAsBooleanCondition( 12666 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12667 return EvalOK; 12668 } 12669 12670 private: 12671 SequenceChecker &Self; 12672 EvaluationTracker *Prev; 12673 bool EvalOK = true; 12674 } *EvalTracker = nullptr; 12675 12676 /// Find the object which is produced by the specified expression, 12677 /// if any. 12678 Object getObject(const Expr *E, bool Mod) const { 12679 E = E->IgnoreParenCasts(); 12680 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12681 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12682 return getObject(UO->getSubExpr(), Mod); 12683 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12684 if (BO->getOpcode() == BO_Comma) 12685 return getObject(BO->getRHS(), Mod); 12686 if (Mod && BO->isAssignmentOp()) 12687 return getObject(BO->getLHS(), Mod); 12688 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12689 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12690 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12691 return ME->getMemberDecl(); 12692 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12693 // FIXME: If this is a reference, map through to its value. 12694 return DRE->getDecl(); 12695 return nullptr; 12696 } 12697 12698 /// Note that an object \p O was modified or used by an expression 12699 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12700 /// the object \p O as obtained via the \p UsageMap. 12701 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12702 // Get the old usage for the given object and usage kind. 12703 Usage &U = UI.Uses[UK]; 12704 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12705 // If we have a modification as side effect and are in a sequenced 12706 // subexpression, save the old Usage so that we can restore it later 12707 // in SequencedSubexpression::~SequencedSubexpression. 12708 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12709 ModAsSideEffect->push_back(std::make_pair(O, U)); 12710 // Then record the new usage with the current sequencing region. 12711 U.UsageExpr = UsageExpr; 12712 U.Seq = Region; 12713 } 12714 } 12715 12716 /// Check whether a modification or use of an object \p O in an expression 12717 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12718 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12719 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12720 /// usage and false we are checking for a mod-use unsequenced usage. 12721 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12722 UsageKind OtherKind, bool IsModMod) { 12723 if (UI.Diagnosed) 12724 return; 12725 12726 const Usage &U = UI.Uses[OtherKind]; 12727 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12728 return; 12729 12730 const Expr *Mod = U.UsageExpr; 12731 const Expr *ModOrUse = UsageExpr; 12732 if (OtherKind == UK_Use) 12733 std::swap(Mod, ModOrUse); 12734 12735 SemaRef.DiagRuntimeBehavior( 12736 Mod->getExprLoc(), {Mod, ModOrUse}, 12737 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12738 : diag::warn_unsequenced_mod_use) 12739 << O << SourceRange(ModOrUse->getExprLoc())); 12740 UI.Diagnosed = true; 12741 } 12742 12743 // A note on note{Pre, Post}{Use, Mod}: 12744 // 12745 // (It helps to follow the algorithm with an expression such as 12746 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12747 // operations before C++17 and both are well-defined in C++17). 12748 // 12749 // When visiting a node which uses/modify an object we first call notePreUse 12750 // or notePreMod before visiting its sub-expression(s). At this point the 12751 // children of the current node have not yet been visited and so the eventual 12752 // uses/modifications resulting from the children of the current node have not 12753 // been recorded yet. 12754 // 12755 // We then visit the children of the current node. After that notePostUse or 12756 // notePostMod is called. These will 1) detect an unsequenced modification 12757 // as side effect (as in "k++ + k") and 2) add a new usage with the 12758 // appropriate usage kind. 12759 // 12760 // We also have to be careful that some operation sequences modification as 12761 // side effect as well (for example: || or ,). To account for this we wrap 12762 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12763 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12764 // which record usages which are modifications as side effect, and then 12765 // downgrade them (or more accurately restore the previous usage which was a 12766 // modification as side effect) when exiting the scope of the sequenced 12767 // subexpression. 12768 12769 void notePreUse(Object O, const Expr *UseExpr) { 12770 UsageInfo &UI = UsageMap[O]; 12771 // Uses conflict with other modifications. 12772 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12773 } 12774 12775 void notePostUse(Object O, const Expr *UseExpr) { 12776 UsageInfo &UI = UsageMap[O]; 12777 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12778 /*IsModMod=*/false); 12779 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12780 } 12781 12782 void notePreMod(Object O, const Expr *ModExpr) { 12783 UsageInfo &UI = UsageMap[O]; 12784 // Modifications conflict with other modifications and with uses. 12785 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12786 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12787 } 12788 12789 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12790 UsageInfo &UI = UsageMap[O]; 12791 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12792 /*IsModMod=*/true); 12793 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12794 } 12795 12796 public: 12797 SequenceChecker(Sema &S, const Expr *E, 12798 SmallVectorImpl<const Expr *> &WorkList) 12799 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12800 Visit(E); 12801 // Silence a -Wunused-private-field since WorkList is now unused. 12802 // TODO: Evaluate if it can be used, and if not remove it. 12803 (void)this->WorkList; 12804 } 12805 12806 void VisitStmt(const Stmt *S) { 12807 // Skip all statements which aren't expressions for now. 12808 } 12809 12810 void VisitExpr(const Expr *E) { 12811 // By default, just recurse to evaluated subexpressions. 12812 Base::VisitStmt(E); 12813 } 12814 12815 void VisitCastExpr(const CastExpr *E) { 12816 Object O = Object(); 12817 if (E->getCastKind() == CK_LValueToRValue) 12818 O = getObject(E->getSubExpr(), false); 12819 12820 if (O) 12821 notePreUse(O, E); 12822 VisitExpr(E); 12823 if (O) 12824 notePostUse(O, E); 12825 } 12826 12827 void VisitSequencedExpressions(const Expr *SequencedBefore, 12828 const Expr *SequencedAfter) { 12829 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12830 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12831 SequenceTree::Seq OldRegion = Region; 12832 12833 { 12834 SequencedSubexpression SeqBefore(*this); 12835 Region = BeforeRegion; 12836 Visit(SequencedBefore); 12837 } 12838 12839 Region = AfterRegion; 12840 Visit(SequencedAfter); 12841 12842 Region = OldRegion; 12843 12844 Tree.merge(BeforeRegion); 12845 Tree.merge(AfterRegion); 12846 } 12847 12848 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12849 // C++17 [expr.sub]p1: 12850 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12851 // expression E1 is sequenced before the expression E2. 12852 if (SemaRef.getLangOpts().CPlusPlus17) 12853 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12854 else { 12855 Visit(ASE->getLHS()); 12856 Visit(ASE->getRHS()); 12857 } 12858 } 12859 12860 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12861 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12862 void VisitBinPtrMem(const BinaryOperator *BO) { 12863 // C++17 [expr.mptr.oper]p4: 12864 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12865 // the expression E1 is sequenced before the expression E2. 12866 if (SemaRef.getLangOpts().CPlusPlus17) 12867 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12868 else { 12869 Visit(BO->getLHS()); 12870 Visit(BO->getRHS()); 12871 } 12872 } 12873 12874 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12875 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12876 void VisitBinShlShr(const BinaryOperator *BO) { 12877 // C++17 [expr.shift]p4: 12878 // The expression E1 is sequenced before the expression E2. 12879 if (SemaRef.getLangOpts().CPlusPlus17) 12880 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12881 else { 12882 Visit(BO->getLHS()); 12883 Visit(BO->getRHS()); 12884 } 12885 } 12886 12887 void VisitBinComma(const BinaryOperator *BO) { 12888 // C++11 [expr.comma]p1: 12889 // Every value computation and side effect associated with the left 12890 // expression is sequenced before every value computation and side 12891 // effect associated with the right expression. 12892 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12893 } 12894 12895 void VisitBinAssign(const BinaryOperator *BO) { 12896 SequenceTree::Seq RHSRegion; 12897 SequenceTree::Seq LHSRegion; 12898 if (SemaRef.getLangOpts().CPlusPlus17) { 12899 RHSRegion = Tree.allocate(Region); 12900 LHSRegion = Tree.allocate(Region); 12901 } else { 12902 RHSRegion = Region; 12903 LHSRegion = Region; 12904 } 12905 SequenceTree::Seq OldRegion = Region; 12906 12907 // C++11 [expr.ass]p1: 12908 // [...] the assignment is sequenced after the value computation 12909 // of the right and left operands, [...] 12910 // 12911 // so check it before inspecting the operands and update the 12912 // map afterwards. 12913 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12914 if (O) 12915 notePreMod(O, BO); 12916 12917 if (SemaRef.getLangOpts().CPlusPlus17) { 12918 // C++17 [expr.ass]p1: 12919 // [...] The right operand is sequenced before the left operand. [...] 12920 { 12921 SequencedSubexpression SeqBefore(*this); 12922 Region = RHSRegion; 12923 Visit(BO->getRHS()); 12924 } 12925 12926 Region = LHSRegion; 12927 Visit(BO->getLHS()); 12928 12929 if (O && isa<CompoundAssignOperator>(BO)) 12930 notePostUse(O, BO); 12931 12932 } else { 12933 // C++11 does not specify any sequencing between the LHS and RHS. 12934 Region = LHSRegion; 12935 Visit(BO->getLHS()); 12936 12937 if (O && isa<CompoundAssignOperator>(BO)) 12938 notePostUse(O, BO); 12939 12940 Region = RHSRegion; 12941 Visit(BO->getRHS()); 12942 } 12943 12944 // C++11 [expr.ass]p1: 12945 // the assignment is sequenced [...] before the value computation of the 12946 // assignment expression. 12947 // C11 6.5.16/3 has no such rule. 12948 Region = OldRegion; 12949 if (O) 12950 notePostMod(O, BO, 12951 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12952 : UK_ModAsSideEffect); 12953 if (SemaRef.getLangOpts().CPlusPlus17) { 12954 Tree.merge(RHSRegion); 12955 Tree.merge(LHSRegion); 12956 } 12957 } 12958 12959 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12960 VisitBinAssign(CAO); 12961 } 12962 12963 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12964 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12965 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12966 Object O = getObject(UO->getSubExpr(), true); 12967 if (!O) 12968 return VisitExpr(UO); 12969 12970 notePreMod(O, UO); 12971 Visit(UO->getSubExpr()); 12972 // C++11 [expr.pre.incr]p1: 12973 // the expression ++x is equivalent to x+=1 12974 notePostMod(O, UO, 12975 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12976 : UK_ModAsSideEffect); 12977 } 12978 12979 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12980 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12981 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12982 Object O = getObject(UO->getSubExpr(), true); 12983 if (!O) 12984 return VisitExpr(UO); 12985 12986 notePreMod(O, UO); 12987 Visit(UO->getSubExpr()); 12988 notePostMod(O, UO, UK_ModAsSideEffect); 12989 } 12990 12991 void VisitBinLOr(const BinaryOperator *BO) { 12992 // C++11 [expr.log.or]p2: 12993 // If the second expression is evaluated, every value computation and 12994 // side effect associated with the first expression is sequenced before 12995 // every value computation and side effect associated with the 12996 // second expression. 12997 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12998 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12999 SequenceTree::Seq OldRegion = Region; 13000 13001 EvaluationTracker Eval(*this); 13002 { 13003 SequencedSubexpression Sequenced(*this); 13004 Region = LHSRegion; 13005 Visit(BO->getLHS()); 13006 } 13007 13008 // C++11 [expr.log.or]p1: 13009 // [...] the second operand is not evaluated if the first operand 13010 // evaluates to true. 13011 bool EvalResult = false; 13012 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13013 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13014 if (ShouldVisitRHS) { 13015 Region = RHSRegion; 13016 Visit(BO->getRHS()); 13017 } 13018 13019 Region = OldRegion; 13020 Tree.merge(LHSRegion); 13021 Tree.merge(RHSRegion); 13022 } 13023 13024 void VisitBinLAnd(const BinaryOperator *BO) { 13025 // C++11 [expr.log.and]p2: 13026 // If the second expression is evaluated, every value computation and 13027 // side effect associated with the first expression is sequenced before 13028 // every value computation and side effect associated with the 13029 // second expression. 13030 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13031 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13032 SequenceTree::Seq OldRegion = Region; 13033 13034 EvaluationTracker Eval(*this); 13035 { 13036 SequencedSubexpression Sequenced(*this); 13037 Region = LHSRegion; 13038 Visit(BO->getLHS()); 13039 } 13040 13041 // C++11 [expr.log.and]p1: 13042 // [...] the second operand is not evaluated if the first operand is false. 13043 bool EvalResult = false; 13044 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13045 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13046 if (ShouldVisitRHS) { 13047 Region = RHSRegion; 13048 Visit(BO->getRHS()); 13049 } 13050 13051 Region = OldRegion; 13052 Tree.merge(LHSRegion); 13053 Tree.merge(RHSRegion); 13054 } 13055 13056 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13057 // C++11 [expr.cond]p1: 13058 // [...] Every value computation and side effect associated with the first 13059 // expression is sequenced before every value computation and side effect 13060 // associated with the second or third expression. 13061 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13062 13063 // No sequencing is specified between the true and false expression. 13064 // However since exactly one of both is going to be evaluated we can 13065 // consider them to be sequenced. This is needed to avoid warning on 13066 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13067 // both the true and false expressions because we can't evaluate x. 13068 // This will still allow us to detect an expression like (pre C++17) 13069 // "(x ? y += 1 : y += 2) = y". 13070 // 13071 // We don't wrap the visitation of the true and false expression with 13072 // SequencedSubexpression because we don't want to downgrade modifications 13073 // as side effect in the true and false expressions after the visition 13074 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13075 // not warn between the two "y++", but we should warn between the "y++" 13076 // and the "y". 13077 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13078 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13079 SequenceTree::Seq OldRegion = Region; 13080 13081 EvaluationTracker Eval(*this); 13082 { 13083 SequencedSubexpression Sequenced(*this); 13084 Region = ConditionRegion; 13085 Visit(CO->getCond()); 13086 } 13087 13088 // C++11 [expr.cond]p1: 13089 // [...] The first expression is contextually converted to bool (Clause 4). 13090 // It is evaluated and if it is true, the result of the conditional 13091 // expression is the value of the second expression, otherwise that of the 13092 // third expression. Only one of the second and third expressions is 13093 // evaluated. [...] 13094 bool EvalResult = false; 13095 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13096 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13097 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13098 if (ShouldVisitTrueExpr) { 13099 Region = TrueRegion; 13100 Visit(CO->getTrueExpr()); 13101 } 13102 if (ShouldVisitFalseExpr) { 13103 Region = FalseRegion; 13104 Visit(CO->getFalseExpr()); 13105 } 13106 13107 Region = OldRegion; 13108 Tree.merge(ConditionRegion); 13109 Tree.merge(TrueRegion); 13110 Tree.merge(FalseRegion); 13111 } 13112 13113 void VisitCallExpr(const CallExpr *CE) { 13114 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13115 13116 if (CE->isUnevaluatedBuiltinCall(Context)) 13117 return; 13118 13119 // C++11 [intro.execution]p15: 13120 // When calling a function [...], every value computation and side effect 13121 // associated with any argument expression, or with the postfix expression 13122 // designating the called function, is sequenced before execution of every 13123 // expression or statement in the body of the function [and thus before 13124 // the value computation of its result]. 13125 SequencedSubexpression Sequenced(*this); 13126 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13127 // C++17 [expr.call]p5 13128 // The postfix-expression is sequenced before each expression in the 13129 // expression-list and any default argument. [...] 13130 SequenceTree::Seq CalleeRegion; 13131 SequenceTree::Seq OtherRegion; 13132 if (SemaRef.getLangOpts().CPlusPlus17) { 13133 CalleeRegion = Tree.allocate(Region); 13134 OtherRegion = Tree.allocate(Region); 13135 } else { 13136 CalleeRegion = Region; 13137 OtherRegion = Region; 13138 } 13139 SequenceTree::Seq OldRegion = Region; 13140 13141 // Visit the callee expression first. 13142 Region = CalleeRegion; 13143 if (SemaRef.getLangOpts().CPlusPlus17) { 13144 SequencedSubexpression Sequenced(*this); 13145 Visit(CE->getCallee()); 13146 } else { 13147 Visit(CE->getCallee()); 13148 } 13149 13150 // Then visit the argument expressions. 13151 Region = OtherRegion; 13152 for (const Expr *Argument : CE->arguments()) 13153 Visit(Argument); 13154 13155 Region = OldRegion; 13156 if (SemaRef.getLangOpts().CPlusPlus17) { 13157 Tree.merge(CalleeRegion); 13158 Tree.merge(OtherRegion); 13159 } 13160 }); 13161 } 13162 13163 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13164 // C++17 [over.match.oper]p2: 13165 // [...] the operator notation is first transformed to the equivalent 13166 // function-call notation as summarized in Table 12 (where @ denotes one 13167 // of the operators covered in the specified subclause). However, the 13168 // operands are sequenced in the order prescribed for the built-in 13169 // operator (Clause 8). 13170 // 13171 // From the above only overloaded binary operators and overloaded call 13172 // operators have sequencing rules in C++17 that we need to handle 13173 // separately. 13174 if (!SemaRef.getLangOpts().CPlusPlus17 || 13175 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13176 return VisitCallExpr(CXXOCE); 13177 13178 enum { 13179 NoSequencing, 13180 LHSBeforeRHS, 13181 RHSBeforeLHS, 13182 LHSBeforeRest 13183 } SequencingKind; 13184 switch (CXXOCE->getOperator()) { 13185 case OO_Equal: 13186 case OO_PlusEqual: 13187 case OO_MinusEqual: 13188 case OO_StarEqual: 13189 case OO_SlashEqual: 13190 case OO_PercentEqual: 13191 case OO_CaretEqual: 13192 case OO_AmpEqual: 13193 case OO_PipeEqual: 13194 case OO_LessLessEqual: 13195 case OO_GreaterGreaterEqual: 13196 SequencingKind = RHSBeforeLHS; 13197 break; 13198 13199 case OO_LessLess: 13200 case OO_GreaterGreater: 13201 case OO_AmpAmp: 13202 case OO_PipePipe: 13203 case OO_Comma: 13204 case OO_ArrowStar: 13205 case OO_Subscript: 13206 SequencingKind = LHSBeforeRHS; 13207 break; 13208 13209 case OO_Call: 13210 SequencingKind = LHSBeforeRest; 13211 break; 13212 13213 default: 13214 SequencingKind = NoSequencing; 13215 break; 13216 } 13217 13218 if (SequencingKind == NoSequencing) 13219 return VisitCallExpr(CXXOCE); 13220 13221 // This is a call, so all subexpressions are sequenced before the result. 13222 SequencedSubexpression Sequenced(*this); 13223 13224 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13225 assert(SemaRef.getLangOpts().CPlusPlus17 && 13226 "Should only get there with C++17 and above!"); 13227 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13228 "Should only get there with an overloaded binary operator" 13229 " or an overloaded call operator!"); 13230 13231 if (SequencingKind == LHSBeforeRest) { 13232 assert(CXXOCE->getOperator() == OO_Call && 13233 "We should only have an overloaded call operator here!"); 13234 13235 // This is very similar to VisitCallExpr, except that we only have the 13236 // C++17 case. The postfix-expression is the first argument of the 13237 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13238 // are in the following arguments. 13239 // 13240 // Note that we intentionally do not visit the callee expression since 13241 // it is just a decayed reference to a function. 13242 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13243 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13244 SequenceTree::Seq OldRegion = Region; 13245 13246 assert(CXXOCE->getNumArgs() >= 1 && 13247 "An overloaded call operator must have at least one argument" 13248 " for the postfix-expression!"); 13249 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13250 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13251 CXXOCE->getNumArgs() - 1); 13252 13253 // Visit the postfix-expression first. 13254 { 13255 Region = PostfixExprRegion; 13256 SequencedSubexpression Sequenced(*this); 13257 Visit(PostfixExpr); 13258 } 13259 13260 // Then visit the argument expressions. 13261 Region = ArgsRegion; 13262 for (const Expr *Arg : Args) 13263 Visit(Arg); 13264 13265 Region = OldRegion; 13266 Tree.merge(PostfixExprRegion); 13267 Tree.merge(ArgsRegion); 13268 } else { 13269 assert(CXXOCE->getNumArgs() == 2 && 13270 "Should only have two arguments here!"); 13271 assert((SequencingKind == LHSBeforeRHS || 13272 SequencingKind == RHSBeforeLHS) && 13273 "Unexpected sequencing kind!"); 13274 13275 // We do not visit the callee expression since it is just a decayed 13276 // reference to a function. 13277 const Expr *E1 = CXXOCE->getArg(0); 13278 const Expr *E2 = CXXOCE->getArg(1); 13279 if (SequencingKind == RHSBeforeLHS) 13280 std::swap(E1, E2); 13281 13282 return VisitSequencedExpressions(E1, E2); 13283 } 13284 }); 13285 } 13286 13287 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13288 // This is a call, so all subexpressions are sequenced before the result. 13289 SequencedSubexpression Sequenced(*this); 13290 13291 if (!CCE->isListInitialization()) 13292 return VisitExpr(CCE); 13293 13294 // In C++11, list initializations are sequenced. 13295 SmallVector<SequenceTree::Seq, 32> Elts; 13296 SequenceTree::Seq Parent = Region; 13297 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13298 E = CCE->arg_end(); 13299 I != E; ++I) { 13300 Region = Tree.allocate(Parent); 13301 Elts.push_back(Region); 13302 Visit(*I); 13303 } 13304 13305 // Forget that the initializers are sequenced. 13306 Region = Parent; 13307 for (unsigned I = 0; I < Elts.size(); ++I) 13308 Tree.merge(Elts[I]); 13309 } 13310 13311 void VisitInitListExpr(const InitListExpr *ILE) { 13312 if (!SemaRef.getLangOpts().CPlusPlus11) 13313 return VisitExpr(ILE); 13314 13315 // In C++11, list initializations are sequenced. 13316 SmallVector<SequenceTree::Seq, 32> Elts; 13317 SequenceTree::Seq Parent = Region; 13318 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13319 const Expr *E = ILE->getInit(I); 13320 if (!E) 13321 continue; 13322 Region = Tree.allocate(Parent); 13323 Elts.push_back(Region); 13324 Visit(E); 13325 } 13326 13327 // Forget that the initializers are sequenced. 13328 Region = Parent; 13329 for (unsigned I = 0; I < Elts.size(); ++I) 13330 Tree.merge(Elts[I]); 13331 } 13332 }; 13333 13334 } // namespace 13335 13336 void Sema::CheckUnsequencedOperations(const Expr *E) { 13337 SmallVector<const Expr *, 8> WorkList; 13338 WorkList.push_back(E); 13339 while (!WorkList.empty()) { 13340 const Expr *Item = WorkList.pop_back_val(); 13341 SequenceChecker(*this, Item, WorkList); 13342 } 13343 } 13344 13345 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13346 bool IsConstexpr) { 13347 llvm::SaveAndRestore<bool> ConstantContext( 13348 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13349 CheckImplicitConversions(E, CheckLoc); 13350 if (!E->isInstantiationDependent()) 13351 CheckUnsequencedOperations(E); 13352 if (!IsConstexpr && !E->isValueDependent()) 13353 CheckForIntOverflow(E); 13354 DiagnoseMisalignedMembers(); 13355 } 13356 13357 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13358 FieldDecl *BitField, 13359 Expr *Init) { 13360 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13361 } 13362 13363 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13364 SourceLocation Loc) { 13365 if (!PType->isVariablyModifiedType()) 13366 return; 13367 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13368 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13369 return; 13370 } 13371 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13372 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13373 return; 13374 } 13375 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13376 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13377 return; 13378 } 13379 13380 const ArrayType *AT = S.Context.getAsArrayType(PType); 13381 if (!AT) 13382 return; 13383 13384 if (AT->getSizeModifier() != ArrayType::Star) { 13385 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13386 return; 13387 } 13388 13389 S.Diag(Loc, diag::err_array_star_in_function_definition); 13390 } 13391 13392 /// CheckParmsForFunctionDef - Check that the parameters of the given 13393 /// function are appropriate for the definition of a function. This 13394 /// takes care of any checks that cannot be performed on the 13395 /// declaration itself, e.g., that the types of each of the function 13396 /// parameters are complete. 13397 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13398 bool CheckParameterNames) { 13399 bool HasInvalidParm = false; 13400 for (ParmVarDecl *Param : Parameters) { 13401 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13402 // function declarator that is part of a function definition of 13403 // that function shall not have incomplete type. 13404 // 13405 // This is also C++ [dcl.fct]p6. 13406 if (!Param->isInvalidDecl() && 13407 RequireCompleteType(Param->getLocation(), Param->getType(), 13408 diag::err_typecheck_decl_incomplete_type)) { 13409 Param->setInvalidDecl(); 13410 HasInvalidParm = true; 13411 } 13412 13413 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13414 // declaration of each parameter shall include an identifier. 13415 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13416 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13417 // Diagnose this as an extension in C17 and earlier. 13418 if (!getLangOpts().C2x) 13419 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13420 } 13421 13422 // C99 6.7.5.3p12: 13423 // If the function declarator is not part of a definition of that 13424 // function, parameters may have incomplete type and may use the [*] 13425 // notation in their sequences of declarator specifiers to specify 13426 // variable length array types. 13427 QualType PType = Param->getOriginalType(); 13428 // FIXME: This diagnostic should point the '[*]' if source-location 13429 // information is added for it. 13430 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13431 13432 // If the parameter is a c++ class type and it has to be destructed in the 13433 // callee function, declare the destructor so that it can be called by the 13434 // callee function. Do not perform any direct access check on the dtor here. 13435 if (!Param->isInvalidDecl()) { 13436 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13437 if (!ClassDecl->isInvalidDecl() && 13438 !ClassDecl->hasIrrelevantDestructor() && 13439 !ClassDecl->isDependentContext() && 13440 ClassDecl->isParamDestroyedInCallee()) { 13441 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13442 MarkFunctionReferenced(Param->getLocation(), Destructor); 13443 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13444 } 13445 } 13446 } 13447 13448 // Parameters with the pass_object_size attribute only need to be marked 13449 // constant at function definitions. Because we lack information about 13450 // whether we're on a declaration or definition when we're instantiating the 13451 // attribute, we need to check for constness here. 13452 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13453 if (!Param->getType().isConstQualified()) 13454 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13455 << Attr->getSpelling() << 1; 13456 13457 // Check for parameter names shadowing fields from the class. 13458 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13459 // The owning context for the parameter should be the function, but we 13460 // want to see if this function's declaration context is a record. 13461 DeclContext *DC = Param->getDeclContext(); 13462 if (DC && DC->isFunctionOrMethod()) { 13463 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13464 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13465 RD, /*DeclIsField*/ false); 13466 } 13467 } 13468 } 13469 13470 return HasInvalidParm; 13471 } 13472 13473 Optional<std::pair<CharUnits, CharUnits>> 13474 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13475 13476 /// Compute the alignment and offset of the base class object given the 13477 /// derived-to-base cast expression and the alignment and offset of the derived 13478 /// class object. 13479 static std::pair<CharUnits, CharUnits> 13480 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13481 CharUnits BaseAlignment, CharUnits Offset, 13482 ASTContext &Ctx) { 13483 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13484 ++PathI) { 13485 const CXXBaseSpecifier *Base = *PathI; 13486 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13487 if (Base->isVirtual()) { 13488 // The complete object may have a lower alignment than the non-virtual 13489 // alignment of the base, in which case the base may be misaligned. Choose 13490 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13491 // conservative lower bound of the complete object alignment. 13492 CharUnits NonVirtualAlignment = 13493 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13494 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13495 Offset = CharUnits::Zero(); 13496 } else { 13497 const ASTRecordLayout &RL = 13498 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13499 Offset += RL.getBaseClassOffset(BaseDecl); 13500 } 13501 DerivedType = Base->getType(); 13502 } 13503 13504 return std::make_pair(BaseAlignment, Offset); 13505 } 13506 13507 /// Compute the alignment and offset of a binary additive operator. 13508 static Optional<std::pair<CharUnits, CharUnits>> 13509 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13510 bool IsSub, ASTContext &Ctx) { 13511 QualType PointeeType = PtrE->getType()->getPointeeType(); 13512 13513 if (!PointeeType->isConstantSizeType()) 13514 return llvm::None; 13515 13516 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13517 13518 if (!P) 13519 return llvm::None; 13520 13521 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13522 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13523 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13524 if (IsSub) 13525 Offset = -Offset; 13526 return std::make_pair(P->first, P->second + Offset); 13527 } 13528 13529 // If the integer expression isn't a constant expression, compute the lower 13530 // bound of the alignment using the alignment and offset of the pointer 13531 // expression and the element size. 13532 return std::make_pair( 13533 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13534 CharUnits::Zero()); 13535 } 13536 13537 /// This helper function takes an lvalue expression and returns the alignment of 13538 /// a VarDecl and a constant offset from the VarDecl. 13539 Optional<std::pair<CharUnits, CharUnits>> 13540 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13541 E = E->IgnoreParens(); 13542 switch (E->getStmtClass()) { 13543 default: 13544 break; 13545 case Stmt::CStyleCastExprClass: 13546 case Stmt::CXXStaticCastExprClass: 13547 case Stmt::ImplicitCastExprClass: { 13548 auto *CE = cast<CastExpr>(E); 13549 const Expr *From = CE->getSubExpr(); 13550 switch (CE->getCastKind()) { 13551 default: 13552 break; 13553 case CK_NoOp: 13554 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13555 case CK_UncheckedDerivedToBase: 13556 case CK_DerivedToBase: { 13557 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13558 if (!P) 13559 break; 13560 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13561 P->second, Ctx); 13562 } 13563 } 13564 break; 13565 } 13566 case Stmt::ArraySubscriptExprClass: { 13567 auto *ASE = cast<ArraySubscriptExpr>(E); 13568 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13569 false, Ctx); 13570 } 13571 case Stmt::DeclRefExprClass: { 13572 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13573 // FIXME: If VD is captured by copy or is an escaping __block variable, 13574 // use the alignment of VD's type. 13575 if (!VD->getType()->isReferenceType()) 13576 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13577 if (VD->hasInit()) 13578 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13579 } 13580 break; 13581 } 13582 case Stmt::MemberExprClass: { 13583 auto *ME = cast<MemberExpr>(E); 13584 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13585 if (!FD || FD->getType()->isReferenceType()) 13586 break; 13587 Optional<std::pair<CharUnits, CharUnits>> P; 13588 if (ME->isArrow()) 13589 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 13590 else 13591 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13592 if (!P) 13593 break; 13594 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13595 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13596 return std::make_pair(P->first, 13597 P->second + CharUnits::fromQuantity(Offset)); 13598 } 13599 case Stmt::UnaryOperatorClass: { 13600 auto *UO = cast<UnaryOperator>(E); 13601 switch (UO->getOpcode()) { 13602 default: 13603 break; 13604 case UO_Deref: 13605 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13606 } 13607 break; 13608 } 13609 case Stmt::BinaryOperatorClass: { 13610 auto *BO = cast<BinaryOperator>(E); 13611 auto Opcode = BO->getOpcode(); 13612 switch (Opcode) { 13613 default: 13614 break; 13615 case BO_Comma: 13616 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13617 } 13618 break; 13619 } 13620 } 13621 return llvm::None; 13622 } 13623 13624 /// This helper function takes a pointer expression and returns the alignment of 13625 /// a VarDecl and a constant offset from the VarDecl. 13626 Optional<std::pair<CharUnits, CharUnits>> 13627 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13628 E = E->IgnoreParens(); 13629 switch (E->getStmtClass()) { 13630 default: 13631 break; 13632 case Stmt::CStyleCastExprClass: 13633 case Stmt::CXXStaticCastExprClass: 13634 case Stmt::ImplicitCastExprClass: { 13635 auto *CE = cast<CastExpr>(E); 13636 const Expr *From = CE->getSubExpr(); 13637 switch (CE->getCastKind()) { 13638 default: 13639 break; 13640 case CK_NoOp: 13641 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13642 case CK_ArrayToPointerDecay: 13643 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13644 case CK_UncheckedDerivedToBase: 13645 case CK_DerivedToBase: { 13646 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13647 if (!P) 13648 break; 13649 return getDerivedToBaseAlignmentAndOffset( 13650 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13651 } 13652 } 13653 break; 13654 } 13655 case Stmt::CXXThisExprClass: { 13656 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 13657 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 13658 return std::make_pair(Alignment, CharUnits::Zero()); 13659 } 13660 case Stmt::UnaryOperatorClass: { 13661 auto *UO = cast<UnaryOperator>(E); 13662 if (UO->getOpcode() == UO_AddrOf) 13663 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13664 break; 13665 } 13666 case Stmt::BinaryOperatorClass: { 13667 auto *BO = cast<BinaryOperator>(E); 13668 auto Opcode = BO->getOpcode(); 13669 switch (Opcode) { 13670 default: 13671 break; 13672 case BO_Add: 13673 case BO_Sub: { 13674 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13675 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13676 std::swap(LHS, RHS); 13677 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13678 Ctx); 13679 } 13680 case BO_Comma: 13681 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13682 } 13683 break; 13684 } 13685 } 13686 return llvm::None; 13687 } 13688 13689 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13690 // See if we can compute the alignment of a VarDecl and an offset from it. 13691 Optional<std::pair<CharUnits, CharUnits>> P = 13692 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13693 13694 if (P) 13695 return P->first.alignmentAtOffset(P->second); 13696 13697 // If that failed, return the type's alignment. 13698 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13699 } 13700 13701 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13702 /// pointer cast increases the alignment requirements. 13703 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13704 // This is actually a lot of work to potentially be doing on every 13705 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13706 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13707 return; 13708 13709 // Ignore dependent types. 13710 if (T->isDependentType() || Op->getType()->isDependentType()) 13711 return; 13712 13713 // Require that the destination be a pointer type. 13714 const PointerType *DestPtr = T->getAs<PointerType>(); 13715 if (!DestPtr) return; 13716 13717 // If the destination has alignment 1, we're done. 13718 QualType DestPointee = DestPtr->getPointeeType(); 13719 if (DestPointee->isIncompleteType()) return; 13720 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13721 if (DestAlign.isOne()) return; 13722 13723 // Require that the source be a pointer type. 13724 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13725 if (!SrcPtr) return; 13726 QualType SrcPointee = SrcPtr->getPointeeType(); 13727 13728 // Explicitly allow casts from cv void*. We already implicitly 13729 // allowed casts to cv void*, since they have alignment 1. 13730 // Also allow casts involving incomplete types, which implicitly 13731 // includes 'void'. 13732 if (SrcPointee->isIncompleteType()) return; 13733 13734 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13735 13736 if (SrcAlign >= DestAlign) return; 13737 13738 Diag(TRange.getBegin(), diag::warn_cast_align) 13739 << Op->getType() << T 13740 << static_cast<unsigned>(SrcAlign.getQuantity()) 13741 << static_cast<unsigned>(DestAlign.getQuantity()) 13742 << TRange << Op->getSourceRange(); 13743 } 13744 13745 /// Check whether this array fits the idiom of a size-one tail padded 13746 /// array member of a struct. 13747 /// 13748 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13749 /// commonly used to emulate flexible arrays in C89 code. 13750 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13751 const NamedDecl *ND) { 13752 if (Size != 1 || !ND) return false; 13753 13754 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13755 if (!FD) return false; 13756 13757 // Don't consider sizes resulting from macro expansions or template argument 13758 // substitution to form C89 tail-padded arrays. 13759 13760 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13761 while (TInfo) { 13762 TypeLoc TL = TInfo->getTypeLoc(); 13763 // Look through typedefs. 13764 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13765 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13766 TInfo = TDL->getTypeSourceInfo(); 13767 continue; 13768 } 13769 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13770 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13771 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13772 return false; 13773 } 13774 break; 13775 } 13776 13777 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13778 if (!RD) return false; 13779 if (RD->isUnion()) return false; 13780 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13781 if (!CRD->isStandardLayout()) return false; 13782 } 13783 13784 // See if this is the last field decl in the record. 13785 const Decl *D = FD; 13786 while ((D = D->getNextDeclInContext())) 13787 if (isa<FieldDecl>(D)) 13788 return false; 13789 return true; 13790 } 13791 13792 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13793 const ArraySubscriptExpr *ASE, 13794 bool AllowOnePastEnd, bool IndexNegated) { 13795 // Already diagnosed by the constant evaluator. 13796 if (isConstantEvaluated()) 13797 return; 13798 13799 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13800 if (IndexExpr->isValueDependent()) 13801 return; 13802 13803 const Type *EffectiveType = 13804 BaseExpr->getType()->getPointeeOrArrayElementType(); 13805 BaseExpr = BaseExpr->IgnoreParenCasts(); 13806 const ConstantArrayType *ArrayTy = 13807 Context.getAsConstantArrayType(BaseExpr->getType()); 13808 13809 if (!ArrayTy) 13810 return; 13811 13812 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13813 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13814 return; 13815 13816 Expr::EvalResult Result; 13817 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13818 return; 13819 13820 llvm::APSInt index = Result.Val.getInt(); 13821 if (IndexNegated) 13822 index = -index; 13823 13824 const NamedDecl *ND = nullptr; 13825 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13826 ND = DRE->getDecl(); 13827 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13828 ND = ME->getMemberDecl(); 13829 13830 if (index.isUnsigned() || !index.isNegative()) { 13831 // It is possible that the type of the base expression after 13832 // IgnoreParenCasts is incomplete, even though the type of the base 13833 // expression before IgnoreParenCasts is complete (see PR39746 for an 13834 // example). In this case we have no information about whether the array 13835 // access exceeds the array bounds. However we can still diagnose an array 13836 // access which precedes the array bounds. 13837 if (BaseType->isIncompleteType()) 13838 return; 13839 13840 llvm::APInt size = ArrayTy->getSize(); 13841 if (!size.isStrictlyPositive()) 13842 return; 13843 13844 if (BaseType != EffectiveType) { 13845 // Make sure we're comparing apples to apples when comparing index to size 13846 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13847 uint64_t array_typesize = Context.getTypeSize(BaseType); 13848 // Handle ptrarith_typesize being zero, such as when casting to void* 13849 if (!ptrarith_typesize) ptrarith_typesize = 1; 13850 if (ptrarith_typesize != array_typesize) { 13851 // There's a cast to a different size type involved 13852 uint64_t ratio = array_typesize / ptrarith_typesize; 13853 // TODO: Be smarter about handling cases where array_typesize is not a 13854 // multiple of ptrarith_typesize 13855 if (ptrarith_typesize * ratio == array_typesize) 13856 size *= llvm::APInt(size.getBitWidth(), ratio); 13857 } 13858 } 13859 13860 if (size.getBitWidth() > index.getBitWidth()) 13861 index = index.zext(size.getBitWidth()); 13862 else if (size.getBitWidth() < index.getBitWidth()) 13863 size = size.zext(index.getBitWidth()); 13864 13865 // For array subscripting the index must be less than size, but for pointer 13866 // arithmetic also allow the index (offset) to be equal to size since 13867 // computing the next address after the end of the array is legal and 13868 // commonly done e.g. in C++ iterators and range-based for loops. 13869 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13870 return; 13871 13872 // Also don't warn for arrays of size 1 which are members of some 13873 // structure. These are often used to approximate flexible arrays in C89 13874 // code. 13875 if (IsTailPaddedMemberArray(*this, size, ND)) 13876 return; 13877 13878 // Suppress the warning if the subscript expression (as identified by the 13879 // ']' location) and the index expression are both from macro expansions 13880 // within a system header. 13881 if (ASE) { 13882 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13883 ASE->getRBracketLoc()); 13884 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13885 SourceLocation IndexLoc = 13886 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13887 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13888 return; 13889 } 13890 } 13891 13892 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13893 if (ASE) 13894 DiagID = diag::warn_array_index_exceeds_bounds; 13895 13896 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13897 PDiag(DiagID) << index.toString(10, true) 13898 << size.toString(10, true) 13899 << (unsigned)size.getLimitedValue(~0U) 13900 << IndexExpr->getSourceRange()); 13901 } else { 13902 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13903 if (!ASE) { 13904 DiagID = diag::warn_ptr_arith_precedes_bounds; 13905 if (index.isNegative()) index = -index; 13906 } 13907 13908 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13909 PDiag(DiagID) << index.toString(10, true) 13910 << IndexExpr->getSourceRange()); 13911 } 13912 13913 if (!ND) { 13914 // Try harder to find a NamedDecl to point at in the note. 13915 while (const ArraySubscriptExpr *ASE = 13916 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13917 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13918 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13919 ND = DRE->getDecl(); 13920 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13921 ND = ME->getMemberDecl(); 13922 } 13923 13924 if (ND) 13925 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13926 PDiag(diag::note_array_declared_here) << ND); 13927 } 13928 13929 void Sema::CheckArrayAccess(const Expr *expr) { 13930 int AllowOnePastEnd = 0; 13931 while (expr) { 13932 expr = expr->IgnoreParenImpCasts(); 13933 switch (expr->getStmtClass()) { 13934 case Stmt::ArraySubscriptExprClass: { 13935 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13936 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13937 AllowOnePastEnd > 0); 13938 expr = ASE->getBase(); 13939 break; 13940 } 13941 case Stmt::MemberExprClass: { 13942 expr = cast<MemberExpr>(expr)->getBase(); 13943 break; 13944 } 13945 case Stmt::OMPArraySectionExprClass: { 13946 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13947 if (ASE->getLowerBound()) 13948 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13949 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13950 return; 13951 } 13952 case Stmt::UnaryOperatorClass: { 13953 // Only unwrap the * and & unary operators 13954 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13955 expr = UO->getSubExpr(); 13956 switch (UO->getOpcode()) { 13957 case UO_AddrOf: 13958 AllowOnePastEnd++; 13959 break; 13960 case UO_Deref: 13961 AllowOnePastEnd--; 13962 break; 13963 default: 13964 return; 13965 } 13966 break; 13967 } 13968 case Stmt::ConditionalOperatorClass: { 13969 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13970 if (const Expr *lhs = cond->getLHS()) 13971 CheckArrayAccess(lhs); 13972 if (const Expr *rhs = cond->getRHS()) 13973 CheckArrayAccess(rhs); 13974 return; 13975 } 13976 case Stmt::CXXOperatorCallExprClass: { 13977 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13978 for (const auto *Arg : OCE->arguments()) 13979 CheckArrayAccess(Arg); 13980 return; 13981 } 13982 default: 13983 return; 13984 } 13985 } 13986 } 13987 13988 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13989 13990 namespace { 13991 13992 struct RetainCycleOwner { 13993 VarDecl *Variable = nullptr; 13994 SourceRange Range; 13995 SourceLocation Loc; 13996 bool Indirect = false; 13997 13998 RetainCycleOwner() = default; 13999 14000 void setLocsFrom(Expr *e) { 14001 Loc = e->getExprLoc(); 14002 Range = e->getSourceRange(); 14003 } 14004 }; 14005 14006 } // namespace 14007 14008 /// Consider whether capturing the given variable can possibly lead to 14009 /// a retain cycle. 14010 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14011 // In ARC, it's captured strongly iff the variable has __strong 14012 // lifetime. In MRR, it's captured strongly if the variable is 14013 // __block and has an appropriate type. 14014 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14015 return false; 14016 14017 owner.Variable = var; 14018 if (ref) 14019 owner.setLocsFrom(ref); 14020 return true; 14021 } 14022 14023 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14024 while (true) { 14025 e = e->IgnoreParens(); 14026 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14027 switch (cast->getCastKind()) { 14028 case CK_BitCast: 14029 case CK_LValueBitCast: 14030 case CK_LValueToRValue: 14031 case CK_ARCReclaimReturnedObject: 14032 e = cast->getSubExpr(); 14033 continue; 14034 14035 default: 14036 return false; 14037 } 14038 } 14039 14040 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14041 ObjCIvarDecl *ivar = ref->getDecl(); 14042 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14043 return false; 14044 14045 // Try to find a retain cycle in the base. 14046 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14047 return false; 14048 14049 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14050 owner.Indirect = true; 14051 return true; 14052 } 14053 14054 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14055 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14056 if (!var) return false; 14057 return considerVariable(var, ref, owner); 14058 } 14059 14060 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14061 if (member->isArrow()) return false; 14062 14063 // Don't count this as an indirect ownership. 14064 e = member->getBase(); 14065 continue; 14066 } 14067 14068 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14069 // Only pay attention to pseudo-objects on property references. 14070 ObjCPropertyRefExpr *pre 14071 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14072 ->IgnoreParens()); 14073 if (!pre) return false; 14074 if (pre->isImplicitProperty()) return false; 14075 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14076 if (!property->isRetaining() && 14077 !(property->getPropertyIvarDecl() && 14078 property->getPropertyIvarDecl()->getType() 14079 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14080 return false; 14081 14082 owner.Indirect = true; 14083 if (pre->isSuperReceiver()) { 14084 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14085 if (!owner.Variable) 14086 return false; 14087 owner.Loc = pre->getLocation(); 14088 owner.Range = pre->getSourceRange(); 14089 return true; 14090 } 14091 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14092 ->getSourceExpr()); 14093 continue; 14094 } 14095 14096 // Array ivars? 14097 14098 return false; 14099 } 14100 } 14101 14102 namespace { 14103 14104 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14105 ASTContext &Context; 14106 VarDecl *Variable; 14107 Expr *Capturer = nullptr; 14108 bool VarWillBeReased = false; 14109 14110 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14111 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14112 Context(Context), Variable(variable) {} 14113 14114 void VisitDeclRefExpr(DeclRefExpr *ref) { 14115 if (ref->getDecl() == Variable && !Capturer) 14116 Capturer = ref; 14117 } 14118 14119 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14120 if (Capturer) return; 14121 Visit(ref->getBase()); 14122 if (Capturer && ref->isFreeIvar()) 14123 Capturer = ref; 14124 } 14125 14126 void VisitBlockExpr(BlockExpr *block) { 14127 // Look inside nested blocks 14128 if (block->getBlockDecl()->capturesVariable(Variable)) 14129 Visit(block->getBlockDecl()->getBody()); 14130 } 14131 14132 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14133 if (Capturer) return; 14134 if (OVE->getSourceExpr()) 14135 Visit(OVE->getSourceExpr()); 14136 } 14137 14138 void VisitBinaryOperator(BinaryOperator *BinOp) { 14139 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14140 return; 14141 Expr *LHS = BinOp->getLHS(); 14142 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14143 if (DRE->getDecl() != Variable) 14144 return; 14145 if (Expr *RHS = BinOp->getRHS()) { 14146 RHS = RHS->IgnoreParenCasts(); 14147 Optional<llvm::APSInt> Value; 14148 VarWillBeReased = 14149 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14150 *Value == 0); 14151 } 14152 } 14153 } 14154 }; 14155 14156 } // namespace 14157 14158 /// Check whether the given argument is a block which captures a 14159 /// variable. 14160 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14161 assert(owner.Variable && owner.Loc.isValid()); 14162 14163 e = e->IgnoreParenCasts(); 14164 14165 // Look through [^{...} copy] and Block_copy(^{...}). 14166 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14167 Selector Cmd = ME->getSelector(); 14168 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14169 e = ME->getInstanceReceiver(); 14170 if (!e) 14171 return nullptr; 14172 e = e->IgnoreParenCasts(); 14173 } 14174 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14175 if (CE->getNumArgs() == 1) { 14176 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14177 if (Fn) { 14178 const IdentifierInfo *FnI = Fn->getIdentifier(); 14179 if (FnI && FnI->isStr("_Block_copy")) { 14180 e = CE->getArg(0)->IgnoreParenCasts(); 14181 } 14182 } 14183 } 14184 } 14185 14186 BlockExpr *block = dyn_cast<BlockExpr>(e); 14187 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14188 return nullptr; 14189 14190 FindCaptureVisitor visitor(S.Context, owner.Variable); 14191 visitor.Visit(block->getBlockDecl()->getBody()); 14192 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14193 } 14194 14195 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14196 RetainCycleOwner &owner) { 14197 assert(capturer); 14198 assert(owner.Variable && owner.Loc.isValid()); 14199 14200 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14201 << owner.Variable << capturer->getSourceRange(); 14202 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14203 << owner.Indirect << owner.Range; 14204 } 14205 14206 /// Check for a keyword selector that starts with the word 'add' or 14207 /// 'set'. 14208 static bool isSetterLikeSelector(Selector sel) { 14209 if (sel.isUnarySelector()) return false; 14210 14211 StringRef str = sel.getNameForSlot(0); 14212 while (!str.empty() && str.front() == '_') str = str.substr(1); 14213 if (str.startswith("set")) 14214 str = str.substr(3); 14215 else if (str.startswith("add")) { 14216 // Specially allow 'addOperationWithBlock:'. 14217 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14218 return false; 14219 str = str.substr(3); 14220 } 14221 else 14222 return false; 14223 14224 if (str.empty()) return true; 14225 return !isLowercase(str.front()); 14226 } 14227 14228 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14229 ObjCMessageExpr *Message) { 14230 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14231 Message->getReceiverInterface(), 14232 NSAPI::ClassId_NSMutableArray); 14233 if (!IsMutableArray) { 14234 return None; 14235 } 14236 14237 Selector Sel = Message->getSelector(); 14238 14239 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14240 S.NSAPIObj->getNSArrayMethodKind(Sel); 14241 if (!MKOpt) { 14242 return None; 14243 } 14244 14245 NSAPI::NSArrayMethodKind MK = *MKOpt; 14246 14247 switch (MK) { 14248 case NSAPI::NSMutableArr_addObject: 14249 case NSAPI::NSMutableArr_insertObjectAtIndex: 14250 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14251 return 0; 14252 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14253 return 1; 14254 14255 default: 14256 return None; 14257 } 14258 14259 return None; 14260 } 14261 14262 static 14263 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14264 ObjCMessageExpr *Message) { 14265 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14266 Message->getReceiverInterface(), 14267 NSAPI::ClassId_NSMutableDictionary); 14268 if (!IsMutableDictionary) { 14269 return None; 14270 } 14271 14272 Selector Sel = Message->getSelector(); 14273 14274 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14275 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14276 if (!MKOpt) { 14277 return None; 14278 } 14279 14280 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14281 14282 switch (MK) { 14283 case NSAPI::NSMutableDict_setObjectForKey: 14284 case NSAPI::NSMutableDict_setValueForKey: 14285 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14286 return 0; 14287 14288 default: 14289 return None; 14290 } 14291 14292 return None; 14293 } 14294 14295 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14296 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14297 Message->getReceiverInterface(), 14298 NSAPI::ClassId_NSMutableSet); 14299 14300 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14301 Message->getReceiverInterface(), 14302 NSAPI::ClassId_NSMutableOrderedSet); 14303 if (!IsMutableSet && !IsMutableOrderedSet) { 14304 return None; 14305 } 14306 14307 Selector Sel = Message->getSelector(); 14308 14309 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14310 if (!MKOpt) { 14311 return None; 14312 } 14313 14314 NSAPI::NSSetMethodKind MK = *MKOpt; 14315 14316 switch (MK) { 14317 case NSAPI::NSMutableSet_addObject: 14318 case NSAPI::NSOrderedSet_setObjectAtIndex: 14319 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14320 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14321 return 0; 14322 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14323 return 1; 14324 } 14325 14326 return None; 14327 } 14328 14329 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14330 if (!Message->isInstanceMessage()) { 14331 return; 14332 } 14333 14334 Optional<int> ArgOpt; 14335 14336 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14337 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14338 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14339 return; 14340 } 14341 14342 int ArgIndex = *ArgOpt; 14343 14344 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14345 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14346 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14347 } 14348 14349 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14350 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14351 if (ArgRE->isObjCSelfExpr()) { 14352 Diag(Message->getSourceRange().getBegin(), 14353 diag::warn_objc_circular_container) 14354 << ArgRE->getDecl() << StringRef("'super'"); 14355 } 14356 } 14357 } else { 14358 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14359 14360 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14361 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14362 } 14363 14364 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14365 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14366 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14367 ValueDecl *Decl = ReceiverRE->getDecl(); 14368 Diag(Message->getSourceRange().getBegin(), 14369 diag::warn_objc_circular_container) 14370 << Decl << Decl; 14371 if (!ArgRE->isObjCSelfExpr()) { 14372 Diag(Decl->getLocation(), 14373 diag::note_objc_circular_container_declared_here) 14374 << Decl; 14375 } 14376 } 14377 } 14378 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14379 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14380 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14381 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14382 Diag(Message->getSourceRange().getBegin(), 14383 diag::warn_objc_circular_container) 14384 << Decl << Decl; 14385 Diag(Decl->getLocation(), 14386 diag::note_objc_circular_container_declared_here) 14387 << Decl; 14388 } 14389 } 14390 } 14391 } 14392 } 14393 14394 /// Check a message send to see if it's likely to cause a retain cycle. 14395 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14396 // Only check instance methods whose selector looks like a setter. 14397 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14398 return; 14399 14400 // Try to find a variable that the receiver is strongly owned by. 14401 RetainCycleOwner owner; 14402 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14403 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14404 return; 14405 } else { 14406 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14407 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14408 owner.Loc = msg->getSuperLoc(); 14409 owner.Range = msg->getSuperLoc(); 14410 } 14411 14412 // Check whether the receiver is captured by any of the arguments. 14413 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14414 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14415 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14416 // noescape blocks should not be retained by the method. 14417 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14418 continue; 14419 return diagnoseRetainCycle(*this, capturer, owner); 14420 } 14421 } 14422 } 14423 14424 /// Check a property assign to see if it's likely to cause a retain cycle. 14425 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14426 RetainCycleOwner owner; 14427 if (!findRetainCycleOwner(*this, receiver, owner)) 14428 return; 14429 14430 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14431 diagnoseRetainCycle(*this, capturer, owner); 14432 } 14433 14434 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14435 RetainCycleOwner Owner; 14436 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14437 return; 14438 14439 // Because we don't have an expression for the variable, we have to set the 14440 // location explicitly here. 14441 Owner.Loc = Var->getLocation(); 14442 Owner.Range = Var->getSourceRange(); 14443 14444 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14445 diagnoseRetainCycle(*this, Capturer, Owner); 14446 } 14447 14448 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14449 Expr *RHS, bool isProperty) { 14450 // Check if RHS is an Objective-C object literal, which also can get 14451 // immediately zapped in a weak reference. Note that we explicitly 14452 // allow ObjCStringLiterals, since those are designed to never really die. 14453 RHS = RHS->IgnoreParenImpCasts(); 14454 14455 // This enum needs to match with the 'select' in 14456 // warn_objc_arc_literal_assign (off-by-1). 14457 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14458 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14459 return false; 14460 14461 S.Diag(Loc, diag::warn_arc_literal_assign) 14462 << (unsigned) Kind 14463 << (isProperty ? 0 : 1) 14464 << RHS->getSourceRange(); 14465 14466 return true; 14467 } 14468 14469 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14470 Qualifiers::ObjCLifetime LT, 14471 Expr *RHS, bool isProperty) { 14472 // Strip off any implicit cast added to get to the one ARC-specific. 14473 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14474 if (cast->getCastKind() == CK_ARCConsumeObject) { 14475 S.Diag(Loc, diag::warn_arc_retained_assign) 14476 << (LT == Qualifiers::OCL_ExplicitNone) 14477 << (isProperty ? 0 : 1) 14478 << RHS->getSourceRange(); 14479 return true; 14480 } 14481 RHS = cast->getSubExpr(); 14482 } 14483 14484 if (LT == Qualifiers::OCL_Weak && 14485 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14486 return true; 14487 14488 return false; 14489 } 14490 14491 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14492 QualType LHS, Expr *RHS) { 14493 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14494 14495 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14496 return false; 14497 14498 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14499 return true; 14500 14501 return false; 14502 } 14503 14504 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14505 Expr *LHS, Expr *RHS) { 14506 QualType LHSType; 14507 // PropertyRef on LHS type need be directly obtained from 14508 // its declaration as it has a PseudoType. 14509 ObjCPropertyRefExpr *PRE 14510 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14511 if (PRE && !PRE->isImplicitProperty()) { 14512 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14513 if (PD) 14514 LHSType = PD->getType(); 14515 } 14516 14517 if (LHSType.isNull()) 14518 LHSType = LHS->getType(); 14519 14520 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14521 14522 if (LT == Qualifiers::OCL_Weak) { 14523 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14524 getCurFunction()->markSafeWeakUse(LHS); 14525 } 14526 14527 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14528 return; 14529 14530 // FIXME. Check for other life times. 14531 if (LT != Qualifiers::OCL_None) 14532 return; 14533 14534 if (PRE) { 14535 if (PRE->isImplicitProperty()) 14536 return; 14537 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14538 if (!PD) 14539 return; 14540 14541 unsigned Attributes = PD->getPropertyAttributes(); 14542 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14543 // when 'assign' attribute was not explicitly specified 14544 // by user, ignore it and rely on property type itself 14545 // for lifetime info. 14546 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14547 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14548 LHSType->isObjCRetainableType()) 14549 return; 14550 14551 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14552 if (cast->getCastKind() == CK_ARCConsumeObject) { 14553 Diag(Loc, diag::warn_arc_retained_property_assign) 14554 << RHS->getSourceRange(); 14555 return; 14556 } 14557 RHS = cast->getSubExpr(); 14558 } 14559 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14560 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14561 return; 14562 } 14563 } 14564 } 14565 14566 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14567 14568 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14569 SourceLocation StmtLoc, 14570 const NullStmt *Body) { 14571 // Do not warn if the body is a macro that expands to nothing, e.g: 14572 // 14573 // #define CALL(x) 14574 // if (condition) 14575 // CALL(0); 14576 if (Body->hasLeadingEmptyMacro()) 14577 return false; 14578 14579 // Get line numbers of statement and body. 14580 bool StmtLineInvalid; 14581 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14582 &StmtLineInvalid); 14583 if (StmtLineInvalid) 14584 return false; 14585 14586 bool BodyLineInvalid; 14587 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14588 &BodyLineInvalid); 14589 if (BodyLineInvalid) 14590 return false; 14591 14592 // Warn if null statement and body are on the same line. 14593 if (StmtLine != BodyLine) 14594 return false; 14595 14596 return true; 14597 } 14598 14599 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14600 const Stmt *Body, 14601 unsigned DiagID) { 14602 // Since this is a syntactic check, don't emit diagnostic for template 14603 // instantiations, this just adds noise. 14604 if (CurrentInstantiationScope) 14605 return; 14606 14607 // The body should be a null statement. 14608 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14609 if (!NBody) 14610 return; 14611 14612 // Do the usual checks. 14613 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14614 return; 14615 14616 Diag(NBody->getSemiLoc(), DiagID); 14617 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14618 } 14619 14620 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14621 const Stmt *PossibleBody) { 14622 assert(!CurrentInstantiationScope); // Ensured by caller 14623 14624 SourceLocation StmtLoc; 14625 const Stmt *Body; 14626 unsigned DiagID; 14627 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14628 StmtLoc = FS->getRParenLoc(); 14629 Body = FS->getBody(); 14630 DiagID = diag::warn_empty_for_body; 14631 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14632 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14633 Body = WS->getBody(); 14634 DiagID = diag::warn_empty_while_body; 14635 } else 14636 return; // Neither `for' nor `while'. 14637 14638 // The body should be a null statement. 14639 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14640 if (!NBody) 14641 return; 14642 14643 // Skip expensive checks if diagnostic is disabled. 14644 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14645 return; 14646 14647 // Do the usual checks. 14648 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14649 return; 14650 14651 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14652 // noise level low, emit diagnostics only if for/while is followed by a 14653 // CompoundStmt, e.g.: 14654 // for (int i = 0; i < n; i++); 14655 // { 14656 // a(i); 14657 // } 14658 // or if for/while is followed by a statement with more indentation 14659 // than for/while itself: 14660 // for (int i = 0; i < n; i++); 14661 // a(i); 14662 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14663 if (!ProbableTypo) { 14664 bool BodyColInvalid; 14665 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14666 PossibleBody->getBeginLoc(), &BodyColInvalid); 14667 if (BodyColInvalid) 14668 return; 14669 14670 bool StmtColInvalid; 14671 unsigned StmtCol = 14672 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14673 if (StmtColInvalid) 14674 return; 14675 14676 if (BodyCol > StmtCol) 14677 ProbableTypo = true; 14678 } 14679 14680 if (ProbableTypo) { 14681 Diag(NBody->getSemiLoc(), DiagID); 14682 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14683 } 14684 } 14685 14686 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14687 14688 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14689 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14690 SourceLocation OpLoc) { 14691 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14692 return; 14693 14694 if (inTemplateInstantiation()) 14695 return; 14696 14697 // Strip parens and casts away. 14698 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14699 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14700 14701 // Check for a call expression 14702 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14703 if (!CE || CE->getNumArgs() != 1) 14704 return; 14705 14706 // Check for a call to std::move 14707 if (!CE->isCallToStdMove()) 14708 return; 14709 14710 // Get argument from std::move 14711 RHSExpr = CE->getArg(0); 14712 14713 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14714 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14715 14716 // Two DeclRefExpr's, check that the decls are the same. 14717 if (LHSDeclRef && RHSDeclRef) { 14718 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14719 return; 14720 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14721 RHSDeclRef->getDecl()->getCanonicalDecl()) 14722 return; 14723 14724 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14725 << LHSExpr->getSourceRange() 14726 << RHSExpr->getSourceRange(); 14727 return; 14728 } 14729 14730 // Member variables require a different approach to check for self moves. 14731 // MemberExpr's are the same if every nested MemberExpr refers to the same 14732 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14733 // the base Expr's are CXXThisExpr's. 14734 const Expr *LHSBase = LHSExpr; 14735 const Expr *RHSBase = RHSExpr; 14736 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14737 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14738 if (!LHSME || !RHSME) 14739 return; 14740 14741 while (LHSME && RHSME) { 14742 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14743 RHSME->getMemberDecl()->getCanonicalDecl()) 14744 return; 14745 14746 LHSBase = LHSME->getBase(); 14747 RHSBase = RHSME->getBase(); 14748 LHSME = dyn_cast<MemberExpr>(LHSBase); 14749 RHSME = dyn_cast<MemberExpr>(RHSBase); 14750 } 14751 14752 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14753 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14754 if (LHSDeclRef && RHSDeclRef) { 14755 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14756 return; 14757 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14758 RHSDeclRef->getDecl()->getCanonicalDecl()) 14759 return; 14760 14761 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14762 << LHSExpr->getSourceRange() 14763 << RHSExpr->getSourceRange(); 14764 return; 14765 } 14766 14767 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14768 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14769 << LHSExpr->getSourceRange() 14770 << RHSExpr->getSourceRange(); 14771 } 14772 14773 //===--- Layout compatibility ----------------------------------------------// 14774 14775 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14776 14777 /// Check if two enumeration types are layout-compatible. 14778 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14779 // C++11 [dcl.enum] p8: 14780 // Two enumeration types are layout-compatible if they have the same 14781 // underlying type. 14782 return ED1->isComplete() && ED2->isComplete() && 14783 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14784 } 14785 14786 /// Check if two fields are layout-compatible. 14787 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14788 FieldDecl *Field2) { 14789 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14790 return false; 14791 14792 if (Field1->isBitField() != Field2->isBitField()) 14793 return false; 14794 14795 if (Field1->isBitField()) { 14796 // Make sure that the bit-fields are the same length. 14797 unsigned Bits1 = Field1->getBitWidthValue(C); 14798 unsigned Bits2 = Field2->getBitWidthValue(C); 14799 14800 if (Bits1 != Bits2) 14801 return false; 14802 } 14803 14804 return true; 14805 } 14806 14807 /// Check if two standard-layout structs are layout-compatible. 14808 /// (C++11 [class.mem] p17) 14809 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14810 RecordDecl *RD2) { 14811 // If both records are C++ classes, check that base classes match. 14812 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14813 // If one of records is a CXXRecordDecl we are in C++ mode, 14814 // thus the other one is a CXXRecordDecl, too. 14815 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14816 // Check number of base classes. 14817 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14818 return false; 14819 14820 // Check the base classes. 14821 for (CXXRecordDecl::base_class_const_iterator 14822 Base1 = D1CXX->bases_begin(), 14823 BaseEnd1 = D1CXX->bases_end(), 14824 Base2 = D2CXX->bases_begin(); 14825 Base1 != BaseEnd1; 14826 ++Base1, ++Base2) { 14827 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14828 return false; 14829 } 14830 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14831 // If only RD2 is a C++ class, it should have zero base classes. 14832 if (D2CXX->getNumBases() > 0) 14833 return false; 14834 } 14835 14836 // Check the fields. 14837 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14838 Field2End = RD2->field_end(), 14839 Field1 = RD1->field_begin(), 14840 Field1End = RD1->field_end(); 14841 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14842 if (!isLayoutCompatible(C, *Field1, *Field2)) 14843 return false; 14844 } 14845 if (Field1 != Field1End || Field2 != Field2End) 14846 return false; 14847 14848 return true; 14849 } 14850 14851 /// Check if two standard-layout unions are layout-compatible. 14852 /// (C++11 [class.mem] p18) 14853 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14854 RecordDecl *RD2) { 14855 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14856 for (auto *Field2 : RD2->fields()) 14857 UnmatchedFields.insert(Field2); 14858 14859 for (auto *Field1 : RD1->fields()) { 14860 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14861 I = UnmatchedFields.begin(), 14862 E = UnmatchedFields.end(); 14863 14864 for ( ; I != E; ++I) { 14865 if (isLayoutCompatible(C, Field1, *I)) { 14866 bool Result = UnmatchedFields.erase(*I); 14867 (void) Result; 14868 assert(Result); 14869 break; 14870 } 14871 } 14872 if (I == E) 14873 return false; 14874 } 14875 14876 return UnmatchedFields.empty(); 14877 } 14878 14879 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14880 RecordDecl *RD2) { 14881 if (RD1->isUnion() != RD2->isUnion()) 14882 return false; 14883 14884 if (RD1->isUnion()) 14885 return isLayoutCompatibleUnion(C, RD1, RD2); 14886 else 14887 return isLayoutCompatibleStruct(C, RD1, RD2); 14888 } 14889 14890 /// Check if two types are layout-compatible in C++11 sense. 14891 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14892 if (T1.isNull() || T2.isNull()) 14893 return false; 14894 14895 // C++11 [basic.types] p11: 14896 // If two types T1 and T2 are the same type, then T1 and T2 are 14897 // layout-compatible types. 14898 if (C.hasSameType(T1, T2)) 14899 return true; 14900 14901 T1 = T1.getCanonicalType().getUnqualifiedType(); 14902 T2 = T2.getCanonicalType().getUnqualifiedType(); 14903 14904 const Type::TypeClass TC1 = T1->getTypeClass(); 14905 const Type::TypeClass TC2 = T2->getTypeClass(); 14906 14907 if (TC1 != TC2) 14908 return false; 14909 14910 if (TC1 == Type::Enum) { 14911 return isLayoutCompatible(C, 14912 cast<EnumType>(T1)->getDecl(), 14913 cast<EnumType>(T2)->getDecl()); 14914 } else if (TC1 == Type::Record) { 14915 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14916 return false; 14917 14918 return isLayoutCompatible(C, 14919 cast<RecordType>(T1)->getDecl(), 14920 cast<RecordType>(T2)->getDecl()); 14921 } 14922 14923 return false; 14924 } 14925 14926 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14927 14928 /// Given a type tag expression find the type tag itself. 14929 /// 14930 /// \param TypeExpr Type tag expression, as it appears in user's code. 14931 /// 14932 /// \param VD Declaration of an identifier that appears in a type tag. 14933 /// 14934 /// \param MagicValue Type tag magic value. 14935 /// 14936 /// \param isConstantEvaluated wether the evalaution should be performed in 14937 14938 /// constant context. 14939 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14940 const ValueDecl **VD, uint64_t *MagicValue, 14941 bool isConstantEvaluated) { 14942 while(true) { 14943 if (!TypeExpr) 14944 return false; 14945 14946 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14947 14948 switch (TypeExpr->getStmtClass()) { 14949 case Stmt::UnaryOperatorClass: { 14950 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14951 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14952 TypeExpr = UO->getSubExpr(); 14953 continue; 14954 } 14955 return false; 14956 } 14957 14958 case Stmt::DeclRefExprClass: { 14959 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14960 *VD = DRE->getDecl(); 14961 return true; 14962 } 14963 14964 case Stmt::IntegerLiteralClass: { 14965 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14966 llvm::APInt MagicValueAPInt = IL->getValue(); 14967 if (MagicValueAPInt.getActiveBits() <= 64) { 14968 *MagicValue = MagicValueAPInt.getZExtValue(); 14969 return true; 14970 } else 14971 return false; 14972 } 14973 14974 case Stmt::BinaryConditionalOperatorClass: 14975 case Stmt::ConditionalOperatorClass: { 14976 const AbstractConditionalOperator *ACO = 14977 cast<AbstractConditionalOperator>(TypeExpr); 14978 bool Result; 14979 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14980 isConstantEvaluated)) { 14981 if (Result) 14982 TypeExpr = ACO->getTrueExpr(); 14983 else 14984 TypeExpr = ACO->getFalseExpr(); 14985 continue; 14986 } 14987 return false; 14988 } 14989 14990 case Stmt::BinaryOperatorClass: { 14991 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14992 if (BO->getOpcode() == BO_Comma) { 14993 TypeExpr = BO->getRHS(); 14994 continue; 14995 } 14996 return false; 14997 } 14998 14999 default: 15000 return false; 15001 } 15002 } 15003 } 15004 15005 /// Retrieve the C type corresponding to type tag TypeExpr. 15006 /// 15007 /// \param TypeExpr Expression that specifies a type tag. 15008 /// 15009 /// \param MagicValues Registered magic values. 15010 /// 15011 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15012 /// kind. 15013 /// 15014 /// \param TypeInfo Information about the corresponding C type. 15015 /// 15016 /// \param isConstantEvaluated wether the evalaution should be performed in 15017 /// constant context. 15018 /// 15019 /// \returns true if the corresponding C type was found. 15020 static bool GetMatchingCType( 15021 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15022 const ASTContext &Ctx, 15023 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15024 *MagicValues, 15025 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15026 bool isConstantEvaluated) { 15027 FoundWrongKind = false; 15028 15029 // Variable declaration that has type_tag_for_datatype attribute. 15030 const ValueDecl *VD = nullptr; 15031 15032 uint64_t MagicValue; 15033 15034 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15035 return false; 15036 15037 if (VD) { 15038 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15039 if (I->getArgumentKind() != ArgumentKind) { 15040 FoundWrongKind = true; 15041 return false; 15042 } 15043 TypeInfo.Type = I->getMatchingCType(); 15044 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15045 TypeInfo.MustBeNull = I->getMustBeNull(); 15046 return true; 15047 } 15048 return false; 15049 } 15050 15051 if (!MagicValues) 15052 return false; 15053 15054 llvm::DenseMap<Sema::TypeTagMagicValue, 15055 Sema::TypeTagData>::const_iterator I = 15056 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15057 if (I == MagicValues->end()) 15058 return false; 15059 15060 TypeInfo = I->second; 15061 return true; 15062 } 15063 15064 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15065 uint64_t MagicValue, QualType Type, 15066 bool LayoutCompatible, 15067 bool MustBeNull) { 15068 if (!TypeTagForDatatypeMagicValues) 15069 TypeTagForDatatypeMagicValues.reset( 15070 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15071 15072 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15073 (*TypeTagForDatatypeMagicValues)[Magic] = 15074 TypeTagData(Type, LayoutCompatible, MustBeNull); 15075 } 15076 15077 static bool IsSameCharType(QualType T1, QualType T2) { 15078 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15079 if (!BT1) 15080 return false; 15081 15082 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15083 if (!BT2) 15084 return false; 15085 15086 BuiltinType::Kind T1Kind = BT1->getKind(); 15087 BuiltinType::Kind T2Kind = BT2->getKind(); 15088 15089 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15090 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15091 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15092 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15093 } 15094 15095 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15096 const ArrayRef<const Expr *> ExprArgs, 15097 SourceLocation CallSiteLoc) { 15098 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15099 bool IsPointerAttr = Attr->getIsPointer(); 15100 15101 // Retrieve the argument representing the 'type_tag'. 15102 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15103 if (TypeTagIdxAST >= ExprArgs.size()) { 15104 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15105 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15106 return; 15107 } 15108 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15109 bool FoundWrongKind; 15110 TypeTagData TypeInfo; 15111 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15112 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15113 TypeInfo, isConstantEvaluated())) { 15114 if (FoundWrongKind) 15115 Diag(TypeTagExpr->getExprLoc(), 15116 diag::warn_type_tag_for_datatype_wrong_kind) 15117 << TypeTagExpr->getSourceRange(); 15118 return; 15119 } 15120 15121 // Retrieve the argument representing the 'arg_idx'. 15122 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15123 if (ArgumentIdxAST >= ExprArgs.size()) { 15124 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15125 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15126 return; 15127 } 15128 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15129 if (IsPointerAttr) { 15130 // Skip implicit cast of pointer to `void *' (as a function argument). 15131 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15132 if (ICE->getType()->isVoidPointerType() && 15133 ICE->getCastKind() == CK_BitCast) 15134 ArgumentExpr = ICE->getSubExpr(); 15135 } 15136 QualType ArgumentType = ArgumentExpr->getType(); 15137 15138 // Passing a `void*' pointer shouldn't trigger a warning. 15139 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15140 return; 15141 15142 if (TypeInfo.MustBeNull) { 15143 // Type tag with matching void type requires a null pointer. 15144 if (!ArgumentExpr->isNullPointerConstant(Context, 15145 Expr::NPC_ValueDependentIsNotNull)) { 15146 Diag(ArgumentExpr->getExprLoc(), 15147 diag::warn_type_safety_null_pointer_required) 15148 << ArgumentKind->getName() 15149 << ArgumentExpr->getSourceRange() 15150 << TypeTagExpr->getSourceRange(); 15151 } 15152 return; 15153 } 15154 15155 QualType RequiredType = TypeInfo.Type; 15156 if (IsPointerAttr) 15157 RequiredType = Context.getPointerType(RequiredType); 15158 15159 bool mismatch = false; 15160 if (!TypeInfo.LayoutCompatible) { 15161 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15162 15163 // C++11 [basic.fundamental] p1: 15164 // Plain char, signed char, and unsigned char are three distinct types. 15165 // 15166 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15167 // char' depending on the current char signedness mode. 15168 if (mismatch) 15169 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15170 RequiredType->getPointeeType())) || 15171 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15172 mismatch = false; 15173 } else 15174 if (IsPointerAttr) 15175 mismatch = !isLayoutCompatible(Context, 15176 ArgumentType->getPointeeType(), 15177 RequiredType->getPointeeType()); 15178 else 15179 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15180 15181 if (mismatch) 15182 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15183 << ArgumentType << ArgumentKind 15184 << TypeInfo.LayoutCompatible << RequiredType 15185 << ArgumentExpr->getSourceRange() 15186 << TypeTagExpr->getSourceRange(); 15187 } 15188 15189 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15190 CharUnits Alignment) { 15191 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15192 } 15193 15194 void Sema::DiagnoseMisalignedMembers() { 15195 for (MisalignedMember &m : MisalignedMembers) { 15196 const NamedDecl *ND = m.RD; 15197 if (ND->getName().empty()) { 15198 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15199 ND = TD; 15200 } 15201 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15202 << m.MD << ND << m.E->getSourceRange(); 15203 } 15204 MisalignedMembers.clear(); 15205 } 15206 15207 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15208 E = E->IgnoreParens(); 15209 if (!T->isPointerType() && !T->isIntegerType()) 15210 return; 15211 if (isa<UnaryOperator>(E) && 15212 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15213 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15214 if (isa<MemberExpr>(Op)) { 15215 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15216 if (MA != MisalignedMembers.end() && 15217 (T->isIntegerType() || 15218 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15219 Context.getTypeAlignInChars( 15220 T->getPointeeType()) <= MA->Alignment)))) 15221 MisalignedMembers.erase(MA); 15222 } 15223 } 15224 } 15225 15226 void Sema::RefersToMemberWithReducedAlignment( 15227 Expr *E, 15228 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15229 Action) { 15230 const auto *ME = dyn_cast<MemberExpr>(E); 15231 if (!ME) 15232 return; 15233 15234 // No need to check expressions with an __unaligned-qualified type. 15235 if (E->getType().getQualifiers().hasUnaligned()) 15236 return; 15237 15238 // For a chain of MemberExpr like "a.b.c.d" this list 15239 // will keep FieldDecl's like [d, c, b]. 15240 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15241 const MemberExpr *TopME = nullptr; 15242 bool AnyIsPacked = false; 15243 do { 15244 QualType BaseType = ME->getBase()->getType(); 15245 if (BaseType->isDependentType()) 15246 return; 15247 if (ME->isArrow()) 15248 BaseType = BaseType->getPointeeType(); 15249 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15250 if (RD->isInvalidDecl()) 15251 return; 15252 15253 ValueDecl *MD = ME->getMemberDecl(); 15254 auto *FD = dyn_cast<FieldDecl>(MD); 15255 // We do not care about non-data members. 15256 if (!FD || FD->isInvalidDecl()) 15257 return; 15258 15259 AnyIsPacked = 15260 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15261 ReverseMemberChain.push_back(FD); 15262 15263 TopME = ME; 15264 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15265 } while (ME); 15266 assert(TopME && "We did not compute a topmost MemberExpr!"); 15267 15268 // Not the scope of this diagnostic. 15269 if (!AnyIsPacked) 15270 return; 15271 15272 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15273 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15274 // TODO: The innermost base of the member expression may be too complicated. 15275 // For now, just disregard these cases. This is left for future 15276 // improvement. 15277 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15278 return; 15279 15280 // Alignment expected by the whole expression. 15281 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15282 15283 // No need to do anything else with this case. 15284 if (ExpectedAlignment.isOne()) 15285 return; 15286 15287 // Synthesize offset of the whole access. 15288 CharUnits Offset; 15289 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15290 I++) { 15291 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15292 } 15293 15294 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15295 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15296 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15297 15298 // The base expression of the innermost MemberExpr may give 15299 // stronger guarantees than the class containing the member. 15300 if (DRE && !TopME->isArrow()) { 15301 const ValueDecl *VD = DRE->getDecl(); 15302 if (!VD->getType()->isReferenceType()) 15303 CompleteObjectAlignment = 15304 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15305 } 15306 15307 // Check if the synthesized offset fulfills the alignment. 15308 if (Offset % ExpectedAlignment != 0 || 15309 // It may fulfill the offset it but the effective alignment may still be 15310 // lower than the expected expression alignment. 15311 CompleteObjectAlignment < ExpectedAlignment) { 15312 // If this happens, we want to determine a sensible culprit of this. 15313 // Intuitively, watching the chain of member expressions from right to 15314 // left, we start with the required alignment (as required by the field 15315 // type) but some packed attribute in that chain has reduced the alignment. 15316 // It may happen that another packed structure increases it again. But if 15317 // we are here such increase has not been enough. So pointing the first 15318 // FieldDecl that either is packed or else its RecordDecl is, 15319 // seems reasonable. 15320 FieldDecl *FD = nullptr; 15321 CharUnits Alignment; 15322 for (FieldDecl *FDI : ReverseMemberChain) { 15323 if (FDI->hasAttr<PackedAttr>() || 15324 FDI->getParent()->hasAttr<PackedAttr>()) { 15325 FD = FDI; 15326 Alignment = std::min( 15327 Context.getTypeAlignInChars(FD->getType()), 15328 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15329 break; 15330 } 15331 } 15332 assert(FD && "We did not find a packed FieldDecl!"); 15333 Action(E, FD->getParent(), FD, Alignment); 15334 } 15335 } 15336 15337 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15338 using namespace std::placeholders; 15339 15340 RefersToMemberWithReducedAlignment( 15341 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15342 _2, _3, _4)); 15343 } 15344 15345 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15346 ExprResult CallResult) { 15347 if (checkArgCount(*this, TheCall, 1)) 15348 return ExprError(); 15349 15350 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15351 if (MatrixArg.isInvalid()) 15352 return MatrixArg; 15353 Expr *Matrix = MatrixArg.get(); 15354 15355 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15356 if (!MType) { 15357 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15358 return ExprError(); 15359 } 15360 15361 // Create returned matrix type by swapping rows and columns of the argument 15362 // matrix type. 15363 QualType ResultType = Context.getConstantMatrixType( 15364 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15365 15366 // Change the return type to the type of the returned matrix. 15367 TheCall->setType(ResultType); 15368 15369 // Update call argument to use the possibly converted matrix argument. 15370 TheCall->setArg(0, Matrix); 15371 return CallResult; 15372 } 15373 15374 // Get and verify the matrix dimensions. 15375 static llvm::Optional<unsigned> 15376 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15377 SourceLocation ErrorPos; 15378 Optional<llvm::APSInt> Value = 15379 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15380 if (!Value) { 15381 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15382 << Name; 15383 return {}; 15384 } 15385 uint64_t Dim = Value->getZExtValue(); 15386 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15387 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15388 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15389 return {}; 15390 } 15391 return Dim; 15392 } 15393 15394 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15395 ExprResult CallResult) { 15396 if (!getLangOpts().MatrixTypes) { 15397 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15398 return ExprError(); 15399 } 15400 15401 if (checkArgCount(*this, TheCall, 4)) 15402 return ExprError(); 15403 15404 unsigned PtrArgIdx = 0; 15405 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15406 Expr *RowsExpr = TheCall->getArg(1); 15407 Expr *ColumnsExpr = TheCall->getArg(2); 15408 Expr *StrideExpr = TheCall->getArg(3); 15409 15410 bool ArgError = false; 15411 15412 // Check pointer argument. 15413 { 15414 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15415 if (PtrConv.isInvalid()) 15416 return PtrConv; 15417 PtrExpr = PtrConv.get(); 15418 TheCall->setArg(0, PtrExpr); 15419 if (PtrExpr->isTypeDependent()) { 15420 TheCall->setType(Context.DependentTy); 15421 return TheCall; 15422 } 15423 } 15424 15425 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15426 QualType ElementTy; 15427 if (!PtrTy) { 15428 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15429 << PtrArgIdx + 1; 15430 ArgError = true; 15431 } else { 15432 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15433 15434 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15435 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15436 << PtrArgIdx + 1; 15437 ArgError = true; 15438 } 15439 } 15440 15441 // Apply default Lvalue conversions and convert the expression to size_t. 15442 auto ApplyArgumentConversions = [this](Expr *E) { 15443 ExprResult Conv = DefaultLvalueConversion(E); 15444 if (Conv.isInvalid()) 15445 return Conv; 15446 15447 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15448 }; 15449 15450 // Apply conversion to row and column expressions. 15451 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15452 if (!RowsConv.isInvalid()) { 15453 RowsExpr = RowsConv.get(); 15454 TheCall->setArg(1, RowsExpr); 15455 } else 15456 RowsExpr = nullptr; 15457 15458 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15459 if (!ColumnsConv.isInvalid()) { 15460 ColumnsExpr = ColumnsConv.get(); 15461 TheCall->setArg(2, ColumnsExpr); 15462 } else 15463 ColumnsExpr = nullptr; 15464 15465 // If any any part of the result matrix type is still pending, just use 15466 // Context.DependentTy, until all parts are resolved. 15467 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15468 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15469 TheCall->setType(Context.DependentTy); 15470 return CallResult; 15471 } 15472 15473 // Check row and column dimenions. 15474 llvm::Optional<unsigned> MaybeRows; 15475 if (RowsExpr) 15476 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15477 15478 llvm::Optional<unsigned> MaybeColumns; 15479 if (ColumnsExpr) 15480 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15481 15482 // Check stride argument. 15483 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15484 if (StrideConv.isInvalid()) 15485 return ExprError(); 15486 StrideExpr = StrideConv.get(); 15487 TheCall->setArg(3, StrideExpr); 15488 15489 if (MaybeRows) { 15490 if (Optional<llvm::APSInt> Value = 15491 StrideExpr->getIntegerConstantExpr(Context)) { 15492 uint64_t Stride = Value->getZExtValue(); 15493 if (Stride < *MaybeRows) { 15494 Diag(StrideExpr->getBeginLoc(), 15495 diag::err_builtin_matrix_stride_too_small); 15496 ArgError = true; 15497 } 15498 } 15499 } 15500 15501 if (ArgError || !MaybeRows || !MaybeColumns) 15502 return ExprError(); 15503 15504 TheCall->setType( 15505 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15506 return CallResult; 15507 } 15508 15509 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15510 ExprResult CallResult) { 15511 if (checkArgCount(*this, TheCall, 3)) 15512 return ExprError(); 15513 15514 unsigned PtrArgIdx = 1; 15515 Expr *MatrixExpr = TheCall->getArg(0); 15516 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15517 Expr *StrideExpr = TheCall->getArg(2); 15518 15519 bool ArgError = false; 15520 15521 { 15522 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15523 if (MatrixConv.isInvalid()) 15524 return MatrixConv; 15525 MatrixExpr = MatrixConv.get(); 15526 TheCall->setArg(0, MatrixExpr); 15527 } 15528 if (MatrixExpr->isTypeDependent()) { 15529 TheCall->setType(Context.DependentTy); 15530 return TheCall; 15531 } 15532 15533 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15534 if (!MatrixTy) { 15535 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15536 ArgError = true; 15537 } 15538 15539 { 15540 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15541 if (PtrConv.isInvalid()) 15542 return PtrConv; 15543 PtrExpr = PtrConv.get(); 15544 TheCall->setArg(1, PtrExpr); 15545 if (PtrExpr->isTypeDependent()) { 15546 TheCall->setType(Context.DependentTy); 15547 return TheCall; 15548 } 15549 } 15550 15551 // Check pointer argument. 15552 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15553 if (!PtrTy) { 15554 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15555 << PtrArgIdx + 1; 15556 ArgError = true; 15557 } else { 15558 QualType ElementTy = PtrTy->getPointeeType(); 15559 if (ElementTy.isConstQualified()) { 15560 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15561 ArgError = true; 15562 } 15563 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15564 if (MatrixTy && 15565 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15566 Diag(PtrExpr->getBeginLoc(), 15567 diag::err_builtin_matrix_pointer_arg_mismatch) 15568 << ElementTy << MatrixTy->getElementType(); 15569 ArgError = true; 15570 } 15571 } 15572 15573 // Apply default Lvalue conversions and convert the stride expression to 15574 // size_t. 15575 { 15576 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15577 if (StrideConv.isInvalid()) 15578 return StrideConv; 15579 15580 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15581 if (StrideConv.isInvalid()) 15582 return StrideConv; 15583 StrideExpr = StrideConv.get(); 15584 TheCall->setArg(2, StrideExpr); 15585 } 15586 15587 // Check stride argument. 15588 if (MatrixTy) { 15589 if (Optional<llvm::APSInt> Value = 15590 StrideExpr->getIntegerConstantExpr(Context)) { 15591 uint64_t Stride = Value->getZExtValue(); 15592 if (Stride < MatrixTy->getNumRows()) { 15593 Diag(StrideExpr->getBeginLoc(), 15594 diag::err_builtin_matrix_stride_too_small); 15595 ArgError = true; 15596 } 15597 } 15598 } 15599 15600 if (ArgError) 15601 return ExprError(); 15602 15603 return CallResult; 15604 } 15605