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 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2561 if (Arg->getType()->getAsPlaceholderType()) 2562 return false; 2563 2564 // The first argument needs to be a record field access. 2565 // If it is an array element access, we delay decision 2566 // to BPF backend to check whether the access is a 2567 // field access or not. 2568 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2569 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2570 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2571 } 2572 2573 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2574 QualType ArgType = Arg->getType(); 2575 if (ArgType->getAsPlaceholderType()) 2576 return false; 2577 2578 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2579 // format: 2580 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2581 // 2. <type> var; 2582 // __builtin_preserve_type_info(var, flag); 2583 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2584 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2585 return false; 2586 2587 // Typedef type. 2588 if (ArgType->getAs<TypedefType>()) 2589 return true; 2590 2591 // Record type or Enum type. 2592 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2593 if (const auto *RT = Ty->getAs<RecordType>()) { 2594 if (!RT->getDecl()->getDeclName().isEmpty()) 2595 return true; 2596 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2597 if (!ET->getDecl()->getDeclName().isEmpty()) 2598 return true; 2599 } 2600 2601 return false; 2602 } 2603 2604 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2605 QualType ArgType = Arg->getType(); 2606 if (ArgType->getAsPlaceholderType()) 2607 return false; 2608 2609 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2610 // format: 2611 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2612 // flag); 2613 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2614 if (!UO) 2615 return false; 2616 2617 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2618 if (!CE || CE->getCastKind() != CK_IntegralToPointer) 2619 return false; 2620 2621 // The integer must be from an EnumConstantDecl. 2622 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2623 if (!DR) 2624 return false; 2625 2626 const EnumConstantDecl *Enumerator = 2627 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2628 if (!Enumerator) 2629 return false; 2630 2631 // The type must be EnumType. 2632 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2633 const auto *ET = Ty->getAs<EnumType>(); 2634 if (!ET) 2635 return false; 2636 2637 // The enum value must be supported. 2638 for (auto *EDI : ET->getDecl()->enumerators()) { 2639 if (EDI == Enumerator) 2640 return true; 2641 } 2642 2643 return false; 2644 } 2645 2646 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2647 CallExpr *TheCall) { 2648 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2649 BuiltinID == BPF::BI__builtin_btf_type_id || 2650 BuiltinID == BPF::BI__builtin_preserve_type_info || 2651 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2652 "unexpected BPF builtin"); 2653 2654 if (checkArgCount(*this, TheCall, 2)) 2655 return true; 2656 2657 // The second argument needs to be a constant int 2658 Expr *Arg = TheCall->getArg(1); 2659 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2660 diag::kind kind; 2661 if (!Value) { 2662 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2663 kind = diag::err_preserve_field_info_not_const; 2664 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2665 kind = diag::err_btf_type_id_not_const; 2666 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2667 kind = diag::err_preserve_type_info_not_const; 2668 else 2669 kind = diag::err_preserve_enum_value_not_const; 2670 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2671 return true; 2672 } 2673 2674 // The first argument 2675 Arg = TheCall->getArg(0); 2676 bool InvalidArg = false; 2677 bool ReturnUnsignedInt = true; 2678 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2679 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2680 InvalidArg = true; 2681 kind = diag::err_preserve_field_info_not_field; 2682 } 2683 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2684 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2685 InvalidArg = true; 2686 kind = diag::err_preserve_type_info_invalid; 2687 } 2688 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2689 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2690 InvalidArg = true; 2691 kind = diag::err_preserve_enum_value_invalid; 2692 } 2693 ReturnUnsignedInt = false; 2694 } 2695 2696 if (InvalidArg) { 2697 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2698 return true; 2699 } 2700 2701 if (ReturnUnsignedInt) 2702 TheCall->setType(Context.UnsignedIntTy); 2703 else 2704 TheCall->setType(Context.UnsignedLongTy); 2705 return false; 2706 } 2707 2708 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2709 struct ArgInfo { 2710 uint8_t OpNum; 2711 bool IsSigned; 2712 uint8_t BitWidth; 2713 uint8_t Align; 2714 }; 2715 struct BuiltinInfo { 2716 unsigned BuiltinID; 2717 ArgInfo Infos[2]; 2718 }; 2719 2720 static BuiltinInfo Infos[] = { 2721 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2722 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2723 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2724 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2725 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2726 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2727 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2728 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2729 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2730 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2731 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2732 2733 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2744 2745 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2797 {{ 1, false, 6, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2805 {{ 1, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2812 { 2, false, 5, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2814 { 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2816 { 3, false, 5, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2818 { 3, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2835 {{ 2, false, 4, 0 }, 2836 { 3, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2838 {{ 2, false, 4, 0 }, 2839 { 3, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2841 {{ 2, false, 4, 0 }, 2842 { 3, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2844 {{ 2, false, 4, 0 }, 2845 { 3, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2857 { 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2859 { 2, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2869 {{ 1, false, 4, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2872 {{ 1, false, 4, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2893 {{ 3, false, 1, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2898 {{ 3, false, 1, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2903 {{ 3, false, 1, 0 }} }, 2904 }; 2905 2906 // Use a dynamically initialized static to sort the table exactly once on 2907 // first run. 2908 static const bool SortOnce = 2909 (llvm::sort(Infos, 2910 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2911 return LHS.BuiltinID < RHS.BuiltinID; 2912 }), 2913 true); 2914 (void)SortOnce; 2915 2916 const BuiltinInfo *F = llvm::partition_point( 2917 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2918 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2919 return false; 2920 2921 bool Error = false; 2922 2923 for (const ArgInfo &A : F->Infos) { 2924 // Ignore empty ArgInfo elements. 2925 if (A.BitWidth == 0) 2926 continue; 2927 2928 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2929 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2930 if (!A.Align) { 2931 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2932 } else { 2933 unsigned M = 1 << A.Align; 2934 Min *= M; 2935 Max *= M; 2936 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2937 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2938 } 2939 } 2940 return Error; 2941 } 2942 2943 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2944 CallExpr *TheCall) { 2945 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2946 } 2947 2948 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2949 unsigned BuiltinID, CallExpr *TheCall) { 2950 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2951 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2952 } 2953 2954 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2955 CallExpr *TheCall) { 2956 2957 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2958 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2959 if (!TI.hasFeature("dsp")) 2960 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2961 } 2962 2963 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2964 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2965 if (!TI.hasFeature("dspr2")) 2966 return Diag(TheCall->getBeginLoc(), 2967 diag::err_mips_builtin_requires_dspr2); 2968 } 2969 2970 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2971 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2972 if (!TI.hasFeature("msa")) 2973 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2974 } 2975 2976 return false; 2977 } 2978 2979 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2980 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2981 // ordering for DSP is unspecified. MSA is ordered by the data format used 2982 // by the underlying instruction i.e., df/m, df/n and then by size. 2983 // 2984 // FIXME: The size tests here should instead be tablegen'd along with the 2985 // definitions from include/clang/Basic/BuiltinsMips.def. 2986 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2987 // be too. 2988 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2989 unsigned i = 0, l = 0, u = 0, m = 0; 2990 switch (BuiltinID) { 2991 default: return false; 2992 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2993 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2994 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2995 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2996 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2997 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2998 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2999 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3000 // df/m field. 3001 // These intrinsics take an unsigned 3 bit immediate. 3002 case Mips::BI__builtin_msa_bclri_b: 3003 case Mips::BI__builtin_msa_bnegi_b: 3004 case Mips::BI__builtin_msa_bseti_b: 3005 case Mips::BI__builtin_msa_sat_s_b: 3006 case Mips::BI__builtin_msa_sat_u_b: 3007 case Mips::BI__builtin_msa_slli_b: 3008 case Mips::BI__builtin_msa_srai_b: 3009 case Mips::BI__builtin_msa_srari_b: 3010 case Mips::BI__builtin_msa_srli_b: 3011 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3012 case Mips::BI__builtin_msa_binsli_b: 3013 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3014 // These intrinsics take an unsigned 4 bit immediate. 3015 case Mips::BI__builtin_msa_bclri_h: 3016 case Mips::BI__builtin_msa_bnegi_h: 3017 case Mips::BI__builtin_msa_bseti_h: 3018 case Mips::BI__builtin_msa_sat_s_h: 3019 case Mips::BI__builtin_msa_sat_u_h: 3020 case Mips::BI__builtin_msa_slli_h: 3021 case Mips::BI__builtin_msa_srai_h: 3022 case Mips::BI__builtin_msa_srari_h: 3023 case Mips::BI__builtin_msa_srli_h: 3024 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3025 case Mips::BI__builtin_msa_binsli_h: 3026 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3027 // These intrinsics take an unsigned 5 bit immediate. 3028 // The first block of intrinsics actually have an unsigned 5 bit field, 3029 // not a df/n field. 3030 case Mips::BI__builtin_msa_cfcmsa: 3031 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3032 case Mips::BI__builtin_msa_clei_u_b: 3033 case Mips::BI__builtin_msa_clei_u_h: 3034 case Mips::BI__builtin_msa_clei_u_w: 3035 case Mips::BI__builtin_msa_clei_u_d: 3036 case Mips::BI__builtin_msa_clti_u_b: 3037 case Mips::BI__builtin_msa_clti_u_h: 3038 case Mips::BI__builtin_msa_clti_u_w: 3039 case Mips::BI__builtin_msa_clti_u_d: 3040 case Mips::BI__builtin_msa_maxi_u_b: 3041 case Mips::BI__builtin_msa_maxi_u_h: 3042 case Mips::BI__builtin_msa_maxi_u_w: 3043 case Mips::BI__builtin_msa_maxi_u_d: 3044 case Mips::BI__builtin_msa_mini_u_b: 3045 case Mips::BI__builtin_msa_mini_u_h: 3046 case Mips::BI__builtin_msa_mini_u_w: 3047 case Mips::BI__builtin_msa_mini_u_d: 3048 case Mips::BI__builtin_msa_addvi_b: 3049 case Mips::BI__builtin_msa_addvi_h: 3050 case Mips::BI__builtin_msa_addvi_w: 3051 case Mips::BI__builtin_msa_addvi_d: 3052 case Mips::BI__builtin_msa_bclri_w: 3053 case Mips::BI__builtin_msa_bnegi_w: 3054 case Mips::BI__builtin_msa_bseti_w: 3055 case Mips::BI__builtin_msa_sat_s_w: 3056 case Mips::BI__builtin_msa_sat_u_w: 3057 case Mips::BI__builtin_msa_slli_w: 3058 case Mips::BI__builtin_msa_srai_w: 3059 case Mips::BI__builtin_msa_srari_w: 3060 case Mips::BI__builtin_msa_srli_w: 3061 case Mips::BI__builtin_msa_srlri_w: 3062 case Mips::BI__builtin_msa_subvi_b: 3063 case Mips::BI__builtin_msa_subvi_h: 3064 case Mips::BI__builtin_msa_subvi_w: 3065 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3066 case Mips::BI__builtin_msa_binsli_w: 3067 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3068 // These intrinsics take an unsigned 6 bit immediate. 3069 case Mips::BI__builtin_msa_bclri_d: 3070 case Mips::BI__builtin_msa_bnegi_d: 3071 case Mips::BI__builtin_msa_bseti_d: 3072 case Mips::BI__builtin_msa_sat_s_d: 3073 case Mips::BI__builtin_msa_sat_u_d: 3074 case Mips::BI__builtin_msa_slli_d: 3075 case Mips::BI__builtin_msa_srai_d: 3076 case Mips::BI__builtin_msa_srari_d: 3077 case Mips::BI__builtin_msa_srli_d: 3078 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3079 case Mips::BI__builtin_msa_binsli_d: 3080 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3081 // These intrinsics take a signed 5 bit immediate. 3082 case Mips::BI__builtin_msa_ceqi_b: 3083 case Mips::BI__builtin_msa_ceqi_h: 3084 case Mips::BI__builtin_msa_ceqi_w: 3085 case Mips::BI__builtin_msa_ceqi_d: 3086 case Mips::BI__builtin_msa_clti_s_b: 3087 case Mips::BI__builtin_msa_clti_s_h: 3088 case Mips::BI__builtin_msa_clti_s_w: 3089 case Mips::BI__builtin_msa_clti_s_d: 3090 case Mips::BI__builtin_msa_clei_s_b: 3091 case Mips::BI__builtin_msa_clei_s_h: 3092 case Mips::BI__builtin_msa_clei_s_w: 3093 case Mips::BI__builtin_msa_clei_s_d: 3094 case Mips::BI__builtin_msa_maxi_s_b: 3095 case Mips::BI__builtin_msa_maxi_s_h: 3096 case Mips::BI__builtin_msa_maxi_s_w: 3097 case Mips::BI__builtin_msa_maxi_s_d: 3098 case Mips::BI__builtin_msa_mini_s_b: 3099 case Mips::BI__builtin_msa_mini_s_h: 3100 case Mips::BI__builtin_msa_mini_s_w: 3101 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3102 // These intrinsics take an unsigned 8 bit immediate. 3103 case Mips::BI__builtin_msa_andi_b: 3104 case Mips::BI__builtin_msa_nori_b: 3105 case Mips::BI__builtin_msa_ori_b: 3106 case Mips::BI__builtin_msa_shf_b: 3107 case Mips::BI__builtin_msa_shf_h: 3108 case Mips::BI__builtin_msa_shf_w: 3109 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3110 case Mips::BI__builtin_msa_bseli_b: 3111 case Mips::BI__builtin_msa_bmnzi_b: 3112 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3113 // df/n format 3114 // These intrinsics take an unsigned 4 bit immediate. 3115 case Mips::BI__builtin_msa_copy_s_b: 3116 case Mips::BI__builtin_msa_copy_u_b: 3117 case Mips::BI__builtin_msa_insve_b: 3118 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3119 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3120 // These intrinsics take an unsigned 3 bit immediate. 3121 case Mips::BI__builtin_msa_copy_s_h: 3122 case Mips::BI__builtin_msa_copy_u_h: 3123 case Mips::BI__builtin_msa_insve_h: 3124 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3125 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3126 // These intrinsics take an unsigned 2 bit immediate. 3127 case Mips::BI__builtin_msa_copy_s_w: 3128 case Mips::BI__builtin_msa_copy_u_w: 3129 case Mips::BI__builtin_msa_insve_w: 3130 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3131 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3132 // These intrinsics take an unsigned 1 bit immediate. 3133 case Mips::BI__builtin_msa_copy_s_d: 3134 case Mips::BI__builtin_msa_copy_u_d: 3135 case Mips::BI__builtin_msa_insve_d: 3136 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3137 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3138 // Memory offsets and immediate loads. 3139 // These intrinsics take a signed 10 bit immediate. 3140 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3141 case Mips::BI__builtin_msa_ldi_h: 3142 case Mips::BI__builtin_msa_ldi_w: 3143 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3144 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3145 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3146 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3147 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3148 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3149 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3150 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3151 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3152 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3153 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3154 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3155 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3156 } 3157 3158 if (!m) 3159 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3160 3161 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3162 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3163 } 3164 3165 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3166 CallExpr *TheCall) { 3167 unsigned i = 0, l = 0, u = 0; 3168 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3169 BuiltinID == PPC::BI__builtin_divdeu || 3170 BuiltinID == PPC::BI__builtin_bpermd; 3171 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3172 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3173 BuiltinID == PPC::BI__builtin_divweu || 3174 BuiltinID == PPC::BI__builtin_divde || 3175 BuiltinID == PPC::BI__builtin_divdeu; 3176 3177 if (Is64BitBltin && !IsTarget64Bit) 3178 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3179 << TheCall->getSourceRange(); 3180 3181 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3182 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3183 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3184 << TheCall->getSourceRange(); 3185 3186 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3187 if (!TI.hasFeature("vsx")) 3188 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3189 << TheCall->getSourceRange(); 3190 return false; 3191 }; 3192 3193 switch (BuiltinID) { 3194 default: return false; 3195 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3196 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3197 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3198 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3199 case PPC::BI__builtin_altivec_dss: 3200 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3201 case PPC::BI__builtin_tbegin: 3202 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3203 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3204 case PPC::BI__builtin_tabortwc: 3205 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3206 case PPC::BI__builtin_tabortwci: 3207 case PPC::BI__builtin_tabortdci: 3208 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3209 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3210 case PPC::BI__builtin_altivec_dst: 3211 case PPC::BI__builtin_altivec_dstt: 3212 case PPC::BI__builtin_altivec_dstst: 3213 case PPC::BI__builtin_altivec_dststt: 3214 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3215 case PPC::BI__builtin_vsx_xxpermdi: 3216 case PPC::BI__builtin_vsx_xxsldwi: 3217 return SemaBuiltinVSX(TheCall); 3218 case PPC::BI__builtin_unpack_vector_int128: 3219 return SemaVSXCheck(TheCall) || 3220 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3221 case PPC::BI__builtin_pack_vector_int128: 3222 return SemaVSXCheck(TheCall); 3223 case PPC::BI__builtin_altivec_vgnb: 3224 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3225 case PPC::BI__builtin_vsx_xxeval: 3226 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3227 case PPC::BI__builtin_altivec_vsldbi: 3228 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3229 case PPC::BI__builtin_altivec_vsrdbi: 3230 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3231 case PPC::BI__builtin_vsx_xxpermx: 3232 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3233 } 3234 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3235 } 3236 3237 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3238 CallExpr *TheCall) { 3239 // position of memory order and scope arguments in the builtin 3240 unsigned OrderIndex, ScopeIndex; 3241 switch (BuiltinID) { 3242 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3243 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3244 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3245 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3246 OrderIndex = 2; 3247 ScopeIndex = 3; 3248 break; 3249 case AMDGPU::BI__builtin_amdgcn_fence: 3250 OrderIndex = 0; 3251 ScopeIndex = 1; 3252 break; 3253 default: 3254 return false; 3255 } 3256 3257 ExprResult Arg = TheCall->getArg(OrderIndex); 3258 auto ArgExpr = Arg.get(); 3259 Expr::EvalResult ArgResult; 3260 3261 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3262 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3263 << ArgExpr->getType(); 3264 int ord = ArgResult.Val.getInt().getZExtValue(); 3265 3266 // Check valididty of memory ordering as per C11 / C++11's memody model. 3267 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3268 case llvm::AtomicOrderingCABI::acquire: 3269 case llvm::AtomicOrderingCABI::release: 3270 case llvm::AtomicOrderingCABI::acq_rel: 3271 case llvm::AtomicOrderingCABI::seq_cst: 3272 break; 3273 default: { 3274 return Diag(ArgExpr->getBeginLoc(), 3275 diag::warn_atomic_op_has_invalid_memory_order) 3276 << ArgExpr->getSourceRange(); 3277 } 3278 } 3279 3280 Arg = TheCall->getArg(ScopeIndex); 3281 ArgExpr = Arg.get(); 3282 Expr::EvalResult ArgResult1; 3283 // Check that sync scope is a constant literal 3284 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3285 Context)) 3286 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3287 << ArgExpr->getType(); 3288 3289 return false; 3290 } 3291 3292 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3293 CallExpr *TheCall) { 3294 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3295 Expr *Arg = TheCall->getArg(0); 3296 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3297 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3298 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3299 << Arg->getSourceRange(); 3300 } 3301 3302 // For intrinsics which take an immediate value as part of the instruction, 3303 // range check them here. 3304 unsigned i = 0, l = 0, u = 0; 3305 switch (BuiltinID) { 3306 default: return false; 3307 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3308 case SystemZ::BI__builtin_s390_verimb: 3309 case SystemZ::BI__builtin_s390_verimh: 3310 case SystemZ::BI__builtin_s390_verimf: 3311 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3312 case SystemZ::BI__builtin_s390_vfaeb: 3313 case SystemZ::BI__builtin_s390_vfaeh: 3314 case SystemZ::BI__builtin_s390_vfaef: 3315 case SystemZ::BI__builtin_s390_vfaebs: 3316 case SystemZ::BI__builtin_s390_vfaehs: 3317 case SystemZ::BI__builtin_s390_vfaefs: 3318 case SystemZ::BI__builtin_s390_vfaezb: 3319 case SystemZ::BI__builtin_s390_vfaezh: 3320 case SystemZ::BI__builtin_s390_vfaezf: 3321 case SystemZ::BI__builtin_s390_vfaezbs: 3322 case SystemZ::BI__builtin_s390_vfaezhs: 3323 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3324 case SystemZ::BI__builtin_s390_vfisb: 3325 case SystemZ::BI__builtin_s390_vfidb: 3326 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3327 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3328 case SystemZ::BI__builtin_s390_vftcisb: 3329 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3330 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3331 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3332 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3333 case SystemZ::BI__builtin_s390_vstrcb: 3334 case SystemZ::BI__builtin_s390_vstrch: 3335 case SystemZ::BI__builtin_s390_vstrcf: 3336 case SystemZ::BI__builtin_s390_vstrczb: 3337 case SystemZ::BI__builtin_s390_vstrczh: 3338 case SystemZ::BI__builtin_s390_vstrczf: 3339 case SystemZ::BI__builtin_s390_vstrcbs: 3340 case SystemZ::BI__builtin_s390_vstrchs: 3341 case SystemZ::BI__builtin_s390_vstrcfs: 3342 case SystemZ::BI__builtin_s390_vstrczbs: 3343 case SystemZ::BI__builtin_s390_vstrczhs: 3344 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3345 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3346 case SystemZ::BI__builtin_s390_vfminsb: 3347 case SystemZ::BI__builtin_s390_vfmaxsb: 3348 case SystemZ::BI__builtin_s390_vfmindb: 3349 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3350 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3351 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3352 } 3353 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3354 } 3355 3356 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3357 /// This checks that the target supports __builtin_cpu_supports and 3358 /// that the string argument is constant and valid. 3359 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3360 CallExpr *TheCall) { 3361 Expr *Arg = TheCall->getArg(0); 3362 3363 // Check if the argument is a string literal. 3364 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3365 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3366 << Arg->getSourceRange(); 3367 3368 // Check the contents of the string. 3369 StringRef Feature = 3370 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3371 if (!TI.validateCpuSupports(Feature)) 3372 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3373 << Arg->getSourceRange(); 3374 return false; 3375 } 3376 3377 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3378 /// This checks that the target supports __builtin_cpu_is and 3379 /// that the string argument is constant and valid. 3380 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3381 Expr *Arg = TheCall->getArg(0); 3382 3383 // Check if the argument is a string literal. 3384 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3385 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3386 << Arg->getSourceRange(); 3387 3388 // Check the contents of the string. 3389 StringRef Feature = 3390 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3391 if (!TI.validateCpuIs(Feature)) 3392 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3393 << Arg->getSourceRange(); 3394 return false; 3395 } 3396 3397 // Check if the rounding mode is legal. 3398 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3399 // Indicates if this instruction has rounding control or just SAE. 3400 bool HasRC = false; 3401 3402 unsigned ArgNum = 0; 3403 switch (BuiltinID) { 3404 default: 3405 return false; 3406 case X86::BI__builtin_ia32_vcvttsd2si32: 3407 case X86::BI__builtin_ia32_vcvttsd2si64: 3408 case X86::BI__builtin_ia32_vcvttsd2usi32: 3409 case X86::BI__builtin_ia32_vcvttsd2usi64: 3410 case X86::BI__builtin_ia32_vcvttss2si32: 3411 case X86::BI__builtin_ia32_vcvttss2si64: 3412 case X86::BI__builtin_ia32_vcvttss2usi32: 3413 case X86::BI__builtin_ia32_vcvttss2usi64: 3414 ArgNum = 1; 3415 break; 3416 case X86::BI__builtin_ia32_maxpd512: 3417 case X86::BI__builtin_ia32_maxps512: 3418 case X86::BI__builtin_ia32_minpd512: 3419 case X86::BI__builtin_ia32_minps512: 3420 ArgNum = 2; 3421 break; 3422 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3423 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3424 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3425 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3426 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3427 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3428 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3429 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3430 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3431 case X86::BI__builtin_ia32_exp2pd_mask: 3432 case X86::BI__builtin_ia32_exp2ps_mask: 3433 case X86::BI__builtin_ia32_getexppd512_mask: 3434 case X86::BI__builtin_ia32_getexpps512_mask: 3435 case X86::BI__builtin_ia32_rcp28pd_mask: 3436 case X86::BI__builtin_ia32_rcp28ps_mask: 3437 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3438 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3439 case X86::BI__builtin_ia32_vcomisd: 3440 case X86::BI__builtin_ia32_vcomiss: 3441 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3442 ArgNum = 3; 3443 break; 3444 case X86::BI__builtin_ia32_cmppd512_mask: 3445 case X86::BI__builtin_ia32_cmpps512_mask: 3446 case X86::BI__builtin_ia32_cmpsd_mask: 3447 case X86::BI__builtin_ia32_cmpss_mask: 3448 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3449 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3450 case X86::BI__builtin_ia32_getexpss128_round_mask: 3451 case X86::BI__builtin_ia32_getmantpd512_mask: 3452 case X86::BI__builtin_ia32_getmantps512_mask: 3453 case X86::BI__builtin_ia32_maxsd_round_mask: 3454 case X86::BI__builtin_ia32_maxss_round_mask: 3455 case X86::BI__builtin_ia32_minsd_round_mask: 3456 case X86::BI__builtin_ia32_minss_round_mask: 3457 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3458 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3459 case X86::BI__builtin_ia32_reducepd512_mask: 3460 case X86::BI__builtin_ia32_reduceps512_mask: 3461 case X86::BI__builtin_ia32_rndscalepd_mask: 3462 case X86::BI__builtin_ia32_rndscaleps_mask: 3463 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3464 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3465 ArgNum = 4; 3466 break; 3467 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3468 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3469 case X86::BI__builtin_ia32_fixupimmps512_mask: 3470 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3471 case X86::BI__builtin_ia32_fixupimmsd_mask: 3472 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3473 case X86::BI__builtin_ia32_fixupimmss_mask: 3474 case X86::BI__builtin_ia32_fixupimmss_maskz: 3475 case X86::BI__builtin_ia32_getmantsd_round_mask: 3476 case X86::BI__builtin_ia32_getmantss_round_mask: 3477 case X86::BI__builtin_ia32_rangepd512_mask: 3478 case X86::BI__builtin_ia32_rangeps512_mask: 3479 case X86::BI__builtin_ia32_rangesd128_round_mask: 3480 case X86::BI__builtin_ia32_rangess128_round_mask: 3481 case X86::BI__builtin_ia32_reducesd_mask: 3482 case X86::BI__builtin_ia32_reducess_mask: 3483 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3484 case X86::BI__builtin_ia32_rndscaless_round_mask: 3485 ArgNum = 5; 3486 break; 3487 case X86::BI__builtin_ia32_vcvtsd2si64: 3488 case X86::BI__builtin_ia32_vcvtsd2si32: 3489 case X86::BI__builtin_ia32_vcvtsd2usi32: 3490 case X86::BI__builtin_ia32_vcvtsd2usi64: 3491 case X86::BI__builtin_ia32_vcvtss2si32: 3492 case X86::BI__builtin_ia32_vcvtss2si64: 3493 case X86::BI__builtin_ia32_vcvtss2usi32: 3494 case X86::BI__builtin_ia32_vcvtss2usi64: 3495 case X86::BI__builtin_ia32_sqrtpd512: 3496 case X86::BI__builtin_ia32_sqrtps512: 3497 ArgNum = 1; 3498 HasRC = true; 3499 break; 3500 case X86::BI__builtin_ia32_addpd512: 3501 case X86::BI__builtin_ia32_addps512: 3502 case X86::BI__builtin_ia32_divpd512: 3503 case X86::BI__builtin_ia32_divps512: 3504 case X86::BI__builtin_ia32_mulpd512: 3505 case X86::BI__builtin_ia32_mulps512: 3506 case X86::BI__builtin_ia32_subpd512: 3507 case X86::BI__builtin_ia32_subps512: 3508 case X86::BI__builtin_ia32_cvtsi2sd64: 3509 case X86::BI__builtin_ia32_cvtsi2ss32: 3510 case X86::BI__builtin_ia32_cvtsi2ss64: 3511 case X86::BI__builtin_ia32_cvtusi2sd64: 3512 case X86::BI__builtin_ia32_cvtusi2ss32: 3513 case X86::BI__builtin_ia32_cvtusi2ss64: 3514 ArgNum = 2; 3515 HasRC = true; 3516 break; 3517 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3518 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3519 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3520 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3521 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3522 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3523 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3524 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3525 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3526 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3527 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3528 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3529 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3530 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3531 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3532 ArgNum = 3; 3533 HasRC = true; 3534 break; 3535 case X86::BI__builtin_ia32_addss_round_mask: 3536 case X86::BI__builtin_ia32_addsd_round_mask: 3537 case X86::BI__builtin_ia32_divss_round_mask: 3538 case X86::BI__builtin_ia32_divsd_round_mask: 3539 case X86::BI__builtin_ia32_mulss_round_mask: 3540 case X86::BI__builtin_ia32_mulsd_round_mask: 3541 case X86::BI__builtin_ia32_subss_round_mask: 3542 case X86::BI__builtin_ia32_subsd_round_mask: 3543 case X86::BI__builtin_ia32_scalefpd512_mask: 3544 case X86::BI__builtin_ia32_scalefps512_mask: 3545 case X86::BI__builtin_ia32_scalefsd_round_mask: 3546 case X86::BI__builtin_ia32_scalefss_round_mask: 3547 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3548 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3549 case X86::BI__builtin_ia32_sqrtss_round_mask: 3550 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3551 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3552 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3553 case X86::BI__builtin_ia32_vfmaddss3_mask: 3554 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3555 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3556 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3557 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3558 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3559 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3560 case X86::BI__builtin_ia32_vfmaddps512_mask: 3561 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3562 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3563 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3564 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3565 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3566 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3567 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3568 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3569 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3570 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3571 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3572 ArgNum = 4; 3573 HasRC = true; 3574 break; 3575 } 3576 3577 llvm::APSInt Result; 3578 3579 // We can't check the value of a dependent argument. 3580 Expr *Arg = TheCall->getArg(ArgNum); 3581 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3582 return false; 3583 3584 // Check constant-ness first. 3585 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3586 return true; 3587 3588 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3589 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3590 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3591 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3592 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3593 Result == 8/*ROUND_NO_EXC*/ || 3594 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3595 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3596 return false; 3597 3598 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3599 << Arg->getSourceRange(); 3600 } 3601 3602 // Check if the gather/scatter scale is legal. 3603 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3604 CallExpr *TheCall) { 3605 unsigned ArgNum = 0; 3606 switch (BuiltinID) { 3607 default: 3608 return false; 3609 case X86::BI__builtin_ia32_gatherpfdpd: 3610 case X86::BI__builtin_ia32_gatherpfdps: 3611 case X86::BI__builtin_ia32_gatherpfqpd: 3612 case X86::BI__builtin_ia32_gatherpfqps: 3613 case X86::BI__builtin_ia32_scatterpfdpd: 3614 case X86::BI__builtin_ia32_scatterpfdps: 3615 case X86::BI__builtin_ia32_scatterpfqpd: 3616 case X86::BI__builtin_ia32_scatterpfqps: 3617 ArgNum = 3; 3618 break; 3619 case X86::BI__builtin_ia32_gatherd_pd: 3620 case X86::BI__builtin_ia32_gatherd_pd256: 3621 case X86::BI__builtin_ia32_gatherq_pd: 3622 case X86::BI__builtin_ia32_gatherq_pd256: 3623 case X86::BI__builtin_ia32_gatherd_ps: 3624 case X86::BI__builtin_ia32_gatherd_ps256: 3625 case X86::BI__builtin_ia32_gatherq_ps: 3626 case X86::BI__builtin_ia32_gatherq_ps256: 3627 case X86::BI__builtin_ia32_gatherd_q: 3628 case X86::BI__builtin_ia32_gatherd_q256: 3629 case X86::BI__builtin_ia32_gatherq_q: 3630 case X86::BI__builtin_ia32_gatherq_q256: 3631 case X86::BI__builtin_ia32_gatherd_d: 3632 case X86::BI__builtin_ia32_gatherd_d256: 3633 case X86::BI__builtin_ia32_gatherq_d: 3634 case X86::BI__builtin_ia32_gatherq_d256: 3635 case X86::BI__builtin_ia32_gather3div2df: 3636 case X86::BI__builtin_ia32_gather3div2di: 3637 case X86::BI__builtin_ia32_gather3div4df: 3638 case X86::BI__builtin_ia32_gather3div4di: 3639 case X86::BI__builtin_ia32_gather3div4sf: 3640 case X86::BI__builtin_ia32_gather3div4si: 3641 case X86::BI__builtin_ia32_gather3div8sf: 3642 case X86::BI__builtin_ia32_gather3div8si: 3643 case X86::BI__builtin_ia32_gather3siv2df: 3644 case X86::BI__builtin_ia32_gather3siv2di: 3645 case X86::BI__builtin_ia32_gather3siv4df: 3646 case X86::BI__builtin_ia32_gather3siv4di: 3647 case X86::BI__builtin_ia32_gather3siv4sf: 3648 case X86::BI__builtin_ia32_gather3siv4si: 3649 case X86::BI__builtin_ia32_gather3siv8sf: 3650 case X86::BI__builtin_ia32_gather3siv8si: 3651 case X86::BI__builtin_ia32_gathersiv8df: 3652 case X86::BI__builtin_ia32_gathersiv16sf: 3653 case X86::BI__builtin_ia32_gatherdiv8df: 3654 case X86::BI__builtin_ia32_gatherdiv16sf: 3655 case X86::BI__builtin_ia32_gathersiv8di: 3656 case X86::BI__builtin_ia32_gathersiv16si: 3657 case X86::BI__builtin_ia32_gatherdiv8di: 3658 case X86::BI__builtin_ia32_gatherdiv16si: 3659 case X86::BI__builtin_ia32_scatterdiv2df: 3660 case X86::BI__builtin_ia32_scatterdiv2di: 3661 case X86::BI__builtin_ia32_scatterdiv4df: 3662 case X86::BI__builtin_ia32_scatterdiv4di: 3663 case X86::BI__builtin_ia32_scatterdiv4sf: 3664 case X86::BI__builtin_ia32_scatterdiv4si: 3665 case X86::BI__builtin_ia32_scatterdiv8sf: 3666 case X86::BI__builtin_ia32_scatterdiv8si: 3667 case X86::BI__builtin_ia32_scattersiv2df: 3668 case X86::BI__builtin_ia32_scattersiv2di: 3669 case X86::BI__builtin_ia32_scattersiv4df: 3670 case X86::BI__builtin_ia32_scattersiv4di: 3671 case X86::BI__builtin_ia32_scattersiv4sf: 3672 case X86::BI__builtin_ia32_scattersiv4si: 3673 case X86::BI__builtin_ia32_scattersiv8sf: 3674 case X86::BI__builtin_ia32_scattersiv8si: 3675 case X86::BI__builtin_ia32_scattersiv8df: 3676 case X86::BI__builtin_ia32_scattersiv16sf: 3677 case X86::BI__builtin_ia32_scatterdiv8df: 3678 case X86::BI__builtin_ia32_scatterdiv16sf: 3679 case X86::BI__builtin_ia32_scattersiv8di: 3680 case X86::BI__builtin_ia32_scattersiv16si: 3681 case X86::BI__builtin_ia32_scatterdiv8di: 3682 case X86::BI__builtin_ia32_scatterdiv16si: 3683 ArgNum = 4; 3684 break; 3685 } 3686 3687 llvm::APSInt Result; 3688 3689 // We can't check the value of a dependent argument. 3690 Expr *Arg = TheCall->getArg(ArgNum); 3691 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3692 return false; 3693 3694 // Check constant-ness first. 3695 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3696 return true; 3697 3698 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3699 return false; 3700 3701 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3702 << Arg->getSourceRange(); 3703 } 3704 3705 enum { TileRegLow = 0, TileRegHigh = 7 }; 3706 3707 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3708 ArrayRef<int> ArgNums) { 3709 for (int ArgNum : ArgNums) { 3710 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3711 return true; 3712 } 3713 return false; 3714 } 3715 3716 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum) { 3717 return SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh); 3718 } 3719 3720 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3721 ArrayRef<int> ArgNums) { 3722 // Because the max number of tile register is TileRegHigh + 1, so here we use 3723 // each bit to represent the usage of them in bitset. 3724 std::bitset<TileRegHigh + 1> ArgValues; 3725 for (int ArgNum : ArgNums) { 3726 llvm::APSInt Arg; 3727 SemaBuiltinConstantArg(TheCall, ArgNum, Arg); 3728 int ArgExtValue = Arg.getExtValue(); 3729 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3730 "Incorrect tile register num."); 3731 if (ArgValues.test(ArgExtValue)) 3732 return Diag(TheCall->getBeginLoc(), 3733 diag::err_x86_builtin_tile_arg_duplicate) 3734 << TheCall->getArg(ArgNum)->getSourceRange(); 3735 ArgValues.set(ArgExtValue); 3736 } 3737 return false; 3738 } 3739 3740 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3741 ArrayRef<int> ArgNums) { 3742 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3743 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3744 } 3745 3746 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3747 switch (BuiltinID) { 3748 default: 3749 return false; 3750 case X86::BI__builtin_ia32_tileloadd64: 3751 case X86::BI__builtin_ia32_tileloaddt164: 3752 case X86::BI__builtin_ia32_tilestored64: 3753 case X86::BI__builtin_ia32_tilezero: 3754 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3755 case X86::BI__builtin_ia32_tdpbssd: 3756 case X86::BI__builtin_ia32_tdpbsud: 3757 case X86::BI__builtin_ia32_tdpbusd: 3758 case X86::BI__builtin_ia32_tdpbuud: 3759 case X86::BI__builtin_ia32_tdpbf16ps: 3760 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3761 } 3762 } 3763 static bool isX86_32Builtin(unsigned BuiltinID) { 3764 // These builtins only work on x86-32 targets. 3765 switch (BuiltinID) { 3766 case X86::BI__builtin_ia32_readeflags_u32: 3767 case X86::BI__builtin_ia32_writeeflags_u32: 3768 return true; 3769 } 3770 3771 return false; 3772 } 3773 3774 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3775 CallExpr *TheCall) { 3776 if (BuiltinID == X86::BI__builtin_cpu_supports) 3777 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3778 3779 if (BuiltinID == X86::BI__builtin_cpu_is) 3780 return SemaBuiltinCpuIs(*this, TI, TheCall); 3781 3782 // Check for 32-bit only builtins on a 64-bit target. 3783 const llvm::Triple &TT = TI.getTriple(); 3784 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3785 return Diag(TheCall->getCallee()->getBeginLoc(), 3786 diag::err_32_bit_builtin_64_bit_tgt); 3787 3788 // If the intrinsic has rounding or SAE make sure its valid. 3789 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3790 return true; 3791 3792 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3793 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3794 return true; 3795 3796 // If the intrinsic has a tile arguments, make sure they are valid. 3797 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3798 return true; 3799 3800 // For intrinsics which take an immediate value as part of the instruction, 3801 // range check them here. 3802 int i = 0, l = 0, u = 0; 3803 switch (BuiltinID) { 3804 default: 3805 return false; 3806 case X86::BI__builtin_ia32_vec_ext_v2si: 3807 case X86::BI__builtin_ia32_vec_ext_v2di: 3808 case X86::BI__builtin_ia32_vextractf128_pd256: 3809 case X86::BI__builtin_ia32_vextractf128_ps256: 3810 case X86::BI__builtin_ia32_vextractf128_si256: 3811 case X86::BI__builtin_ia32_extract128i256: 3812 case X86::BI__builtin_ia32_extractf64x4_mask: 3813 case X86::BI__builtin_ia32_extracti64x4_mask: 3814 case X86::BI__builtin_ia32_extractf32x8_mask: 3815 case X86::BI__builtin_ia32_extracti32x8_mask: 3816 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3817 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3818 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3819 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3820 i = 1; l = 0; u = 1; 3821 break; 3822 case X86::BI__builtin_ia32_vec_set_v2di: 3823 case X86::BI__builtin_ia32_vinsertf128_pd256: 3824 case X86::BI__builtin_ia32_vinsertf128_ps256: 3825 case X86::BI__builtin_ia32_vinsertf128_si256: 3826 case X86::BI__builtin_ia32_insert128i256: 3827 case X86::BI__builtin_ia32_insertf32x8: 3828 case X86::BI__builtin_ia32_inserti32x8: 3829 case X86::BI__builtin_ia32_insertf64x4: 3830 case X86::BI__builtin_ia32_inserti64x4: 3831 case X86::BI__builtin_ia32_insertf64x2_256: 3832 case X86::BI__builtin_ia32_inserti64x2_256: 3833 case X86::BI__builtin_ia32_insertf32x4_256: 3834 case X86::BI__builtin_ia32_inserti32x4_256: 3835 i = 2; l = 0; u = 1; 3836 break; 3837 case X86::BI__builtin_ia32_vpermilpd: 3838 case X86::BI__builtin_ia32_vec_ext_v4hi: 3839 case X86::BI__builtin_ia32_vec_ext_v4si: 3840 case X86::BI__builtin_ia32_vec_ext_v4sf: 3841 case X86::BI__builtin_ia32_vec_ext_v4di: 3842 case X86::BI__builtin_ia32_extractf32x4_mask: 3843 case X86::BI__builtin_ia32_extracti32x4_mask: 3844 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3845 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3846 i = 1; l = 0; u = 3; 3847 break; 3848 case X86::BI_mm_prefetch: 3849 case X86::BI__builtin_ia32_vec_ext_v8hi: 3850 case X86::BI__builtin_ia32_vec_ext_v8si: 3851 i = 1; l = 0; u = 7; 3852 break; 3853 case X86::BI__builtin_ia32_sha1rnds4: 3854 case X86::BI__builtin_ia32_blendpd: 3855 case X86::BI__builtin_ia32_shufpd: 3856 case X86::BI__builtin_ia32_vec_set_v4hi: 3857 case X86::BI__builtin_ia32_vec_set_v4si: 3858 case X86::BI__builtin_ia32_vec_set_v4di: 3859 case X86::BI__builtin_ia32_shuf_f32x4_256: 3860 case X86::BI__builtin_ia32_shuf_f64x2_256: 3861 case X86::BI__builtin_ia32_shuf_i32x4_256: 3862 case X86::BI__builtin_ia32_shuf_i64x2_256: 3863 case X86::BI__builtin_ia32_insertf64x2_512: 3864 case X86::BI__builtin_ia32_inserti64x2_512: 3865 case X86::BI__builtin_ia32_insertf32x4: 3866 case X86::BI__builtin_ia32_inserti32x4: 3867 i = 2; l = 0; u = 3; 3868 break; 3869 case X86::BI__builtin_ia32_vpermil2pd: 3870 case X86::BI__builtin_ia32_vpermil2pd256: 3871 case X86::BI__builtin_ia32_vpermil2ps: 3872 case X86::BI__builtin_ia32_vpermil2ps256: 3873 i = 3; l = 0; u = 3; 3874 break; 3875 case X86::BI__builtin_ia32_cmpb128_mask: 3876 case X86::BI__builtin_ia32_cmpw128_mask: 3877 case X86::BI__builtin_ia32_cmpd128_mask: 3878 case X86::BI__builtin_ia32_cmpq128_mask: 3879 case X86::BI__builtin_ia32_cmpb256_mask: 3880 case X86::BI__builtin_ia32_cmpw256_mask: 3881 case X86::BI__builtin_ia32_cmpd256_mask: 3882 case X86::BI__builtin_ia32_cmpq256_mask: 3883 case X86::BI__builtin_ia32_cmpb512_mask: 3884 case X86::BI__builtin_ia32_cmpw512_mask: 3885 case X86::BI__builtin_ia32_cmpd512_mask: 3886 case X86::BI__builtin_ia32_cmpq512_mask: 3887 case X86::BI__builtin_ia32_ucmpb128_mask: 3888 case X86::BI__builtin_ia32_ucmpw128_mask: 3889 case X86::BI__builtin_ia32_ucmpd128_mask: 3890 case X86::BI__builtin_ia32_ucmpq128_mask: 3891 case X86::BI__builtin_ia32_ucmpb256_mask: 3892 case X86::BI__builtin_ia32_ucmpw256_mask: 3893 case X86::BI__builtin_ia32_ucmpd256_mask: 3894 case X86::BI__builtin_ia32_ucmpq256_mask: 3895 case X86::BI__builtin_ia32_ucmpb512_mask: 3896 case X86::BI__builtin_ia32_ucmpw512_mask: 3897 case X86::BI__builtin_ia32_ucmpd512_mask: 3898 case X86::BI__builtin_ia32_ucmpq512_mask: 3899 case X86::BI__builtin_ia32_vpcomub: 3900 case X86::BI__builtin_ia32_vpcomuw: 3901 case X86::BI__builtin_ia32_vpcomud: 3902 case X86::BI__builtin_ia32_vpcomuq: 3903 case X86::BI__builtin_ia32_vpcomb: 3904 case X86::BI__builtin_ia32_vpcomw: 3905 case X86::BI__builtin_ia32_vpcomd: 3906 case X86::BI__builtin_ia32_vpcomq: 3907 case X86::BI__builtin_ia32_vec_set_v8hi: 3908 case X86::BI__builtin_ia32_vec_set_v8si: 3909 i = 2; l = 0; u = 7; 3910 break; 3911 case X86::BI__builtin_ia32_vpermilpd256: 3912 case X86::BI__builtin_ia32_roundps: 3913 case X86::BI__builtin_ia32_roundpd: 3914 case X86::BI__builtin_ia32_roundps256: 3915 case X86::BI__builtin_ia32_roundpd256: 3916 case X86::BI__builtin_ia32_getmantpd128_mask: 3917 case X86::BI__builtin_ia32_getmantpd256_mask: 3918 case X86::BI__builtin_ia32_getmantps128_mask: 3919 case X86::BI__builtin_ia32_getmantps256_mask: 3920 case X86::BI__builtin_ia32_getmantpd512_mask: 3921 case X86::BI__builtin_ia32_getmantps512_mask: 3922 case X86::BI__builtin_ia32_vec_ext_v16qi: 3923 case X86::BI__builtin_ia32_vec_ext_v16hi: 3924 i = 1; l = 0; u = 15; 3925 break; 3926 case X86::BI__builtin_ia32_pblendd128: 3927 case X86::BI__builtin_ia32_blendps: 3928 case X86::BI__builtin_ia32_blendpd256: 3929 case X86::BI__builtin_ia32_shufpd256: 3930 case X86::BI__builtin_ia32_roundss: 3931 case X86::BI__builtin_ia32_roundsd: 3932 case X86::BI__builtin_ia32_rangepd128_mask: 3933 case X86::BI__builtin_ia32_rangepd256_mask: 3934 case X86::BI__builtin_ia32_rangepd512_mask: 3935 case X86::BI__builtin_ia32_rangeps128_mask: 3936 case X86::BI__builtin_ia32_rangeps256_mask: 3937 case X86::BI__builtin_ia32_rangeps512_mask: 3938 case X86::BI__builtin_ia32_getmantsd_round_mask: 3939 case X86::BI__builtin_ia32_getmantss_round_mask: 3940 case X86::BI__builtin_ia32_vec_set_v16qi: 3941 case X86::BI__builtin_ia32_vec_set_v16hi: 3942 i = 2; l = 0; u = 15; 3943 break; 3944 case X86::BI__builtin_ia32_vec_ext_v32qi: 3945 i = 1; l = 0; u = 31; 3946 break; 3947 case X86::BI__builtin_ia32_cmpps: 3948 case X86::BI__builtin_ia32_cmpss: 3949 case X86::BI__builtin_ia32_cmppd: 3950 case X86::BI__builtin_ia32_cmpsd: 3951 case X86::BI__builtin_ia32_cmpps256: 3952 case X86::BI__builtin_ia32_cmppd256: 3953 case X86::BI__builtin_ia32_cmpps128_mask: 3954 case X86::BI__builtin_ia32_cmppd128_mask: 3955 case X86::BI__builtin_ia32_cmpps256_mask: 3956 case X86::BI__builtin_ia32_cmppd256_mask: 3957 case X86::BI__builtin_ia32_cmpps512_mask: 3958 case X86::BI__builtin_ia32_cmppd512_mask: 3959 case X86::BI__builtin_ia32_cmpsd_mask: 3960 case X86::BI__builtin_ia32_cmpss_mask: 3961 case X86::BI__builtin_ia32_vec_set_v32qi: 3962 i = 2; l = 0; u = 31; 3963 break; 3964 case X86::BI__builtin_ia32_permdf256: 3965 case X86::BI__builtin_ia32_permdi256: 3966 case X86::BI__builtin_ia32_permdf512: 3967 case X86::BI__builtin_ia32_permdi512: 3968 case X86::BI__builtin_ia32_vpermilps: 3969 case X86::BI__builtin_ia32_vpermilps256: 3970 case X86::BI__builtin_ia32_vpermilpd512: 3971 case X86::BI__builtin_ia32_vpermilps512: 3972 case X86::BI__builtin_ia32_pshufd: 3973 case X86::BI__builtin_ia32_pshufd256: 3974 case X86::BI__builtin_ia32_pshufd512: 3975 case X86::BI__builtin_ia32_pshufhw: 3976 case X86::BI__builtin_ia32_pshufhw256: 3977 case X86::BI__builtin_ia32_pshufhw512: 3978 case X86::BI__builtin_ia32_pshuflw: 3979 case X86::BI__builtin_ia32_pshuflw256: 3980 case X86::BI__builtin_ia32_pshuflw512: 3981 case X86::BI__builtin_ia32_vcvtps2ph: 3982 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3983 case X86::BI__builtin_ia32_vcvtps2ph256: 3984 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3985 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3986 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3987 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3988 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3989 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3990 case X86::BI__builtin_ia32_rndscaleps_mask: 3991 case X86::BI__builtin_ia32_rndscalepd_mask: 3992 case X86::BI__builtin_ia32_reducepd128_mask: 3993 case X86::BI__builtin_ia32_reducepd256_mask: 3994 case X86::BI__builtin_ia32_reducepd512_mask: 3995 case X86::BI__builtin_ia32_reduceps128_mask: 3996 case X86::BI__builtin_ia32_reduceps256_mask: 3997 case X86::BI__builtin_ia32_reduceps512_mask: 3998 case X86::BI__builtin_ia32_prold512: 3999 case X86::BI__builtin_ia32_prolq512: 4000 case X86::BI__builtin_ia32_prold128: 4001 case X86::BI__builtin_ia32_prold256: 4002 case X86::BI__builtin_ia32_prolq128: 4003 case X86::BI__builtin_ia32_prolq256: 4004 case X86::BI__builtin_ia32_prord512: 4005 case X86::BI__builtin_ia32_prorq512: 4006 case X86::BI__builtin_ia32_prord128: 4007 case X86::BI__builtin_ia32_prord256: 4008 case X86::BI__builtin_ia32_prorq128: 4009 case X86::BI__builtin_ia32_prorq256: 4010 case X86::BI__builtin_ia32_fpclasspd128_mask: 4011 case X86::BI__builtin_ia32_fpclasspd256_mask: 4012 case X86::BI__builtin_ia32_fpclassps128_mask: 4013 case X86::BI__builtin_ia32_fpclassps256_mask: 4014 case X86::BI__builtin_ia32_fpclassps512_mask: 4015 case X86::BI__builtin_ia32_fpclasspd512_mask: 4016 case X86::BI__builtin_ia32_fpclasssd_mask: 4017 case X86::BI__builtin_ia32_fpclassss_mask: 4018 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4019 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4020 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4021 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4022 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4023 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4024 case X86::BI__builtin_ia32_kshiftliqi: 4025 case X86::BI__builtin_ia32_kshiftlihi: 4026 case X86::BI__builtin_ia32_kshiftlisi: 4027 case X86::BI__builtin_ia32_kshiftlidi: 4028 case X86::BI__builtin_ia32_kshiftriqi: 4029 case X86::BI__builtin_ia32_kshiftrihi: 4030 case X86::BI__builtin_ia32_kshiftrisi: 4031 case X86::BI__builtin_ia32_kshiftridi: 4032 i = 1; l = 0; u = 255; 4033 break; 4034 case X86::BI__builtin_ia32_vperm2f128_pd256: 4035 case X86::BI__builtin_ia32_vperm2f128_ps256: 4036 case X86::BI__builtin_ia32_vperm2f128_si256: 4037 case X86::BI__builtin_ia32_permti256: 4038 case X86::BI__builtin_ia32_pblendw128: 4039 case X86::BI__builtin_ia32_pblendw256: 4040 case X86::BI__builtin_ia32_blendps256: 4041 case X86::BI__builtin_ia32_pblendd256: 4042 case X86::BI__builtin_ia32_palignr128: 4043 case X86::BI__builtin_ia32_palignr256: 4044 case X86::BI__builtin_ia32_palignr512: 4045 case X86::BI__builtin_ia32_alignq512: 4046 case X86::BI__builtin_ia32_alignd512: 4047 case X86::BI__builtin_ia32_alignd128: 4048 case X86::BI__builtin_ia32_alignd256: 4049 case X86::BI__builtin_ia32_alignq128: 4050 case X86::BI__builtin_ia32_alignq256: 4051 case X86::BI__builtin_ia32_vcomisd: 4052 case X86::BI__builtin_ia32_vcomiss: 4053 case X86::BI__builtin_ia32_shuf_f32x4: 4054 case X86::BI__builtin_ia32_shuf_f64x2: 4055 case X86::BI__builtin_ia32_shuf_i32x4: 4056 case X86::BI__builtin_ia32_shuf_i64x2: 4057 case X86::BI__builtin_ia32_shufpd512: 4058 case X86::BI__builtin_ia32_shufps: 4059 case X86::BI__builtin_ia32_shufps256: 4060 case X86::BI__builtin_ia32_shufps512: 4061 case X86::BI__builtin_ia32_dbpsadbw128: 4062 case X86::BI__builtin_ia32_dbpsadbw256: 4063 case X86::BI__builtin_ia32_dbpsadbw512: 4064 case X86::BI__builtin_ia32_vpshldd128: 4065 case X86::BI__builtin_ia32_vpshldd256: 4066 case X86::BI__builtin_ia32_vpshldd512: 4067 case X86::BI__builtin_ia32_vpshldq128: 4068 case X86::BI__builtin_ia32_vpshldq256: 4069 case X86::BI__builtin_ia32_vpshldq512: 4070 case X86::BI__builtin_ia32_vpshldw128: 4071 case X86::BI__builtin_ia32_vpshldw256: 4072 case X86::BI__builtin_ia32_vpshldw512: 4073 case X86::BI__builtin_ia32_vpshrdd128: 4074 case X86::BI__builtin_ia32_vpshrdd256: 4075 case X86::BI__builtin_ia32_vpshrdd512: 4076 case X86::BI__builtin_ia32_vpshrdq128: 4077 case X86::BI__builtin_ia32_vpshrdq256: 4078 case X86::BI__builtin_ia32_vpshrdq512: 4079 case X86::BI__builtin_ia32_vpshrdw128: 4080 case X86::BI__builtin_ia32_vpshrdw256: 4081 case X86::BI__builtin_ia32_vpshrdw512: 4082 i = 2; l = 0; u = 255; 4083 break; 4084 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4085 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4086 case X86::BI__builtin_ia32_fixupimmps512_mask: 4087 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4088 case X86::BI__builtin_ia32_fixupimmsd_mask: 4089 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4090 case X86::BI__builtin_ia32_fixupimmss_mask: 4091 case X86::BI__builtin_ia32_fixupimmss_maskz: 4092 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4093 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4094 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4095 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4096 case X86::BI__builtin_ia32_fixupimmps128_mask: 4097 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4098 case X86::BI__builtin_ia32_fixupimmps256_mask: 4099 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4100 case X86::BI__builtin_ia32_pternlogd512_mask: 4101 case X86::BI__builtin_ia32_pternlogd512_maskz: 4102 case X86::BI__builtin_ia32_pternlogq512_mask: 4103 case X86::BI__builtin_ia32_pternlogq512_maskz: 4104 case X86::BI__builtin_ia32_pternlogd128_mask: 4105 case X86::BI__builtin_ia32_pternlogd128_maskz: 4106 case X86::BI__builtin_ia32_pternlogd256_mask: 4107 case X86::BI__builtin_ia32_pternlogd256_maskz: 4108 case X86::BI__builtin_ia32_pternlogq128_mask: 4109 case X86::BI__builtin_ia32_pternlogq128_maskz: 4110 case X86::BI__builtin_ia32_pternlogq256_mask: 4111 case X86::BI__builtin_ia32_pternlogq256_maskz: 4112 i = 3; l = 0; u = 255; 4113 break; 4114 case X86::BI__builtin_ia32_gatherpfdpd: 4115 case X86::BI__builtin_ia32_gatherpfdps: 4116 case X86::BI__builtin_ia32_gatherpfqpd: 4117 case X86::BI__builtin_ia32_gatherpfqps: 4118 case X86::BI__builtin_ia32_scatterpfdpd: 4119 case X86::BI__builtin_ia32_scatterpfdps: 4120 case X86::BI__builtin_ia32_scatterpfqpd: 4121 case X86::BI__builtin_ia32_scatterpfqps: 4122 i = 4; l = 2; u = 3; 4123 break; 4124 case X86::BI__builtin_ia32_reducesd_mask: 4125 case X86::BI__builtin_ia32_reducess_mask: 4126 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4127 case X86::BI__builtin_ia32_rndscaless_round_mask: 4128 i = 4; l = 0; u = 255; 4129 break; 4130 } 4131 4132 // Note that we don't force a hard error on the range check here, allowing 4133 // template-generated or macro-generated dead code to potentially have out-of- 4134 // range values. These need to code generate, but don't need to necessarily 4135 // make any sense. We use a warning that defaults to an error. 4136 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4137 } 4138 4139 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4140 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4141 /// Returns true when the format fits the function and the FormatStringInfo has 4142 /// been populated. 4143 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4144 FormatStringInfo *FSI) { 4145 FSI->HasVAListArg = Format->getFirstArg() == 0; 4146 FSI->FormatIdx = Format->getFormatIdx() - 1; 4147 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4148 4149 // The way the format attribute works in GCC, the implicit this argument 4150 // of member functions is counted. However, it doesn't appear in our own 4151 // lists, so decrement format_idx in that case. 4152 if (IsCXXMember) { 4153 if(FSI->FormatIdx == 0) 4154 return false; 4155 --FSI->FormatIdx; 4156 if (FSI->FirstDataArg != 0) 4157 --FSI->FirstDataArg; 4158 } 4159 return true; 4160 } 4161 4162 /// Checks if a the given expression evaluates to null. 4163 /// 4164 /// Returns true if the value evaluates to null. 4165 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4166 // If the expression has non-null type, it doesn't evaluate to null. 4167 if (auto nullability 4168 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4169 if (*nullability == NullabilityKind::NonNull) 4170 return false; 4171 } 4172 4173 // As a special case, transparent unions initialized with zero are 4174 // considered null for the purposes of the nonnull attribute. 4175 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4176 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4177 if (const CompoundLiteralExpr *CLE = 4178 dyn_cast<CompoundLiteralExpr>(Expr)) 4179 if (const InitListExpr *ILE = 4180 dyn_cast<InitListExpr>(CLE->getInitializer())) 4181 Expr = ILE->getInit(0); 4182 } 4183 4184 bool Result; 4185 return (!Expr->isValueDependent() && 4186 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4187 !Result); 4188 } 4189 4190 static void CheckNonNullArgument(Sema &S, 4191 const Expr *ArgExpr, 4192 SourceLocation CallSiteLoc) { 4193 if (CheckNonNullExpr(S, ArgExpr)) 4194 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4195 S.PDiag(diag::warn_null_arg) 4196 << ArgExpr->getSourceRange()); 4197 } 4198 4199 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4200 FormatStringInfo FSI; 4201 if ((GetFormatStringType(Format) == FST_NSString) && 4202 getFormatStringInfo(Format, false, &FSI)) { 4203 Idx = FSI.FormatIdx; 4204 return true; 4205 } 4206 return false; 4207 } 4208 4209 /// Diagnose use of %s directive in an NSString which is being passed 4210 /// as formatting string to formatting method. 4211 static void 4212 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4213 const NamedDecl *FDecl, 4214 Expr **Args, 4215 unsigned NumArgs) { 4216 unsigned Idx = 0; 4217 bool Format = false; 4218 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4219 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4220 Idx = 2; 4221 Format = true; 4222 } 4223 else 4224 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4225 if (S.GetFormatNSStringIdx(I, Idx)) { 4226 Format = true; 4227 break; 4228 } 4229 } 4230 if (!Format || NumArgs <= Idx) 4231 return; 4232 const Expr *FormatExpr = Args[Idx]; 4233 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4234 FormatExpr = CSCE->getSubExpr(); 4235 const StringLiteral *FormatString; 4236 if (const ObjCStringLiteral *OSL = 4237 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4238 FormatString = OSL->getString(); 4239 else 4240 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4241 if (!FormatString) 4242 return; 4243 if (S.FormatStringHasSArg(FormatString)) { 4244 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4245 << "%s" << 1 << 1; 4246 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4247 << FDecl->getDeclName(); 4248 } 4249 } 4250 4251 /// Determine whether the given type has a non-null nullability annotation. 4252 static bool isNonNullType(ASTContext &ctx, QualType type) { 4253 if (auto nullability = type->getNullability(ctx)) 4254 return *nullability == NullabilityKind::NonNull; 4255 4256 return false; 4257 } 4258 4259 static void CheckNonNullArguments(Sema &S, 4260 const NamedDecl *FDecl, 4261 const FunctionProtoType *Proto, 4262 ArrayRef<const Expr *> Args, 4263 SourceLocation CallSiteLoc) { 4264 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4265 4266 // Already checked by by constant evaluator. 4267 if (S.isConstantEvaluated()) 4268 return; 4269 // Check the attributes attached to the method/function itself. 4270 llvm::SmallBitVector NonNullArgs; 4271 if (FDecl) { 4272 // Handle the nonnull attribute on the function/method declaration itself. 4273 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4274 if (!NonNull->args_size()) { 4275 // Easy case: all pointer arguments are nonnull. 4276 for (const auto *Arg : Args) 4277 if (S.isValidPointerAttrType(Arg->getType())) 4278 CheckNonNullArgument(S, Arg, CallSiteLoc); 4279 return; 4280 } 4281 4282 for (const ParamIdx &Idx : NonNull->args()) { 4283 unsigned IdxAST = Idx.getASTIndex(); 4284 if (IdxAST >= Args.size()) 4285 continue; 4286 if (NonNullArgs.empty()) 4287 NonNullArgs.resize(Args.size()); 4288 NonNullArgs.set(IdxAST); 4289 } 4290 } 4291 } 4292 4293 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4294 // Handle the nonnull attribute on the parameters of the 4295 // function/method. 4296 ArrayRef<ParmVarDecl*> parms; 4297 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4298 parms = FD->parameters(); 4299 else 4300 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4301 4302 unsigned ParamIndex = 0; 4303 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4304 I != E; ++I, ++ParamIndex) { 4305 const ParmVarDecl *PVD = *I; 4306 if (PVD->hasAttr<NonNullAttr>() || 4307 isNonNullType(S.Context, PVD->getType())) { 4308 if (NonNullArgs.empty()) 4309 NonNullArgs.resize(Args.size()); 4310 4311 NonNullArgs.set(ParamIndex); 4312 } 4313 } 4314 } else { 4315 // If we have a non-function, non-method declaration but no 4316 // function prototype, try to dig out the function prototype. 4317 if (!Proto) { 4318 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4319 QualType type = VD->getType().getNonReferenceType(); 4320 if (auto pointerType = type->getAs<PointerType>()) 4321 type = pointerType->getPointeeType(); 4322 else if (auto blockType = type->getAs<BlockPointerType>()) 4323 type = blockType->getPointeeType(); 4324 // FIXME: data member pointers? 4325 4326 // Dig out the function prototype, if there is one. 4327 Proto = type->getAs<FunctionProtoType>(); 4328 } 4329 } 4330 4331 // Fill in non-null argument information from the nullability 4332 // information on the parameter types (if we have them). 4333 if (Proto) { 4334 unsigned Index = 0; 4335 for (auto paramType : Proto->getParamTypes()) { 4336 if (isNonNullType(S.Context, paramType)) { 4337 if (NonNullArgs.empty()) 4338 NonNullArgs.resize(Args.size()); 4339 4340 NonNullArgs.set(Index); 4341 } 4342 4343 ++Index; 4344 } 4345 } 4346 } 4347 4348 // Check for non-null arguments. 4349 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4350 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4351 if (NonNullArgs[ArgIndex]) 4352 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4353 } 4354 } 4355 4356 /// Handles the checks for format strings, non-POD arguments to vararg 4357 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4358 /// attributes. 4359 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4360 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4361 bool IsMemberFunction, SourceLocation Loc, 4362 SourceRange Range, VariadicCallType CallType) { 4363 // FIXME: We should check as much as we can in the template definition. 4364 if (CurContext->isDependentContext()) 4365 return; 4366 4367 // Printf and scanf checking. 4368 llvm::SmallBitVector CheckedVarArgs; 4369 if (FDecl) { 4370 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4371 // Only create vector if there are format attributes. 4372 CheckedVarArgs.resize(Args.size()); 4373 4374 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4375 CheckedVarArgs); 4376 } 4377 } 4378 4379 // Refuse POD arguments that weren't caught by the format string 4380 // checks above. 4381 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4382 if (CallType != VariadicDoesNotApply && 4383 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4384 unsigned NumParams = Proto ? Proto->getNumParams() 4385 : FDecl && isa<FunctionDecl>(FDecl) 4386 ? cast<FunctionDecl>(FDecl)->getNumParams() 4387 : FDecl && isa<ObjCMethodDecl>(FDecl) 4388 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4389 : 0; 4390 4391 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4392 // Args[ArgIdx] can be null in malformed code. 4393 if (const Expr *Arg = Args[ArgIdx]) { 4394 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4395 checkVariadicArgument(Arg, CallType); 4396 } 4397 } 4398 } 4399 4400 if (FDecl || Proto) { 4401 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4402 4403 // Type safety checking. 4404 if (FDecl) { 4405 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4406 CheckArgumentWithTypeTag(I, Args, Loc); 4407 } 4408 } 4409 4410 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4411 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4412 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4413 if (!Arg->isValueDependent()) { 4414 Expr::EvalResult Align; 4415 if (Arg->EvaluateAsInt(Align, Context)) { 4416 const llvm::APSInt &I = Align.Val.getInt(); 4417 if (!I.isPowerOf2()) 4418 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4419 << Arg->getSourceRange(); 4420 4421 if (I > Sema::MaximumAlignment) 4422 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4423 << Arg->getSourceRange() << Sema::MaximumAlignment; 4424 } 4425 } 4426 } 4427 4428 if (FD) 4429 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4430 } 4431 4432 /// CheckConstructorCall - Check a constructor call for correctness and safety 4433 /// properties not enforced by the C type system. 4434 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4435 ArrayRef<const Expr *> Args, 4436 const FunctionProtoType *Proto, 4437 SourceLocation Loc) { 4438 VariadicCallType CallType = 4439 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4440 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4441 Loc, SourceRange(), CallType); 4442 } 4443 4444 /// CheckFunctionCall - Check a direct function call for various correctness 4445 /// and safety properties not strictly enforced by the C type system. 4446 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4447 const FunctionProtoType *Proto) { 4448 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4449 isa<CXXMethodDecl>(FDecl); 4450 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4451 IsMemberOperatorCall; 4452 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4453 TheCall->getCallee()); 4454 Expr** Args = TheCall->getArgs(); 4455 unsigned NumArgs = TheCall->getNumArgs(); 4456 4457 Expr *ImplicitThis = nullptr; 4458 if (IsMemberOperatorCall) { 4459 // If this is a call to a member operator, hide the first argument 4460 // from checkCall. 4461 // FIXME: Our choice of AST representation here is less than ideal. 4462 ImplicitThis = Args[0]; 4463 ++Args; 4464 --NumArgs; 4465 } else if (IsMemberFunction) 4466 ImplicitThis = 4467 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4468 4469 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4470 IsMemberFunction, TheCall->getRParenLoc(), 4471 TheCall->getCallee()->getSourceRange(), CallType); 4472 4473 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4474 // None of the checks below are needed for functions that don't have 4475 // simple names (e.g., C++ conversion functions). 4476 if (!FnInfo) 4477 return false; 4478 4479 CheckAbsoluteValueFunction(TheCall, FDecl); 4480 CheckMaxUnsignedZero(TheCall, FDecl); 4481 4482 if (getLangOpts().ObjC) 4483 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4484 4485 unsigned CMId = FDecl->getMemoryFunctionKind(); 4486 if (CMId == 0) 4487 return false; 4488 4489 // Handle memory setting and copying functions. 4490 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4491 CheckStrlcpycatArguments(TheCall, FnInfo); 4492 else if (CMId == Builtin::BIstrncat) 4493 CheckStrncatArguments(TheCall, FnInfo); 4494 else 4495 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4496 4497 return false; 4498 } 4499 4500 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4501 ArrayRef<const Expr *> Args) { 4502 VariadicCallType CallType = 4503 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4504 4505 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4506 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4507 CallType); 4508 4509 return false; 4510 } 4511 4512 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4513 const FunctionProtoType *Proto) { 4514 QualType Ty; 4515 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4516 Ty = V->getType().getNonReferenceType(); 4517 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4518 Ty = F->getType().getNonReferenceType(); 4519 else 4520 return false; 4521 4522 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4523 !Ty->isFunctionProtoType()) 4524 return false; 4525 4526 VariadicCallType CallType; 4527 if (!Proto || !Proto->isVariadic()) { 4528 CallType = VariadicDoesNotApply; 4529 } else if (Ty->isBlockPointerType()) { 4530 CallType = VariadicBlock; 4531 } else { // Ty->isFunctionPointerType() 4532 CallType = VariadicFunction; 4533 } 4534 4535 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4536 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4537 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4538 TheCall->getCallee()->getSourceRange(), CallType); 4539 4540 return false; 4541 } 4542 4543 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4544 /// such as function pointers returned from functions. 4545 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4546 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4547 TheCall->getCallee()); 4548 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4549 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4550 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4551 TheCall->getCallee()->getSourceRange(), CallType); 4552 4553 return false; 4554 } 4555 4556 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4557 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4558 return false; 4559 4560 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4561 switch (Op) { 4562 case AtomicExpr::AO__c11_atomic_init: 4563 case AtomicExpr::AO__opencl_atomic_init: 4564 llvm_unreachable("There is no ordering argument for an init"); 4565 4566 case AtomicExpr::AO__c11_atomic_load: 4567 case AtomicExpr::AO__opencl_atomic_load: 4568 case AtomicExpr::AO__atomic_load_n: 4569 case AtomicExpr::AO__atomic_load: 4570 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4571 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4572 4573 case AtomicExpr::AO__c11_atomic_store: 4574 case AtomicExpr::AO__opencl_atomic_store: 4575 case AtomicExpr::AO__atomic_store: 4576 case AtomicExpr::AO__atomic_store_n: 4577 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4578 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4579 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4580 4581 default: 4582 return true; 4583 } 4584 } 4585 4586 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4587 AtomicExpr::AtomicOp Op) { 4588 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4589 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4590 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4591 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4592 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4593 Op); 4594 } 4595 4596 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4597 SourceLocation RParenLoc, MultiExprArg Args, 4598 AtomicExpr::AtomicOp Op, 4599 AtomicArgumentOrder ArgOrder) { 4600 // All the non-OpenCL operations take one of the following forms. 4601 // The OpenCL operations take the __c11 forms with one extra argument for 4602 // synchronization scope. 4603 enum { 4604 // C __c11_atomic_init(A *, C) 4605 Init, 4606 4607 // C __c11_atomic_load(A *, int) 4608 Load, 4609 4610 // void __atomic_load(A *, CP, int) 4611 LoadCopy, 4612 4613 // void __atomic_store(A *, CP, int) 4614 Copy, 4615 4616 // C __c11_atomic_add(A *, M, int) 4617 Arithmetic, 4618 4619 // C __atomic_exchange_n(A *, CP, int) 4620 Xchg, 4621 4622 // void __atomic_exchange(A *, C *, CP, int) 4623 GNUXchg, 4624 4625 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4626 C11CmpXchg, 4627 4628 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4629 GNUCmpXchg 4630 } Form = Init; 4631 4632 const unsigned NumForm = GNUCmpXchg + 1; 4633 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4634 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4635 // where: 4636 // C is an appropriate type, 4637 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4638 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4639 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4640 // the int parameters are for orderings. 4641 4642 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4643 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4644 "need to update code for modified forms"); 4645 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4646 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4647 AtomicExpr::AO__atomic_load, 4648 "need to update code for modified C11 atomics"); 4649 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4650 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4651 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4652 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4653 IsOpenCL; 4654 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4655 Op == AtomicExpr::AO__atomic_store_n || 4656 Op == AtomicExpr::AO__atomic_exchange_n || 4657 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4658 bool IsAddSub = false; 4659 4660 switch (Op) { 4661 case AtomicExpr::AO__c11_atomic_init: 4662 case AtomicExpr::AO__opencl_atomic_init: 4663 Form = Init; 4664 break; 4665 4666 case AtomicExpr::AO__c11_atomic_load: 4667 case AtomicExpr::AO__opencl_atomic_load: 4668 case AtomicExpr::AO__atomic_load_n: 4669 Form = Load; 4670 break; 4671 4672 case AtomicExpr::AO__atomic_load: 4673 Form = LoadCopy; 4674 break; 4675 4676 case AtomicExpr::AO__c11_atomic_store: 4677 case AtomicExpr::AO__opencl_atomic_store: 4678 case AtomicExpr::AO__atomic_store: 4679 case AtomicExpr::AO__atomic_store_n: 4680 Form = Copy; 4681 break; 4682 4683 case AtomicExpr::AO__c11_atomic_fetch_add: 4684 case AtomicExpr::AO__c11_atomic_fetch_sub: 4685 case AtomicExpr::AO__opencl_atomic_fetch_add: 4686 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4687 case AtomicExpr::AO__atomic_fetch_add: 4688 case AtomicExpr::AO__atomic_fetch_sub: 4689 case AtomicExpr::AO__atomic_add_fetch: 4690 case AtomicExpr::AO__atomic_sub_fetch: 4691 IsAddSub = true; 4692 LLVM_FALLTHROUGH; 4693 case AtomicExpr::AO__c11_atomic_fetch_and: 4694 case AtomicExpr::AO__c11_atomic_fetch_or: 4695 case AtomicExpr::AO__c11_atomic_fetch_xor: 4696 case AtomicExpr::AO__opencl_atomic_fetch_and: 4697 case AtomicExpr::AO__opencl_atomic_fetch_or: 4698 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4699 case AtomicExpr::AO__atomic_fetch_and: 4700 case AtomicExpr::AO__atomic_fetch_or: 4701 case AtomicExpr::AO__atomic_fetch_xor: 4702 case AtomicExpr::AO__atomic_fetch_nand: 4703 case AtomicExpr::AO__atomic_and_fetch: 4704 case AtomicExpr::AO__atomic_or_fetch: 4705 case AtomicExpr::AO__atomic_xor_fetch: 4706 case AtomicExpr::AO__atomic_nand_fetch: 4707 case AtomicExpr::AO__c11_atomic_fetch_min: 4708 case AtomicExpr::AO__c11_atomic_fetch_max: 4709 case AtomicExpr::AO__opencl_atomic_fetch_min: 4710 case AtomicExpr::AO__opencl_atomic_fetch_max: 4711 case AtomicExpr::AO__atomic_min_fetch: 4712 case AtomicExpr::AO__atomic_max_fetch: 4713 case AtomicExpr::AO__atomic_fetch_min: 4714 case AtomicExpr::AO__atomic_fetch_max: 4715 Form = Arithmetic; 4716 break; 4717 4718 case AtomicExpr::AO__c11_atomic_exchange: 4719 case AtomicExpr::AO__opencl_atomic_exchange: 4720 case AtomicExpr::AO__atomic_exchange_n: 4721 Form = Xchg; 4722 break; 4723 4724 case AtomicExpr::AO__atomic_exchange: 4725 Form = GNUXchg; 4726 break; 4727 4728 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4729 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4730 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4731 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4732 Form = C11CmpXchg; 4733 break; 4734 4735 case AtomicExpr::AO__atomic_compare_exchange: 4736 case AtomicExpr::AO__atomic_compare_exchange_n: 4737 Form = GNUCmpXchg; 4738 break; 4739 } 4740 4741 unsigned AdjustedNumArgs = NumArgs[Form]; 4742 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4743 ++AdjustedNumArgs; 4744 // Check we have the right number of arguments. 4745 if (Args.size() < AdjustedNumArgs) { 4746 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4747 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4748 << ExprRange; 4749 return ExprError(); 4750 } else if (Args.size() > AdjustedNumArgs) { 4751 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4752 diag::err_typecheck_call_too_many_args) 4753 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4754 << ExprRange; 4755 return ExprError(); 4756 } 4757 4758 // Inspect the first argument of the atomic operation. 4759 Expr *Ptr = Args[0]; 4760 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4761 if (ConvertedPtr.isInvalid()) 4762 return ExprError(); 4763 4764 Ptr = ConvertedPtr.get(); 4765 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4766 if (!pointerType) { 4767 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4768 << Ptr->getType() << Ptr->getSourceRange(); 4769 return ExprError(); 4770 } 4771 4772 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4773 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4774 QualType ValType = AtomTy; // 'C' 4775 if (IsC11) { 4776 if (!AtomTy->isAtomicType()) { 4777 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4778 << Ptr->getType() << Ptr->getSourceRange(); 4779 return ExprError(); 4780 } 4781 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4782 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4783 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4784 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4785 << Ptr->getSourceRange(); 4786 return ExprError(); 4787 } 4788 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4789 } else if (Form != Load && Form != LoadCopy) { 4790 if (ValType.isConstQualified()) { 4791 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4792 << Ptr->getType() << Ptr->getSourceRange(); 4793 return ExprError(); 4794 } 4795 } 4796 4797 // For an arithmetic operation, the implied arithmetic must be well-formed. 4798 if (Form == Arithmetic) { 4799 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4800 if (IsAddSub && !ValType->isIntegerType() 4801 && !ValType->isPointerType()) { 4802 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4803 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4804 return ExprError(); 4805 } 4806 if (!IsAddSub && !ValType->isIntegerType()) { 4807 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4808 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4809 return ExprError(); 4810 } 4811 if (IsC11 && ValType->isPointerType() && 4812 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4813 diag::err_incomplete_type)) { 4814 return ExprError(); 4815 } 4816 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4817 // For __atomic_*_n operations, the value type must be a scalar integral or 4818 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4819 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4820 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4821 return ExprError(); 4822 } 4823 4824 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4825 !AtomTy->isScalarType()) { 4826 // For GNU atomics, require a trivially-copyable type. This is not part of 4827 // the GNU atomics specification, but we enforce it for sanity. 4828 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4829 << Ptr->getType() << Ptr->getSourceRange(); 4830 return ExprError(); 4831 } 4832 4833 switch (ValType.getObjCLifetime()) { 4834 case Qualifiers::OCL_None: 4835 case Qualifiers::OCL_ExplicitNone: 4836 // okay 4837 break; 4838 4839 case Qualifiers::OCL_Weak: 4840 case Qualifiers::OCL_Strong: 4841 case Qualifiers::OCL_Autoreleasing: 4842 // FIXME: Can this happen? By this point, ValType should be known 4843 // to be trivially copyable. 4844 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4845 << ValType << Ptr->getSourceRange(); 4846 return ExprError(); 4847 } 4848 4849 // All atomic operations have an overload which takes a pointer to a volatile 4850 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4851 // into the result or the other operands. Similarly atomic_load takes a 4852 // pointer to a const 'A'. 4853 ValType.removeLocalVolatile(); 4854 ValType.removeLocalConst(); 4855 QualType ResultType = ValType; 4856 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4857 Form == Init) 4858 ResultType = Context.VoidTy; 4859 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4860 ResultType = Context.BoolTy; 4861 4862 // The type of a parameter passed 'by value'. In the GNU atomics, such 4863 // arguments are actually passed as pointers. 4864 QualType ByValType = ValType; // 'CP' 4865 bool IsPassedByAddress = false; 4866 if (!IsC11 && !IsN) { 4867 ByValType = Ptr->getType(); 4868 IsPassedByAddress = true; 4869 } 4870 4871 SmallVector<Expr *, 5> APIOrderedArgs; 4872 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4873 APIOrderedArgs.push_back(Args[0]); 4874 switch (Form) { 4875 case Init: 4876 case Load: 4877 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4878 break; 4879 case LoadCopy: 4880 case Copy: 4881 case Arithmetic: 4882 case Xchg: 4883 APIOrderedArgs.push_back(Args[2]); // Val1 4884 APIOrderedArgs.push_back(Args[1]); // Order 4885 break; 4886 case GNUXchg: 4887 APIOrderedArgs.push_back(Args[2]); // Val1 4888 APIOrderedArgs.push_back(Args[3]); // Val2 4889 APIOrderedArgs.push_back(Args[1]); // Order 4890 break; 4891 case C11CmpXchg: 4892 APIOrderedArgs.push_back(Args[2]); // Val1 4893 APIOrderedArgs.push_back(Args[4]); // Val2 4894 APIOrderedArgs.push_back(Args[1]); // Order 4895 APIOrderedArgs.push_back(Args[3]); // OrderFail 4896 break; 4897 case GNUCmpXchg: 4898 APIOrderedArgs.push_back(Args[2]); // Val1 4899 APIOrderedArgs.push_back(Args[4]); // Val2 4900 APIOrderedArgs.push_back(Args[5]); // Weak 4901 APIOrderedArgs.push_back(Args[1]); // Order 4902 APIOrderedArgs.push_back(Args[3]); // OrderFail 4903 break; 4904 } 4905 } else 4906 APIOrderedArgs.append(Args.begin(), Args.end()); 4907 4908 // The first argument's non-CV pointer type is used to deduce the type of 4909 // subsequent arguments, except for: 4910 // - weak flag (always converted to bool) 4911 // - memory order (always converted to int) 4912 // - scope (always converted to int) 4913 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4914 QualType Ty; 4915 if (i < NumVals[Form] + 1) { 4916 switch (i) { 4917 case 0: 4918 // The first argument is always a pointer. It has a fixed type. 4919 // It is always dereferenced, a nullptr is undefined. 4920 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4921 // Nothing else to do: we already know all we want about this pointer. 4922 continue; 4923 case 1: 4924 // The second argument is the non-atomic operand. For arithmetic, this 4925 // is always passed by value, and for a compare_exchange it is always 4926 // passed by address. For the rest, GNU uses by-address and C11 uses 4927 // by-value. 4928 assert(Form != Load); 4929 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4930 Ty = ValType; 4931 else if (Form == Copy || Form == Xchg) { 4932 if (IsPassedByAddress) { 4933 // The value pointer is always dereferenced, a nullptr is undefined. 4934 CheckNonNullArgument(*this, APIOrderedArgs[i], 4935 ExprRange.getBegin()); 4936 } 4937 Ty = ByValType; 4938 } else if (Form == Arithmetic) 4939 Ty = Context.getPointerDiffType(); 4940 else { 4941 Expr *ValArg = APIOrderedArgs[i]; 4942 // The value pointer is always dereferenced, a nullptr is undefined. 4943 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4944 LangAS AS = LangAS::Default; 4945 // Keep address space of non-atomic pointer type. 4946 if (const PointerType *PtrTy = 4947 ValArg->getType()->getAs<PointerType>()) { 4948 AS = PtrTy->getPointeeType().getAddressSpace(); 4949 } 4950 Ty = Context.getPointerType( 4951 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4952 } 4953 break; 4954 case 2: 4955 // The third argument to compare_exchange / GNU exchange is the desired 4956 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4957 if (IsPassedByAddress) 4958 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4959 Ty = ByValType; 4960 break; 4961 case 3: 4962 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4963 Ty = Context.BoolTy; 4964 break; 4965 } 4966 } else { 4967 // The order(s) and scope are always converted to int. 4968 Ty = Context.IntTy; 4969 } 4970 4971 InitializedEntity Entity = 4972 InitializedEntity::InitializeParameter(Context, Ty, false); 4973 ExprResult Arg = APIOrderedArgs[i]; 4974 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4975 if (Arg.isInvalid()) 4976 return true; 4977 APIOrderedArgs[i] = Arg.get(); 4978 } 4979 4980 // Permute the arguments into a 'consistent' order. 4981 SmallVector<Expr*, 5> SubExprs; 4982 SubExprs.push_back(Ptr); 4983 switch (Form) { 4984 case Init: 4985 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4986 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4987 break; 4988 case Load: 4989 SubExprs.push_back(APIOrderedArgs[1]); // Order 4990 break; 4991 case LoadCopy: 4992 case Copy: 4993 case Arithmetic: 4994 case Xchg: 4995 SubExprs.push_back(APIOrderedArgs[2]); // Order 4996 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4997 break; 4998 case GNUXchg: 4999 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5000 SubExprs.push_back(APIOrderedArgs[3]); // Order 5001 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5002 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5003 break; 5004 case C11CmpXchg: 5005 SubExprs.push_back(APIOrderedArgs[3]); // Order 5006 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5007 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5008 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5009 break; 5010 case GNUCmpXchg: 5011 SubExprs.push_back(APIOrderedArgs[4]); // Order 5012 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5013 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5014 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5015 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5016 break; 5017 } 5018 5019 if (SubExprs.size() >= 2 && Form != Init) { 5020 if (Optional<llvm::APSInt> Result = 5021 SubExprs[1]->getIntegerConstantExpr(Context)) 5022 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5023 Diag(SubExprs[1]->getBeginLoc(), 5024 diag::warn_atomic_op_has_invalid_memory_order) 5025 << SubExprs[1]->getSourceRange(); 5026 } 5027 5028 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5029 auto *Scope = Args[Args.size() - 1]; 5030 if (Optional<llvm::APSInt> Result = 5031 Scope->getIntegerConstantExpr(Context)) { 5032 if (!ScopeModel->isValid(Result->getZExtValue())) 5033 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5034 << Scope->getSourceRange(); 5035 } 5036 SubExprs.push_back(Scope); 5037 } 5038 5039 AtomicExpr *AE = new (Context) 5040 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5041 5042 if ((Op == AtomicExpr::AO__c11_atomic_load || 5043 Op == AtomicExpr::AO__c11_atomic_store || 5044 Op == AtomicExpr::AO__opencl_atomic_load || 5045 Op == AtomicExpr::AO__opencl_atomic_store ) && 5046 Context.AtomicUsesUnsupportedLibcall(AE)) 5047 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5048 << ((Op == AtomicExpr::AO__c11_atomic_load || 5049 Op == AtomicExpr::AO__opencl_atomic_load) 5050 ? 0 5051 : 1); 5052 5053 return AE; 5054 } 5055 5056 /// checkBuiltinArgument - Given a call to a builtin function, perform 5057 /// normal type-checking on the given argument, updating the call in 5058 /// place. This is useful when a builtin function requires custom 5059 /// type-checking for some of its arguments but not necessarily all of 5060 /// them. 5061 /// 5062 /// Returns true on error. 5063 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5064 FunctionDecl *Fn = E->getDirectCallee(); 5065 assert(Fn && "builtin call without direct callee!"); 5066 5067 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5068 InitializedEntity Entity = 5069 InitializedEntity::InitializeParameter(S.Context, Param); 5070 5071 ExprResult Arg = E->getArg(0); 5072 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5073 if (Arg.isInvalid()) 5074 return true; 5075 5076 E->setArg(ArgIndex, Arg.get()); 5077 return false; 5078 } 5079 5080 /// We have a call to a function like __sync_fetch_and_add, which is an 5081 /// overloaded function based on the pointer type of its first argument. 5082 /// The main BuildCallExpr routines have already promoted the types of 5083 /// arguments because all of these calls are prototyped as void(...). 5084 /// 5085 /// This function goes through and does final semantic checking for these 5086 /// builtins, as well as generating any warnings. 5087 ExprResult 5088 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5089 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5090 Expr *Callee = TheCall->getCallee(); 5091 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5092 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5093 5094 // Ensure that we have at least one argument to do type inference from. 5095 if (TheCall->getNumArgs() < 1) { 5096 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5097 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5098 return ExprError(); 5099 } 5100 5101 // Inspect the first argument of the atomic builtin. This should always be 5102 // a pointer type, whose element is an integral scalar or pointer type. 5103 // Because it is a pointer type, we don't have to worry about any implicit 5104 // casts here. 5105 // FIXME: We don't allow floating point scalars as input. 5106 Expr *FirstArg = TheCall->getArg(0); 5107 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5108 if (FirstArgResult.isInvalid()) 5109 return ExprError(); 5110 FirstArg = FirstArgResult.get(); 5111 TheCall->setArg(0, FirstArg); 5112 5113 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5114 if (!pointerType) { 5115 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5116 << FirstArg->getType() << FirstArg->getSourceRange(); 5117 return ExprError(); 5118 } 5119 5120 QualType ValType = pointerType->getPointeeType(); 5121 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5122 !ValType->isBlockPointerType()) { 5123 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5124 << FirstArg->getType() << FirstArg->getSourceRange(); 5125 return ExprError(); 5126 } 5127 5128 if (ValType.isConstQualified()) { 5129 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5130 << FirstArg->getType() << FirstArg->getSourceRange(); 5131 return ExprError(); 5132 } 5133 5134 switch (ValType.getObjCLifetime()) { 5135 case Qualifiers::OCL_None: 5136 case Qualifiers::OCL_ExplicitNone: 5137 // okay 5138 break; 5139 5140 case Qualifiers::OCL_Weak: 5141 case Qualifiers::OCL_Strong: 5142 case Qualifiers::OCL_Autoreleasing: 5143 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5144 << ValType << FirstArg->getSourceRange(); 5145 return ExprError(); 5146 } 5147 5148 // Strip any qualifiers off ValType. 5149 ValType = ValType.getUnqualifiedType(); 5150 5151 // The majority of builtins return a value, but a few have special return 5152 // types, so allow them to override appropriately below. 5153 QualType ResultType = ValType; 5154 5155 // We need to figure out which concrete builtin this maps onto. For example, 5156 // __sync_fetch_and_add with a 2 byte object turns into 5157 // __sync_fetch_and_add_2. 5158 #define BUILTIN_ROW(x) \ 5159 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5160 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5161 5162 static const unsigned BuiltinIndices[][5] = { 5163 BUILTIN_ROW(__sync_fetch_and_add), 5164 BUILTIN_ROW(__sync_fetch_and_sub), 5165 BUILTIN_ROW(__sync_fetch_and_or), 5166 BUILTIN_ROW(__sync_fetch_and_and), 5167 BUILTIN_ROW(__sync_fetch_and_xor), 5168 BUILTIN_ROW(__sync_fetch_and_nand), 5169 5170 BUILTIN_ROW(__sync_add_and_fetch), 5171 BUILTIN_ROW(__sync_sub_and_fetch), 5172 BUILTIN_ROW(__sync_and_and_fetch), 5173 BUILTIN_ROW(__sync_or_and_fetch), 5174 BUILTIN_ROW(__sync_xor_and_fetch), 5175 BUILTIN_ROW(__sync_nand_and_fetch), 5176 5177 BUILTIN_ROW(__sync_val_compare_and_swap), 5178 BUILTIN_ROW(__sync_bool_compare_and_swap), 5179 BUILTIN_ROW(__sync_lock_test_and_set), 5180 BUILTIN_ROW(__sync_lock_release), 5181 BUILTIN_ROW(__sync_swap) 5182 }; 5183 #undef BUILTIN_ROW 5184 5185 // Determine the index of the size. 5186 unsigned SizeIndex; 5187 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5188 case 1: SizeIndex = 0; break; 5189 case 2: SizeIndex = 1; break; 5190 case 4: SizeIndex = 2; break; 5191 case 8: SizeIndex = 3; break; 5192 case 16: SizeIndex = 4; break; 5193 default: 5194 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5195 << FirstArg->getType() << FirstArg->getSourceRange(); 5196 return ExprError(); 5197 } 5198 5199 // Each of these builtins has one pointer argument, followed by some number of 5200 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5201 // that we ignore. Find out which row of BuiltinIndices to read from as well 5202 // as the number of fixed args. 5203 unsigned BuiltinID = FDecl->getBuiltinID(); 5204 unsigned BuiltinIndex, NumFixed = 1; 5205 bool WarnAboutSemanticsChange = false; 5206 switch (BuiltinID) { 5207 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5208 case Builtin::BI__sync_fetch_and_add: 5209 case Builtin::BI__sync_fetch_and_add_1: 5210 case Builtin::BI__sync_fetch_and_add_2: 5211 case Builtin::BI__sync_fetch_and_add_4: 5212 case Builtin::BI__sync_fetch_and_add_8: 5213 case Builtin::BI__sync_fetch_and_add_16: 5214 BuiltinIndex = 0; 5215 break; 5216 5217 case Builtin::BI__sync_fetch_and_sub: 5218 case Builtin::BI__sync_fetch_and_sub_1: 5219 case Builtin::BI__sync_fetch_and_sub_2: 5220 case Builtin::BI__sync_fetch_and_sub_4: 5221 case Builtin::BI__sync_fetch_and_sub_8: 5222 case Builtin::BI__sync_fetch_and_sub_16: 5223 BuiltinIndex = 1; 5224 break; 5225 5226 case Builtin::BI__sync_fetch_and_or: 5227 case Builtin::BI__sync_fetch_and_or_1: 5228 case Builtin::BI__sync_fetch_and_or_2: 5229 case Builtin::BI__sync_fetch_and_or_4: 5230 case Builtin::BI__sync_fetch_and_or_8: 5231 case Builtin::BI__sync_fetch_and_or_16: 5232 BuiltinIndex = 2; 5233 break; 5234 5235 case Builtin::BI__sync_fetch_and_and: 5236 case Builtin::BI__sync_fetch_and_and_1: 5237 case Builtin::BI__sync_fetch_and_and_2: 5238 case Builtin::BI__sync_fetch_and_and_4: 5239 case Builtin::BI__sync_fetch_and_and_8: 5240 case Builtin::BI__sync_fetch_and_and_16: 5241 BuiltinIndex = 3; 5242 break; 5243 5244 case Builtin::BI__sync_fetch_and_xor: 5245 case Builtin::BI__sync_fetch_and_xor_1: 5246 case Builtin::BI__sync_fetch_and_xor_2: 5247 case Builtin::BI__sync_fetch_and_xor_4: 5248 case Builtin::BI__sync_fetch_and_xor_8: 5249 case Builtin::BI__sync_fetch_and_xor_16: 5250 BuiltinIndex = 4; 5251 break; 5252 5253 case Builtin::BI__sync_fetch_and_nand: 5254 case Builtin::BI__sync_fetch_and_nand_1: 5255 case Builtin::BI__sync_fetch_and_nand_2: 5256 case Builtin::BI__sync_fetch_and_nand_4: 5257 case Builtin::BI__sync_fetch_and_nand_8: 5258 case Builtin::BI__sync_fetch_and_nand_16: 5259 BuiltinIndex = 5; 5260 WarnAboutSemanticsChange = true; 5261 break; 5262 5263 case Builtin::BI__sync_add_and_fetch: 5264 case Builtin::BI__sync_add_and_fetch_1: 5265 case Builtin::BI__sync_add_and_fetch_2: 5266 case Builtin::BI__sync_add_and_fetch_4: 5267 case Builtin::BI__sync_add_and_fetch_8: 5268 case Builtin::BI__sync_add_and_fetch_16: 5269 BuiltinIndex = 6; 5270 break; 5271 5272 case Builtin::BI__sync_sub_and_fetch: 5273 case Builtin::BI__sync_sub_and_fetch_1: 5274 case Builtin::BI__sync_sub_and_fetch_2: 5275 case Builtin::BI__sync_sub_and_fetch_4: 5276 case Builtin::BI__sync_sub_and_fetch_8: 5277 case Builtin::BI__sync_sub_and_fetch_16: 5278 BuiltinIndex = 7; 5279 break; 5280 5281 case Builtin::BI__sync_and_and_fetch: 5282 case Builtin::BI__sync_and_and_fetch_1: 5283 case Builtin::BI__sync_and_and_fetch_2: 5284 case Builtin::BI__sync_and_and_fetch_4: 5285 case Builtin::BI__sync_and_and_fetch_8: 5286 case Builtin::BI__sync_and_and_fetch_16: 5287 BuiltinIndex = 8; 5288 break; 5289 5290 case Builtin::BI__sync_or_and_fetch: 5291 case Builtin::BI__sync_or_and_fetch_1: 5292 case Builtin::BI__sync_or_and_fetch_2: 5293 case Builtin::BI__sync_or_and_fetch_4: 5294 case Builtin::BI__sync_or_and_fetch_8: 5295 case Builtin::BI__sync_or_and_fetch_16: 5296 BuiltinIndex = 9; 5297 break; 5298 5299 case Builtin::BI__sync_xor_and_fetch: 5300 case Builtin::BI__sync_xor_and_fetch_1: 5301 case Builtin::BI__sync_xor_and_fetch_2: 5302 case Builtin::BI__sync_xor_and_fetch_4: 5303 case Builtin::BI__sync_xor_and_fetch_8: 5304 case Builtin::BI__sync_xor_and_fetch_16: 5305 BuiltinIndex = 10; 5306 break; 5307 5308 case Builtin::BI__sync_nand_and_fetch: 5309 case Builtin::BI__sync_nand_and_fetch_1: 5310 case Builtin::BI__sync_nand_and_fetch_2: 5311 case Builtin::BI__sync_nand_and_fetch_4: 5312 case Builtin::BI__sync_nand_and_fetch_8: 5313 case Builtin::BI__sync_nand_and_fetch_16: 5314 BuiltinIndex = 11; 5315 WarnAboutSemanticsChange = true; 5316 break; 5317 5318 case Builtin::BI__sync_val_compare_and_swap: 5319 case Builtin::BI__sync_val_compare_and_swap_1: 5320 case Builtin::BI__sync_val_compare_and_swap_2: 5321 case Builtin::BI__sync_val_compare_and_swap_4: 5322 case Builtin::BI__sync_val_compare_and_swap_8: 5323 case Builtin::BI__sync_val_compare_and_swap_16: 5324 BuiltinIndex = 12; 5325 NumFixed = 2; 5326 break; 5327 5328 case Builtin::BI__sync_bool_compare_and_swap: 5329 case Builtin::BI__sync_bool_compare_and_swap_1: 5330 case Builtin::BI__sync_bool_compare_and_swap_2: 5331 case Builtin::BI__sync_bool_compare_and_swap_4: 5332 case Builtin::BI__sync_bool_compare_and_swap_8: 5333 case Builtin::BI__sync_bool_compare_and_swap_16: 5334 BuiltinIndex = 13; 5335 NumFixed = 2; 5336 ResultType = Context.BoolTy; 5337 break; 5338 5339 case Builtin::BI__sync_lock_test_and_set: 5340 case Builtin::BI__sync_lock_test_and_set_1: 5341 case Builtin::BI__sync_lock_test_and_set_2: 5342 case Builtin::BI__sync_lock_test_and_set_4: 5343 case Builtin::BI__sync_lock_test_and_set_8: 5344 case Builtin::BI__sync_lock_test_and_set_16: 5345 BuiltinIndex = 14; 5346 break; 5347 5348 case Builtin::BI__sync_lock_release: 5349 case Builtin::BI__sync_lock_release_1: 5350 case Builtin::BI__sync_lock_release_2: 5351 case Builtin::BI__sync_lock_release_4: 5352 case Builtin::BI__sync_lock_release_8: 5353 case Builtin::BI__sync_lock_release_16: 5354 BuiltinIndex = 15; 5355 NumFixed = 0; 5356 ResultType = Context.VoidTy; 5357 break; 5358 5359 case Builtin::BI__sync_swap: 5360 case Builtin::BI__sync_swap_1: 5361 case Builtin::BI__sync_swap_2: 5362 case Builtin::BI__sync_swap_4: 5363 case Builtin::BI__sync_swap_8: 5364 case Builtin::BI__sync_swap_16: 5365 BuiltinIndex = 16; 5366 break; 5367 } 5368 5369 // Now that we know how many fixed arguments we expect, first check that we 5370 // have at least that many. 5371 if (TheCall->getNumArgs() < 1+NumFixed) { 5372 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5373 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5374 << Callee->getSourceRange(); 5375 return ExprError(); 5376 } 5377 5378 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5379 << Callee->getSourceRange(); 5380 5381 if (WarnAboutSemanticsChange) { 5382 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5383 << Callee->getSourceRange(); 5384 } 5385 5386 // Get the decl for the concrete builtin from this, we can tell what the 5387 // concrete integer type we should convert to is. 5388 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5389 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5390 FunctionDecl *NewBuiltinDecl; 5391 if (NewBuiltinID == BuiltinID) 5392 NewBuiltinDecl = FDecl; 5393 else { 5394 // Perform builtin lookup to avoid redeclaring it. 5395 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5396 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5397 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5398 assert(Res.getFoundDecl()); 5399 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5400 if (!NewBuiltinDecl) 5401 return ExprError(); 5402 } 5403 5404 // The first argument --- the pointer --- has a fixed type; we 5405 // deduce the types of the rest of the arguments accordingly. Walk 5406 // the remaining arguments, converting them to the deduced value type. 5407 for (unsigned i = 0; i != NumFixed; ++i) { 5408 ExprResult Arg = TheCall->getArg(i+1); 5409 5410 // GCC does an implicit conversion to the pointer or integer ValType. This 5411 // can fail in some cases (1i -> int**), check for this error case now. 5412 // Initialize the argument. 5413 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5414 ValType, /*consume*/ false); 5415 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5416 if (Arg.isInvalid()) 5417 return ExprError(); 5418 5419 // Okay, we have something that *can* be converted to the right type. Check 5420 // to see if there is a potentially weird extension going on here. This can 5421 // happen when you do an atomic operation on something like an char* and 5422 // pass in 42. The 42 gets converted to char. This is even more strange 5423 // for things like 45.123 -> char, etc. 5424 // FIXME: Do this check. 5425 TheCall->setArg(i+1, Arg.get()); 5426 } 5427 5428 // Create a new DeclRefExpr to refer to the new decl. 5429 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5430 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5431 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5432 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5433 5434 // Set the callee in the CallExpr. 5435 // FIXME: This loses syntactic information. 5436 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5437 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5438 CK_BuiltinFnToFnPtr); 5439 TheCall->setCallee(PromotedCall.get()); 5440 5441 // Change the result type of the call to match the original value type. This 5442 // is arbitrary, but the codegen for these builtins ins design to handle it 5443 // gracefully. 5444 TheCall->setType(ResultType); 5445 5446 // Prohibit use of _ExtInt with atomic builtins. 5447 // The arguments would have already been converted to the first argument's 5448 // type, so only need to check the first argument. 5449 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5450 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5451 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5452 return ExprError(); 5453 } 5454 5455 return TheCallResult; 5456 } 5457 5458 /// SemaBuiltinNontemporalOverloaded - We have a call to 5459 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5460 /// overloaded function based on the pointer type of its last argument. 5461 /// 5462 /// This function goes through and does final semantic checking for these 5463 /// builtins. 5464 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5465 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5466 DeclRefExpr *DRE = 5467 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5468 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5469 unsigned BuiltinID = FDecl->getBuiltinID(); 5470 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5471 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5472 "Unexpected nontemporal load/store builtin!"); 5473 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5474 unsigned numArgs = isStore ? 2 : 1; 5475 5476 // Ensure that we have the proper number of arguments. 5477 if (checkArgCount(*this, TheCall, numArgs)) 5478 return ExprError(); 5479 5480 // Inspect the last argument of the nontemporal builtin. This should always 5481 // be a pointer type, from which we imply the type of the memory access. 5482 // Because it is a pointer type, we don't have to worry about any implicit 5483 // casts here. 5484 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5485 ExprResult PointerArgResult = 5486 DefaultFunctionArrayLvalueConversion(PointerArg); 5487 5488 if (PointerArgResult.isInvalid()) 5489 return ExprError(); 5490 PointerArg = PointerArgResult.get(); 5491 TheCall->setArg(numArgs - 1, PointerArg); 5492 5493 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5494 if (!pointerType) { 5495 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5496 << PointerArg->getType() << PointerArg->getSourceRange(); 5497 return ExprError(); 5498 } 5499 5500 QualType ValType = pointerType->getPointeeType(); 5501 5502 // Strip any qualifiers off ValType. 5503 ValType = ValType.getUnqualifiedType(); 5504 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5505 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5506 !ValType->isVectorType()) { 5507 Diag(DRE->getBeginLoc(), 5508 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5509 << PointerArg->getType() << PointerArg->getSourceRange(); 5510 return ExprError(); 5511 } 5512 5513 if (!isStore) { 5514 TheCall->setType(ValType); 5515 return TheCallResult; 5516 } 5517 5518 ExprResult ValArg = TheCall->getArg(0); 5519 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5520 Context, ValType, /*consume*/ false); 5521 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5522 if (ValArg.isInvalid()) 5523 return ExprError(); 5524 5525 TheCall->setArg(0, ValArg.get()); 5526 TheCall->setType(Context.VoidTy); 5527 return TheCallResult; 5528 } 5529 5530 /// CheckObjCString - Checks that the argument to the builtin 5531 /// CFString constructor is correct 5532 /// Note: It might also make sense to do the UTF-16 conversion here (would 5533 /// simplify the backend). 5534 bool Sema::CheckObjCString(Expr *Arg) { 5535 Arg = Arg->IgnoreParenCasts(); 5536 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5537 5538 if (!Literal || !Literal->isAscii()) { 5539 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5540 << Arg->getSourceRange(); 5541 return true; 5542 } 5543 5544 if (Literal->containsNonAsciiOrNull()) { 5545 StringRef String = Literal->getString(); 5546 unsigned NumBytes = String.size(); 5547 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5548 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5549 llvm::UTF16 *ToPtr = &ToBuf[0]; 5550 5551 llvm::ConversionResult Result = 5552 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5553 ToPtr + NumBytes, llvm::strictConversion); 5554 // Check for conversion failure. 5555 if (Result != llvm::conversionOK) 5556 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5557 << Arg->getSourceRange(); 5558 } 5559 return false; 5560 } 5561 5562 /// CheckObjCString - Checks that the format string argument to the os_log() 5563 /// and os_trace() functions is correct, and converts it to const char *. 5564 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5565 Arg = Arg->IgnoreParenCasts(); 5566 auto *Literal = dyn_cast<StringLiteral>(Arg); 5567 if (!Literal) { 5568 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5569 Literal = ObjcLiteral->getString(); 5570 } 5571 } 5572 5573 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5574 return ExprError( 5575 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5576 << Arg->getSourceRange()); 5577 } 5578 5579 ExprResult Result(Literal); 5580 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5581 InitializedEntity Entity = 5582 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5583 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5584 return Result; 5585 } 5586 5587 /// Check that the user is calling the appropriate va_start builtin for the 5588 /// target and calling convention. 5589 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5590 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5591 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5592 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5593 TT.getArch() == llvm::Triple::aarch64_32); 5594 bool IsWindows = TT.isOSWindows(); 5595 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5596 if (IsX64 || IsAArch64) { 5597 CallingConv CC = CC_C; 5598 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5599 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5600 if (IsMSVAStart) { 5601 // Don't allow this in System V ABI functions. 5602 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5603 return S.Diag(Fn->getBeginLoc(), 5604 diag::err_ms_va_start_used_in_sysv_function); 5605 } else { 5606 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5607 // On x64 Windows, don't allow this in System V ABI functions. 5608 // (Yes, that means there's no corresponding way to support variadic 5609 // System V ABI functions on Windows.) 5610 if ((IsWindows && CC == CC_X86_64SysV) || 5611 (!IsWindows && CC == CC_Win64)) 5612 return S.Diag(Fn->getBeginLoc(), 5613 diag::err_va_start_used_in_wrong_abi_function) 5614 << !IsWindows; 5615 } 5616 return false; 5617 } 5618 5619 if (IsMSVAStart) 5620 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5621 return false; 5622 } 5623 5624 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5625 ParmVarDecl **LastParam = nullptr) { 5626 // Determine whether the current function, block, or obj-c method is variadic 5627 // and get its parameter list. 5628 bool IsVariadic = false; 5629 ArrayRef<ParmVarDecl *> Params; 5630 DeclContext *Caller = S.CurContext; 5631 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5632 IsVariadic = Block->isVariadic(); 5633 Params = Block->parameters(); 5634 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5635 IsVariadic = FD->isVariadic(); 5636 Params = FD->parameters(); 5637 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5638 IsVariadic = MD->isVariadic(); 5639 // FIXME: This isn't correct for methods (results in bogus warning). 5640 Params = MD->parameters(); 5641 } else if (isa<CapturedDecl>(Caller)) { 5642 // We don't support va_start in a CapturedDecl. 5643 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5644 return true; 5645 } else { 5646 // This must be some other declcontext that parses exprs. 5647 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5648 return true; 5649 } 5650 5651 if (!IsVariadic) { 5652 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5653 return true; 5654 } 5655 5656 if (LastParam) 5657 *LastParam = Params.empty() ? nullptr : Params.back(); 5658 5659 return false; 5660 } 5661 5662 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5663 /// for validity. Emit an error and return true on failure; return false 5664 /// on success. 5665 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5666 Expr *Fn = TheCall->getCallee(); 5667 5668 if (checkVAStartABI(*this, BuiltinID, Fn)) 5669 return true; 5670 5671 if (checkArgCount(*this, TheCall, 2)) 5672 return true; 5673 5674 // Type-check the first argument normally. 5675 if (checkBuiltinArgument(*this, TheCall, 0)) 5676 return true; 5677 5678 // Check that the current function is variadic, and get its last parameter. 5679 ParmVarDecl *LastParam; 5680 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5681 return true; 5682 5683 // Verify that the second argument to the builtin is the last argument of the 5684 // current function or method. 5685 bool SecondArgIsLastNamedArgument = false; 5686 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5687 5688 // These are valid if SecondArgIsLastNamedArgument is false after the next 5689 // block. 5690 QualType Type; 5691 SourceLocation ParamLoc; 5692 bool IsCRegister = false; 5693 5694 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5695 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5696 SecondArgIsLastNamedArgument = PV == LastParam; 5697 5698 Type = PV->getType(); 5699 ParamLoc = PV->getLocation(); 5700 IsCRegister = 5701 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5702 } 5703 } 5704 5705 if (!SecondArgIsLastNamedArgument) 5706 Diag(TheCall->getArg(1)->getBeginLoc(), 5707 diag::warn_second_arg_of_va_start_not_last_named_param); 5708 else if (IsCRegister || Type->isReferenceType() || 5709 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5710 // Promotable integers are UB, but enumerations need a bit of 5711 // extra checking to see what their promotable type actually is. 5712 if (!Type->isPromotableIntegerType()) 5713 return false; 5714 if (!Type->isEnumeralType()) 5715 return true; 5716 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5717 return !(ED && 5718 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5719 }()) { 5720 unsigned Reason = 0; 5721 if (Type->isReferenceType()) Reason = 1; 5722 else if (IsCRegister) Reason = 2; 5723 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5724 Diag(ParamLoc, diag::note_parameter_type) << Type; 5725 } 5726 5727 TheCall->setType(Context.VoidTy); 5728 return false; 5729 } 5730 5731 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5732 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5733 // const char *named_addr); 5734 5735 Expr *Func = Call->getCallee(); 5736 5737 if (Call->getNumArgs() < 3) 5738 return Diag(Call->getEndLoc(), 5739 diag::err_typecheck_call_too_few_args_at_least) 5740 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5741 5742 // Type-check the first argument normally. 5743 if (checkBuiltinArgument(*this, Call, 0)) 5744 return true; 5745 5746 // Check that the current function is variadic. 5747 if (checkVAStartIsInVariadicFunction(*this, Func)) 5748 return true; 5749 5750 // __va_start on Windows does not validate the parameter qualifiers 5751 5752 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5753 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5754 5755 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5756 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5757 5758 const QualType &ConstCharPtrTy = 5759 Context.getPointerType(Context.CharTy.withConst()); 5760 if (!Arg1Ty->isPointerType() || 5761 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5762 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5763 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5764 << 0 /* qualifier difference */ 5765 << 3 /* parameter mismatch */ 5766 << 2 << Arg1->getType() << ConstCharPtrTy; 5767 5768 const QualType SizeTy = Context.getSizeType(); 5769 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5770 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5771 << Arg2->getType() << SizeTy << 1 /* different class */ 5772 << 0 /* qualifier difference */ 5773 << 3 /* parameter mismatch */ 5774 << 3 << Arg2->getType() << SizeTy; 5775 5776 return false; 5777 } 5778 5779 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5780 /// friends. This is declared to take (...), so we have to check everything. 5781 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5782 if (checkArgCount(*this, TheCall, 2)) 5783 return true; 5784 5785 ExprResult OrigArg0 = TheCall->getArg(0); 5786 ExprResult OrigArg1 = TheCall->getArg(1); 5787 5788 // Do standard promotions between the two arguments, returning their common 5789 // type. 5790 QualType Res = UsualArithmeticConversions( 5791 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5792 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5793 return true; 5794 5795 // Make sure any conversions are pushed back into the call; this is 5796 // type safe since unordered compare builtins are declared as "_Bool 5797 // foo(...)". 5798 TheCall->setArg(0, OrigArg0.get()); 5799 TheCall->setArg(1, OrigArg1.get()); 5800 5801 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5802 return false; 5803 5804 // If the common type isn't a real floating type, then the arguments were 5805 // invalid for this operation. 5806 if (Res.isNull() || !Res->isRealFloatingType()) 5807 return Diag(OrigArg0.get()->getBeginLoc(), 5808 diag::err_typecheck_call_invalid_ordered_compare) 5809 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5810 << SourceRange(OrigArg0.get()->getBeginLoc(), 5811 OrigArg1.get()->getEndLoc()); 5812 5813 return false; 5814 } 5815 5816 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5817 /// __builtin_isnan and friends. This is declared to take (...), so we have 5818 /// to check everything. We expect the last argument to be a floating point 5819 /// value. 5820 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5821 if (checkArgCount(*this, TheCall, NumArgs)) 5822 return true; 5823 5824 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5825 // on all preceding parameters just being int. Try all of those. 5826 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5827 Expr *Arg = TheCall->getArg(i); 5828 5829 if (Arg->isTypeDependent()) 5830 return false; 5831 5832 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5833 5834 if (Res.isInvalid()) 5835 return true; 5836 TheCall->setArg(i, Res.get()); 5837 } 5838 5839 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5840 5841 if (OrigArg->isTypeDependent()) 5842 return false; 5843 5844 // Usual Unary Conversions will convert half to float, which we want for 5845 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5846 // type how it is, but do normal L->Rvalue conversions. 5847 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5848 OrigArg = UsualUnaryConversions(OrigArg).get(); 5849 else 5850 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5851 TheCall->setArg(NumArgs - 1, OrigArg); 5852 5853 // This operation requires a non-_Complex floating-point number. 5854 if (!OrigArg->getType()->isRealFloatingType()) 5855 return Diag(OrigArg->getBeginLoc(), 5856 diag::err_typecheck_call_invalid_unary_fp) 5857 << OrigArg->getType() << OrigArg->getSourceRange(); 5858 5859 return false; 5860 } 5861 5862 /// Perform semantic analysis for a call to __builtin_complex. 5863 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5864 if (checkArgCount(*this, TheCall, 2)) 5865 return true; 5866 5867 bool Dependent = false; 5868 for (unsigned I = 0; I != 2; ++I) { 5869 Expr *Arg = TheCall->getArg(I); 5870 QualType T = Arg->getType(); 5871 if (T->isDependentType()) { 5872 Dependent = true; 5873 continue; 5874 } 5875 5876 // Despite supporting _Complex int, GCC requires a real floating point type 5877 // for the operands of __builtin_complex. 5878 if (!T->isRealFloatingType()) { 5879 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5880 << Arg->getType() << Arg->getSourceRange(); 5881 } 5882 5883 ExprResult Converted = DefaultLvalueConversion(Arg); 5884 if (Converted.isInvalid()) 5885 return true; 5886 TheCall->setArg(I, Converted.get()); 5887 } 5888 5889 if (Dependent) { 5890 TheCall->setType(Context.DependentTy); 5891 return false; 5892 } 5893 5894 Expr *Real = TheCall->getArg(0); 5895 Expr *Imag = TheCall->getArg(1); 5896 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 5897 return Diag(Real->getBeginLoc(), 5898 diag::err_typecheck_call_different_arg_types) 5899 << Real->getType() << Imag->getType() 5900 << Real->getSourceRange() << Imag->getSourceRange(); 5901 } 5902 5903 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 5904 // don't allow this builtin to form those types either. 5905 // FIXME: Should we allow these types? 5906 if (Real->getType()->isFloat16Type()) 5907 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5908 << "_Float16"; 5909 if (Real->getType()->isHalfType()) 5910 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5911 << "half"; 5912 5913 TheCall->setType(Context.getComplexType(Real->getType())); 5914 return false; 5915 } 5916 5917 // Customized Sema Checking for VSX builtins that have the following signature: 5918 // vector [...] builtinName(vector [...], vector [...], const int); 5919 // Which takes the same type of vectors (any legal vector type) for the first 5920 // two arguments and takes compile time constant for the third argument. 5921 // Example builtins are : 5922 // vector double vec_xxpermdi(vector double, vector double, int); 5923 // vector short vec_xxsldwi(vector short, vector short, int); 5924 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5925 unsigned ExpectedNumArgs = 3; 5926 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 5927 return true; 5928 5929 // Check the third argument is a compile time constant 5930 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 5931 return Diag(TheCall->getBeginLoc(), 5932 diag::err_vsx_builtin_nonconstant_argument) 5933 << 3 /* argument index */ << TheCall->getDirectCallee() 5934 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5935 TheCall->getArg(2)->getEndLoc()); 5936 5937 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5938 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5939 5940 // Check the type of argument 1 and argument 2 are vectors. 5941 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5942 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5943 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5944 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5945 << TheCall->getDirectCallee() 5946 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5947 TheCall->getArg(1)->getEndLoc()); 5948 } 5949 5950 // Check the first two arguments are the same type. 5951 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5952 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5953 << TheCall->getDirectCallee() 5954 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5955 TheCall->getArg(1)->getEndLoc()); 5956 } 5957 5958 // When default clang type checking is turned off and the customized type 5959 // checking is used, the returning type of the function must be explicitly 5960 // set. Otherwise it is _Bool by default. 5961 TheCall->setType(Arg1Ty); 5962 5963 return false; 5964 } 5965 5966 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5967 // This is declared to take (...), so we have to check everything. 5968 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5969 if (TheCall->getNumArgs() < 2) 5970 return ExprError(Diag(TheCall->getEndLoc(), 5971 diag::err_typecheck_call_too_few_args_at_least) 5972 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5973 << TheCall->getSourceRange()); 5974 5975 // Determine which of the following types of shufflevector we're checking: 5976 // 1) unary, vector mask: (lhs, mask) 5977 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5978 QualType resType = TheCall->getArg(0)->getType(); 5979 unsigned numElements = 0; 5980 5981 if (!TheCall->getArg(0)->isTypeDependent() && 5982 !TheCall->getArg(1)->isTypeDependent()) { 5983 QualType LHSType = TheCall->getArg(0)->getType(); 5984 QualType RHSType = TheCall->getArg(1)->getType(); 5985 5986 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5987 return ExprError( 5988 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5989 << TheCall->getDirectCallee() 5990 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5991 TheCall->getArg(1)->getEndLoc())); 5992 5993 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5994 unsigned numResElements = TheCall->getNumArgs() - 2; 5995 5996 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5997 // with mask. If so, verify that RHS is an integer vector type with the 5998 // same number of elts as lhs. 5999 if (TheCall->getNumArgs() == 2) { 6000 if (!RHSType->hasIntegerRepresentation() || 6001 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6002 return ExprError(Diag(TheCall->getBeginLoc(), 6003 diag::err_vec_builtin_incompatible_vector) 6004 << TheCall->getDirectCallee() 6005 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6006 TheCall->getArg(1)->getEndLoc())); 6007 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6008 return ExprError(Diag(TheCall->getBeginLoc(), 6009 diag::err_vec_builtin_incompatible_vector) 6010 << TheCall->getDirectCallee() 6011 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6012 TheCall->getArg(1)->getEndLoc())); 6013 } else if (numElements != numResElements) { 6014 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6015 resType = Context.getVectorType(eltType, numResElements, 6016 VectorType::GenericVector); 6017 } 6018 } 6019 6020 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6021 if (TheCall->getArg(i)->isTypeDependent() || 6022 TheCall->getArg(i)->isValueDependent()) 6023 continue; 6024 6025 Optional<llvm::APSInt> Result; 6026 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6027 return ExprError(Diag(TheCall->getBeginLoc(), 6028 diag::err_shufflevector_nonconstant_argument) 6029 << TheCall->getArg(i)->getSourceRange()); 6030 6031 // Allow -1 which will be translated to undef in the IR. 6032 if (Result->isSigned() && Result->isAllOnesValue()) 6033 continue; 6034 6035 if (Result->getActiveBits() > 64 || 6036 Result->getZExtValue() >= numElements * 2) 6037 return ExprError(Diag(TheCall->getBeginLoc(), 6038 diag::err_shufflevector_argument_too_large) 6039 << TheCall->getArg(i)->getSourceRange()); 6040 } 6041 6042 SmallVector<Expr*, 32> exprs; 6043 6044 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6045 exprs.push_back(TheCall->getArg(i)); 6046 TheCall->setArg(i, nullptr); 6047 } 6048 6049 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6050 TheCall->getCallee()->getBeginLoc(), 6051 TheCall->getRParenLoc()); 6052 } 6053 6054 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6055 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6056 SourceLocation BuiltinLoc, 6057 SourceLocation RParenLoc) { 6058 ExprValueKind VK = VK_RValue; 6059 ExprObjectKind OK = OK_Ordinary; 6060 QualType DstTy = TInfo->getType(); 6061 QualType SrcTy = E->getType(); 6062 6063 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6064 return ExprError(Diag(BuiltinLoc, 6065 diag::err_convertvector_non_vector) 6066 << E->getSourceRange()); 6067 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6068 return ExprError(Diag(BuiltinLoc, 6069 diag::err_convertvector_non_vector_type)); 6070 6071 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6072 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6073 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6074 if (SrcElts != DstElts) 6075 return ExprError(Diag(BuiltinLoc, 6076 diag::err_convertvector_incompatible_vector) 6077 << E->getSourceRange()); 6078 } 6079 6080 return new (Context) 6081 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6082 } 6083 6084 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6085 // This is declared to take (const void*, ...) and can take two 6086 // optional constant int args. 6087 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6088 unsigned NumArgs = TheCall->getNumArgs(); 6089 6090 if (NumArgs > 3) 6091 return Diag(TheCall->getEndLoc(), 6092 diag::err_typecheck_call_too_many_args_at_most) 6093 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6094 6095 // Argument 0 is checked for us and the remaining arguments must be 6096 // constant integers. 6097 for (unsigned i = 1; i != NumArgs; ++i) 6098 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6099 return true; 6100 6101 return false; 6102 } 6103 6104 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6105 // __assume does not evaluate its arguments, and should warn if its argument 6106 // has side effects. 6107 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6108 Expr *Arg = TheCall->getArg(0); 6109 if (Arg->isInstantiationDependent()) return false; 6110 6111 if (Arg->HasSideEffects(Context)) 6112 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6113 << Arg->getSourceRange() 6114 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6115 6116 return false; 6117 } 6118 6119 /// Handle __builtin_alloca_with_align. This is declared 6120 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6121 /// than 8. 6122 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6123 // The alignment must be a constant integer. 6124 Expr *Arg = TheCall->getArg(1); 6125 6126 // We can't check the value of a dependent argument. 6127 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6128 if (const auto *UE = 6129 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6130 if (UE->getKind() == UETT_AlignOf || 6131 UE->getKind() == UETT_PreferredAlignOf) 6132 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6133 << Arg->getSourceRange(); 6134 6135 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6136 6137 if (!Result.isPowerOf2()) 6138 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6139 << Arg->getSourceRange(); 6140 6141 if (Result < Context.getCharWidth()) 6142 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6143 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6144 6145 if (Result > std::numeric_limits<int32_t>::max()) 6146 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6147 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6148 } 6149 6150 return false; 6151 } 6152 6153 /// Handle __builtin_assume_aligned. This is declared 6154 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6155 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6156 unsigned NumArgs = TheCall->getNumArgs(); 6157 6158 if (NumArgs > 3) 6159 return Diag(TheCall->getEndLoc(), 6160 diag::err_typecheck_call_too_many_args_at_most) 6161 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6162 6163 // The alignment must be a constant integer. 6164 Expr *Arg = TheCall->getArg(1); 6165 6166 // We can't check the value of a dependent argument. 6167 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6168 llvm::APSInt Result; 6169 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6170 return true; 6171 6172 if (!Result.isPowerOf2()) 6173 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6174 << Arg->getSourceRange(); 6175 6176 if (Result > Sema::MaximumAlignment) 6177 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6178 << Arg->getSourceRange() << Sema::MaximumAlignment; 6179 } 6180 6181 if (NumArgs > 2) { 6182 ExprResult Arg(TheCall->getArg(2)); 6183 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6184 Context.getSizeType(), false); 6185 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6186 if (Arg.isInvalid()) return true; 6187 TheCall->setArg(2, Arg.get()); 6188 } 6189 6190 return false; 6191 } 6192 6193 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6194 unsigned BuiltinID = 6195 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6196 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6197 6198 unsigned NumArgs = TheCall->getNumArgs(); 6199 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6200 if (NumArgs < NumRequiredArgs) { 6201 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6202 << 0 /* function call */ << NumRequiredArgs << NumArgs 6203 << TheCall->getSourceRange(); 6204 } 6205 if (NumArgs >= NumRequiredArgs + 0x100) { 6206 return Diag(TheCall->getEndLoc(), 6207 diag::err_typecheck_call_too_many_args_at_most) 6208 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6209 << TheCall->getSourceRange(); 6210 } 6211 unsigned i = 0; 6212 6213 // For formatting call, check buffer arg. 6214 if (!IsSizeCall) { 6215 ExprResult Arg(TheCall->getArg(i)); 6216 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6217 Context, Context.VoidPtrTy, false); 6218 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6219 if (Arg.isInvalid()) 6220 return true; 6221 TheCall->setArg(i, Arg.get()); 6222 i++; 6223 } 6224 6225 // Check string literal arg. 6226 unsigned FormatIdx = i; 6227 { 6228 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6229 if (Arg.isInvalid()) 6230 return true; 6231 TheCall->setArg(i, Arg.get()); 6232 i++; 6233 } 6234 6235 // Make sure variadic args are scalar. 6236 unsigned FirstDataArg = i; 6237 while (i < NumArgs) { 6238 ExprResult Arg = DefaultVariadicArgumentPromotion( 6239 TheCall->getArg(i), VariadicFunction, nullptr); 6240 if (Arg.isInvalid()) 6241 return true; 6242 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6243 if (ArgSize.getQuantity() >= 0x100) { 6244 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6245 << i << (int)ArgSize.getQuantity() << 0xff 6246 << TheCall->getSourceRange(); 6247 } 6248 TheCall->setArg(i, Arg.get()); 6249 i++; 6250 } 6251 6252 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6253 // call to avoid duplicate diagnostics. 6254 if (!IsSizeCall) { 6255 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6256 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6257 bool Success = CheckFormatArguments( 6258 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6259 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6260 CheckedVarArgs); 6261 if (!Success) 6262 return true; 6263 } 6264 6265 if (IsSizeCall) { 6266 TheCall->setType(Context.getSizeType()); 6267 } else { 6268 TheCall->setType(Context.VoidPtrTy); 6269 } 6270 return false; 6271 } 6272 6273 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6274 /// TheCall is a constant expression. 6275 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6276 llvm::APSInt &Result) { 6277 Expr *Arg = TheCall->getArg(ArgNum); 6278 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6280 6281 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6282 6283 Optional<llvm::APSInt> R; 6284 if (!(R = Arg->getIntegerConstantExpr(Context))) 6285 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6286 << FDecl->getDeclName() << Arg->getSourceRange(); 6287 Result = *R; 6288 return false; 6289 } 6290 6291 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6292 /// TheCall is a constant expression in the range [Low, High]. 6293 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6294 int Low, int High, bool RangeIsError) { 6295 if (isConstantEvaluated()) 6296 return false; 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 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6309 if (RangeIsError) 6310 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6311 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6312 else 6313 // Defer the warning until we know if the code will be emitted so that 6314 // dead code can ignore this. 6315 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6316 PDiag(diag::warn_argument_invalid_range) 6317 << Result.toString(10) << Low << High 6318 << Arg->getSourceRange()); 6319 } 6320 6321 return false; 6322 } 6323 6324 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6325 /// TheCall is a constant expression is a multiple of Num.. 6326 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6327 unsigned Num) { 6328 llvm::APSInt Result; 6329 6330 // We can't check the value of a dependent argument. 6331 Expr *Arg = TheCall->getArg(ArgNum); 6332 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6333 return false; 6334 6335 // Check constant-ness first. 6336 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6337 return true; 6338 6339 if (Result.getSExtValue() % Num != 0) 6340 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6341 << Num << Arg->getSourceRange(); 6342 6343 return false; 6344 } 6345 6346 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6347 /// constant expression representing a power of 2. 6348 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6349 llvm::APSInt Result; 6350 6351 // We can't check the value of a dependent argument. 6352 Expr *Arg = TheCall->getArg(ArgNum); 6353 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6354 return false; 6355 6356 // Check constant-ness first. 6357 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6358 return true; 6359 6360 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6361 // and only if x is a power of 2. 6362 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6363 return false; 6364 6365 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6366 << Arg->getSourceRange(); 6367 } 6368 6369 static bool IsShiftedByte(llvm::APSInt Value) { 6370 if (Value.isNegative()) 6371 return false; 6372 6373 // Check if it's a shifted byte, by shifting it down 6374 while (true) { 6375 // If the value fits in the bottom byte, the check passes. 6376 if (Value < 0x100) 6377 return true; 6378 6379 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6380 // fails. 6381 if ((Value & 0xFF) != 0) 6382 return false; 6383 6384 // If the bottom 8 bits are all 0, but something above that is nonzero, 6385 // then shifting the value right by 8 bits won't affect whether it's a 6386 // shifted byte or not. So do that, and go round again. 6387 Value >>= 8; 6388 } 6389 } 6390 6391 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6392 /// a constant expression representing an arbitrary byte value shifted left by 6393 /// a multiple of 8 bits. 6394 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6395 unsigned ArgBits) { 6396 llvm::APSInt Result; 6397 6398 // We can't check the value of a dependent argument. 6399 Expr *Arg = TheCall->getArg(ArgNum); 6400 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6401 return false; 6402 6403 // Check constant-ness first. 6404 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6405 return true; 6406 6407 // Truncate to the given size. 6408 Result = Result.getLoBits(ArgBits); 6409 Result.setIsUnsigned(true); 6410 6411 if (IsShiftedByte(Result)) 6412 return false; 6413 6414 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6415 << Arg->getSourceRange(); 6416 } 6417 6418 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6419 /// TheCall is a constant expression representing either a shifted byte value, 6420 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6421 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6422 /// Arm MVE intrinsics. 6423 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6424 int ArgNum, 6425 unsigned ArgBits) { 6426 llvm::APSInt Result; 6427 6428 // We can't check the value of a dependent argument. 6429 Expr *Arg = TheCall->getArg(ArgNum); 6430 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6431 return false; 6432 6433 // Check constant-ness first. 6434 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6435 return true; 6436 6437 // Truncate to the given size. 6438 Result = Result.getLoBits(ArgBits); 6439 Result.setIsUnsigned(true); 6440 6441 // Check to see if it's in either of the required forms. 6442 if (IsShiftedByte(Result) || 6443 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6444 return false; 6445 6446 return Diag(TheCall->getBeginLoc(), 6447 diag::err_argument_not_shifted_byte_or_xxff) 6448 << Arg->getSourceRange(); 6449 } 6450 6451 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6452 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6453 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6454 if (checkArgCount(*this, TheCall, 2)) 6455 return true; 6456 Expr *Arg0 = TheCall->getArg(0); 6457 Expr *Arg1 = TheCall->getArg(1); 6458 6459 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6460 if (FirstArg.isInvalid()) 6461 return true; 6462 QualType FirstArgType = FirstArg.get()->getType(); 6463 if (!FirstArgType->isAnyPointerType()) 6464 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6465 << "first" << FirstArgType << Arg0->getSourceRange(); 6466 TheCall->setArg(0, FirstArg.get()); 6467 6468 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6469 if (SecArg.isInvalid()) 6470 return true; 6471 QualType SecArgType = SecArg.get()->getType(); 6472 if (!SecArgType->isIntegerType()) 6473 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6474 << "second" << SecArgType << Arg1->getSourceRange(); 6475 6476 // Derive the return type from the pointer argument. 6477 TheCall->setType(FirstArgType); 6478 return false; 6479 } 6480 6481 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6482 if (checkArgCount(*this, TheCall, 2)) 6483 return true; 6484 6485 Expr *Arg0 = TheCall->getArg(0); 6486 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6487 if (FirstArg.isInvalid()) 6488 return true; 6489 QualType FirstArgType = FirstArg.get()->getType(); 6490 if (!FirstArgType->isAnyPointerType()) 6491 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6492 << "first" << FirstArgType << Arg0->getSourceRange(); 6493 TheCall->setArg(0, FirstArg.get()); 6494 6495 // Derive the return type from the pointer argument. 6496 TheCall->setType(FirstArgType); 6497 6498 // Second arg must be an constant in range [0,15] 6499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6500 } 6501 6502 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6503 if (checkArgCount(*this, TheCall, 2)) 6504 return true; 6505 Expr *Arg0 = TheCall->getArg(0); 6506 Expr *Arg1 = TheCall->getArg(1); 6507 6508 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6509 if (FirstArg.isInvalid()) 6510 return true; 6511 QualType FirstArgType = FirstArg.get()->getType(); 6512 if (!FirstArgType->isAnyPointerType()) 6513 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6514 << "first" << FirstArgType << Arg0->getSourceRange(); 6515 6516 QualType SecArgType = Arg1->getType(); 6517 if (!SecArgType->isIntegerType()) 6518 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6519 << "second" << SecArgType << Arg1->getSourceRange(); 6520 TheCall->setType(Context.IntTy); 6521 return false; 6522 } 6523 6524 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6525 BuiltinID == AArch64::BI__builtin_arm_stg) { 6526 if (checkArgCount(*this, TheCall, 1)) 6527 return true; 6528 Expr *Arg0 = TheCall->getArg(0); 6529 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6530 if (FirstArg.isInvalid()) 6531 return true; 6532 6533 QualType FirstArgType = FirstArg.get()->getType(); 6534 if (!FirstArgType->isAnyPointerType()) 6535 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6536 << "first" << FirstArgType << Arg0->getSourceRange(); 6537 TheCall->setArg(0, FirstArg.get()); 6538 6539 // Derive the return type from the pointer argument. 6540 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6541 TheCall->setType(FirstArgType); 6542 return false; 6543 } 6544 6545 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6546 Expr *ArgA = TheCall->getArg(0); 6547 Expr *ArgB = TheCall->getArg(1); 6548 6549 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6550 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6551 6552 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6553 return true; 6554 6555 QualType ArgTypeA = ArgExprA.get()->getType(); 6556 QualType ArgTypeB = ArgExprB.get()->getType(); 6557 6558 auto isNull = [&] (Expr *E) -> bool { 6559 return E->isNullPointerConstant( 6560 Context, Expr::NPC_ValueDependentIsNotNull); }; 6561 6562 // argument should be either a pointer or null 6563 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6564 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6565 << "first" << ArgTypeA << ArgA->getSourceRange(); 6566 6567 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6568 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6569 << "second" << ArgTypeB << ArgB->getSourceRange(); 6570 6571 // Ensure Pointee types are compatible 6572 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6573 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6574 QualType pointeeA = ArgTypeA->getPointeeType(); 6575 QualType pointeeB = ArgTypeB->getPointeeType(); 6576 if (!Context.typesAreCompatible( 6577 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6578 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6579 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6580 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6581 << ArgB->getSourceRange(); 6582 } 6583 } 6584 6585 // at least one argument should be pointer type 6586 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6587 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6588 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6589 6590 if (isNull(ArgA)) // adopt type of the other pointer 6591 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6592 6593 if (isNull(ArgB)) 6594 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6595 6596 TheCall->setArg(0, ArgExprA.get()); 6597 TheCall->setArg(1, ArgExprB.get()); 6598 TheCall->setType(Context.LongLongTy); 6599 return false; 6600 } 6601 assert(false && "Unhandled ARM MTE intrinsic"); 6602 return true; 6603 } 6604 6605 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6606 /// TheCall is an ARM/AArch64 special register string literal. 6607 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6608 int ArgNum, unsigned ExpectedFieldNum, 6609 bool AllowName) { 6610 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6611 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6612 BuiltinID == ARM::BI__builtin_arm_rsr || 6613 BuiltinID == ARM::BI__builtin_arm_rsrp || 6614 BuiltinID == ARM::BI__builtin_arm_wsr || 6615 BuiltinID == ARM::BI__builtin_arm_wsrp; 6616 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6617 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6618 BuiltinID == AArch64::BI__builtin_arm_rsr || 6619 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6620 BuiltinID == AArch64::BI__builtin_arm_wsr || 6621 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6622 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6623 6624 // We can't check the value of a dependent argument. 6625 Expr *Arg = TheCall->getArg(ArgNum); 6626 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6627 return false; 6628 6629 // Check if the argument is a string literal. 6630 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6631 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6632 << Arg->getSourceRange(); 6633 6634 // Check the type of special register given. 6635 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6636 SmallVector<StringRef, 6> Fields; 6637 Reg.split(Fields, ":"); 6638 6639 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6640 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6641 << Arg->getSourceRange(); 6642 6643 // If the string is the name of a register then we cannot check that it is 6644 // valid here but if the string is of one the forms described in ACLE then we 6645 // can check that the supplied fields are integers and within the valid 6646 // ranges. 6647 if (Fields.size() > 1) { 6648 bool FiveFields = Fields.size() == 5; 6649 6650 bool ValidString = true; 6651 if (IsARMBuiltin) { 6652 ValidString &= Fields[0].startswith_lower("cp") || 6653 Fields[0].startswith_lower("p"); 6654 if (ValidString) 6655 Fields[0] = 6656 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6657 6658 ValidString &= Fields[2].startswith_lower("c"); 6659 if (ValidString) 6660 Fields[2] = Fields[2].drop_front(1); 6661 6662 if (FiveFields) { 6663 ValidString &= Fields[3].startswith_lower("c"); 6664 if (ValidString) 6665 Fields[3] = Fields[3].drop_front(1); 6666 } 6667 } 6668 6669 SmallVector<int, 5> Ranges; 6670 if (FiveFields) 6671 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6672 else 6673 Ranges.append({15, 7, 15}); 6674 6675 for (unsigned i=0; i<Fields.size(); ++i) { 6676 int IntField; 6677 ValidString &= !Fields[i].getAsInteger(10, IntField); 6678 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6679 } 6680 6681 if (!ValidString) 6682 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6683 << Arg->getSourceRange(); 6684 } else if (IsAArch64Builtin && Fields.size() == 1) { 6685 // If the register name is one of those that appear in the condition below 6686 // and the special register builtin being used is one of the write builtins, 6687 // then we require that the argument provided for writing to the register 6688 // is an integer constant expression. This is because it will be lowered to 6689 // an MSR (immediate) instruction, so we need to know the immediate at 6690 // compile time. 6691 if (TheCall->getNumArgs() != 2) 6692 return false; 6693 6694 std::string RegLower = Reg.lower(); 6695 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6696 RegLower != "pan" && RegLower != "uao") 6697 return false; 6698 6699 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6700 } 6701 6702 return false; 6703 } 6704 6705 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6706 /// This checks that the target supports __builtin_longjmp and 6707 /// that val is a constant 1. 6708 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6709 if (!Context.getTargetInfo().hasSjLjLowering()) 6710 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6711 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6712 6713 Expr *Arg = TheCall->getArg(1); 6714 llvm::APSInt Result; 6715 6716 // TODO: This is less than ideal. Overload this to take a value. 6717 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6718 return true; 6719 6720 if (Result != 1) 6721 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6722 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6723 6724 return false; 6725 } 6726 6727 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6728 /// This checks that the target supports __builtin_setjmp. 6729 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6730 if (!Context.getTargetInfo().hasSjLjLowering()) 6731 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6732 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6733 return false; 6734 } 6735 6736 namespace { 6737 6738 class UncoveredArgHandler { 6739 enum { Unknown = -1, AllCovered = -2 }; 6740 6741 signed FirstUncoveredArg = Unknown; 6742 SmallVector<const Expr *, 4> DiagnosticExprs; 6743 6744 public: 6745 UncoveredArgHandler() = default; 6746 6747 bool hasUncoveredArg() const { 6748 return (FirstUncoveredArg >= 0); 6749 } 6750 6751 unsigned getUncoveredArg() const { 6752 assert(hasUncoveredArg() && "no uncovered argument"); 6753 return FirstUncoveredArg; 6754 } 6755 6756 void setAllCovered() { 6757 // A string has been found with all arguments covered, so clear out 6758 // the diagnostics. 6759 DiagnosticExprs.clear(); 6760 FirstUncoveredArg = AllCovered; 6761 } 6762 6763 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6764 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6765 6766 // Don't update if a previous string covers all arguments. 6767 if (FirstUncoveredArg == AllCovered) 6768 return; 6769 6770 // UncoveredArgHandler tracks the highest uncovered argument index 6771 // and with it all the strings that match this index. 6772 if (NewFirstUncoveredArg == FirstUncoveredArg) 6773 DiagnosticExprs.push_back(StrExpr); 6774 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6775 DiagnosticExprs.clear(); 6776 DiagnosticExprs.push_back(StrExpr); 6777 FirstUncoveredArg = NewFirstUncoveredArg; 6778 } 6779 } 6780 6781 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6782 }; 6783 6784 enum StringLiteralCheckType { 6785 SLCT_NotALiteral, 6786 SLCT_UncheckedLiteral, 6787 SLCT_CheckedLiteral 6788 }; 6789 6790 } // namespace 6791 6792 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6793 BinaryOperatorKind BinOpKind, 6794 bool AddendIsRight) { 6795 unsigned BitWidth = Offset.getBitWidth(); 6796 unsigned AddendBitWidth = Addend.getBitWidth(); 6797 // There might be negative interim results. 6798 if (Addend.isUnsigned()) { 6799 Addend = Addend.zext(++AddendBitWidth); 6800 Addend.setIsSigned(true); 6801 } 6802 // Adjust the bit width of the APSInts. 6803 if (AddendBitWidth > BitWidth) { 6804 Offset = Offset.sext(AddendBitWidth); 6805 BitWidth = AddendBitWidth; 6806 } else if (BitWidth > AddendBitWidth) { 6807 Addend = Addend.sext(BitWidth); 6808 } 6809 6810 bool Ov = false; 6811 llvm::APSInt ResOffset = Offset; 6812 if (BinOpKind == BO_Add) 6813 ResOffset = Offset.sadd_ov(Addend, Ov); 6814 else { 6815 assert(AddendIsRight && BinOpKind == BO_Sub && 6816 "operator must be add or sub with addend on the right"); 6817 ResOffset = Offset.ssub_ov(Addend, Ov); 6818 } 6819 6820 // We add an offset to a pointer here so we should support an offset as big as 6821 // possible. 6822 if (Ov) { 6823 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6824 "index (intermediate) result too big"); 6825 Offset = Offset.sext(2 * BitWidth); 6826 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6827 return; 6828 } 6829 6830 Offset = ResOffset; 6831 } 6832 6833 namespace { 6834 6835 // This is a wrapper class around StringLiteral to support offsetted string 6836 // literals as format strings. It takes the offset into account when returning 6837 // the string and its length or the source locations to display notes correctly. 6838 class FormatStringLiteral { 6839 const StringLiteral *FExpr; 6840 int64_t Offset; 6841 6842 public: 6843 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6844 : FExpr(fexpr), Offset(Offset) {} 6845 6846 StringRef getString() const { 6847 return FExpr->getString().drop_front(Offset); 6848 } 6849 6850 unsigned getByteLength() const { 6851 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6852 } 6853 6854 unsigned getLength() const { return FExpr->getLength() - Offset; } 6855 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6856 6857 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6858 6859 QualType getType() const { return FExpr->getType(); } 6860 6861 bool isAscii() const { return FExpr->isAscii(); } 6862 bool isWide() const { return FExpr->isWide(); } 6863 bool isUTF8() const { return FExpr->isUTF8(); } 6864 bool isUTF16() const { return FExpr->isUTF16(); } 6865 bool isUTF32() const { return FExpr->isUTF32(); } 6866 bool isPascal() const { return FExpr->isPascal(); } 6867 6868 SourceLocation getLocationOfByte( 6869 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6870 const TargetInfo &Target, unsigned *StartToken = nullptr, 6871 unsigned *StartTokenByteOffset = nullptr) const { 6872 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6873 StartToken, StartTokenByteOffset); 6874 } 6875 6876 SourceLocation getBeginLoc() const LLVM_READONLY { 6877 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6878 } 6879 6880 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6881 }; 6882 6883 } // namespace 6884 6885 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6886 const Expr *OrigFormatExpr, 6887 ArrayRef<const Expr *> Args, 6888 bool HasVAListArg, unsigned format_idx, 6889 unsigned firstDataArg, 6890 Sema::FormatStringType Type, 6891 bool inFunctionCall, 6892 Sema::VariadicCallType CallType, 6893 llvm::SmallBitVector &CheckedVarArgs, 6894 UncoveredArgHandler &UncoveredArg, 6895 bool IgnoreStringsWithoutSpecifiers); 6896 6897 // Determine if an expression is a string literal or constant string. 6898 // If this function returns false on the arguments to a function expecting a 6899 // format string, we will usually need to emit a warning. 6900 // True string literals are then checked by CheckFormatString. 6901 static StringLiteralCheckType 6902 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6903 bool HasVAListArg, unsigned format_idx, 6904 unsigned firstDataArg, Sema::FormatStringType Type, 6905 Sema::VariadicCallType CallType, bool InFunctionCall, 6906 llvm::SmallBitVector &CheckedVarArgs, 6907 UncoveredArgHandler &UncoveredArg, 6908 llvm::APSInt Offset, 6909 bool IgnoreStringsWithoutSpecifiers = false) { 6910 if (S.isConstantEvaluated()) 6911 return SLCT_NotALiteral; 6912 tryAgain: 6913 assert(Offset.isSigned() && "invalid offset"); 6914 6915 if (E->isTypeDependent() || E->isValueDependent()) 6916 return SLCT_NotALiteral; 6917 6918 E = E->IgnoreParenCasts(); 6919 6920 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6921 // Technically -Wformat-nonliteral does not warn about this case. 6922 // The behavior of printf and friends in this case is implementation 6923 // dependent. Ideally if the format string cannot be null then 6924 // it should have a 'nonnull' attribute in the function prototype. 6925 return SLCT_UncheckedLiteral; 6926 6927 switch (E->getStmtClass()) { 6928 case Stmt::BinaryConditionalOperatorClass: 6929 case Stmt::ConditionalOperatorClass: { 6930 // The expression is a literal if both sub-expressions were, and it was 6931 // completely checked only if both sub-expressions were checked. 6932 const AbstractConditionalOperator *C = 6933 cast<AbstractConditionalOperator>(E); 6934 6935 // Determine whether it is necessary to check both sub-expressions, for 6936 // example, because the condition expression is a constant that can be 6937 // evaluated at compile time. 6938 bool CheckLeft = true, CheckRight = true; 6939 6940 bool Cond; 6941 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6942 S.isConstantEvaluated())) { 6943 if (Cond) 6944 CheckRight = false; 6945 else 6946 CheckLeft = false; 6947 } 6948 6949 // We need to maintain the offsets for the right and the left hand side 6950 // separately to check if every possible indexed expression is a valid 6951 // string literal. They might have different offsets for different string 6952 // literals in the end. 6953 StringLiteralCheckType Left; 6954 if (!CheckLeft) 6955 Left = SLCT_UncheckedLiteral; 6956 else { 6957 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6958 HasVAListArg, format_idx, firstDataArg, 6959 Type, CallType, InFunctionCall, 6960 CheckedVarArgs, UncoveredArg, Offset, 6961 IgnoreStringsWithoutSpecifiers); 6962 if (Left == SLCT_NotALiteral || !CheckRight) { 6963 return Left; 6964 } 6965 } 6966 6967 StringLiteralCheckType Right = checkFormatStringExpr( 6968 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6969 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6970 IgnoreStringsWithoutSpecifiers); 6971 6972 return (CheckLeft && Left < Right) ? Left : Right; 6973 } 6974 6975 case Stmt::ImplicitCastExprClass: 6976 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6977 goto tryAgain; 6978 6979 case Stmt::OpaqueValueExprClass: 6980 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6981 E = src; 6982 goto tryAgain; 6983 } 6984 return SLCT_NotALiteral; 6985 6986 case Stmt::PredefinedExprClass: 6987 // While __func__, etc., are technically not string literals, they 6988 // cannot contain format specifiers and thus are not a security 6989 // liability. 6990 return SLCT_UncheckedLiteral; 6991 6992 case Stmt::DeclRefExprClass: { 6993 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6994 6995 // As an exception, do not flag errors for variables binding to 6996 // const string literals. 6997 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6998 bool isConstant = false; 6999 QualType T = DR->getType(); 7000 7001 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7002 isConstant = AT->getElementType().isConstant(S.Context); 7003 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7004 isConstant = T.isConstant(S.Context) && 7005 PT->getPointeeType().isConstant(S.Context); 7006 } else if (T->isObjCObjectPointerType()) { 7007 // In ObjC, there is usually no "const ObjectPointer" type, 7008 // so don't check if the pointee type is constant. 7009 isConstant = T.isConstant(S.Context); 7010 } 7011 7012 if (isConstant) { 7013 if (const Expr *Init = VD->getAnyInitializer()) { 7014 // Look through initializers like const char c[] = { "foo" } 7015 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7016 if (InitList->isStringLiteralInit()) 7017 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7018 } 7019 return checkFormatStringExpr(S, Init, Args, 7020 HasVAListArg, format_idx, 7021 firstDataArg, Type, CallType, 7022 /*InFunctionCall*/ false, CheckedVarArgs, 7023 UncoveredArg, Offset); 7024 } 7025 } 7026 7027 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7028 // special check to see if the format string is a function parameter 7029 // of the function calling the printf function. If the function 7030 // has an attribute indicating it is a printf-like function, then we 7031 // should suppress warnings concerning non-literals being used in a call 7032 // to a vprintf function. For example: 7033 // 7034 // void 7035 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7036 // va_list ap; 7037 // va_start(ap, fmt); 7038 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7039 // ... 7040 // } 7041 if (HasVAListArg) { 7042 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7043 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7044 int PVIndex = PV->getFunctionScopeIndex() + 1; 7045 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7046 // adjust for implicit parameter 7047 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7048 if (MD->isInstance()) 7049 ++PVIndex; 7050 // We also check if the formats are compatible. 7051 // We can't pass a 'scanf' string to a 'printf' function. 7052 if (PVIndex == PVFormat->getFormatIdx() && 7053 Type == S.GetFormatStringType(PVFormat)) 7054 return SLCT_UncheckedLiteral; 7055 } 7056 } 7057 } 7058 } 7059 } 7060 7061 return SLCT_NotALiteral; 7062 } 7063 7064 case Stmt::CallExprClass: 7065 case Stmt::CXXMemberCallExprClass: { 7066 const CallExpr *CE = cast<CallExpr>(E); 7067 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7068 bool IsFirst = true; 7069 StringLiteralCheckType CommonResult; 7070 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7071 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7072 StringLiteralCheckType Result = checkFormatStringExpr( 7073 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7074 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7075 IgnoreStringsWithoutSpecifiers); 7076 if (IsFirst) { 7077 CommonResult = Result; 7078 IsFirst = false; 7079 } 7080 } 7081 if (!IsFirst) 7082 return CommonResult; 7083 7084 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7085 unsigned BuiltinID = FD->getBuiltinID(); 7086 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7087 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7088 const Expr *Arg = CE->getArg(0); 7089 return checkFormatStringExpr(S, Arg, Args, 7090 HasVAListArg, format_idx, 7091 firstDataArg, Type, CallType, 7092 InFunctionCall, CheckedVarArgs, 7093 UncoveredArg, Offset, 7094 IgnoreStringsWithoutSpecifiers); 7095 } 7096 } 7097 } 7098 7099 return SLCT_NotALiteral; 7100 } 7101 case Stmt::ObjCMessageExprClass: { 7102 const auto *ME = cast<ObjCMessageExpr>(E); 7103 if (const auto *MD = ME->getMethodDecl()) { 7104 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7105 // As a special case heuristic, if we're using the method -[NSBundle 7106 // localizedStringForKey:value:table:], ignore any key strings that lack 7107 // format specifiers. The idea is that if the key doesn't have any 7108 // format specifiers then its probably just a key to map to the 7109 // localized strings. If it does have format specifiers though, then its 7110 // likely that the text of the key is the format string in the 7111 // programmer's language, and should be checked. 7112 const ObjCInterfaceDecl *IFace; 7113 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7114 IFace->getIdentifier()->isStr("NSBundle") && 7115 MD->getSelector().isKeywordSelector( 7116 {"localizedStringForKey", "value", "table"})) { 7117 IgnoreStringsWithoutSpecifiers = true; 7118 } 7119 7120 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7121 return checkFormatStringExpr( 7122 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7123 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7124 IgnoreStringsWithoutSpecifiers); 7125 } 7126 } 7127 7128 return SLCT_NotALiteral; 7129 } 7130 case Stmt::ObjCStringLiteralClass: 7131 case Stmt::StringLiteralClass: { 7132 const StringLiteral *StrE = nullptr; 7133 7134 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7135 StrE = ObjCFExpr->getString(); 7136 else 7137 StrE = cast<StringLiteral>(E); 7138 7139 if (StrE) { 7140 if (Offset.isNegative() || Offset > StrE->getLength()) { 7141 // TODO: It would be better to have an explicit warning for out of 7142 // bounds literals. 7143 return SLCT_NotALiteral; 7144 } 7145 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7146 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7147 firstDataArg, Type, InFunctionCall, CallType, 7148 CheckedVarArgs, UncoveredArg, 7149 IgnoreStringsWithoutSpecifiers); 7150 return SLCT_CheckedLiteral; 7151 } 7152 7153 return SLCT_NotALiteral; 7154 } 7155 case Stmt::BinaryOperatorClass: { 7156 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7157 7158 // A string literal + an int offset is still a string literal. 7159 if (BinOp->isAdditiveOp()) { 7160 Expr::EvalResult LResult, RResult; 7161 7162 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7163 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7164 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7165 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7166 7167 if (LIsInt != RIsInt) { 7168 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7169 7170 if (LIsInt) { 7171 if (BinOpKind == BO_Add) { 7172 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7173 E = BinOp->getRHS(); 7174 goto tryAgain; 7175 } 7176 } else { 7177 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7178 E = BinOp->getLHS(); 7179 goto tryAgain; 7180 } 7181 } 7182 } 7183 7184 return SLCT_NotALiteral; 7185 } 7186 case Stmt::UnaryOperatorClass: { 7187 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7188 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7189 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7190 Expr::EvalResult IndexResult; 7191 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7192 Expr::SE_NoSideEffects, 7193 S.isConstantEvaluated())) { 7194 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7195 /*RHS is int*/ true); 7196 E = ASE->getBase(); 7197 goto tryAgain; 7198 } 7199 } 7200 7201 return SLCT_NotALiteral; 7202 } 7203 7204 default: 7205 return SLCT_NotALiteral; 7206 } 7207 } 7208 7209 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7210 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7211 .Case("scanf", FST_Scanf) 7212 .Cases("printf", "printf0", FST_Printf) 7213 .Cases("NSString", "CFString", FST_NSString) 7214 .Case("strftime", FST_Strftime) 7215 .Case("strfmon", FST_Strfmon) 7216 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7217 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7218 .Case("os_trace", FST_OSLog) 7219 .Case("os_log", FST_OSLog) 7220 .Default(FST_Unknown); 7221 } 7222 7223 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7224 /// functions) for correct use of format strings. 7225 /// Returns true if a format string has been fully checked. 7226 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7227 ArrayRef<const Expr *> Args, 7228 bool IsCXXMember, 7229 VariadicCallType CallType, 7230 SourceLocation Loc, SourceRange Range, 7231 llvm::SmallBitVector &CheckedVarArgs) { 7232 FormatStringInfo FSI; 7233 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7234 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7235 FSI.FirstDataArg, GetFormatStringType(Format), 7236 CallType, Loc, Range, CheckedVarArgs); 7237 return false; 7238 } 7239 7240 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7241 bool HasVAListArg, unsigned format_idx, 7242 unsigned firstDataArg, FormatStringType Type, 7243 VariadicCallType CallType, 7244 SourceLocation Loc, SourceRange Range, 7245 llvm::SmallBitVector &CheckedVarArgs) { 7246 // CHECK: printf/scanf-like function is called with no format string. 7247 if (format_idx >= Args.size()) { 7248 Diag(Loc, diag::warn_missing_format_string) << Range; 7249 return false; 7250 } 7251 7252 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7253 7254 // CHECK: format string is not a string literal. 7255 // 7256 // Dynamically generated format strings are difficult to 7257 // automatically vet at compile time. Requiring that format strings 7258 // are string literals: (1) permits the checking of format strings by 7259 // the compiler and thereby (2) can practically remove the source of 7260 // many format string exploits. 7261 7262 // Format string can be either ObjC string (e.g. @"%d") or 7263 // C string (e.g. "%d") 7264 // ObjC string uses the same format specifiers as C string, so we can use 7265 // the same format string checking logic for both ObjC and C strings. 7266 UncoveredArgHandler UncoveredArg; 7267 StringLiteralCheckType CT = 7268 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7269 format_idx, firstDataArg, Type, CallType, 7270 /*IsFunctionCall*/ true, CheckedVarArgs, 7271 UncoveredArg, 7272 /*no string offset*/ llvm::APSInt(64, false) = 0); 7273 7274 // Generate a diagnostic where an uncovered argument is detected. 7275 if (UncoveredArg.hasUncoveredArg()) { 7276 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7277 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7278 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7279 } 7280 7281 if (CT != SLCT_NotALiteral) 7282 // Literal format string found, check done! 7283 return CT == SLCT_CheckedLiteral; 7284 7285 // Strftime is particular as it always uses a single 'time' argument, 7286 // so it is safe to pass a non-literal string. 7287 if (Type == FST_Strftime) 7288 return false; 7289 7290 // Do not emit diag when the string param is a macro expansion and the 7291 // format is either NSString or CFString. This is a hack to prevent 7292 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7293 // which are usually used in place of NS and CF string literals. 7294 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7295 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7296 return false; 7297 7298 // If there are no arguments specified, warn with -Wformat-security, otherwise 7299 // warn only with -Wformat-nonliteral. 7300 if (Args.size() == firstDataArg) { 7301 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7302 << OrigFormatExpr->getSourceRange(); 7303 switch (Type) { 7304 default: 7305 break; 7306 case FST_Kprintf: 7307 case FST_FreeBSDKPrintf: 7308 case FST_Printf: 7309 Diag(FormatLoc, diag::note_format_security_fixit) 7310 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7311 break; 7312 case FST_NSString: 7313 Diag(FormatLoc, diag::note_format_security_fixit) 7314 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7315 break; 7316 } 7317 } else { 7318 Diag(FormatLoc, diag::warn_format_nonliteral) 7319 << OrigFormatExpr->getSourceRange(); 7320 } 7321 return false; 7322 } 7323 7324 namespace { 7325 7326 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7327 protected: 7328 Sema &S; 7329 const FormatStringLiteral *FExpr; 7330 const Expr *OrigFormatExpr; 7331 const Sema::FormatStringType FSType; 7332 const unsigned FirstDataArg; 7333 const unsigned NumDataArgs; 7334 const char *Beg; // Start of format string. 7335 const bool HasVAListArg; 7336 ArrayRef<const Expr *> Args; 7337 unsigned FormatIdx; 7338 llvm::SmallBitVector CoveredArgs; 7339 bool usesPositionalArgs = false; 7340 bool atFirstArg = true; 7341 bool inFunctionCall; 7342 Sema::VariadicCallType CallType; 7343 llvm::SmallBitVector &CheckedVarArgs; 7344 UncoveredArgHandler &UncoveredArg; 7345 7346 public: 7347 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7348 const Expr *origFormatExpr, 7349 const Sema::FormatStringType type, unsigned firstDataArg, 7350 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7351 ArrayRef<const Expr *> Args, unsigned formatIdx, 7352 bool inFunctionCall, Sema::VariadicCallType callType, 7353 llvm::SmallBitVector &CheckedVarArgs, 7354 UncoveredArgHandler &UncoveredArg) 7355 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7356 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7357 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7358 inFunctionCall(inFunctionCall), CallType(callType), 7359 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7360 CoveredArgs.resize(numDataArgs); 7361 CoveredArgs.reset(); 7362 } 7363 7364 void DoneProcessing(); 7365 7366 void HandleIncompleteSpecifier(const char *startSpecifier, 7367 unsigned specifierLen) override; 7368 7369 void HandleInvalidLengthModifier( 7370 const analyze_format_string::FormatSpecifier &FS, 7371 const analyze_format_string::ConversionSpecifier &CS, 7372 const char *startSpecifier, unsigned specifierLen, 7373 unsigned DiagID); 7374 7375 void HandleNonStandardLengthModifier( 7376 const analyze_format_string::FormatSpecifier &FS, 7377 const char *startSpecifier, unsigned specifierLen); 7378 7379 void HandleNonStandardConversionSpecifier( 7380 const analyze_format_string::ConversionSpecifier &CS, 7381 const char *startSpecifier, unsigned specifierLen); 7382 7383 void HandlePosition(const char *startPos, unsigned posLen) override; 7384 7385 void HandleInvalidPosition(const char *startSpecifier, 7386 unsigned specifierLen, 7387 analyze_format_string::PositionContext p) override; 7388 7389 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7390 7391 void HandleNullChar(const char *nullCharacter) override; 7392 7393 template <typename Range> 7394 static void 7395 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7396 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7397 bool IsStringLocation, Range StringRange, 7398 ArrayRef<FixItHint> Fixit = None); 7399 7400 protected: 7401 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7402 const char *startSpec, 7403 unsigned specifierLen, 7404 const char *csStart, unsigned csLen); 7405 7406 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7407 const char *startSpec, 7408 unsigned specifierLen); 7409 7410 SourceRange getFormatStringRange(); 7411 CharSourceRange getSpecifierRange(const char *startSpecifier, 7412 unsigned specifierLen); 7413 SourceLocation getLocationOfByte(const char *x); 7414 7415 const Expr *getDataArg(unsigned i) const; 7416 7417 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7418 const analyze_format_string::ConversionSpecifier &CS, 7419 const char *startSpecifier, unsigned specifierLen, 7420 unsigned argIndex); 7421 7422 template <typename Range> 7423 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7424 bool IsStringLocation, Range StringRange, 7425 ArrayRef<FixItHint> Fixit = None); 7426 }; 7427 7428 } // namespace 7429 7430 SourceRange CheckFormatHandler::getFormatStringRange() { 7431 return OrigFormatExpr->getSourceRange(); 7432 } 7433 7434 CharSourceRange CheckFormatHandler:: 7435 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7436 SourceLocation Start = getLocationOfByte(startSpecifier); 7437 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7438 7439 // Advance the end SourceLocation by one due to half-open ranges. 7440 End = End.getLocWithOffset(1); 7441 7442 return CharSourceRange::getCharRange(Start, End); 7443 } 7444 7445 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7446 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7447 S.getLangOpts(), S.Context.getTargetInfo()); 7448 } 7449 7450 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7451 unsigned specifierLen){ 7452 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7453 getLocationOfByte(startSpecifier), 7454 /*IsStringLocation*/true, 7455 getSpecifierRange(startSpecifier, specifierLen)); 7456 } 7457 7458 void CheckFormatHandler::HandleInvalidLengthModifier( 7459 const analyze_format_string::FormatSpecifier &FS, 7460 const analyze_format_string::ConversionSpecifier &CS, 7461 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7462 using namespace analyze_format_string; 7463 7464 const LengthModifier &LM = FS.getLengthModifier(); 7465 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7466 7467 // See if we know how to fix this length modifier. 7468 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7469 if (FixedLM) { 7470 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7471 getLocationOfByte(LM.getStart()), 7472 /*IsStringLocation*/true, 7473 getSpecifierRange(startSpecifier, specifierLen)); 7474 7475 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7476 << FixedLM->toString() 7477 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7478 7479 } else { 7480 FixItHint Hint; 7481 if (DiagID == diag::warn_format_nonsensical_length) 7482 Hint = FixItHint::CreateRemoval(LMRange); 7483 7484 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7485 getLocationOfByte(LM.getStart()), 7486 /*IsStringLocation*/true, 7487 getSpecifierRange(startSpecifier, specifierLen), 7488 Hint); 7489 } 7490 } 7491 7492 void CheckFormatHandler::HandleNonStandardLengthModifier( 7493 const analyze_format_string::FormatSpecifier &FS, 7494 const char *startSpecifier, unsigned specifierLen) { 7495 using namespace analyze_format_string; 7496 7497 const LengthModifier &LM = FS.getLengthModifier(); 7498 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7499 7500 // See if we know how to fix this length modifier. 7501 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7502 if (FixedLM) { 7503 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7504 << LM.toString() << 0, 7505 getLocationOfByte(LM.getStart()), 7506 /*IsStringLocation*/true, 7507 getSpecifierRange(startSpecifier, specifierLen)); 7508 7509 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7510 << FixedLM->toString() 7511 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7512 7513 } else { 7514 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7515 << LM.toString() << 0, 7516 getLocationOfByte(LM.getStart()), 7517 /*IsStringLocation*/true, 7518 getSpecifierRange(startSpecifier, specifierLen)); 7519 } 7520 } 7521 7522 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7523 const analyze_format_string::ConversionSpecifier &CS, 7524 const char *startSpecifier, unsigned specifierLen) { 7525 using namespace analyze_format_string; 7526 7527 // See if we know how to fix this conversion specifier. 7528 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7529 if (FixedCS) { 7530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7531 << CS.toString() << /*conversion specifier*/1, 7532 getLocationOfByte(CS.getStart()), 7533 /*IsStringLocation*/true, 7534 getSpecifierRange(startSpecifier, specifierLen)); 7535 7536 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7537 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7538 << FixedCS->toString() 7539 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7540 } else { 7541 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7542 << CS.toString() << /*conversion specifier*/1, 7543 getLocationOfByte(CS.getStart()), 7544 /*IsStringLocation*/true, 7545 getSpecifierRange(startSpecifier, specifierLen)); 7546 } 7547 } 7548 7549 void CheckFormatHandler::HandlePosition(const char *startPos, 7550 unsigned posLen) { 7551 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7552 getLocationOfByte(startPos), 7553 /*IsStringLocation*/true, 7554 getSpecifierRange(startPos, posLen)); 7555 } 7556 7557 void 7558 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7559 analyze_format_string::PositionContext p) { 7560 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7561 << (unsigned) p, 7562 getLocationOfByte(startPos), /*IsStringLocation*/true, 7563 getSpecifierRange(startPos, posLen)); 7564 } 7565 7566 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7567 unsigned posLen) { 7568 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7569 getLocationOfByte(startPos), 7570 /*IsStringLocation*/true, 7571 getSpecifierRange(startPos, posLen)); 7572 } 7573 7574 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7575 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7576 // The presence of a null character is likely an error. 7577 EmitFormatDiagnostic( 7578 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7579 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7580 getFormatStringRange()); 7581 } 7582 } 7583 7584 // Note that this may return NULL if there was an error parsing or building 7585 // one of the argument expressions. 7586 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7587 return Args[FirstDataArg + i]; 7588 } 7589 7590 void CheckFormatHandler::DoneProcessing() { 7591 // Does the number of data arguments exceed the number of 7592 // format conversions in the format string? 7593 if (!HasVAListArg) { 7594 // Find any arguments that weren't covered. 7595 CoveredArgs.flip(); 7596 signed notCoveredArg = CoveredArgs.find_first(); 7597 if (notCoveredArg >= 0) { 7598 assert((unsigned)notCoveredArg < NumDataArgs); 7599 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7600 } else { 7601 UncoveredArg.setAllCovered(); 7602 } 7603 } 7604 } 7605 7606 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7607 const Expr *ArgExpr) { 7608 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7609 "Invalid state"); 7610 7611 if (!ArgExpr) 7612 return; 7613 7614 SourceLocation Loc = ArgExpr->getBeginLoc(); 7615 7616 if (S.getSourceManager().isInSystemMacro(Loc)) 7617 return; 7618 7619 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7620 for (auto E : DiagnosticExprs) 7621 PDiag << E->getSourceRange(); 7622 7623 CheckFormatHandler::EmitFormatDiagnostic( 7624 S, IsFunctionCall, DiagnosticExprs[0], 7625 PDiag, Loc, /*IsStringLocation*/false, 7626 DiagnosticExprs[0]->getSourceRange()); 7627 } 7628 7629 bool 7630 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7631 SourceLocation Loc, 7632 const char *startSpec, 7633 unsigned specifierLen, 7634 const char *csStart, 7635 unsigned csLen) { 7636 bool keepGoing = true; 7637 if (argIndex < NumDataArgs) { 7638 // Consider the argument coverered, even though the specifier doesn't 7639 // make sense. 7640 CoveredArgs.set(argIndex); 7641 } 7642 else { 7643 // If argIndex exceeds the number of data arguments we 7644 // don't issue a warning because that is just a cascade of warnings (and 7645 // they may have intended '%%' anyway). We don't want to continue processing 7646 // the format string after this point, however, as we will like just get 7647 // gibberish when trying to match arguments. 7648 keepGoing = false; 7649 } 7650 7651 StringRef Specifier(csStart, csLen); 7652 7653 // If the specifier in non-printable, it could be the first byte of a UTF-8 7654 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7655 // hex value. 7656 std::string CodePointStr; 7657 if (!llvm::sys::locale::isPrint(*csStart)) { 7658 llvm::UTF32 CodePoint; 7659 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7660 const llvm::UTF8 *E = 7661 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7662 llvm::ConversionResult Result = 7663 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7664 7665 if (Result != llvm::conversionOK) { 7666 unsigned char FirstChar = *csStart; 7667 CodePoint = (llvm::UTF32)FirstChar; 7668 } 7669 7670 llvm::raw_string_ostream OS(CodePointStr); 7671 if (CodePoint < 256) 7672 OS << "\\x" << llvm::format("%02x", CodePoint); 7673 else if (CodePoint <= 0xFFFF) 7674 OS << "\\u" << llvm::format("%04x", CodePoint); 7675 else 7676 OS << "\\U" << llvm::format("%08x", CodePoint); 7677 OS.flush(); 7678 Specifier = CodePointStr; 7679 } 7680 7681 EmitFormatDiagnostic( 7682 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7683 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7684 7685 return keepGoing; 7686 } 7687 7688 void 7689 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7690 const char *startSpec, 7691 unsigned specifierLen) { 7692 EmitFormatDiagnostic( 7693 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7694 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7695 } 7696 7697 bool 7698 CheckFormatHandler::CheckNumArgs( 7699 const analyze_format_string::FormatSpecifier &FS, 7700 const analyze_format_string::ConversionSpecifier &CS, 7701 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7702 7703 if (argIndex >= NumDataArgs) { 7704 PartialDiagnostic PDiag = FS.usesPositionalArg() 7705 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7706 << (argIndex+1) << NumDataArgs) 7707 : S.PDiag(diag::warn_printf_insufficient_data_args); 7708 EmitFormatDiagnostic( 7709 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7710 getSpecifierRange(startSpecifier, specifierLen)); 7711 7712 // Since more arguments than conversion tokens are given, by extension 7713 // all arguments are covered, so mark this as so. 7714 UncoveredArg.setAllCovered(); 7715 return false; 7716 } 7717 return true; 7718 } 7719 7720 template<typename Range> 7721 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7722 SourceLocation Loc, 7723 bool IsStringLocation, 7724 Range StringRange, 7725 ArrayRef<FixItHint> FixIt) { 7726 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7727 Loc, IsStringLocation, StringRange, FixIt); 7728 } 7729 7730 /// If the format string is not within the function call, emit a note 7731 /// so that the function call and string are in diagnostic messages. 7732 /// 7733 /// \param InFunctionCall if true, the format string is within the function 7734 /// call and only one diagnostic message will be produced. Otherwise, an 7735 /// extra note will be emitted pointing to location of the format string. 7736 /// 7737 /// \param ArgumentExpr the expression that is passed as the format string 7738 /// argument in the function call. Used for getting locations when two 7739 /// diagnostics are emitted. 7740 /// 7741 /// \param PDiag the callee should already have provided any strings for the 7742 /// diagnostic message. This function only adds locations and fixits 7743 /// to diagnostics. 7744 /// 7745 /// \param Loc primary location for diagnostic. If two diagnostics are 7746 /// required, one will be at Loc and a new SourceLocation will be created for 7747 /// the other one. 7748 /// 7749 /// \param IsStringLocation if true, Loc points to the format string should be 7750 /// used for the note. Otherwise, Loc points to the argument list and will 7751 /// be used with PDiag. 7752 /// 7753 /// \param StringRange some or all of the string to highlight. This is 7754 /// templated so it can accept either a CharSourceRange or a SourceRange. 7755 /// 7756 /// \param FixIt optional fix it hint for the format string. 7757 template <typename Range> 7758 void CheckFormatHandler::EmitFormatDiagnostic( 7759 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7760 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7761 Range StringRange, ArrayRef<FixItHint> FixIt) { 7762 if (InFunctionCall) { 7763 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7764 D << StringRange; 7765 D << FixIt; 7766 } else { 7767 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7768 << ArgumentExpr->getSourceRange(); 7769 7770 const Sema::SemaDiagnosticBuilder &Note = 7771 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7772 diag::note_format_string_defined); 7773 7774 Note << StringRange; 7775 Note << FixIt; 7776 } 7777 } 7778 7779 //===--- CHECK: Printf format string checking ------------------------------===// 7780 7781 namespace { 7782 7783 class CheckPrintfHandler : public CheckFormatHandler { 7784 public: 7785 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7786 const Expr *origFormatExpr, 7787 const Sema::FormatStringType type, unsigned firstDataArg, 7788 unsigned numDataArgs, bool isObjC, const char *beg, 7789 bool hasVAListArg, ArrayRef<const Expr *> Args, 7790 unsigned formatIdx, bool inFunctionCall, 7791 Sema::VariadicCallType CallType, 7792 llvm::SmallBitVector &CheckedVarArgs, 7793 UncoveredArgHandler &UncoveredArg) 7794 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7795 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7796 inFunctionCall, CallType, CheckedVarArgs, 7797 UncoveredArg) {} 7798 7799 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7800 7801 /// Returns true if '%@' specifiers are allowed in the format string. 7802 bool allowsObjCArg() const { 7803 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7804 FSType == Sema::FST_OSTrace; 7805 } 7806 7807 bool HandleInvalidPrintfConversionSpecifier( 7808 const analyze_printf::PrintfSpecifier &FS, 7809 const char *startSpecifier, 7810 unsigned specifierLen) override; 7811 7812 void handleInvalidMaskType(StringRef MaskType) override; 7813 7814 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7815 const char *startSpecifier, 7816 unsigned specifierLen) override; 7817 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7818 const char *StartSpecifier, 7819 unsigned SpecifierLen, 7820 const Expr *E); 7821 7822 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7823 const char *startSpecifier, unsigned specifierLen); 7824 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7825 const analyze_printf::OptionalAmount &Amt, 7826 unsigned type, 7827 const char *startSpecifier, unsigned specifierLen); 7828 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7829 const analyze_printf::OptionalFlag &flag, 7830 const char *startSpecifier, unsigned specifierLen); 7831 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7832 const analyze_printf::OptionalFlag &ignoredFlag, 7833 const analyze_printf::OptionalFlag &flag, 7834 const char *startSpecifier, unsigned specifierLen); 7835 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7836 const Expr *E); 7837 7838 void HandleEmptyObjCModifierFlag(const char *startFlag, 7839 unsigned flagLen) override; 7840 7841 void HandleInvalidObjCModifierFlag(const char *startFlag, 7842 unsigned flagLen) override; 7843 7844 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7845 const char *flagsEnd, 7846 const char *conversionPosition) 7847 override; 7848 }; 7849 7850 } // namespace 7851 7852 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7853 const analyze_printf::PrintfSpecifier &FS, 7854 const char *startSpecifier, 7855 unsigned specifierLen) { 7856 const analyze_printf::PrintfConversionSpecifier &CS = 7857 FS.getConversionSpecifier(); 7858 7859 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7860 getLocationOfByte(CS.getStart()), 7861 startSpecifier, specifierLen, 7862 CS.getStart(), CS.getLength()); 7863 } 7864 7865 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7866 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7867 } 7868 7869 bool CheckPrintfHandler::HandleAmount( 7870 const analyze_format_string::OptionalAmount &Amt, 7871 unsigned k, const char *startSpecifier, 7872 unsigned specifierLen) { 7873 if (Amt.hasDataArgument()) { 7874 if (!HasVAListArg) { 7875 unsigned argIndex = Amt.getArgIndex(); 7876 if (argIndex >= NumDataArgs) { 7877 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7878 << k, 7879 getLocationOfByte(Amt.getStart()), 7880 /*IsStringLocation*/true, 7881 getSpecifierRange(startSpecifier, specifierLen)); 7882 // Don't do any more checking. We will just emit 7883 // spurious errors. 7884 return false; 7885 } 7886 7887 // Type check the data argument. It should be an 'int'. 7888 // Although not in conformance with C99, we also allow the argument to be 7889 // an 'unsigned int' as that is a reasonably safe case. GCC also 7890 // doesn't emit a warning for that case. 7891 CoveredArgs.set(argIndex); 7892 const Expr *Arg = getDataArg(argIndex); 7893 if (!Arg) 7894 return false; 7895 7896 QualType T = Arg->getType(); 7897 7898 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7899 assert(AT.isValid()); 7900 7901 if (!AT.matchesType(S.Context, T)) { 7902 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7903 << k << AT.getRepresentativeTypeName(S.Context) 7904 << T << Arg->getSourceRange(), 7905 getLocationOfByte(Amt.getStart()), 7906 /*IsStringLocation*/true, 7907 getSpecifierRange(startSpecifier, specifierLen)); 7908 // Don't do any more checking. We will just emit 7909 // spurious errors. 7910 return false; 7911 } 7912 } 7913 } 7914 return true; 7915 } 7916 7917 void CheckPrintfHandler::HandleInvalidAmount( 7918 const analyze_printf::PrintfSpecifier &FS, 7919 const analyze_printf::OptionalAmount &Amt, 7920 unsigned type, 7921 const char *startSpecifier, 7922 unsigned specifierLen) { 7923 const analyze_printf::PrintfConversionSpecifier &CS = 7924 FS.getConversionSpecifier(); 7925 7926 FixItHint fixit = 7927 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7928 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7929 Amt.getConstantLength())) 7930 : FixItHint(); 7931 7932 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7933 << type << CS.toString(), 7934 getLocationOfByte(Amt.getStart()), 7935 /*IsStringLocation*/true, 7936 getSpecifierRange(startSpecifier, specifierLen), 7937 fixit); 7938 } 7939 7940 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7941 const analyze_printf::OptionalFlag &flag, 7942 const char *startSpecifier, 7943 unsigned specifierLen) { 7944 // Warn about pointless flag with a fixit removal. 7945 const analyze_printf::PrintfConversionSpecifier &CS = 7946 FS.getConversionSpecifier(); 7947 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7948 << flag.toString() << CS.toString(), 7949 getLocationOfByte(flag.getPosition()), 7950 /*IsStringLocation*/true, 7951 getSpecifierRange(startSpecifier, specifierLen), 7952 FixItHint::CreateRemoval( 7953 getSpecifierRange(flag.getPosition(), 1))); 7954 } 7955 7956 void CheckPrintfHandler::HandleIgnoredFlag( 7957 const analyze_printf::PrintfSpecifier &FS, 7958 const analyze_printf::OptionalFlag &ignoredFlag, 7959 const analyze_printf::OptionalFlag &flag, 7960 const char *startSpecifier, 7961 unsigned specifierLen) { 7962 // Warn about ignored flag with a fixit removal. 7963 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7964 << ignoredFlag.toString() << flag.toString(), 7965 getLocationOfByte(ignoredFlag.getPosition()), 7966 /*IsStringLocation*/true, 7967 getSpecifierRange(startSpecifier, specifierLen), 7968 FixItHint::CreateRemoval( 7969 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7970 } 7971 7972 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7973 unsigned flagLen) { 7974 // Warn about an empty flag. 7975 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7976 getLocationOfByte(startFlag), 7977 /*IsStringLocation*/true, 7978 getSpecifierRange(startFlag, flagLen)); 7979 } 7980 7981 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7982 unsigned flagLen) { 7983 // Warn about an invalid flag. 7984 auto Range = getSpecifierRange(startFlag, flagLen); 7985 StringRef flag(startFlag, flagLen); 7986 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7987 getLocationOfByte(startFlag), 7988 /*IsStringLocation*/true, 7989 Range, FixItHint::CreateRemoval(Range)); 7990 } 7991 7992 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7993 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7994 // Warn about using '[...]' without a '@' conversion. 7995 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7996 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7997 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7998 getLocationOfByte(conversionPosition), 7999 /*IsStringLocation*/true, 8000 Range, FixItHint::CreateRemoval(Range)); 8001 } 8002 8003 // Determines if the specified is a C++ class or struct containing 8004 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8005 // "c_str()"). 8006 template<typename MemberKind> 8007 static llvm::SmallPtrSet<MemberKind*, 1> 8008 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8009 const RecordType *RT = Ty->getAs<RecordType>(); 8010 llvm::SmallPtrSet<MemberKind*, 1> Results; 8011 8012 if (!RT) 8013 return Results; 8014 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8015 if (!RD || !RD->getDefinition()) 8016 return Results; 8017 8018 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8019 Sema::LookupMemberName); 8020 R.suppressDiagnostics(); 8021 8022 // We just need to include all members of the right kind turned up by the 8023 // filter, at this point. 8024 if (S.LookupQualifiedName(R, RT->getDecl())) 8025 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8026 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8027 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8028 Results.insert(FK); 8029 } 8030 return Results; 8031 } 8032 8033 /// Check if we could call '.c_str()' on an object. 8034 /// 8035 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8036 /// allow the call, or if it would be ambiguous). 8037 bool Sema::hasCStrMethod(const Expr *E) { 8038 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8039 8040 MethodSet Results = 8041 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8042 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8043 MI != ME; ++MI) 8044 if ((*MI)->getMinRequiredArguments() == 0) 8045 return true; 8046 return false; 8047 } 8048 8049 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8050 // better diagnostic if so. AT is assumed to be valid. 8051 // Returns true when a c_str() conversion method is found. 8052 bool CheckPrintfHandler::checkForCStrMembers( 8053 const analyze_printf::ArgType &AT, const Expr *E) { 8054 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8055 8056 MethodSet Results = 8057 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8058 8059 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8060 MI != ME; ++MI) { 8061 const CXXMethodDecl *Method = *MI; 8062 if (Method->getMinRequiredArguments() == 0 && 8063 AT.matchesType(S.Context, Method->getReturnType())) { 8064 // FIXME: Suggest parens if the expression needs them. 8065 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8066 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8067 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8068 return true; 8069 } 8070 } 8071 8072 return false; 8073 } 8074 8075 bool 8076 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8077 &FS, 8078 const char *startSpecifier, 8079 unsigned specifierLen) { 8080 using namespace analyze_format_string; 8081 using namespace analyze_printf; 8082 8083 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8084 8085 if (FS.consumesDataArgument()) { 8086 if (atFirstArg) { 8087 atFirstArg = false; 8088 usesPositionalArgs = FS.usesPositionalArg(); 8089 } 8090 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8091 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8092 startSpecifier, specifierLen); 8093 return false; 8094 } 8095 } 8096 8097 // First check if the field width, precision, and conversion specifier 8098 // have matching data arguments. 8099 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8100 startSpecifier, specifierLen)) { 8101 return false; 8102 } 8103 8104 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8105 startSpecifier, specifierLen)) { 8106 return false; 8107 } 8108 8109 if (!CS.consumesDataArgument()) { 8110 // FIXME: Technically specifying a precision or field width here 8111 // makes no sense. Worth issuing a warning at some point. 8112 return true; 8113 } 8114 8115 // Consume the argument. 8116 unsigned argIndex = FS.getArgIndex(); 8117 if (argIndex < NumDataArgs) { 8118 // The check to see if the argIndex is valid will come later. 8119 // We set the bit here because we may exit early from this 8120 // function if we encounter some other error. 8121 CoveredArgs.set(argIndex); 8122 } 8123 8124 // FreeBSD kernel extensions. 8125 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8126 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8127 // We need at least two arguments. 8128 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8129 return false; 8130 8131 // Claim the second argument. 8132 CoveredArgs.set(argIndex + 1); 8133 8134 // Type check the first argument (int for %b, pointer for %D) 8135 const Expr *Ex = getDataArg(argIndex); 8136 const analyze_printf::ArgType &AT = 8137 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8138 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8139 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8140 EmitFormatDiagnostic( 8141 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8142 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8143 << false << Ex->getSourceRange(), 8144 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8145 getSpecifierRange(startSpecifier, specifierLen)); 8146 8147 // Type check the second argument (char * for both %b and %D) 8148 Ex = getDataArg(argIndex + 1); 8149 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8150 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8151 EmitFormatDiagnostic( 8152 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8153 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8154 << false << Ex->getSourceRange(), 8155 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8156 getSpecifierRange(startSpecifier, specifierLen)); 8157 8158 return true; 8159 } 8160 8161 // Check for using an Objective-C specific conversion specifier 8162 // in a non-ObjC literal. 8163 if (!allowsObjCArg() && CS.isObjCArg()) { 8164 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8165 specifierLen); 8166 } 8167 8168 // %P can only be used with os_log. 8169 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8170 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8171 specifierLen); 8172 } 8173 8174 // %n is not allowed with os_log. 8175 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8176 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8177 getLocationOfByte(CS.getStart()), 8178 /*IsStringLocation*/ false, 8179 getSpecifierRange(startSpecifier, specifierLen)); 8180 8181 return true; 8182 } 8183 8184 // Only scalars are allowed for os_trace. 8185 if (FSType == Sema::FST_OSTrace && 8186 (CS.getKind() == ConversionSpecifier::PArg || 8187 CS.getKind() == ConversionSpecifier::sArg || 8188 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8189 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8190 specifierLen); 8191 } 8192 8193 // Check for use of public/private annotation outside of os_log(). 8194 if (FSType != Sema::FST_OSLog) { 8195 if (FS.isPublic().isSet()) { 8196 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8197 << "public", 8198 getLocationOfByte(FS.isPublic().getPosition()), 8199 /*IsStringLocation*/ false, 8200 getSpecifierRange(startSpecifier, specifierLen)); 8201 } 8202 if (FS.isPrivate().isSet()) { 8203 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8204 << "private", 8205 getLocationOfByte(FS.isPrivate().getPosition()), 8206 /*IsStringLocation*/ false, 8207 getSpecifierRange(startSpecifier, specifierLen)); 8208 } 8209 } 8210 8211 // Check for invalid use of field width 8212 if (!FS.hasValidFieldWidth()) { 8213 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8214 startSpecifier, specifierLen); 8215 } 8216 8217 // Check for invalid use of precision 8218 if (!FS.hasValidPrecision()) { 8219 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8220 startSpecifier, specifierLen); 8221 } 8222 8223 // Precision is mandatory for %P specifier. 8224 if (CS.getKind() == ConversionSpecifier::PArg && 8225 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8226 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8227 getLocationOfByte(startSpecifier), 8228 /*IsStringLocation*/ false, 8229 getSpecifierRange(startSpecifier, specifierLen)); 8230 } 8231 8232 // Check each flag does not conflict with any other component. 8233 if (!FS.hasValidThousandsGroupingPrefix()) 8234 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8235 if (!FS.hasValidLeadingZeros()) 8236 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8237 if (!FS.hasValidPlusPrefix()) 8238 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8239 if (!FS.hasValidSpacePrefix()) 8240 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8241 if (!FS.hasValidAlternativeForm()) 8242 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8243 if (!FS.hasValidLeftJustified()) 8244 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8245 8246 // Check that flags are not ignored by another flag 8247 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8248 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8249 startSpecifier, specifierLen); 8250 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8251 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8252 startSpecifier, specifierLen); 8253 8254 // Check the length modifier is valid with the given conversion specifier. 8255 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8256 S.getLangOpts())) 8257 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8258 diag::warn_format_nonsensical_length); 8259 else if (!FS.hasStandardLengthModifier()) 8260 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8261 else if (!FS.hasStandardLengthConversionCombination()) 8262 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8263 diag::warn_format_non_standard_conversion_spec); 8264 8265 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8266 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8267 8268 // The remaining checks depend on the data arguments. 8269 if (HasVAListArg) 8270 return true; 8271 8272 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8273 return false; 8274 8275 const Expr *Arg = getDataArg(argIndex); 8276 if (!Arg) 8277 return true; 8278 8279 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8280 } 8281 8282 static bool requiresParensToAddCast(const Expr *E) { 8283 // FIXME: We should have a general way to reason about operator 8284 // precedence and whether parens are actually needed here. 8285 // Take care of a few common cases where they aren't. 8286 const Expr *Inside = E->IgnoreImpCasts(); 8287 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8288 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8289 8290 switch (Inside->getStmtClass()) { 8291 case Stmt::ArraySubscriptExprClass: 8292 case Stmt::CallExprClass: 8293 case Stmt::CharacterLiteralClass: 8294 case Stmt::CXXBoolLiteralExprClass: 8295 case Stmt::DeclRefExprClass: 8296 case Stmt::FloatingLiteralClass: 8297 case Stmt::IntegerLiteralClass: 8298 case Stmt::MemberExprClass: 8299 case Stmt::ObjCArrayLiteralClass: 8300 case Stmt::ObjCBoolLiteralExprClass: 8301 case Stmt::ObjCBoxedExprClass: 8302 case Stmt::ObjCDictionaryLiteralClass: 8303 case Stmt::ObjCEncodeExprClass: 8304 case Stmt::ObjCIvarRefExprClass: 8305 case Stmt::ObjCMessageExprClass: 8306 case Stmt::ObjCPropertyRefExprClass: 8307 case Stmt::ObjCStringLiteralClass: 8308 case Stmt::ObjCSubscriptRefExprClass: 8309 case Stmt::ParenExprClass: 8310 case Stmt::StringLiteralClass: 8311 case Stmt::UnaryOperatorClass: 8312 return false; 8313 default: 8314 return true; 8315 } 8316 } 8317 8318 static std::pair<QualType, StringRef> 8319 shouldNotPrintDirectly(const ASTContext &Context, 8320 QualType IntendedTy, 8321 const Expr *E) { 8322 // Use a 'while' to peel off layers of typedefs. 8323 QualType TyTy = IntendedTy; 8324 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8325 StringRef Name = UserTy->getDecl()->getName(); 8326 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8327 .Case("CFIndex", Context.getNSIntegerType()) 8328 .Case("NSInteger", Context.getNSIntegerType()) 8329 .Case("NSUInteger", Context.getNSUIntegerType()) 8330 .Case("SInt32", Context.IntTy) 8331 .Case("UInt32", Context.UnsignedIntTy) 8332 .Default(QualType()); 8333 8334 if (!CastTy.isNull()) 8335 return std::make_pair(CastTy, Name); 8336 8337 TyTy = UserTy->desugar(); 8338 } 8339 8340 // Strip parens if necessary. 8341 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8342 return shouldNotPrintDirectly(Context, 8343 PE->getSubExpr()->getType(), 8344 PE->getSubExpr()); 8345 8346 // If this is a conditional expression, then its result type is constructed 8347 // via usual arithmetic conversions and thus there might be no necessary 8348 // typedef sugar there. Recurse to operands to check for NSInteger & 8349 // Co. usage condition. 8350 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8351 QualType TrueTy, FalseTy; 8352 StringRef TrueName, FalseName; 8353 8354 std::tie(TrueTy, TrueName) = 8355 shouldNotPrintDirectly(Context, 8356 CO->getTrueExpr()->getType(), 8357 CO->getTrueExpr()); 8358 std::tie(FalseTy, FalseName) = 8359 shouldNotPrintDirectly(Context, 8360 CO->getFalseExpr()->getType(), 8361 CO->getFalseExpr()); 8362 8363 if (TrueTy == FalseTy) 8364 return std::make_pair(TrueTy, TrueName); 8365 else if (TrueTy.isNull()) 8366 return std::make_pair(FalseTy, FalseName); 8367 else if (FalseTy.isNull()) 8368 return std::make_pair(TrueTy, TrueName); 8369 } 8370 8371 return std::make_pair(QualType(), StringRef()); 8372 } 8373 8374 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8375 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8376 /// type do not count. 8377 static bool 8378 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8379 QualType From = ICE->getSubExpr()->getType(); 8380 QualType To = ICE->getType(); 8381 // It's an integer promotion if the destination type is the promoted 8382 // source type. 8383 if (ICE->getCastKind() == CK_IntegralCast && 8384 From->isPromotableIntegerType() && 8385 S.Context.getPromotedIntegerType(From) == To) 8386 return true; 8387 // Look through vector types, since we do default argument promotion for 8388 // those in OpenCL. 8389 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8390 From = VecTy->getElementType(); 8391 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8392 To = VecTy->getElementType(); 8393 // It's a floating promotion if the source type is a lower rank. 8394 return ICE->getCastKind() == CK_FloatingCast && 8395 S.Context.getFloatingTypeOrder(From, To) < 0; 8396 } 8397 8398 bool 8399 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8400 const char *StartSpecifier, 8401 unsigned SpecifierLen, 8402 const Expr *E) { 8403 using namespace analyze_format_string; 8404 using namespace analyze_printf; 8405 8406 // Now type check the data expression that matches the 8407 // format specifier. 8408 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8409 if (!AT.isValid()) 8410 return true; 8411 8412 QualType ExprTy = E->getType(); 8413 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8414 ExprTy = TET->getUnderlyingExpr()->getType(); 8415 } 8416 8417 // Diagnose attempts to print a boolean value as a character. Unlike other 8418 // -Wformat diagnostics, this is fine from a type perspective, but it still 8419 // doesn't make sense. 8420 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8421 E->isKnownToHaveBooleanValue()) { 8422 const CharSourceRange &CSR = 8423 getSpecifierRange(StartSpecifier, SpecifierLen); 8424 SmallString<4> FSString; 8425 llvm::raw_svector_ostream os(FSString); 8426 FS.toString(os); 8427 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8428 << FSString, 8429 E->getExprLoc(), false, CSR); 8430 return true; 8431 } 8432 8433 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8434 if (Match == analyze_printf::ArgType::Match) 8435 return true; 8436 8437 // Look through argument promotions for our error message's reported type. 8438 // This includes the integral and floating promotions, but excludes array 8439 // and function pointer decay (seeing that an argument intended to be a 8440 // string has type 'char [6]' is probably more confusing than 'char *') and 8441 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8442 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8443 if (isArithmeticArgumentPromotion(S, ICE)) { 8444 E = ICE->getSubExpr(); 8445 ExprTy = E->getType(); 8446 8447 // Check if we didn't match because of an implicit cast from a 'char' 8448 // or 'short' to an 'int'. This is done because printf is a varargs 8449 // function. 8450 if (ICE->getType() == S.Context.IntTy || 8451 ICE->getType() == S.Context.UnsignedIntTy) { 8452 // All further checking is done on the subexpression 8453 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8454 AT.matchesType(S.Context, ExprTy); 8455 if (ImplicitMatch == analyze_printf::ArgType::Match) 8456 return true; 8457 if (ImplicitMatch == ArgType::NoMatchPedantic || 8458 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8459 Match = ImplicitMatch; 8460 } 8461 } 8462 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8463 // Special case for 'a', which has type 'int' in C. 8464 // Note, however, that we do /not/ want to treat multibyte constants like 8465 // 'MooV' as characters! This form is deprecated but still exists. 8466 if (ExprTy == S.Context.IntTy) 8467 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8468 ExprTy = S.Context.CharTy; 8469 } 8470 8471 // Look through enums to their underlying type. 8472 bool IsEnum = false; 8473 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8474 ExprTy = EnumTy->getDecl()->getIntegerType(); 8475 IsEnum = true; 8476 } 8477 8478 // %C in an Objective-C context prints a unichar, not a wchar_t. 8479 // If the argument is an integer of some kind, believe the %C and suggest 8480 // a cast instead of changing the conversion specifier. 8481 QualType IntendedTy = ExprTy; 8482 if (isObjCContext() && 8483 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8484 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8485 !ExprTy->isCharType()) { 8486 // 'unichar' is defined as a typedef of unsigned short, but we should 8487 // prefer using the typedef if it is visible. 8488 IntendedTy = S.Context.UnsignedShortTy; 8489 8490 // While we are here, check if the value is an IntegerLiteral that happens 8491 // to be within the valid range. 8492 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8493 const llvm::APInt &V = IL->getValue(); 8494 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8495 return true; 8496 } 8497 8498 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8499 Sema::LookupOrdinaryName); 8500 if (S.LookupName(Result, S.getCurScope())) { 8501 NamedDecl *ND = Result.getFoundDecl(); 8502 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8503 if (TD->getUnderlyingType() == IntendedTy) 8504 IntendedTy = S.Context.getTypedefType(TD); 8505 } 8506 } 8507 } 8508 8509 // Special-case some of Darwin's platform-independence types by suggesting 8510 // casts to primitive types that are known to be large enough. 8511 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8512 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8513 QualType CastTy; 8514 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8515 if (!CastTy.isNull()) { 8516 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8517 // (long in ASTContext). Only complain to pedants. 8518 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8519 (AT.isSizeT() || AT.isPtrdiffT()) && 8520 AT.matchesType(S.Context, CastTy)) 8521 Match = ArgType::NoMatchPedantic; 8522 IntendedTy = CastTy; 8523 ShouldNotPrintDirectly = true; 8524 } 8525 } 8526 8527 // We may be able to offer a FixItHint if it is a supported type. 8528 PrintfSpecifier fixedFS = FS; 8529 bool Success = 8530 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8531 8532 if (Success) { 8533 // Get the fix string from the fixed format specifier 8534 SmallString<16> buf; 8535 llvm::raw_svector_ostream os(buf); 8536 fixedFS.toString(os); 8537 8538 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8539 8540 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8541 unsigned Diag; 8542 switch (Match) { 8543 case ArgType::Match: llvm_unreachable("expected non-matching"); 8544 case ArgType::NoMatchPedantic: 8545 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8546 break; 8547 case ArgType::NoMatchTypeConfusion: 8548 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8549 break; 8550 case ArgType::NoMatch: 8551 Diag = diag::warn_format_conversion_argument_type_mismatch; 8552 break; 8553 } 8554 8555 // In this case, the specifier is wrong and should be changed to match 8556 // the argument. 8557 EmitFormatDiagnostic(S.PDiag(Diag) 8558 << AT.getRepresentativeTypeName(S.Context) 8559 << IntendedTy << IsEnum << E->getSourceRange(), 8560 E->getBeginLoc(), 8561 /*IsStringLocation*/ false, SpecRange, 8562 FixItHint::CreateReplacement(SpecRange, os.str())); 8563 } else { 8564 // The canonical type for formatting this value is different from the 8565 // actual type of the expression. (This occurs, for example, with Darwin's 8566 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8567 // should be printed as 'long' for 64-bit compatibility.) 8568 // Rather than emitting a normal format/argument mismatch, we want to 8569 // add a cast to the recommended type (and correct the format string 8570 // if necessary). 8571 SmallString<16> CastBuf; 8572 llvm::raw_svector_ostream CastFix(CastBuf); 8573 CastFix << "("; 8574 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8575 CastFix << ")"; 8576 8577 SmallVector<FixItHint,4> Hints; 8578 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8579 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8580 8581 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8582 // If there's already a cast present, just replace it. 8583 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8584 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8585 8586 } else if (!requiresParensToAddCast(E)) { 8587 // If the expression has high enough precedence, 8588 // just write the C-style cast. 8589 Hints.push_back( 8590 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8591 } else { 8592 // Otherwise, add parens around the expression as well as the cast. 8593 CastFix << "("; 8594 Hints.push_back( 8595 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8596 8597 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8598 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8599 } 8600 8601 if (ShouldNotPrintDirectly) { 8602 // The expression has a type that should not be printed directly. 8603 // We extract the name from the typedef because we don't want to show 8604 // the underlying type in the diagnostic. 8605 StringRef Name; 8606 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8607 Name = TypedefTy->getDecl()->getName(); 8608 else 8609 Name = CastTyName; 8610 unsigned Diag = Match == ArgType::NoMatchPedantic 8611 ? diag::warn_format_argument_needs_cast_pedantic 8612 : diag::warn_format_argument_needs_cast; 8613 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8614 << E->getSourceRange(), 8615 E->getBeginLoc(), /*IsStringLocation=*/false, 8616 SpecRange, Hints); 8617 } else { 8618 // In this case, the expression could be printed using a different 8619 // specifier, but we've decided that the specifier is probably correct 8620 // and we should cast instead. Just use the normal warning message. 8621 EmitFormatDiagnostic( 8622 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8623 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8624 << E->getSourceRange(), 8625 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8626 } 8627 } 8628 } else { 8629 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8630 SpecifierLen); 8631 // Since the warning for passing non-POD types to variadic functions 8632 // was deferred until now, we emit a warning for non-POD 8633 // arguments here. 8634 switch (S.isValidVarArgType(ExprTy)) { 8635 case Sema::VAK_Valid: 8636 case Sema::VAK_ValidInCXX11: { 8637 unsigned Diag; 8638 switch (Match) { 8639 case ArgType::Match: llvm_unreachable("expected non-matching"); 8640 case ArgType::NoMatchPedantic: 8641 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8642 break; 8643 case ArgType::NoMatchTypeConfusion: 8644 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8645 break; 8646 case ArgType::NoMatch: 8647 Diag = diag::warn_format_conversion_argument_type_mismatch; 8648 break; 8649 } 8650 8651 EmitFormatDiagnostic( 8652 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8653 << IsEnum << CSR << E->getSourceRange(), 8654 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8655 break; 8656 } 8657 case Sema::VAK_Undefined: 8658 case Sema::VAK_MSVCUndefined: 8659 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8660 << S.getLangOpts().CPlusPlus11 << ExprTy 8661 << CallType 8662 << AT.getRepresentativeTypeName(S.Context) << CSR 8663 << E->getSourceRange(), 8664 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8665 checkForCStrMembers(AT, E); 8666 break; 8667 8668 case Sema::VAK_Invalid: 8669 if (ExprTy->isObjCObjectType()) 8670 EmitFormatDiagnostic( 8671 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8672 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8673 << AT.getRepresentativeTypeName(S.Context) << CSR 8674 << E->getSourceRange(), 8675 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8676 else 8677 // FIXME: If this is an initializer list, suggest removing the braces 8678 // or inserting a cast to the target type. 8679 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8680 << isa<InitListExpr>(E) << ExprTy << CallType 8681 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8682 break; 8683 } 8684 8685 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8686 "format string specifier index out of range"); 8687 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8688 } 8689 8690 return true; 8691 } 8692 8693 //===--- CHECK: Scanf format string checking ------------------------------===// 8694 8695 namespace { 8696 8697 class CheckScanfHandler : public CheckFormatHandler { 8698 public: 8699 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8700 const Expr *origFormatExpr, Sema::FormatStringType type, 8701 unsigned firstDataArg, unsigned numDataArgs, 8702 const char *beg, bool hasVAListArg, 8703 ArrayRef<const Expr *> Args, unsigned formatIdx, 8704 bool inFunctionCall, Sema::VariadicCallType CallType, 8705 llvm::SmallBitVector &CheckedVarArgs, 8706 UncoveredArgHandler &UncoveredArg) 8707 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8708 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8709 inFunctionCall, CallType, CheckedVarArgs, 8710 UncoveredArg) {} 8711 8712 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8713 const char *startSpecifier, 8714 unsigned specifierLen) override; 8715 8716 bool HandleInvalidScanfConversionSpecifier( 8717 const analyze_scanf::ScanfSpecifier &FS, 8718 const char *startSpecifier, 8719 unsigned specifierLen) override; 8720 8721 void HandleIncompleteScanList(const char *start, const char *end) override; 8722 }; 8723 8724 } // namespace 8725 8726 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8727 const char *end) { 8728 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8729 getLocationOfByte(end), /*IsStringLocation*/true, 8730 getSpecifierRange(start, end - start)); 8731 } 8732 8733 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8734 const analyze_scanf::ScanfSpecifier &FS, 8735 const char *startSpecifier, 8736 unsigned specifierLen) { 8737 const analyze_scanf::ScanfConversionSpecifier &CS = 8738 FS.getConversionSpecifier(); 8739 8740 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8741 getLocationOfByte(CS.getStart()), 8742 startSpecifier, specifierLen, 8743 CS.getStart(), CS.getLength()); 8744 } 8745 8746 bool CheckScanfHandler::HandleScanfSpecifier( 8747 const analyze_scanf::ScanfSpecifier &FS, 8748 const char *startSpecifier, 8749 unsigned specifierLen) { 8750 using namespace analyze_scanf; 8751 using namespace analyze_format_string; 8752 8753 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8754 8755 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8756 // be used to decide if we are using positional arguments consistently. 8757 if (FS.consumesDataArgument()) { 8758 if (atFirstArg) { 8759 atFirstArg = false; 8760 usesPositionalArgs = FS.usesPositionalArg(); 8761 } 8762 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8763 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8764 startSpecifier, specifierLen); 8765 return false; 8766 } 8767 } 8768 8769 // Check if the field with is non-zero. 8770 const OptionalAmount &Amt = FS.getFieldWidth(); 8771 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8772 if (Amt.getConstantAmount() == 0) { 8773 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8774 Amt.getConstantLength()); 8775 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8776 getLocationOfByte(Amt.getStart()), 8777 /*IsStringLocation*/true, R, 8778 FixItHint::CreateRemoval(R)); 8779 } 8780 } 8781 8782 if (!FS.consumesDataArgument()) { 8783 // FIXME: Technically specifying a precision or field width here 8784 // makes no sense. Worth issuing a warning at some point. 8785 return true; 8786 } 8787 8788 // Consume the argument. 8789 unsigned argIndex = FS.getArgIndex(); 8790 if (argIndex < NumDataArgs) { 8791 // The check to see if the argIndex is valid will come later. 8792 // We set the bit here because we may exit early from this 8793 // function if we encounter some other error. 8794 CoveredArgs.set(argIndex); 8795 } 8796 8797 // Check the length modifier is valid with the given conversion specifier. 8798 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8799 S.getLangOpts())) 8800 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8801 diag::warn_format_nonsensical_length); 8802 else if (!FS.hasStandardLengthModifier()) 8803 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8804 else if (!FS.hasStandardLengthConversionCombination()) 8805 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8806 diag::warn_format_non_standard_conversion_spec); 8807 8808 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8809 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8810 8811 // The remaining checks depend on the data arguments. 8812 if (HasVAListArg) 8813 return true; 8814 8815 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8816 return false; 8817 8818 // Check that the argument type matches the format specifier. 8819 const Expr *Ex = getDataArg(argIndex); 8820 if (!Ex) 8821 return true; 8822 8823 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8824 8825 if (!AT.isValid()) { 8826 return true; 8827 } 8828 8829 analyze_format_string::ArgType::MatchKind Match = 8830 AT.matchesType(S.Context, Ex->getType()); 8831 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8832 if (Match == analyze_format_string::ArgType::Match) 8833 return true; 8834 8835 ScanfSpecifier fixedFS = FS; 8836 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8837 S.getLangOpts(), S.Context); 8838 8839 unsigned Diag = 8840 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8841 : diag::warn_format_conversion_argument_type_mismatch; 8842 8843 if (Success) { 8844 // Get the fix string from the fixed format specifier. 8845 SmallString<128> buf; 8846 llvm::raw_svector_ostream os(buf); 8847 fixedFS.toString(os); 8848 8849 EmitFormatDiagnostic( 8850 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8851 << Ex->getType() << false << Ex->getSourceRange(), 8852 Ex->getBeginLoc(), 8853 /*IsStringLocation*/ false, 8854 getSpecifierRange(startSpecifier, specifierLen), 8855 FixItHint::CreateReplacement( 8856 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8857 } else { 8858 EmitFormatDiagnostic(S.PDiag(Diag) 8859 << AT.getRepresentativeTypeName(S.Context) 8860 << Ex->getType() << false << Ex->getSourceRange(), 8861 Ex->getBeginLoc(), 8862 /*IsStringLocation*/ false, 8863 getSpecifierRange(startSpecifier, specifierLen)); 8864 } 8865 8866 return true; 8867 } 8868 8869 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8870 const Expr *OrigFormatExpr, 8871 ArrayRef<const Expr *> Args, 8872 bool HasVAListArg, unsigned format_idx, 8873 unsigned firstDataArg, 8874 Sema::FormatStringType Type, 8875 bool inFunctionCall, 8876 Sema::VariadicCallType CallType, 8877 llvm::SmallBitVector &CheckedVarArgs, 8878 UncoveredArgHandler &UncoveredArg, 8879 bool IgnoreStringsWithoutSpecifiers) { 8880 // CHECK: is the format string a wide literal? 8881 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8882 CheckFormatHandler::EmitFormatDiagnostic( 8883 S, inFunctionCall, Args[format_idx], 8884 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8885 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8886 return; 8887 } 8888 8889 // Str - The format string. NOTE: this is NOT null-terminated! 8890 StringRef StrRef = FExpr->getString(); 8891 const char *Str = StrRef.data(); 8892 // Account for cases where the string literal is truncated in a declaration. 8893 const ConstantArrayType *T = 8894 S.Context.getAsConstantArrayType(FExpr->getType()); 8895 assert(T && "String literal not of constant array type!"); 8896 size_t TypeSize = T->getSize().getZExtValue(); 8897 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8898 const unsigned numDataArgs = Args.size() - firstDataArg; 8899 8900 if (IgnoreStringsWithoutSpecifiers && 8901 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8902 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8903 return; 8904 8905 // Emit a warning if the string literal is truncated and does not contain an 8906 // embedded null character. 8907 if (TypeSize <= StrRef.size() && 8908 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8909 CheckFormatHandler::EmitFormatDiagnostic( 8910 S, inFunctionCall, Args[format_idx], 8911 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8912 FExpr->getBeginLoc(), 8913 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8914 return; 8915 } 8916 8917 // CHECK: empty format string? 8918 if (StrLen == 0 && numDataArgs > 0) { 8919 CheckFormatHandler::EmitFormatDiagnostic( 8920 S, inFunctionCall, Args[format_idx], 8921 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8922 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8923 return; 8924 } 8925 8926 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8927 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8928 Type == Sema::FST_OSTrace) { 8929 CheckPrintfHandler H( 8930 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8931 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8932 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8933 CheckedVarArgs, UncoveredArg); 8934 8935 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8936 S.getLangOpts(), 8937 S.Context.getTargetInfo(), 8938 Type == Sema::FST_FreeBSDKPrintf)) 8939 H.DoneProcessing(); 8940 } else if (Type == Sema::FST_Scanf) { 8941 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8942 numDataArgs, Str, HasVAListArg, Args, format_idx, 8943 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8944 8945 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8946 S.getLangOpts(), 8947 S.Context.getTargetInfo())) 8948 H.DoneProcessing(); 8949 } // TODO: handle other formats 8950 } 8951 8952 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8953 // Str - The format string. NOTE: this is NOT null-terminated! 8954 StringRef StrRef = FExpr->getString(); 8955 const char *Str = StrRef.data(); 8956 // Account for cases where the string literal is truncated in a declaration. 8957 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8958 assert(T && "String literal not of constant array type!"); 8959 size_t TypeSize = T->getSize().getZExtValue(); 8960 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8961 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8962 getLangOpts(), 8963 Context.getTargetInfo()); 8964 } 8965 8966 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8967 8968 // Returns the related absolute value function that is larger, of 0 if one 8969 // does not exist. 8970 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8971 switch (AbsFunction) { 8972 default: 8973 return 0; 8974 8975 case Builtin::BI__builtin_abs: 8976 return Builtin::BI__builtin_labs; 8977 case Builtin::BI__builtin_labs: 8978 return Builtin::BI__builtin_llabs; 8979 case Builtin::BI__builtin_llabs: 8980 return 0; 8981 8982 case Builtin::BI__builtin_fabsf: 8983 return Builtin::BI__builtin_fabs; 8984 case Builtin::BI__builtin_fabs: 8985 return Builtin::BI__builtin_fabsl; 8986 case Builtin::BI__builtin_fabsl: 8987 return 0; 8988 8989 case Builtin::BI__builtin_cabsf: 8990 return Builtin::BI__builtin_cabs; 8991 case Builtin::BI__builtin_cabs: 8992 return Builtin::BI__builtin_cabsl; 8993 case Builtin::BI__builtin_cabsl: 8994 return 0; 8995 8996 case Builtin::BIabs: 8997 return Builtin::BIlabs; 8998 case Builtin::BIlabs: 8999 return Builtin::BIllabs; 9000 case Builtin::BIllabs: 9001 return 0; 9002 9003 case Builtin::BIfabsf: 9004 return Builtin::BIfabs; 9005 case Builtin::BIfabs: 9006 return Builtin::BIfabsl; 9007 case Builtin::BIfabsl: 9008 return 0; 9009 9010 case Builtin::BIcabsf: 9011 return Builtin::BIcabs; 9012 case Builtin::BIcabs: 9013 return Builtin::BIcabsl; 9014 case Builtin::BIcabsl: 9015 return 0; 9016 } 9017 } 9018 9019 // Returns the argument type of the absolute value function. 9020 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9021 unsigned AbsType) { 9022 if (AbsType == 0) 9023 return QualType(); 9024 9025 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9026 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9027 if (Error != ASTContext::GE_None) 9028 return QualType(); 9029 9030 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9031 if (!FT) 9032 return QualType(); 9033 9034 if (FT->getNumParams() != 1) 9035 return QualType(); 9036 9037 return FT->getParamType(0); 9038 } 9039 9040 // Returns the best absolute value function, or zero, based on type and 9041 // current absolute value function. 9042 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9043 unsigned AbsFunctionKind) { 9044 unsigned BestKind = 0; 9045 uint64_t ArgSize = Context.getTypeSize(ArgType); 9046 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9047 Kind = getLargerAbsoluteValueFunction(Kind)) { 9048 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9049 if (Context.getTypeSize(ParamType) >= ArgSize) { 9050 if (BestKind == 0) 9051 BestKind = Kind; 9052 else if (Context.hasSameType(ParamType, ArgType)) { 9053 BestKind = Kind; 9054 break; 9055 } 9056 } 9057 } 9058 return BestKind; 9059 } 9060 9061 enum AbsoluteValueKind { 9062 AVK_Integer, 9063 AVK_Floating, 9064 AVK_Complex 9065 }; 9066 9067 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9068 if (T->isIntegralOrEnumerationType()) 9069 return AVK_Integer; 9070 if (T->isRealFloatingType()) 9071 return AVK_Floating; 9072 if (T->isAnyComplexType()) 9073 return AVK_Complex; 9074 9075 llvm_unreachable("Type not integer, floating, or complex"); 9076 } 9077 9078 // Changes the absolute value function to a different type. Preserves whether 9079 // the function is a builtin. 9080 static unsigned changeAbsFunction(unsigned AbsKind, 9081 AbsoluteValueKind ValueKind) { 9082 switch (ValueKind) { 9083 case AVK_Integer: 9084 switch (AbsKind) { 9085 default: 9086 return 0; 9087 case Builtin::BI__builtin_fabsf: 9088 case Builtin::BI__builtin_fabs: 9089 case Builtin::BI__builtin_fabsl: 9090 case Builtin::BI__builtin_cabsf: 9091 case Builtin::BI__builtin_cabs: 9092 case Builtin::BI__builtin_cabsl: 9093 return Builtin::BI__builtin_abs; 9094 case Builtin::BIfabsf: 9095 case Builtin::BIfabs: 9096 case Builtin::BIfabsl: 9097 case Builtin::BIcabsf: 9098 case Builtin::BIcabs: 9099 case Builtin::BIcabsl: 9100 return Builtin::BIabs; 9101 } 9102 case AVK_Floating: 9103 switch (AbsKind) { 9104 default: 9105 return 0; 9106 case Builtin::BI__builtin_abs: 9107 case Builtin::BI__builtin_labs: 9108 case Builtin::BI__builtin_llabs: 9109 case Builtin::BI__builtin_cabsf: 9110 case Builtin::BI__builtin_cabs: 9111 case Builtin::BI__builtin_cabsl: 9112 return Builtin::BI__builtin_fabsf; 9113 case Builtin::BIabs: 9114 case Builtin::BIlabs: 9115 case Builtin::BIllabs: 9116 case Builtin::BIcabsf: 9117 case Builtin::BIcabs: 9118 case Builtin::BIcabsl: 9119 return Builtin::BIfabsf; 9120 } 9121 case AVK_Complex: 9122 switch (AbsKind) { 9123 default: 9124 return 0; 9125 case Builtin::BI__builtin_abs: 9126 case Builtin::BI__builtin_labs: 9127 case Builtin::BI__builtin_llabs: 9128 case Builtin::BI__builtin_fabsf: 9129 case Builtin::BI__builtin_fabs: 9130 case Builtin::BI__builtin_fabsl: 9131 return Builtin::BI__builtin_cabsf; 9132 case Builtin::BIabs: 9133 case Builtin::BIlabs: 9134 case Builtin::BIllabs: 9135 case Builtin::BIfabsf: 9136 case Builtin::BIfabs: 9137 case Builtin::BIfabsl: 9138 return Builtin::BIcabsf; 9139 } 9140 } 9141 llvm_unreachable("Unable to convert function"); 9142 } 9143 9144 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9145 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9146 if (!FnInfo) 9147 return 0; 9148 9149 switch (FDecl->getBuiltinID()) { 9150 default: 9151 return 0; 9152 case Builtin::BI__builtin_abs: 9153 case Builtin::BI__builtin_fabs: 9154 case Builtin::BI__builtin_fabsf: 9155 case Builtin::BI__builtin_fabsl: 9156 case Builtin::BI__builtin_labs: 9157 case Builtin::BI__builtin_llabs: 9158 case Builtin::BI__builtin_cabs: 9159 case Builtin::BI__builtin_cabsf: 9160 case Builtin::BI__builtin_cabsl: 9161 case Builtin::BIabs: 9162 case Builtin::BIlabs: 9163 case Builtin::BIllabs: 9164 case Builtin::BIfabs: 9165 case Builtin::BIfabsf: 9166 case Builtin::BIfabsl: 9167 case Builtin::BIcabs: 9168 case Builtin::BIcabsf: 9169 case Builtin::BIcabsl: 9170 return FDecl->getBuiltinID(); 9171 } 9172 llvm_unreachable("Unknown Builtin type"); 9173 } 9174 9175 // If the replacement is valid, emit a note with replacement function. 9176 // Additionally, suggest including the proper header if not already included. 9177 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9178 unsigned AbsKind, QualType ArgType) { 9179 bool EmitHeaderHint = true; 9180 const char *HeaderName = nullptr; 9181 const char *FunctionName = nullptr; 9182 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9183 FunctionName = "std::abs"; 9184 if (ArgType->isIntegralOrEnumerationType()) { 9185 HeaderName = "cstdlib"; 9186 } else if (ArgType->isRealFloatingType()) { 9187 HeaderName = "cmath"; 9188 } else { 9189 llvm_unreachable("Invalid Type"); 9190 } 9191 9192 // Lookup all std::abs 9193 if (NamespaceDecl *Std = S.getStdNamespace()) { 9194 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9195 R.suppressDiagnostics(); 9196 S.LookupQualifiedName(R, Std); 9197 9198 for (const auto *I : R) { 9199 const FunctionDecl *FDecl = nullptr; 9200 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9201 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9202 } else { 9203 FDecl = dyn_cast<FunctionDecl>(I); 9204 } 9205 if (!FDecl) 9206 continue; 9207 9208 // Found std::abs(), check that they are the right ones. 9209 if (FDecl->getNumParams() != 1) 9210 continue; 9211 9212 // Check that the parameter type can handle the argument. 9213 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9214 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9215 S.Context.getTypeSize(ArgType) <= 9216 S.Context.getTypeSize(ParamType)) { 9217 // Found a function, don't need the header hint. 9218 EmitHeaderHint = false; 9219 break; 9220 } 9221 } 9222 } 9223 } else { 9224 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9225 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9226 9227 if (HeaderName) { 9228 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9229 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9230 R.suppressDiagnostics(); 9231 S.LookupName(R, S.getCurScope()); 9232 9233 if (R.isSingleResult()) { 9234 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9235 if (FD && FD->getBuiltinID() == AbsKind) { 9236 EmitHeaderHint = false; 9237 } else { 9238 return; 9239 } 9240 } else if (!R.empty()) { 9241 return; 9242 } 9243 } 9244 } 9245 9246 S.Diag(Loc, diag::note_replace_abs_function) 9247 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9248 9249 if (!HeaderName) 9250 return; 9251 9252 if (!EmitHeaderHint) 9253 return; 9254 9255 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9256 << FunctionName; 9257 } 9258 9259 template <std::size_t StrLen> 9260 static bool IsStdFunction(const FunctionDecl *FDecl, 9261 const char (&Str)[StrLen]) { 9262 if (!FDecl) 9263 return false; 9264 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9265 return false; 9266 if (!FDecl->isInStdNamespace()) 9267 return false; 9268 9269 return true; 9270 } 9271 9272 // Warn when using the wrong abs() function. 9273 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9274 const FunctionDecl *FDecl) { 9275 if (Call->getNumArgs() != 1) 9276 return; 9277 9278 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9279 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9280 if (AbsKind == 0 && !IsStdAbs) 9281 return; 9282 9283 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9284 QualType ParamType = Call->getArg(0)->getType(); 9285 9286 // Unsigned types cannot be negative. Suggest removing the absolute value 9287 // function call. 9288 if (ArgType->isUnsignedIntegerType()) { 9289 const char *FunctionName = 9290 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9291 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9292 Diag(Call->getExprLoc(), diag::note_remove_abs) 9293 << FunctionName 9294 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9295 return; 9296 } 9297 9298 // Taking the absolute value of a pointer is very suspicious, they probably 9299 // wanted to index into an array, dereference a pointer, call a function, etc. 9300 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9301 unsigned DiagType = 0; 9302 if (ArgType->isFunctionType()) 9303 DiagType = 1; 9304 else if (ArgType->isArrayType()) 9305 DiagType = 2; 9306 9307 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9308 return; 9309 } 9310 9311 // std::abs has overloads which prevent most of the absolute value problems 9312 // from occurring. 9313 if (IsStdAbs) 9314 return; 9315 9316 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9317 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9318 9319 // The argument and parameter are the same kind. Check if they are the right 9320 // size. 9321 if (ArgValueKind == ParamValueKind) { 9322 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9323 return; 9324 9325 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9326 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9327 << FDecl << ArgType << ParamType; 9328 9329 if (NewAbsKind == 0) 9330 return; 9331 9332 emitReplacement(*this, Call->getExprLoc(), 9333 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9334 return; 9335 } 9336 9337 // ArgValueKind != ParamValueKind 9338 // The wrong type of absolute value function was used. Attempt to find the 9339 // proper one. 9340 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9341 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9342 if (NewAbsKind == 0) 9343 return; 9344 9345 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9346 << FDecl << ParamValueKind << ArgValueKind; 9347 9348 emitReplacement(*this, Call->getExprLoc(), 9349 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9350 } 9351 9352 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9353 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9354 const FunctionDecl *FDecl) { 9355 if (!Call || !FDecl) return; 9356 9357 // Ignore template specializations and macros. 9358 if (inTemplateInstantiation()) return; 9359 if (Call->getExprLoc().isMacroID()) return; 9360 9361 // Only care about the one template argument, two function parameter std::max 9362 if (Call->getNumArgs() != 2) return; 9363 if (!IsStdFunction(FDecl, "max")) return; 9364 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9365 if (!ArgList) return; 9366 if (ArgList->size() != 1) return; 9367 9368 // Check that template type argument is unsigned integer. 9369 const auto& TA = ArgList->get(0); 9370 if (TA.getKind() != TemplateArgument::Type) return; 9371 QualType ArgType = TA.getAsType(); 9372 if (!ArgType->isUnsignedIntegerType()) return; 9373 9374 // See if either argument is a literal zero. 9375 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9376 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9377 if (!MTE) return false; 9378 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9379 if (!Num) return false; 9380 if (Num->getValue() != 0) return false; 9381 return true; 9382 }; 9383 9384 const Expr *FirstArg = Call->getArg(0); 9385 const Expr *SecondArg = Call->getArg(1); 9386 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9387 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9388 9389 // Only warn when exactly one argument is zero. 9390 if (IsFirstArgZero == IsSecondArgZero) return; 9391 9392 SourceRange FirstRange = FirstArg->getSourceRange(); 9393 SourceRange SecondRange = SecondArg->getSourceRange(); 9394 9395 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9396 9397 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9398 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9399 9400 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9401 SourceRange RemovalRange; 9402 if (IsFirstArgZero) { 9403 RemovalRange = SourceRange(FirstRange.getBegin(), 9404 SecondRange.getBegin().getLocWithOffset(-1)); 9405 } else { 9406 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9407 SecondRange.getEnd()); 9408 } 9409 9410 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9411 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9412 << FixItHint::CreateRemoval(RemovalRange); 9413 } 9414 9415 //===--- CHECK: Standard memory functions ---------------------------------===// 9416 9417 /// Takes the expression passed to the size_t parameter of functions 9418 /// such as memcmp, strncat, etc and warns if it's a comparison. 9419 /// 9420 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9421 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9422 IdentifierInfo *FnName, 9423 SourceLocation FnLoc, 9424 SourceLocation RParenLoc) { 9425 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9426 if (!Size) 9427 return false; 9428 9429 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9430 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9431 return false; 9432 9433 SourceRange SizeRange = Size->getSourceRange(); 9434 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9435 << SizeRange << FnName; 9436 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9437 << FnName 9438 << FixItHint::CreateInsertion( 9439 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9440 << FixItHint::CreateRemoval(RParenLoc); 9441 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9442 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9443 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9444 ")"); 9445 9446 return true; 9447 } 9448 9449 /// Determine whether the given type is or contains a dynamic class type 9450 /// (e.g., whether it has a vtable). 9451 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9452 bool &IsContained) { 9453 // Look through array types while ignoring qualifiers. 9454 const Type *Ty = T->getBaseElementTypeUnsafe(); 9455 IsContained = false; 9456 9457 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9458 RD = RD ? RD->getDefinition() : nullptr; 9459 if (!RD || RD->isInvalidDecl()) 9460 return nullptr; 9461 9462 if (RD->isDynamicClass()) 9463 return RD; 9464 9465 // Check all the fields. If any bases were dynamic, the class is dynamic. 9466 // It's impossible for a class to transitively contain itself by value, so 9467 // infinite recursion is impossible. 9468 for (auto *FD : RD->fields()) { 9469 bool SubContained; 9470 if (const CXXRecordDecl *ContainedRD = 9471 getContainedDynamicClass(FD->getType(), SubContained)) { 9472 IsContained = true; 9473 return ContainedRD; 9474 } 9475 } 9476 9477 return nullptr; 9478 } 9479 9480 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9481 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9482 if (Unary->getKind() == UETT_SizeOf) 9483 return Unary; 9484 return nullptr; 9485 } 9486 9487 /// If E is a sizeof expression, returns its argument expression, 9488 /// otherwise returns NULL. 9489 static const Expr *getSizeOfExprArg(const Expr *E) { 9490 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9491 if (!SizeOf->isArgumentType()) 9492 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9493 return nullptr; 9494 } 9495 9496 /// If E is a sizeof expression, returns its argument type. 9497 static QualType getSizeOfArgType(const Expr *E) { 9498 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9499 return SizeOf->getTypeOfArgument(); 9500 return QualType(); 9501 } 9502 9503 namespace { 9504 9505 struct SearchNonTrivialToInitializeField 9506 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9507 using Super = 9508 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9509 9510 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9511 9512 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9513 SourceLocation SL) { 9514 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9515 asDerived().visitArray(PDIK, AT, SL); 9516 return; 9517 } 9518 9519 Super::visitWithKind(PDIK, FT, SL); 9520 } 9521 9522 void visitARCStrong(QualType FT, SourceLocation SL) { 9523 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9524 } 9525 void visitARCWeak(QualType FT, SourceLocation SL) { 9526 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9527 } 9528 void visitStruct(QualType FT, SourceLocation SL) { 9529 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9530 visit(FD->getType(), FD->getLocation()); 9531 } 9532 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9533 const ArrayType *AT, SourceLocation SL) { 9534 visit(getContext().getBaseElementType(AT), SL); 9535 } 9536 void visitTrivial(QualType FT, SourceLocation SL) {} 9537 9538 static void diag(QualType RT, const Expr *E, Sema &S) { 9539 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9540 } 9541 9542 ASTContext &getContext() { return S.getASTContext(); } 9543 9544 const Expr *E; 9545 Sema &S; 9546 }; 9547 9548 struct SearchNonTrivialToCopyField 9549 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9550 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9551 9552 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9553 9554 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9555 SourceLocation SL) { 9556 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9557 asDerived().visitArray(PCK, AT, SL); 9558 return; 9559 } 9560 9561 Super::visitWithKind(PCK, FT, SL); 9562 } 9563 9564 void visitARCStrong(QualType FT, SourceLocation SL) { 9565 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9566 } 9567 void visitARCWeak(QualType FT, SourceLocation SL) { 9568 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9569 } 9570 void visitStruct(QualType FT, SourceLocation SL) { 9571 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9572 visit(FD->getType(), FD->getLocation()); 9573 } 9574 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9575 SourceLocation SL) { 9576 visit(getContext().getBaseElementType(AT), SL); 9577 } 9578 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9579 SourceLocation SL) {} 9580 void visitTrivial(QualType FT, SourceLocation SL) {} 9581 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9582 9583 static void diag(QualType RT, const Expr *E, Sema &S) { 9584 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9585 } 9586 9587 ASTContext &getContext() { return S.getASTContext(); } 9588 9589 const Expr *E; 9590 Sema &S; 9591 }; 9592 9593 } 9594 9595 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9596 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9597 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9598 9599 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9600 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9601 return false; 9602 9603 return doesExprLikelyComputeSize(BO->getLHS()) || 9604 doesExprLikelyComputeSize(BO->getRHS()); 9605 } 9606 9607 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9608 } 9609 9610 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9611 /// 9612 /// \code 9613 /// #define MACRO 0 9614 /// foo(MACRO); 9615 /// foo(0); 9616 /// \endcode 9617 /// 9618 /// This should return true for the first call to foo, but not for the second 9619 /// (regardless of whether foo is a macro or function). 9620 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9621 SourceLocation CallLoc, 9622 SourceLocation ArgLoc) { 9623 if (!CallLoc.isMacroID()) 9624 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9625 9626 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9627 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9628 } 9629 9630 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9631 /// last two arguments transposed. 9632 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9633 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9634 return; 9635 9636 const Expr *SizeArg = 9637 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9638 9639 auto isLiteralZero = [](const Expr *E) { 9640 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9641 }; 9642 9643 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9644 SourceLocation CallLoc = Call->getRParenLoc(); 9645 SourceManager &SM = S.getSourceManager(); 9646 if (isLiteralZero(SizeArg) && 9647 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9648 9649 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9650 9651 // Some platforms #define bzero to __builtin_memset. See if this is the 9652 // case, and if so, emit a better diagnostic. 9653 if (BId == Builtin::BIbzero || 9654 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9655 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9656 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9657 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9658 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9659 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9660 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9661 } 9662 return; 9663 } 9664 9665 // If the second argument to a memset is a sizeof expression and the third 9666 // isn't, this is also likely an error. This should catch 9667 // 'memset(buf, sizeof(buf), 0xff)'. 9668 if (BId == Builtin::BImemset && 9669 doesExprLikelyComputeSize(Call->getArg(1)) && 9670 !doesExprLikelyComputeSize(Call->getArg(2))) { 9671 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9672 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9673 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9674 return; 9675 } 9676 } 9677 9678 /// Check for dangerous or invalid arguments to memset(). 9679 /// 9680 /// This issues warnings on known problematic, dangerous or unspecified 9681 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9682 /// function calls. 9683 /// 9684 /// \param Call The call expression to diagnose. 9685 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9686 unsigned BId, 9687 IdentifierInfo *FnName) { 9688 assert(BId != 0); 9689 9690 // It is possible to have a non-standard definition of memset. Validate 9691 // we have enough arguments, and if not, abort further checking. 9692 unsigned ExpectedNumArgs = 9693 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9694 if (Call->getNumArgs() < ExpectedNumArgs) 9695 return; 9696 9697 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9698 BId == Builtin::BIstrndup ? 1 : 2); 9699 unsigned LenArg = 9700 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9701 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9702 9703 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9704 Call->getBeginLoc(), Call->getRParenLoc())) 9705 return; 9706 9707 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9708 CheckMemaccessSize(*this, BId, Call); 9709 9710 // We have special checking when the length is a sizeof expression. 9711 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9712 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9713 llvm::FoldingSetNodeID SizeOfArgID; 9714 9715 // Although widely used, 'bzero' is not a standard function. Be more strict 9716 // with the argument types before allowing diagnostics and only allow the 9717 // form bzero(ptr, sizeof(...)). 9718 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9719 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9720 return; 9721 9722 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9723 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9724 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9725 9726 QualType DestTy = Dest->getType(); 9727 QualType PointeeTy; 9728 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9729 PointeeTy = DestPtrTy->getPointeeType(); 9730 9731 // Never warn about void type pointers. This can be used to suppress 9732 // false positives. 9733 if (PointeeTy->isVoidType()) 9734 continue; 9735 9736 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9737 // actually comparing the expressions for equality. Because computing the 9738 // expression IDs can be expensive, we only do this if the diagnostic is 9739 // enabled. 9740 if (SizeOfArg && 9741 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9742 SizeOfArg->getExprLoc())) { 9743 // We only compute IDs for expressions if the warning is enabled, and 9744 // cache the sizeof arg's ID. 9745 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9746 SizeOfArg->Profile(SizeOfArgID, Context, true); 9747 llvm::FoldingSetNodeID DestID; 9748 Dest->Profile(DestID, Context, true); 9749 if (DestID == SizeOfArgID) { 9750 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9751 // over sizeof(src) as well. 9752 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9753 StringRef ReadableName = FnName->getName(); 9754 9755 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9756 if (UnaryOp->getOpcode() == UO_AddrOf) 9757 ActionIdx = 1; // If its an address-of operator, just remove it. 9758 if (!PointeeTy->isIncompleteType() && 9759 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9760 ActionIdx = 2; // If the pointee's size is sizeof(char), 9761 // suggest an explicit length. 9762 9763 // If the function is defined as a builtin macro, do not show macro 9764 // expansion. 9765 SourceLocation SL = SizeOfArg->getExprLoc(); 9766 SourceRange DSR = Dest->getSourceRange(); 9767 SourceRange SSR = SizeOfArg->getSourceRange(); 9768 SourceManager &SM = getSourceManager(); 9769 9770 if (SM.isMacroArgExpansion(SL)) { 9771 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9772 SL = SM.getSpellingLoc(SL); 9773 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9774 SM.getSpellingLoc(DSR.getEnd())); 9775 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9776 SM.getSpellingLoc(SSR.getEnd())); 9777 } 9778 9779 DiagRuntimeBehavior(SL, SizeOfArg, 9780 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9781 << ReadableName 9782 << PointeeTy 9783 << DestTy 9784 << DSR 9785 << SSR); 9786 DiagRuntimeBehavior(SL, SizeOfArg, 9787 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9788 << ActionIdx 9789 << SSR); 9790 9791 break; 9792 } 9793 } 9794 9795 // Also check for cases where the sizeof argument is the exact same 9796 // type as the memory argument, and where it points to a user-defined 9797 // record type. 9798 if (SizeOfArgTy != QualType()) { 9799 if (PointeeTy->isRecordType() && 9800 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9801 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9802 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9803 << FnName << SizeOfArgTy << ArgIdx 9804 << PointeeTy << Dest->getSourceRange() 9805 << LenExpr->getSourceRange()); 9806 break; 9807 } 9808 } 9809 } else if (DestTy->isArrayType()) { 9810 PointeeTy = DestTy; 9811 } 9812 9813 if (PointeeTy == QualType()) 9814 continue; 9815 9816 // Always complain about dynamic classes. 9817 bool IsContained; 9818 if (const CXXRecordDecl *ContainedRD = 9819 getContainedDynamicClass(PointeeTy, IsContained)) { 9820 9821 unsigned OperationType = 0; 9822 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9823 // "overwritten" if we're warning about the destination for any call 9824 // but memcmp; otherwise a verb appropriate to the call. 9825 if (ArgIdx != 0 || IsCmp) { 9826 if (BId == Builtin::BImemcpy) 9827 OperationType = 1; 9828 else if(BId == Builtin::BImemmove) 9829 OperationType = 2; 9830 else if (IsCmp) 9831 OperationType = 3; 9832 } 9833 9834 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9835 PDiag(diag::warn_dyn_class_memaccess) 9836 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9837 << IsContained << ContainedRD << OperationType 9838 << Call->getCallee()->getSourceRange()); 9839 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9840 BId != Builtin::BImemset) 9841 DiagRuntimeBehavior( 9842 Dest->getExprLoc(), Dest, 9843 PDiag(diag::warn_arc_object_memaccess) 9844 << ArgIdx << FnName << PointeeTy 9845 << Call->getCallee()->getSourceRange()); 9846 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9847 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9848 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9849 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9850 PDiag(diag::warn_cstruct_memaccess) 9851 << ArgIdx << FnName << PointeeTy << 0); 9852 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9853 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9854 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9855 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9856 PDiag(diag::warn_cstruct_memaccess) 9857 << ArgIdx << FnName << PointeeTy << 1); 9858 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9859 } else { 9860 continue; 9861 } 9862 } else 9863 continue; 9864 9865 DiagRuntimeBehavior( 9866 Dest->getExprLoc(), Dest, 9867 PDiag(diag::note_bad_memaccess_silence) 9868 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9869 break; 9870 } 9871 } 9872 9873 // A little helper routine: ignore addition and subtraction of integer literals. 9874 // This intentionally does not ignore all integer constant expressions because 9875 // we don't want to remove sizeof(). 9876 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9877 Ex = Ex->IgnoreParenCasts(); 9878 9879 while (true) { 9880 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9881 if (!BO || !BO->isAdditiveOp()) 9882 break; 9883 9884 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9885 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9886 9887 if (isa<IntegerLiteral>(RHS)) 9888 Ex = LHS; 9889 else if (isa<IntegerLiteral>(LHS)) 9890 Ex = RHS; 9891 else 9892 break; 9893 } 9894 9895 return Ex; 9896 } 9897 9898 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9899 ASTContext &Context) { 9900 // Only handle constant-sized or VLAs, but not flexible members. 9901 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9902 // Only issue the FIXIT for arrays of size > 1. 9903 if (CAT->getSize().getSExtValue() <= 1) 9904 return false; 9905 } else if (!Ty->isVariableArrayType()) { 9906 return false; 9907 } 9908 return true; 9909 } 9910 9911 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9912 // be the size of the source, instead of the destination. 9913 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9914 IdentifierInfo *FnName) { 9915 9916 // Don't crash if the user has the wrong number of arguments 9917 unsigned NumArgs = Call->getNumArgs(); 9918 if ((NumArgs != 3) && (NumArgs != 4)) 9919 return; 9920 9921 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9922 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9923 const Expr *CompareWithSrc = nullptr; 9924 9925 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9926 Call->getBeginLoc(), Call->getRParenLoc())) 9927 return; 9928 9929 // Look for 'strlcpy(dst, x, sizeof(x))' 9930 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9931 CompareWithSrc = Ex; 9932 else { 9933 // Look for 'strlcpy(dst, x, strlen(x))' 9934 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9935 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9936 SizeCall->getNumArgs() == 1) 9937 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9938 } 9939 } 9940 9941 if (!CompareWithSrc) 9942 return; 9943 9944 // Determine if the argument to sizeof/strlen is equal to the source 9945 // argument. In principle there's all kinds of things you could do 9946 // here, for instance creating an == expression and evaluating it with 9947 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9948 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9949 if (!SrcArgDRE) 9950 return; 9951 9952 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9953 if (!CompareWithSrcDRE || 9954 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9955 return; 9956 9957 const Expr *OriginalSizeArg = Call->getArg(2); 9958 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9959 << OriginalSizeArg->getSourceRange() << FnName; 9960 9961 // Output a FIXIT hint if the destination is an array (rather than a 9962 // pointer to an array). This could be enhanced to handle some 9963 // pointers if we know the actual size, like if DstArg is 'array+2' 9964 // we could say 'sizeof(array)-2'. 9965 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9966 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9967 return; 9968 9969 SmallString<128> sizeString; 9970 llvm::raw_svector_ostream OS(sizeString); 9971 OS << "sizeof("; 9972 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9973 OS << ")"; 9974 9975 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9976 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9977 OS.str()); 9978 } 9979 9980 /// Check if two expressions refer to the same declaration. 9981 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9982 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9983 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9984 return D1->getDecl() == D2->getDecl(); 9985 return false; 9986 } 9987 9988 static const Expr *getStrlenExprArg(const Expr *E) { 9989 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9990 const FunctionDecl *FD = CE->getDirectCallee(); 9991 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9992 return nullptr; 9993 return CE->getArg(0)->IgnoreParenCasts(); 9994 } 9995 return nullptr; 9996 } 9997 9998 // Warn on anti-patterns as the 'size' argument to strncat. 9999 // The correct size argument should look like following: 10000 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10001 void Sema::CheckStrncatArguments(const CallExpr *CE, 10002 IdentifierInfo *FnName) { 10003 // Don't crash if the user has the wrong number of arguments. 10004 if (CE->getNumArgs() < 3) 10005 return; 10006 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10007 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10008 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10009 10010 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10011 CE->getRParenLoc())) 10012 return; 10013 10014 // Identify common expressions, which are wrongly used as the size argument 10015 // to strncat and may lead to buffer overflows. 10016 unsigned PatternType = 0; 10017 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10018 // - sizeof(dst) 10019 if (referToTheSameDecl(SizeOfArg, DstArg)) 10020 PatternType = 1; 10021 // - sizeof(src) 10022 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10023 PatternType = 2; 10024 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10025 if (BE->getOpcode() == BO_Sub) { 10026 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10027 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10028 // - sizeof(dst) - strlen(dst) 10029 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10030 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10031 PatternType = 1; 10032 // - sizeof(src) - (anything) 10033 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10034 PatternType = 2; 10035 } 10036 } 10037 10038 if (PatternType == 0) 10039 return; 10040 10041 // Generate the diagnostic. 10042 SourceLocation SL = LenArg->getBeginLoc(); 10043 SourceRange SR = LenArg->getSourceRange(); 10044 SourceManager &SM = getSourceManager(); 10045 10046 // If the function is defined as a builtin macro, do not show macro expansion. 10047 if (SM.isMacroArgExpansion(SL)) { 10048 SL = SM.getSpellingLoc(SL); 10049 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10050 SM.getSpellingLoc(SR.getEnd())); 10051 } 10052 10053 // Check if the destination is an array (rather than a pointer to an array). 10054 QualType DstTy = DstArg->getType(); 10055 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10056 Context); 10057 if (!isKnownSizeArray) { 10058 if (PatternType == 1) 10059 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10060 else 10061 Diag(SL, diag::warn_strncat_src_size) << SR; 10062 return; 10063 } 10064 10065 if (PatternType == 1) 10066 Diag(SL, diag::warn_strncat_large_size) << SR; 10067 else 10068 Diag(SL, diag::warn_strncat_src_size) << SR; 10069 10070 SmallString<128> sizeString; 10071 llvm::raw_svector_ostream OS(sizeString); 10072 OS << "sizeof("; 10073 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10074 OS << ") - "; 10075 OS << "strlen("; 10076 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10077 OS << ") - 1"; 10078 10079 Diag(SL, diag::note_strncat_wrong_size) 10080 << FixItHint::CreateReplacement(SR, OS.str()); 10081 } 10082 10083 void 10084 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10085 SourceLocation ReturnLoc, 10086 bool isObjCMethod, 10087 const AttrVec *Attrs, 10088 const FunctionDecl *FD) { 10089 // Check if the return value is null but should not be. 10090 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10091 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10092 CheckNonNullExpr(*this, RetValExp)) 10093 Diag(ReturnLoc, diag::warn_null_ret) 10094 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10095 10096 // C++11 [basic.stc.dynamic.allocation]p4: 10097 // If an allocation function declared with a non-throwing 10098 // exception-specification fails to allocate storage, it shall return 10099 // a null pointer. Any other allocation function that fails to allocate 10100 // storage shall indicate failure only by throwing an exception [...] 10101 if (FD) { 10102 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10103 if (Op == OO_New || Op == OO_Array_New) { 10104 const FunctionProtoType *Proto 10105 = FD->getType()->castAs<FunctionProtoType>(); 10106 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10107 CheckNonNullExpr(*this, RetValExp)) 10108 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10109 << FD << getLangOpts().CPlusPlus11; 10110 } 10111 } 10112 } 10113 10114 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10115 10116 /// Check for comparisons of floating point operands using != and ==. 10117 /// Issue a warning if these are no self-comparisons, as they are not likely 10118 /// to do what the programmer intended. 10119 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10120 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10121 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10122 10123 // Special case: check for x == x (which is OK). 10124 // Do not emit warnings for such cases. 10125 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10126 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10127 if (DRL->getDecl() == DRR->getDecl()) 10128 return; 10129 10130 // Special case: check for comparisons against literals that can be exactly 10131 // represented by APFloat. In such cases, do not emit a warning. This 10132 // is a heuristic: often comparison against such literals are used to 10133 // detect if a value in a variable has not changed. This clearly can 10134 // lead to false negatives. 10135 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10136 if (FLL->isExact()) 10137 return; 10138 } else 10139 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10140 if (FLR->isExact()) 10141 return; 10142 10143 // Check for comparisons with builtin types. 10144 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10145 if (CL->getBuiltinCallee()) 10146 return; 10147 10148 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10149 if (CR->getBuiltinCallee()) 10150 return; 10151 10152 // Emit the diagnostic. 10153 Diag(Loc, diag::warn_floatingpoint_eq) 10154 << LHS->getSourceRange() << RHS->getSourceRange(); 10155 } 10156 10157 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10158 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10159 10160 namespace { 10161 10162 /// Structure recording the 'active' range of an integer-valued 10163 /// expression. 10164 struct IntRange { 10165 /// The number of bits active in the int. 10166 unsigned Width; 10167 10168 /// True if the int is known not to have negative values. 10169 bool NonNegative; 10170 10171 IntRange(unsigned Width, bool NonNegative) 10172 : Width(Width), NonNegative(NonNegative) {} 10173 10174 /// Returns the range of the bool type. 10175 static IntRange forBoolType() { 10176 return IntRange(1, true); 10177 } 10178 10179 /// Returns the range of an opaque value of the given integral type. 10180 static IntRange forValueOfType(ASTContext &C, QualType T) { 10181 return forValueOfCanonicalType(C, 10182 T->getCanonicalTypeInternal().getTypePtr()); 10183 } 10184 10185 /// Returns the range of an opaque value of a canonical integral type. 10186 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10187 assert(T->isCanonicalUnqualified()); 10188 10189 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10190 T = VT->getElementType().getTypePtr(); 10191 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10192 T = CT->getElementType().getTypePtr(); 10193 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10194 T = AT->getValueType().getTypePtr(); 10195 10196 if (!C.getLangOpts().CPlusPlus) { 10197 // For enum types in C code, use the underlying datatype. 10198 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10199 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10200 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10201 // For enum types in C++, use the known bit width of the enumerators. 10202 EnumDecl *Enum = ET->getDecl(); 10203 // In C++11, enums can have a fixed underlying type. Use this type to 10204 // compute the range. 10205 if (Enum->isFixed()) { 10206 return IntRange(C.getIntWidth(QualType(T, 0)), 10207 !ET->isSignedIntegerOrEnumerationType()); 10208 } 10209 10210 unsigned NumPositive = Enum->getNumPositiveBits(); 10211 unsigned NumNegative = Enum->getNumNegativeBits(); 10212 10213 if (NumNegative == 0) 10214 return IntRange(NumPositive, true/*NonNegative*/); 10215 else 10216 return IntRange(std::max(NumPositive + 1, NumNegative), 10217 false/*NonNegative*/); 10218 } 10219 10220 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10221 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10222 10223 const BuiltinType *BT = cast<BuiltinType>(T); 10224 assert(BT->isInteger()); 10225 10226 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10227 } 10228 10229 /// Returns the "target" range of a canonical integral type, i.e. 10230 /// the range of values expressible in the type. 10231 /// 10232 /// This matches forValueOfCanonicalType except that enums have the 10233 /// full range of their type, not the range of their enumerators. 10234 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10235 assert(T->isCanonicalUnqualified()); 10236 10237 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10238 T = VT->getElementType().getTypePtr(); 10239 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10240 T = CT->getElementType().getTypePtr(); 10241 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10242 T = AT->getValueType().getTypePtr(); 10243 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10244 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10245 10246 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10247 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10248 10249 const BuiltinType *BT = cast<BuiltinType>(T); 10250 assert(BT->isInteger()); 10251 10252 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10253 } 10254 10255 /// Returns the supremum of two ranges: i.e. their conservative merge. 10256 static IntRange join(IntRange L, IntRange R) { 10257 return IntRange(std::max(L.Width, R.Width), 10258 L.NonNegative && R.NonNegative); 10259 } 10260 10261 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10262 static IntRange meet(IntRange L, IntRange R) { 10263 return IntRange(std::min(L.Width, R.Width), 10264 L.NonNegative || R.NonNegative); 10265 } 10266 }; 10267 10268 } // namespace 10269 10270 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10271 unsigned MaxWidth) { 10272 if (value.isSigned() && value.isNegative()) 10273 return IntRange(value.getMinSignedBits(), false); 10274 10275 if (value.getBitWidth() > MaxWidth) 10276 value = value.trunc(MaxWidth); 10277 10278 // isNonNegative() just checks the sign bit without considering 10279 // signedness. 10280 return IntRange(value.getActiveBits(), true); 10281 } 10282 10283 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10284 unsigned MaxWidth) { 10285 if (result.isInt()) 10286 return GetValueRange(C, result.getInt(), MaxWidth); 10287 10288 if (result.isVector()) { 10289 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10290 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10291 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10292 R = IntRange::join(R, El); 10293 } 10294 return R; 10295 } 10296 10297 if (result.isComplexInt()) { 10298 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10299 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10300 return IntRange::join(R, I); 10301 } 10302 10303 // This can happen with lossless casts to intptr_t of "based" lvalues. 10304 // Assume it might use arbitrary bits. 10305 // FIXME: The only reason we need to pass the type in here is to get 10306 // the sign right on this one case. It would be nice if APValue 10307 // preserved this. 10308 assert(result.isLValue() || result.isAddrLabelDiff()); 10309 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10310 } 10311 10312 static QualType GetExprType(const Expr *E) { 10313 QualType Ty = E->getType(); 10314 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10315 Ty = AtomicRHS->getValueType(); 10316 return Ty; 10317 } 10318 10319 /// Pseudo-evaluate the given integer expression, estimating the 10320 /// range of values it might take. 10321 /// 10322 /// \param MaxWidth - the width to which the value will be truncated 10323 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10324 bool InConstantContext) { 10325 E = E->IgnoreParens(); 10326 10327 // Try a full evaluation first. 10328 Expr::EvalResult result; 10329 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10330 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10331 10332 // I think we only want to look through implicit casts here; if the 10333 // user has an explicit widening cast, we should treat the value as 10334 // being of the new, wider type. 10335 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10336 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10337 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10338 10339 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10340 10341 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10342 CE->getCastKind() == CK_BooleanToSignedIntegral; 10343 10344 // Assume that non-integer casts can span the full range of the type. 10345 if (!isIntegerCast) 10346 return OutputTypeRange; 10347 10348 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10349 std::min(MaxWidth, OutputTypeRange.Width), 10350 InConstantContext); 10351 10352 // Bail out if the subexpr's range is as wide as the cast type. 10353 if (SubRange.Width >= OutputTypeRange.Width) 10354 return OutputTypeRange; 10355 10356 // Otherwise, we take the smaller width, and we're non-negative if 10357 // either the output type or the subexpr is. 10358 return IntRange(SubRange.Width, 10359 SubRange.NonNegative || OutputTypeRange.NonNegative); 10360 } 10361 10362 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10363 // If we can fold the condition, just take that operand. 10364 bool CondResult; 10365 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10366 return GetExprRange(C, 10367 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10368 MaxWidth, InConstantContext); 10369 10370 // Otherwise, conservatively merge. 10371 IntRange L = 10372 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10373 IntRange R = 10374 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10375 return IntRange::join(L, R); 10376 } 10377 10378 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10379 switch (BO->getOpcode()) { 10380 case BO_Cmp: 10381 llvm_unreachable("builtin <=> should have class type"); 10382 10383 // Boolean-valued operations are single-bit and positive. 10384 case BO_LAnd: 10385 case BO_LOr: 10386 case BO_LT: 10387 case BO_GT: 10388 case BO_LE: 10389 case BO_GE: 10390 case BO_EQ: 10391 case BO_NE: 10392 return IntRange::forBoolType(); 10393 10394 // The type of the assignments is the type of the LHS, so the RHS 10395 // is not necessarily the same type. 10396 case BO_MulAssign: 10397 case BO_DivAssign: 10398 case BO_RemAssign: 10399 case BO_AddAssign: 10400 case BO_SubAssign: 10401 case BO_XorAssign: 10402 case BO_OrAssign: 10403 // TODO: bitfields? 10404 return IntRange::forValueOfType(C, GetExprType(E)); 10405 10406 // Simple assignments just pass through the RHS, which will have 10407 // been coerced to the LHS type. 10408 case BO_Assign: 10409 // TODO: bitfields? 10410 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10411 10412 // Operations with opaque sources are black-listed. 10413 case BO_PtrMemD: 10414 case BO_PtrMemI: 10415 return IntRange::forValueOfType(C, GetExprType(E)); 10416 10417 // Bitwise-and uses the *infinum* of the two source ranges. 10418 case BO_And: 10419 case BO_AndAssign: 10420 return IntRange::meet( 10421 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10422 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10423 10424 // Left shift gets black-listed based on a judgement call. 10425 case BO_Shl: 10426 // ...except that we want to treat '1 << (blah)' as logically 10427 // positive. It's an important idiom. 10428 if (IntegerLiteral *I 10429 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10430 if (I->getValue() == 1) { 10431 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10432 return IntRange(R.Width, /*NonNegative*/ true); 10433 } 10434 } 10435 LLVM_FALLTHROUGH; 10436 10437 case BO_ShlAssign: 10438 return IntRange::forValueOfType(C, GetExprType(E)); 10439 10440 // Right shift by a constant can narrow its left argument. 10441 case BO_Shr: 10442 case BO_ShrAssign: { 10443 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10444 10445 // If the shift amount is a positive constant, drop the width by 10446 // that much. 10447 if (Optional<llvm::APSInt> shift = 10448 BO->getRHS()->getIntegerConstantExpr(C)) { 10449 if (shift->isNonNegative()) { 10450 unsigned zext = shift->getZExtValue(); 10451 if (zext >= L.Width) 10452 L.Width = (L.NonNegative ? 0 : 1); 10453 else 10454 L.Width -= zext; 10455 } 10456 } 10457 10458 return L; 10459 } 10460 10461 // Comma acts as its right operand. 10462 case BO_Comma: 10463 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10464 10465 // Black-list pointer subtractions. 10466 case BO_Sub: 10467 if (BO->getLHS()->getType()->isPointerType()) 10468 return IntRange::forValueOfType(C, GetExprType(E)); 10469 break; 10470 10471 // The width of a division result is mostly determined by the size 10472 // of the LHS. 10473 case BO_Div: { 10474 // Don't 'pre-truncate' the operands. 10475 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10476 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10477 10478 // If the divisor is constant, use that. 10479 if (Optional<llvm::APSInt> divisor = 10480 BO->getRHS()->getIntegerConstantExpr(C)) { 10481 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10482 if (log2 >= L.Width) 10483 L.Width = (L.NonNegative ? 0 : 1); 10484 else 10485 L.Width = std::min(L.Width - log2, MaxWidth); 10486 return L; 10487 } 10488 10489 // Otherwise, just use the LHS's width. 10490 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10491 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10492 } 10493 10494 // The result of a remainder can't be larger than the result of 10495 // either side. 10496 case BO_Rem: { 10497 // Don't 'pre-truncate' the operands. 10498 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10499 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10500 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10501 10502 IntRange meet = IntRange::meet(L, R); 10503 meet.Width = std::min(meet.Width, MaxWidth); 10504 return meet; 10505 } 10506 10507 // The default behavior is okay for these. 10508 case BO_Mul: 10509 case BO_Add: 10510 case BO_Xor: 10511 case BO_Or: 10512 break; 10513 } 10514 10515 // The default case is to treat the operation as if it were closed 10516 // on the narrowest type that encompasses both operands. 10517 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10518 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10519 return IntRange::join(L, R); 10520 } 10521 10522 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10523 switch (UO->getOpcode()) { 10524 // Boolean-valued operations are white-listed. 10525 case UO_LNot: 10526 return IntRange::forBoolType(); 10527 10528 // Operations with opaque sources are black-listed. 10529 case UO_Deref: 10530 case UO_AddrOf: // should be impossible 10531 return IntRange::forValueOfType(C, GetExprType(E)); 10532 10533 default: 10534 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10535 } 10536 } 10537 10538 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10539 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10540 10541 if (const auto *BitField = E->getSourceBitField()) 10542 return IntRange(BitField->getBitWidthValue(C), 10543 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10544 10545 return IntRange::forValueOfType(C, GetExprType(E)); 10546 } 10547 10548 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10549 bool InConstantContext) { 10550 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10551 } 10552 10553 /// Checks whether the given value, which currently has the given 10554 /// source semantics, has the same value when coerced through the 10555 /// target semantics. 10556 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10557 const llvm::fltSemantics &Src, 10558 const llvm::fltSemantics &Tgt) { 10559 llvm::APFloat truncated = value; 10560 10561 bool ignored; 10562 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10563 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10564 10565 return truncated.bitwiseIsEqual(value); 10566 } 10567 10568 /// Checks whether the given value, which currently has the given 10569 /// source semantics, has the same value when coerced through the 10570 /// target semantics. 10571 /// 10572 /// The value might be a vector of floats (or a complex number). 10573 static bool IsSameFloatAfterCast(const APValue &value, 10574 const llvm::fltSemantics &Src, 10575 const llvm::fltSemantics &Tgt) { 10576 if (value.isFloat()) 10577 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10578 10579 if (value.isVector()) { 10580 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10581 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10582 return false; 10583 return true; 10584 } 10585 10586 assert(value.isComplexFloat()); 10587 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10588 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10589 } 10590 10591 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10592 bool IsListInit = false); 10593 10594 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10595 // Suppress cases where we are comparing against an enum constant. 10596 if (const DeclRefExpr *DR = 10597 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10598 if (isa<EnumConstantDecl>(DR->getDecl())) 10599 return true; 10600 10601 // Suppress cases where the value is expanded from a macro, unless that macro 10602 // is how a language represents a boolean literal. This is the case in both C 10603 // and Objective-C. 10604 SourceLocation BeginLoc = E->getBeginLoc(); 10605 if (BeginLoc.isMacroID()) { 10606 StringRef MacroName = Lexer::getImmediateMacroName( 10607 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10608 return MacroName != "YES" && MacroName != "NO" && 10609 MacroName != "true" && MacroName != "false"; 10610 } 10611 10612 return false; 10613 } 10614 10615 static bool isKnownToHaveUnsignedValue(Expr *E) { 10616 return E->getType()->isIntegerType() && 10617 (!E->getType()->isSignedIntegerType() || 10618 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10619 } 10620 10621 namespace { 10622 /// The promoted range of values of a type. In general this has the 10623 /// following structure: 10624 /// 10625 /// |-----------| . . . |-----------| 10626 /// ^ ^ ^ ^ 10627 /// Min HoleMin HoleMax Max 10628 /// 10629 /// ... where there is only a hole if a signed type is promoted to unsigned 10630 /// (in which case Min and Max are the smallest and largest representable 10631 /// values). 10632 struct PromotedRange { 10633 // Min, or HoleMax if there is a hole. 10634 llvm::APSInt PromotedMin; 10635 // Max, or HoleMin if there is a hole. 10636 llvm::APSInt PromotedMax; 10637 10638 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10639 if (R.Width == 0) 10640 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10641 else if (R.Width >= BitWidth && !Unsigned) { 10642 // Promotion made the type *narrower*. This happens when promoting 10643 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10644 // Treat all values of 'signed int' as being in range for now. 10645 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10646 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10647 } else { 10648 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10649 .extOrTrunc(BitWidth); 10650 PromotedMin.setIsUnsigned(Unsigned); 10651 10652 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10653 .extOrTrunc(BitWidth); 10654 PromotedMax.setIsUnsigned(Unsigned); 10655 } 10656 } 10657 10658 // Determine whether this range is contiguous (has no hole). 10659 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10660 10661 // Where a constant value is within the range. 10662 enum ComparisonResult { 10663 LT = 0x1, 10664 LE = 0x2, 10665 GT = 0x4, 10666 GE = 0x8, 10667 EQ = 0x10, 10668 NE = 0x20, 10669 InRangeFlag = 0x40, 10670 10671 Less = LE | LT | NE, 10672 Min = LE | InRangeFlag, 10673 InRange = InRangeFlag, 10674 Max = GE | InRangeFlag, 10675 Greater = GE | GT | NE, 10676 10677 OnlyValue = LE | GE | EQ | InRangeFlag, 10678 InHole = NE 10679 }; 10680 10681 ComparisonResult compare(const llvm::APSInt &Value) const { 10682 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10683 Value.isUnsigned() == PromotedMin.isUnsigned()); 10684 if (!isContiguous()) { 10685 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10686 if (Value.isMinValue()) return Min; 10687 if (Value.isMaxValue()) return Max; 10688 if (Value >= PromotedMin) return InRange; 10689 if (Value <= PromotedMax) return InRange; 10690 return InHole; 10691 } 10692 10693 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10694 case -1: return Less; 10695 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10696 case 1: 10697 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10698 case -1: return InRange; 10699 case 0: return Max; 10700 case 1: return Greater; 10701 } 10702 } 10703 10704 llvm_unreachable("impossible compare result"); 10705 } 10706 10707 static llvm::Optional<StringRef> 10708 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10709 if (Op == BO_Cmp) { 10710 ComparisonResult LTFlag = LT, GTFlag = GT; 10711 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10712 10713 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10714 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10715 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10716 return llvm::None; 10717 } 10718 10719 ComparisonResult TrueFlag, FalseFlag; 10720 if (Op == BO_EQ) { 10721 TrueFlag = EQ; 10722 FalseFlag = NE; 10723 } else if (Op == BO_NE) { 10724 TrueFlag = NE; 10725 FalseFlag = EQ; 10726 } else { 10727 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10728 TrueFlag = LT; 10729 FalseFlag = GE; 10730 } else { 10731 TrueFlag = GT; 10732 FalseFlag = LE; 10733 } 10734 if (Op == BO_GE || Op == BO_LE) 10735 std::swap(TrueFlag, FalseFlag); 10736 } 10737 if (R & TrueFlag) 10738 return StringRef("true"); 10739 if (R & FalseFlag) 10740 return StringRef("false"); 10741 return llvm::None; 10742 } 10743 }; 10744 } 10745 10746 static bool HasEnumType(Expr *E) { 10747 // Strip off implicit integral promotions. 10748 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10749 if (ICE->getCastKind() != CK_IntegralCast && 10750 ICE->getCastKind() != CK_NoOp) 10751 break; 10752 E = ICE->getSubExpr(); 10753 } 10754 10755 return E->getType()->isEnumeralType(); 10756 } 10757 10758 static int classifyConstantValue(Expr *Constant) { 10759 // The values of this enumeration are used in the diagnostics 10760 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10761 enum ConstantValueKind { 10762 Miscellaneous = 0, 10763 LiteralTrue, 10764 LiteralFalse 10765 }; 10766 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10767 return BL->getValue() ? ConstantValueKind::LiteralTrue 10768 : ConstantValueKind::LiteralFalse; 10769 return ConstantValueKind::Miscellaneous; 10770 } 10771 10772 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10773 Expr *Constant, Expr *Other, 10774 const llvm::APSInt &Value, 10775 bool RhsConstant) { 10776 if (S.inTemplateInstantiation()) 10777 return false; 10778 10779 Expr *OriginalOther = Other; 10780 10781 Constant = Constant->IgnoreParenImpCasts(); 10782 Other = Other->IgnoreParenImpCasts(); 10783 10784 // Suppress warnings on tautological comparisons between values of the same 10785 // enumeration type. There are only two ways we could warn on this: 10786 // - If the constant is outside the range of representable values of 10787 // the enumeration. In such a case, we should warn about the cast 10788 // to enumeration type, not about the comparison. 10789 // - If the constant is the maximum / minimum in-range value. For an 10790 // enumeratin type, such comparisons can be meaningful and useful. 10791 if (Constant->getType()->isEnumeralType() && 10792 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10793 return false; 10794 10795 IntRange OtherValueRange = 10796 GetExprRange(S.Context, Other, S.isConstantEvaluated()); 10797 10798 QualType OtherT = Other->getType(); 10799 if (const auto *AT = OtherT->getAs<AtomicType>()) 10800 OtherT = AT->getValueType(); 10801 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 10802 10803 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10804 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 10805 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10806 S.NSAPIObj->isObjCBOOLType(OtherT) && 10807 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10808 10809 // Whether we're treating Other as being a bool because of the form of 10810 // expression despite it having another type (typically 'int' in C). 10811 bool OtherIsBooleanDespiteType = 10812 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10813 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10814 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 10815 10816 // Check if all values in the range of possible values of this expression 10817 // lead to the same comparison outcome. 10818 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 10819 Value.isUnsigned()); 10820 auto Cmp = OtherPromotedValueRange.compare(Value); 10821 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10822 if (!Result) 10823 return false; 10824 10825 // Also consider the range determined by the type alone. This allows us to 10826 // classify the warning under the proper diagnostic group. 10827 bool TautologicalTypeCompare = false; 10828 { 10829 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 10830 Value.isUnsigned()); 10831 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 10832 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 10833 RhsConstant)) { 10834 TautologicalTypeCompare = true; 10835 Cmp = TypeCmp; 10836 Result = TypeResult; 10837 } 10838 } 10839 10840 // Suppress the diagnostic for an in-range comparison if the constant comes 10841 // from a macro or enumerator. We don't want to diagnose 10842 // 10843 // some_long_value <= INT_MAX 10844 // 10845 // when sizeof(int) == sizeof(long). 10846 bool InRange = Cmp & PromotedRange::InRangeFlag; 10847 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10848 return false; 10849 10850 // If this is a comparison to an enum constant, include that 10851 // constant in the diagnostic. 10852 const EnumConstantDecl *ED = nullptr; 10853 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10854 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10855 10856 // Should be enough for uint128 (39 decimal digits) 10857 SmallString<64> PrettySourceValue; 10858 llvm::raw_svector_ostream OS(PrettySourceValue); 10859 if (ED) { 10860 OS << '\'' << *ED << "' (" << Value << ")"; 10861 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10862 Constant->IgnoreParenImpCasts())) { 10863 OS << (BL->getValue() ? "YES" : "NO"); 10864 } else { 10865 OS << Value; 10866 } 10867 10868 if (!TautologicalTypeCompare) { 10869 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 10870 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 10871 << E->getOpcodeStr() << OS.str() << *Result 10872 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10873 return true; 10874 } 10875 10876 if (IsObjCSignedCharBool) { 10877 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10878 S.PDiag(diag::warn_tautological_compare_objc_bool) 10879 << OS.str() << *Result); 10880 return true; 10881 } 10882 10883 // FIXME: We use a somewhat different formatting for the in-range cases and 10884 // cases involving boolean values for historical reasons. We should pick a 10885 // consistent way of presenting these diagnostics. 10886 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10887 10888 S.DiagRuntimeBehavior( 10889 E->getOperatorLoc(), E, 10890 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10891 : diag::warn_tautological_bool_compare) 10892 << OS.str() << classifyConstantValue(Constant) << OtherT 10893 << OtherIsBooleanDespiteType << *Result 10894 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10895 } else { 10896 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10897 ? (HasEnumType(OriginalOther) 10898 ? diag::warn_unsigned_enum_always_true_comparison 10899 : diag::warn_unsigned_always_true_comparison) 10900 : diag::warn_tautological_constant_compare; 10901 10902 S.Diag(E->getOperatorLoc(), Diag) 10903 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10904 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10905 } 10906 10907 return true; 10908 } 10909 10910 /// Analyze the operands of the given comparison. Implements the 10911 /// fallback case from AnalyzeComparison. 10912 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10913 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10914 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10915 } 10916 10917 /// Implements -Wsign-compare. 10918 /// 10919 /// \param E the binary operator to check for warnings 10920 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10921 // The type the comparison is being performed in. 10922 QualType T = E->getLHS()->getType(); 10923 10924 // Only analyze comparison operators where both sides have been converted to 10925 // the same type. 10926 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10927 return AnalyzeImpConvsInComparison(S, E); 10928 10929 // Don't analyze value-dependent comparisons directly. 10930 if (E->isValueDependent()) 10931 return AnalyzeImpConvsInComparison(S, E); 10932 10933 Expr *LHS = E->getLHS(); 10934 Expr *RHS = E->getRHS(); 10935 10936 if (T->isIntegralType(S.Context)) { 10937 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 10938 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 10939 10940 // We don't care about expressions whose result is a constant. 10941 if (RHSValue && LHSValue) 10942 return AnalyzeImpConvsInComparison(S, E); 10943 10944 // We only care about expressions where just one side is literal 10945 if ((bool)RHSValue ^ (bool)LHSValue) { 10946 // Is the constant on the RHS or LHS? 10947 const bool RhsConstant = (bool)RHSValue; 10948 Expr *Const = RhsConstant ? RHS : LHS; 10949 Expr *Other = RhsConstant ? LHS : RHS; 10950 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 10951 10952 // Check whether an integer constant comparison results in a value 10953 // of 'true' or 'false'. 10954 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10955 return AnalyzeImpConvsInComparison(S, E); 10956 } 10957 } 10958 10959 if (!T->hasUnsignedIntegerRepresentation()) { 10960 // We don't do anything special if this isn't an unsigned integral 10961 // comparison: we're only interested in integral comparisons, and 10962 // signed comparisons only happen in cases we don't care to warn about. 10963 return AnalyzeImpConvsInComparison(S, E); 10964 } 10965 10966 LHS = LHS->IgnoreParenImpCasts(); 10967 RHS = RHS->IgnoreParenImpCasts(); 10968 10969 if (!S.getLangOpts().CPlusPlus) { 10970 // Avoid warning about comparison of integers with different signs when 10971 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10972 // the type of `E`. 10973 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10974 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10975 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10976 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10977 } 10978 10979 // Check to see if one of the (unmodified) operands is of different 10980 // signedness. 10981 Expr *signedOperand, *unsignedOperand; 10982 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10983 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10984 "unsigned comparison between two signed integer expressions?"); 10985 signedOperand = LHS; 10986 unsignedOperand = RHS; 10987 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10988 signedOperand = RHS; 10989 unsignedOperand = LHS; 10990 } else { 10991 return AnalyzeImpConvsInComparison(S, E); 10992 } 10993 10994 // Otherwise, calculate the effective range of the signed operand. 10995 IntRange signedRange = 10996 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10997 10998 // Go ahead and analyze implicit conversions in the operands. Note 10999 // that we skip the implicit conversions on both sides. 11000 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11001 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11002 11003 // If the signed range is non-negative, -Wsign-compare won't fire. 11004 if (signedRange.NonNegative) 11005 return; 11006 11007 // For (in)equality comparisons, if the unsigned operand is a 11008 // constant which cannot collide with a overflowed signed operand, 11009 // then reinterpreting the signed operand as unsigned will not 11010 // change the result of the comparison. 11011 if (E->isEqualityOp()) { 11012 unsigned comparisonWidth = S.Context.getIntWidth(T); 11013 IntRange unsignedRange = 11014 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 11015 11016 // We should never be unable to prove that the unsigned operand is 11017 // non-negative. 11018 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11019 11020 if (unsignedRange.Width < comparisonWidth) 11021 return; 11022 } 11023 11024 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11025 S.PDiag(diag::warn_mixed_sign_comparison) 11026 << LHS->getType() << RHS->getType() 11027 << LHS->getSourceRange() << RHS->getSourceRange()); 11028 } 11029 11030 /// Analyzes an attempt to assign the given value to a bitfield. 11031 /// 11032 /// Returns true if there was something fishy about the attempt. 11033 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11034 SourceLocation InitLoc) { 11035 assert(Bitfield->isBitField()); 11036 if (Bitfield->isInvalidDecl()) 11037 return false; 11038 11039 // White-list bool bitfields. 11040 QualType BitfieldType = Bitfield->getType(); 11041 if (BitfieldType->isBooleanType()) 11042 return false; 11043 11044 if (BitfieldType->isEnumeralType()) { 11045 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11046 // If the underlying enum type was not explicitly specified as an unsigned 11047 // type and the enum contain only positive values, MSVC++ will cause an 11048 // inconsistency by storing this as a signed type. 11049 if (S.getLangOpts().CPlusPlus11 && 11050 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11051 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11052 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11053 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11054 << BitfieldEnumDecl; 11055 } 11056 } 11057 11058 if (Bitfield->getType()->isBooleanType()) 11059 return false; 11060 11061 // Ignore value- or type-dependent expressions. 11062 if (Bitfield->getBitWidth()->isValueDependent() || 11063 Bitfield->getBitWidth()->isTypeDependent() || 11064 Init->isValueDependent() || 11065 Init->isTypeDependent()) 11066 return false; 11067 11068 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11069 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11070 11071 Expr::EvalResult Result; 11072 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11073 Expr::SE_AllowSideEffects)) { 11074 // The RHS is not constant. If the RHS has an enum type, make sure the 11075 // bitfield is wide enough to hold all the values of the enum without 11076 // truncation. 11077 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11078 EnumDecl *ED = EnumTy->getDecl(); 11079 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11080 11081 // Enum types are implicitly signed on Windows, so check if there are any 11082 // negative enumerators to see if the enum was intended to be signed or 11083 // not. 11084 bool SignedEnum = ED->getNumNegativeBits() > 0; 11085 11086 // Check for surprising sign changes when assigning enum values to a 11087 // bitfield of different signedness. If the bitfield is signed and we 11088 // have exactly the right number of bits to store this unsigned enum, 11089 // suggest changing the enum to an unsigned type. This typically happens 11090 // on Windows where unfixed enums always use an underlying type of 'int'. 11091 unsigned DiagID = 0; 11092 if (SignedEnum && !SignedBitfield) { 11093 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11094 } else if (SignedBitfield && !SignedEnum && 11095 ED->getNumPositiveBits() == FieldWidth) { 11096 DiagID = diag::warn_signed_bitfield_enum_conversion; 11097 } 11098 11099 if (DiagID) { 11100 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11101 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11102 SourceRange TypeRange = 11103 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11104 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11105 << SignedEnum << TypeRange; 11106 } 11107 11108 // Compute the required bitwidth. If the enum has negative values, we need 11109 // one more bit than the normal number of positive bits to represent the 11110 // sign bit. 11111 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11112 ED->getNumNegativeBits()) 11113 : ED->getNumPositiveBits(); 11114 11115 // Check the bitwidth. 11116 if (BitsNeeded > FieldWidth) { 11117 Expr *WidthExpr = Bitfield->getBitWidth(); 11118 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11119 << Bitfield << ED; 11120 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11121 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11122 } 11123 } 11124 11125 return false; 11126 } 11127 11128 llvm::APSInt Value = Result.Val.getInt(); 11129 11130 unsigned OriginalWidth = Value.getBitWidth(); 11131 11132 if (!Value.isSigned() || Value.isNegative()) 11133 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11134 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11135 OriginalWidth = Value.getMinSignedBits(); 11136 11137 if (OriginalWidth <= FieldWidth) 11138 return false; 11139 11140 // Compute the value which the bitfield will contain. 11141 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11142 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11143 11144 // Check whether the stored value is equal to the original value. 11145 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11146 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11147 return false; 11148 11149 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11150 // therefore don't strictly fit into a signed bitfield of width 1. 11151 if (FieldWidth == 1 && Value == 1) 11152 return false; 11153 11154 std::string PrettyValue = Value.toString(10); 11155 std::string PrettyTrunc = TruncatedValue.toString(10); 11156 11157 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11158 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11159 << Init->getSourceRange(); 11160 11161 return true; 11162 } 11163 11164 /// Analyze the given simple or compound assignment for warning-worthy 11165 /// operations. 11166 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11167 // Just recurse on the LHS. 11168 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11169 11170 // We want to recurse on the RHS as normal unless we're assigning to 11171 // a bitfield. 11172 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11173 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11174 E->getOperatorLoc())) { 11175 // Recurse, ignoring any implicit conversions on the RHS. 11176 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11177 E->getOperatorLoc()); 11178 } 11179 } 11180 11181 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11182 11183 // Diagnose implicitly sequentially-consistent atomic assignment. 11184 if (E->getLHS()->getType()->isAtomicType()) 11185 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11186 } 11187 11188 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11189 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11190 SourceLocation CContext, unsigned diag, 11191 bool pruneControlFlow = false) { 11192 if (pruneControlFlow) { 11193 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11194 S.PDiag(diag) 11195 << SourceType << T << E->getSourceRange() 11196 << SourceRange(CContext)); 11197 return; 11198 } 11199 S.Diag(E->getExprLoc(), diag) 11200 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11201 } 11202 11203 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11204 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11205 SourceLocation CContext, 11206 unsigned diag, bool pruneControlFlow = false) { 11207 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11208 } 11209 11210 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11211 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11212 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11213 } 11214 11215 static void adornObjCBoolConversionDiagWithTernaryFixit( 11216 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11217 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11218 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11219 Ignored = OVE->getSourceExpr(); 11220 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11221 isa<BinaryOperator>(Ignored) || 11222 isa<CXXOperatorCallExpr>(Ignored); 11223 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11224 if (NeedsParens) 11225 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11226 << FixItHint::CreateInsertion(EndLoc, ")"); 11227 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11228 } 11229 11230 /// Diagnose an implicit cast from a floating point value to an integer value. 11231 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11232 SourceLocation CContext) { 11233 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11234 const bool PruneWarnings = S.inTemplateInstantiation(); 11235 11236 Expr *InnerE = E->IgnoreParenImpCasts(); 11237 // We also want to warn on, e.g., "int i = -1.234" 11238 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11239 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11240 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11241 11242 const bool IsLiteral = 11243 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11244 11245 llvm::APFloat Value(0.0); 11246 bool IsConstant = 11247 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11248 if (!IsConstant) { 11249 if (isObjCSignedCharBool(S, T)) { 11250 return adornObjCBoolConversionDiagWithTernaryFixit( 11251 S, E, 11252 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11253 << E->getType()); 11254 } 11255 11256 return DiagnoseImpCast(S, E, T, CContext, 11257 diag::warn_impcast_float_integer, PruneWarnings); 11258 } 11259 11260 bool isExact = false; 11261 11262 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11263 T->hasUnsignedIntegerRepresentation()); 11264 llvm::APFloat::opStatus Result = Value.convertToInteger( 11265 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11266 11267 // FIXME: Force the precision of the source value down so we don't print 11268 // digits which are usually useless (we don't really care here if we 11269 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11270 // would automatically print the shortest representation, but it's a bit 11271 // tricky to implement. 11272 SmallString<16> PrettySourceValue; 11273 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11274 precision = (precision * 59 + 195) / 196; 11275 Value.toString(PrettySourceValue, precision); 11276 11277 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11278 return adornObjCBoolConversionDiagWithTernaryFixit( 11279 S, E, 11280 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11281 << PrettySourceValue); 11282 } 11283 11284 if (Result == llvm::APFloat::opOK && isExact) { 11285 if (IsLiteral) return; 11286 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11287 PruneWarnings); 11288 } 11289 11290 // Conversion of a floating-point value to a non-bool integer where the 11291 // integral part cannot be represented by the integer type is undefined. 11292 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11293 return DiagnoseImpCast( 11294 S, E, T, CContext, 11295 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11296 : diag::warn_impcast_float_to_integer_out_of_range, 11297 PruneWarnings); 11298 11299 unsigned DiagID = 0; 11300 if (IsLiteral) { 11301 // Warn on floating point literal to integer. 11302 DiagID = diag::warn_impcast_literal_float_to_integer; 11303 } else if (IntegerValue == 0) { 11304 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11305 return DiagnoseImpCast(S, E, T, CContext, 11306 diag::warn_impcast_float_integer, PruneWarnings); 11307 } 11308 // Warn on non-zero to zero conversion. 11309 DiagID = diag::warn_impcast_float_to_integer_zero; 11310 } else { 11311 if (IntegerValue.isUnsigned()) { 11312 if (!IntegerValue.isMaxValue()) { 11313 return DiagnoseImpCast(S, E, T, CContext, 11314 diag::warn_impcast_float_integer, PruneWarnings); 11315 } 11316 } else { // IntegerValue.isSigned() 11317 if (!IntegerValue.isMaxSignedValue() && 11318 !IntegerValue.isMinSignedValue()) { 11319 return DiagnoseImpCast(S, E, T, CContext, 11320 diag::warn_impcast_float_integer, PruneWarnings); 11321 } 11322 } 11323 // Warn on evaluatable floating point expression to integer conversion. 11324 DiagID = diag::warn_impcast_float_to_integer; 11325 } 11326 11327 SmallString<16> PrettyTargetValue; 11328 if (IsBool) 11329 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11330 else 11331 IntegerValue.toString(PrettyTargetValue); 11332 11333 if (PruneWarnings) { 11334 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11335 S.PDiag(DiagID) 11336 << E->getType() << T.getUnqualifiedType() 11337 << PrettySourceValue << PrettyTargetValue 11338 << E->getSourceRange() << SourceRange(CContext)); 11339 } else { 11340 S.Diag(E->getExprLoc(), DiagID) 11341 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11342 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11343 } 11344 } 11345 11346 /// Analyze the given compound assignment for the possible losing of 11347 /// floating-point precision. 11348 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11349 assert(isa<CompoundAssignOperator>(E) && 11350 "Must be compound assignment operation"); 11351 // Recurse on the LHS and RHS in here 11352 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11353 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11354 11355 if (E->getLHS()->getType()->isAtomicType()) 11356 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11357 11358 // Now check the outermost expression 11359 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11360 const auto *RBT = cast<CompoundAssignOperator>(E) 11361 ->getComputationResultType() 11362 ->getAs<BuiltinType>(); 11363 11364 // The below checks assume source is floating point. 11365 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11366 11367 // If source is floating point but target is an integer. 11368 if (ResultBT->isInteger()) 11369 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11370 E->getExprLoc(), diag::warn_impcast_float_integer); 11371 11372 if (!ResultBT->isFloatingPoint()) 11373 return; 11374 11375 // If both source and target are floating points, warn about losing precision. 11376 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11377 QualType(ResultBT, 0), QualType(RBT, 0)); 11378 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11379 // warn about dropping FP rank. 11380 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11381 diag::warn_impcast_float_result_precision); 11382 } 11383 11384 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11385 IntRange Range) { 11386 if (!Range.Width) return "0"; 11387 11388 llvm::APSInt ValueInRange = Value; 11389 ValueInRange.setIsSigned(!Range.NonNegative); 11390 ValueInRange = ValueInRange.trunc(Range.Width); 11391 return ValueInRange.toString(10); 11392 } 11393 11394 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11395 if (!isa<ImplicitCastExpr>(Ex)) 11396 return false; 11397 11398 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11399 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11400 const Type *Source = 11401 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11402 if (Target->isDependentType()) 11403 return false; 11404 11405 const BuiltinType *FloatCandidateBT = 11406 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11407 const Type *BoolCandidateType = ToBool ? Target : Source; 11408 11409 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11410 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11411 } 11412 11413 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11414 SourceLocation CC) { 11415 unsigned NumArgs = TheCall->getNumArgs(); 11416 for (unsigned i = 0; i < NumArgs; ++i) { 11417 Expr *CurrA = TheCall->getArg(i); 11418 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11419 continue; 11420 11421 bool IsSwapped = ((i > 0) && 11422 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11423 IsSwapped |= ((i < (NumArgs - 1)) && 11424 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11425 if (IsSwapped) { 11426 // Warn on this floating-point to bool conversion. 11427 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11428 CurrA->getType(), CC, 11429 diag::warn_impcast_floating_point_to_bool); 11430 } 11431 } 11432 } 11433 11434 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11435 SourceLocation CC) { 11436 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11437 E->getExprLoc())) 11438 return; 11439 11440 // Don't warn on functions which have return type nullptr_t. 11441 if (isa<CallExpr>(E)) 11442 return; 11443 11444 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11445 const Expr::NullPointerConstantKind NullKind = 11446 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11447 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11448 return; 11449 11450 // Return if target type is a safe conversion. 11451 if (T->isAnyPointerType() || T->isBlockPointerType() || 11452 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11453 return; 11454 11455 SourceLocation Loc = E->getSourceRange().getBegin(); 11456 11457 // Venture through the macro stacks to get to the source of macro arguments. 11458 // The new location is a better location than the complete location that was 11459 // passed in. 11460 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11461 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11462 11463 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11464 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11465 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11466 Loc, S.SourceMgr, S.getLangOpts()); 11467 if (MacroName == "NULL") 11468 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11469 } 11470 11471 // Only warn if the null and context location are in the same macro expansion. 11472 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11473 return; 11474 11475 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11476 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11477 << FixItHint::CreateReplacement(Loc, 11478 S.getFixItZeroLiteralForType(T, Loc)); 11479 } 11480 11481 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11482 ObjCArrayLiteral *ArrayLiteral); 11483 11484 static void 11485 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11486 ObjCDictionaryLiteral *DictionaryLiteral); 11487 11488 /// Check a single element within a collection literal against the 11489 /// target element type. 11490 static void checkObjCCollectionLiteralElement(Sema &S, 11491 QualType TargetElementType, 11492 Expr *Element, 11493 unsigned ElementKind) { 11494 // Skip a bitcast to 'id' or qualified 'id'. 11495 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11496 if (ICE->getCastKind() == CK_BitCast && 11497 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11498 Element = ICE->getSubExpr(); 11499 } 11500 11501 QualType ElementType = Element->getType(); 11502 ExprResult ElementResult(Element); 11503 if (ElementType->getAs<ObjCObjectPointerType>() && 11504 S.CheckSingleAssignmentConstraints(TargetElementType, 11505 ElementResult, 11506 false, false) 11507 != Sema::Compatible) { 11508 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11509 << ElementType << ElementKind << TargetElementType 11510 << Element->getSourceRange(); 11511 } 11512 11513 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11514 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11515 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11516 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11517 } 11518 11519 /// Check an Objective-C array literal being converted to the given 11520 /// target type. 11521 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11522 ObjCArrayLiteral *ArrayLiteral) { 11523 if (!S.NSArrayDecl) 11524 return; 11525 11526 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11527 if (!TargetObjCPtr) 11528 return; 11529 11530 if (TargetObjCPtr->isUnspecialized() || 11531 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11532 != S.NSArrayDecl->getCanonicalDecl()) 11533 return; 11534 11535 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11536 if (TypeArgs.size() != 1) 11537 return; 11538 11539 QualType TargetElementType = TypeArgs[0]; 11540 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11541 checkObjCCollectionLiteralElement(S, TargetElementType, 11542 ArrayLiteral->getElement(I), 11543 0); 11544 } 11545 } 11546 11547 /// Check an Objective-C dictionary literal being converted to the given 11548 /// target type. 11549 static void 11550 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11551 ObjCDictionaryLiteral *DictionaryLiteral) { 11552 if (!S.NSDictionaryDecl) 11553 return; 11554 11555 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11556 if (!TargetObjCPtr) 11557 return; 11558 11559 if (TargetObjCPtr->isUnspecialized() || 11560 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11561 != S.NSDictionaryDecl->getCanonicalDecl()) 11562 return; 11563 11564 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11565 if (TypeArgs.size() != 2) 11566 return; 11567 11568 QualType TargetKeyType = TypeArgs[0]; 11569 QualType TargetObjectType = TypeArgs[1]; 11570 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11571 auto Element = DictionaryLiteral->getKeyValueElement(I); 11572 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11573 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11574 } 11575 } 11576 11577 // Helper function to filter out cases for constant width constant conversion. 11578 // Don't warn on char array initialization or for non-decimal values. 11579 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11580 SourceLocation CC) { 11581 // If initializing from a constant, and the constant starts with '0', 11582 // then it is a binary, octal, or hexadecimal. Allow these constants 11583 // to fill all the bits, even if there is a sign change. 11584 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11585 const char FirstLiteralCharacter = 11586 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11587 if (FirstLiteralCharacter == '0') 11588 return false; 11589 } 11590 11591 // If the CC location points to a '{', and the type is char, then assume 11592 // assume it is an array initialization. 11593 if (CC.isValid() && T->isCharType()) { 11594 const char FirstContextCharacter = 11595 S.getSourceManager().getCharacterData(CC)[0]; 11596 if (FirstContextCharacter == '{') 11597 return false; 11598 } 11599 11600 return true; 11601 } 11602 11603 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11604 const auto *IL = dyn_cast<IntegerLiteral>(E); 11605 if (!IL) { 11606 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11607 if (UO->getOpcode() == UO_Minus) 11608 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11609 } 11610 } 11611 11612 return IL; 11613 } 11614 11615 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11616 E = E->IgnoreParenImpCasts(); 11617 SourceLocation ExprLoc = E->getExprLoc(); 11618 11619 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11620 BinaryOperator::Opcode Opc = BO->getOpcode(); 11621 Expr::EvalResult Result; 11622 // Do not diagnose unsigned shifts. 11623 if (Opc == BO_Shl) { 11624 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11625 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11626 if (LHS && LHS->getValue() == 0) 11627 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11628 else if (!E->isValueDependent() && LHS && RHS && 11629 RHS->getValue().isNonNegative() && 11630 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11631 S.Diag(ExprLoc, diag::warn_left_shift_always) 11632 << (Result.Val.getInt() != 0); 11633 else if (E->getType()->isSignedIntegerType()) 11634 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11635 } 11636 } 11637 11638 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11639 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11640 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11641 if (!LHS || !RHS) 11642 return; 11643 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11644 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11645 // Do not diagnose common idioms. 11646 return; 11647 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11648 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11649 } 11650 } 11651 11652 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11653 SourceLocation CC, 11654 bool *ICContext = nullptr, 11655 bool IsListInit = false) { 11656 if (E->isTypeDependent() || E->isValueDependent()) return; 11657 11658 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11659 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11660 if (Source == Target) return; 11661 if (Target->isDependentType()) return; 11662 11663 // If the conversion context location is invalid don't complain. We also 11664 // don't want to emit a warning if the issue occurs from the expansion of 11665 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11666 // delay this check as long as possible. Once we detect we are in that 11667 // scenario, we just return. 11668 if (CC.isInvalid()) 11669 return; 11670 11671 if (Source->isAtomicType()) 11672 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11673 11674 // Diagnose implicit casts to bool. 11675 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11676 if (isa<StringLiteral>(E)) 11677 // Warn on string literal to bool. Checks for string literals in logical 11678 // and expressions, for instance, assert(0 && "error here"), are 11679 // prevented by a check in AnalyzeImplicitConversions(). 11680 return DiagnoseImpCast(S, E, T, CC, 11681 diag::warn_impcast_string_literal_to_bool); 11682 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11683 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11684 // This covers the literal expressions that evaluate to Objective-C 11685 // objects. 11686 return DiagnoseImpCast(S, E, T, CC, 11687 diag::warn_impcast_objective_c_literal_to_bool); 11688 } 11689 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11690 // Warn on pointer to bool conversion that is always true. 11691 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11692 SourceRange(CC)); 11693 } 11694 } 11695 11696 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11697 // is a typedef for signed char (macOS), then that constant value has to be 1 11698 // or 0. 11699 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11700 Expr::EvalResult Result; 11701 if (E->EvaluateAsInt(Result, S.getASTContext(), 11702 Expr::SE_AllowSideEffects)) { 11703 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11704 adornObjCBoolConversionDiagWithTernaryFixit( 11705 S, E, 11706 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11707 << Result.Val.getInt().toString(10)); 11708 } 11709 return; 11710 } 11711 } 11712 11713 // Check implicit casts from Objective-C collection literals to specialized 11714 // collection types, e.g., NSArray<NSString *> *. 11715 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11716 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11717 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11718 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11719 11720 // Strip vector types. 11721 if (isa<VectorType>(Source)) { 11722 if (!isa<VectorType>(Target)) { 11723 if (S.SourceMgr.isInSystemMacro(CC)) 11724 return; 11725 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11726 } 11727 11728 // If the vector cast is cast between two vectors of the same size, it is 11729 // a bitcast, not a conversion. 11730 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11731 return; 11732 11733 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11734 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11735 } 11736 if (auto VecTy = dyn_cast<VectorType>(Target)) 11737 Target = VecTy->getElementType().getTypePtr(); 11738 11739 // Strip complex types. 11740 if (isa<ComplexType>(Source)) { 11741 if (!isa<ComplexType>(Target)) { 11742 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11743 return; 11744 11745 return DiagnoseImpCast(S, E, T, CC, 11746 S.getLangOpts().CPlusPlus 11747 ? diag::err_impcast_complex_scalar 11748 : diag::warn_impcast_complex_scalar); 11749 } 11750 11751 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11752 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11753 } 11754 11755 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11756 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11757 11758 // If the source is floating point... 11759 if (SourceBT && SourceBT->isFloatingPoint()) { 11760 // ...and the target is floating point... 11761 if (TargetBT && TargetBT->isFloatingPoint()) { 11762 // ...then warn if we're dropping FP rank. 11763 11764 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11765 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11766 if (Order > 0) { 11767 // Don't warn about float constants that are precisely 11768 // representable in the target type. 11769 Expr::EvalResult result; 11770 if (E->EvaluateAsRValue(result, S.Context)) { 11771 // Value might be a float, a float vector, or a float complex. 11772 if (IsSameFloatAfterCast(result.Val, 11773 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11774 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11775 return; 11776 } 11777 11778 if (S.SourceMgr.isInSystemMacro(CC)) 11779 return; 11780 11781 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11782 } 11783 // ... or possibly if we're increasing rank, too 11784 else if (Order < 0) { 11785 if (S.SourceMgr.isInSystemMacro(CC)) 11786 return; 11787 11788 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11789 } 11790 return; 11791 } 11792 11793 // If the target is integral, always warn. 11794 if (TargetBT && TargetBT->isInteger()) { 11795 if (S.SourceMgr.isInSystemMacro(CC)) 11796 return; 11797 11798 DiagnoseFloatingImpCast(S, E, T, CC); 11799 } 11800 11801 // Detect the case where a call result is converted from floating-point to 11802 // to bool, and the final argument to the call is converted from bool, to 11803 // discover this typo: 11804 // 11805 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11806 // 11807 // FIXME: This is an incredibly special case; is there some more general 11808 // way to detect this class of misplaced-parentheses bug? 11809 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11810 // Check last argument of function call to see if it is an 11811 // implicit cast from a type matching the type the result 11812 // is being cast to. 11813 CallExpr *CEx = cast<CallExpr>(E); 11814 if (unsigned NumArgs = CEx->getNumArgs()) { 11815 Expr *LastA = CEx->getArg(NumArgs - 1); 11816 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11817 if (isa<ImplicitCastExpr>(LastA) && 11818 InnerE->getType()->isBooleanType()) { 11819 // Warn on this floating-point to bool conversion 11820 DiagnoseImpCast(S, E, T, CC, 11821 diag::warn_impcast_floating_point_to_bool); 11822 } 11823 } 11824 } 11825 return; 11826 } 11827 11828 // Valid casts involving fixed point types should be accounted for here. 11829 if (Source->isFixedPointType()) { 11830 if (Target->isUnsaturatedFixedPointType()) { 11831 Expr::EvalResult Result; 11832 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11833 S.isConstantEvaluated())) { 11834 APFixedPoint Value = Result.Val.getFixedPoint(); 11835 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11836 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11837 if (Value > MaxVal || Value < MinVal) { 11838 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11839 S.PDiag(diag::warn_impcast_fixed_point_range) 11840 << Value.toString() << T 11841 << E->getSourceRange() 11842 << clang::SourceRange(CC)); 11843 return; 11844 } 11845 } 11846 } else if (Target->isIntegerType()) { 11847 Expr::EvalResult Result; 11848 if (!S.isConstantEvaluated() && 11849 E->EvaluateAsFixedPoint(Result, S.Context, 11850 Expr::SE_AllowSideEffects)) { 11851 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11852 11853 bool Overflowed; 11854 llvm::APSInt IntResult = FXResult.convertToInt( 11855 S.Context.getIntWidth(T), 11856 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11857 11858 if (Overflowed) { 11859 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11860 S.PDiag(diag::warn_impcast_fixed_point_range) 11861 << FXResult.toString() << T 11862 << E->getSourceRange() 11863 << clang::SourceRange(CC)); 11864 return; 11865 } 11866 } 11867 } 11868 } else if (Target->isUnsaturatedFixedPointType()) { 11869 if (Source->isIntegerType()) { 11870 Expr::EvalResult Result; 11871 if (!S.isConstantEvaluated() && 11872 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11873 llvm::APSInt Value = Result.Val.getInt(); 11874 11875 bool Overflowed; 11876 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11877 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11878 11879 if (Overflowed) { 11880 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11881 S.PDiag(diag::warn_impcast_fixed_point_range) 11882 << Value.toString(/*Radix=*/10) << T 11883 << E->getSourceRange() 11884 << clang::SourceRange(CC)); 11885 return; 11886 } 11887 } 11888 } 11889 } 11890 11891 // If we are casting an integer type to a floating point type without 11892 // initialization-list syntax, we might lose accuracy if the floating 11893 // point type has a narrower significand than the integer type. 11894 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11895 TargetBT->isFloatingType() && !IsListInit) { 11896 // Determine the number of precision bits in the source integer type. 11897 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11898 unsigned int SourcePrecision = SourceRange.Width; 11899 11900 // Determine the number of precision bits in the 11901 // target floating point type. 11902 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11903 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11904 11905 if (SourcePrecision > 0 && TargetPrecision > 0 && 11906 SourcePrecision > TargetPrecision) { 11907 11908 if (Optional<llvm::APSInt> SourceInt = 11909 E->getIntegerConstantExpr(S.Context)) { 11910 // If the source integer is a constant, convert it to the target 11911 // floating point type. Issue a warning if the value changes 11912 // during the whole conversion. 11913 llvm::APFloat TargetFloatValue( 11914 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11915 llvm::APFloat::opStatus ConversionStatus = 11916 TargetFloatValue.convertFromAPInt( 11917 *SourceInt, SourceBT->isSignedInteger(), 11918 llvm::APFloat::rmNearestTiesToEven); 11919 11920 if (ConversionStatus != llvm::APFloat::opOK) { 11921 std::string PrettySourceValue = SourceInt->toString(10); 11922 SmallString<32> PrettyTargetValue; 11923 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11924 11925 S.DiagRuntimeBehavior( 11926 E->getExprLoc(), E, 11927 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11928 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11929 << E->getSourceRange() << clang::SourceRange(CC)); 11930 } 11931 } else { 11932 // Otherwise, the implicit conversion may lose precision. 11933 DiagnoseImpCast(S, E, T, CC, 11934 diag::warn_impcast_integer_float_precision); 11935 } 11936 } 11937 } 11938 11939 DiagnoseNullConversion(S, E, T, CC); 11940 11941 S.DiscardMisalignedMemberAddress(Target, E); 11942 11943 if (Target->isBooleanType()) 11944 DiagnoseIntInBoolContext(S, E); 11945 11946 if (!Source->isIntegerType() || !Target->isIntegerType()) 11947 return; 11948 11949 // TODO: remove this early return once the false positives for constant->bool 11950 // in templates, macros, etc, are reduced or removed. 11951 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11952 return; 11953 11954 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11955 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11956 return adornObjCBoolConversionDiagWithTernaryFixit( 11957 S, E, 11958 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11959 << E->getType()); 11960 } 11961 11962 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11963 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11964 11965 if (SourceRange.Width > TargetRange.Width) { 11966 // If the source is a constant, use a default-on diagnostic. 11967 // TODO: this should happen for bitfield stores, too. 11968 Expr::EvalResult Result; 11969 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11970 S.isConstantEvaluated())) { 11971 llvm::APSInt Value(32); 11972 Value = Result.Val.getInt(); 11973 11974 if (S.SourceMgr.isInSystemMacro(CC)) 11975 return; 11976 11977 std::string PrettySourceValue = Value.toString(10); 11978 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11979 11980 S.DiagRuntimeBehavior( 11981 E->getExprLoc(), E, 11982 S.PDiag(diag::warn_impcast_integer_precision_constant) 11983 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11984 << E->getSourceRange() << clang::SourceRange(CC)); 11985 return; 11986 } 11987 11988 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11989 if (S.SourceMgr.isInSystemMacro(CC)) 11990 return; 11991 11992 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11993 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11994 /* pruneControlFlow */ true); 11995 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11996 } 11997 11998 if (TargetRange.Width > SourceRange.Width) { 11999 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12000 if (UO->getOpcode() == UO_Minus) 12001 if (Source->isUnsignedIntegerType()) { 12002 if (Target->isUnsignedIntegerType()) 12003 return DiagnoseImpCast(S, E, T, CC, 12004 diag::warn_impcast_high_order_zero_bits); 12005 if (Target->isSignedIntegerType()) 12006 return DiagnoseImpCast(S, E, T, CC, 12007 diag::warn_impcast_nonnegative_result); 12008 } 12009 } 12010 12011 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 12012 SourceRange.NonNegative && Source->isSignedIntegerType()) { 12013 // Warn when doing a signed to signed conversion, warn if the positive 12014 // source value is exactly the width of the target type, which will 12015 // cause a negative value to be stored. 12016 12017 Expr::EvalResult Result; 12018 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12019 !S.SourceMgr.isInSystemMacro(CC)) { 12020 llvm::APSInt Value = Result.Val.getInt(); 12021 if (isSameWidthConstantConversion(S, E, T, CC)) { 12022 std::string PrettySourceValue = Value.toString(10); 12023 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12024 12025 S.DiagRuntimeBehavior( 12026 E->getExprLoc(), E, 12027 S.PDiag(diag::warn_impcast_integer_precision_constant) 12028 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12029 << E->getSourceRange() << clang::SourceRange(CC)); 12030 return; 12031 } 12032 } 12033 12034 // Fall through for non-constants to give a sign conversion warning. 12035 } 12036 12037 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 12038 (!TargetRange.NonNegative && SourceRange.NonNegative && 12039 SourceRange.Width == TargetRange.Width)) { 12040 if (S.SourceMgr.isInSystemMacro(CC)) 12041 return; 12042 12043 unsigned DiagID = diag::warn_impcast_integer_sign; 12044 12045 // Traditionally, gcc has warned about this under -Wsign-compare. 12046 // We also want to warn about it in -Wconversion. 12047 // So if -Wconversion is off, use a completely identical diagnostic 12048 // in the sign-compare group. 12049 // The conditional-checking code will 12050 if (ICContext) { 12051 DiagID = diag::warn_impcast_integer_sign_conditional; 12052 *ICContext = true; 12053 } 12054 12055 return DiagnoseImpCast(S, E, T, CC, DiagID); 12056 } 12057 12058 // Diagnose conversions between different enumeration types. 12059 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12060 // type, to give us better diagnostics. 12061 QualType SourceType = E->getType(); 12062 if (!S.getLangOpts().CPlusPlus) { 12063 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12064 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12065 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12066 SourceType = S.Context.getTypeDeclType(Enum); 12067 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12068 } 12069 } 12070 12071 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12072 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12073 if (SourceEnum->getDecl()->hasNameForLinkage() && 12074 TargetEnum->getDecl()->hasNameForLinkage() && 12075 SourceEnum != TargetEnum) { 12076 if (S.SourceMgr.isInSystemMacro(CC)) 12077 return; 12078 12079 return DiagnoseImpCast(S, E, SourceType, T, CC, 12080 diag::warn_impcast_different_enum_types); 12081 } 12082 } 12083 12084 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12085 SourceLocation CC, QualType T); 12086 12087 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12088 SourceLocation CC, bool &ICContext) { 12089 E = E->IgnoreParenImpCasts(); 12090 12091 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12092 return CheckConditionalOperator(S, CO, CC, T); 12093 12094 AnalyzeImplicitConversions(S, E, CC); 12095 if (E->getType() != T) 12096 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12097 } 12098 12099 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12100 SourceLocation CC, QualType T) { 12101 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12102 12103 Expr *TrueExpr = E->getTrueExpr(); 12104 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12105 TrueExpr = BCO->getCommon(); 12106 12107 bool Suspicious = false; 12108 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12109 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12110 12111 if (T->isBooleanType()) 12112 DiagnoseIntInBoolContext(S, E); 12113 12114 // If -Wconversion would have warned about either of the candidates 12115 // for a signedness conversion to the context type... 12116 if (!Suspicious) return; 12117 12118 // ...but it's currently ignored... 12119 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12120 return; 12121 12122 // ...then check whether it would have warned about either of the 12123 // candidates for a signedness conversion to the condition type. 12124 if (E->getType() == T) return; 12125 12126 Suspicious = false; 12127 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12128 E->getType(), CC, &Suspicious); 12129 if (!Suspicious) 12130 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12131 E->getType(), CC, &Suspicious); 12132 } 12133 12134 /// Check conversion of given expression to boolean. 12135 /// Input argument E is a logical expression. 12136 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12137 if (S.getLangOpts().Bool) 12138 return; 12139 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12140 return; 12141 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12142 } 12143 12144 namespace { 12145 struct AnalyzeImplicitConversionsWorkItem { 12146 Expr *E; 12147 SourceLocation CC; 12148 bool IsListInit; 12149 }; 12150 } 12151 12152 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12153 /// that should be visited are added to WorkList. 12154 static void AnalyzeImplicitConversions( 12155 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12156 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12157 Expr *OrigE = Item.E; 12158 SourceLocation CC = Item.CC; 12159 12160 QualType T = OrigE->getType(); 12161 Expr *E = OrigE->IgnoreParenImpCasts(); 12162 12163 // Propagate whether we are in a C++ list initialization expression. 12164 // If so, we do not issue warnings for implicit int-float conversion 12165 // precision loss, because C++11 narrowing already handles it. 12166 bool IsListInit = Item.IsListInit || 12167 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12168 12169 if (E->isTypeDependent() || E->isValueDependent()) 12170 return; 12171 12172 Expr *SourceExpr = E; 12173 // Examine, but don't traverse into the source expression of an 12174 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12175 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12176 // evaluate it in the context of checking the specific conversion to T though. 12177 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12178 if (auto *Src = OVE->getSourceExpr()) 12179 SourceExpr = Src; 12180 12181 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12182 if (UO->getOpcode() == UO_Not && 12183 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12184 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12185 << OrigE->getSourceRange() << T->isBooleanType() 12186 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12187 12188 // For conditional operators, we analyze the arguments as if they 12189 // were being fed directly into the output. 12190 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12191 CheckConditionalOperator(S, CO, CC, T); 12192 return; 12193 } 12194 12195 // Check implicit argument conversions for function calls. 12196 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12197 CheckImplicitArgumentConversions(S, Call, CC); 12198 12199 // Go ahead and check any implicit conversions we might have skipped. 12200 // The non-canonical typecheck is just an optimization; 12201 // CheckImplicitConversion will filter out dead implicit conversions. 12202 if (SourceExpr->getType() != T) 12203 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12204 12205 // Now continue drilling into this expression. 12206 12207 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12208 // The bound subexpressions in a PseudoObjectExpr are not reachable 12209 // as transitive children. 12210 // FIXME: Use a more uniform representation for this. 12211 for (auto *SE : POE->semantics()) 12212 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12213 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12214 } 12215 12216 // Skip past explicit casts. 12217 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12218 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12219 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12220 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12221 WorkList.push_back({E, CC, IsListInit}); 12222 return; 12223 } 12224 12225 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12226 // Do a somewhat different check with comparison operators. 12227 if (BO->isComparisonOp()) 12228 return AnalyzeComparison(S, BO); 12229 12230 // And with simple assignments. 12231 if (BO->getOpcode() == BO_Assign) 12232 return AnalyzeAssignment(S, BO); 12233 // And with compound assignments. 12234 if (BO->isAssignmentOp()) 12235 return AnalyzeCompoundAssignment(S, BO); 12236 } 12237 12238 // These break the otherwise-useful invariant below. Fortunately, 12239 // we don't really need to recurse into them, because any internal 12240 // expressions should have been analyzed already when they were 12241 // built into statements. 12242 if (isa<StmtExpr>(E)) return; 12243 12244 // Don't descend into unevaluated contexts. 12245 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12246 12247 // Now just recurse over the expression's children. 12248 CC = E->getExprLoc(); 12249 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12250 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12251 for (Stmt *SubStmt : E->children()) { 12252 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12253 if (!ChildExpr) 12254 continue; 12255 12256 if (IsLogicalAndOperator && 12257 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12258 // Ignore checking string literals that are in logical and operators. 12259 // This is a common pattern for asserts. 12260 continue; 12261 WorkList.push_back({ChildExpr, CC, IsListInit}); 12262 } 12263 12264 if (BO && BO->isLogicalOp()) { 12265 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12266 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12267 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12268 12269 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12270 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12271 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12272 } 12273 12274 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12275 if (U->getOpcode() == UO_LNot) { 12276 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12277 } else if (U->getOpcode() != UO_AddrOf) { 12278 if (U->getSubExpr()->getType()->isAtomicType()) 12279 S.Diag(U->getSubExpr()->getBeginLoc(), 12280 diag::warn_atomic_implicit_seq_cst); 12281 } 12282 } 12283 } 12284 12285 /// AnalyzeImplicitConversions - Find and report any interesting 12286 /// implicit conversions in the given expression. There are a couple 12287 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12288 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12289 bool IsListInit/*= false*/) { 12290 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12291 WorkList.push_back({OrigE, CC, IsListInit}); 12292 while (!WorkList.empty()) 12293 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12294 } 12295 12296 /// Diagnose integer type and any valid implicit conversion to it. 12297 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12298 // Taking into account implicit conversions, 12299 // allow any integer. 12300 if (!E->getType()->isIntegerType()) { 12301 S.Diag(E->getBeginLoc(), 12302 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12303 return true; 12304 } 12305 // Potentially emit standard warnings for implicit conversions if enabled 12306 // using -Wconversion. 12307 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12308 return false; 12309 } 12310 12311 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12312 // Returns true when emitting a warning about taking the address of a reference. 12313 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12314 const PartialDiagnostic &PD) { 12315 E = E->IgnoreParenImpCasts(); 12316 12317 const FunctionDecl *FD = nullptr; 12318 12319 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12320 if (!DRE->getDecl()->getType()->isReferenceType()) 12321 return false; 12322 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12323 if (!M->getMemberDecl()->getType()->isReferenceType()) 12324 return false; 12325 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12326 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12327 return false; 12328 FD = Call->getDirectCallee(); 12329 } else { 12330 return false; 12331 } 12332 12333 SemaRef.Diag(E->getExprLoc(), PD); 12334 12335 // If possible, point to location of function. 12336 if (FD) { 12337 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12338 } 12339 12340 return true; 12341 } 12342 12343 // Returns true if the SourceLocation is expanded from any macro body. 12344 // Returns false if the SourceLocation is invalid, is from not in a macro 12345 // expansion, or is from expanded from a top-level macro argument. 12346 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12347 if (Loc.isInvalid()) 12348 return false; 12349 12350 while (Loc.isMacroID()) { 12351 if (SM.isMacroBodyExpansion(Loc)) 12352 return true; 12353 Loc = SM.getImmediateMacroCallerLoc(Loc); 12354 } 12355 12356 return false; 12357 } 12358 12359 /// Diagnose pointers that are always non-null. 12360 /// \param E the expression containing the pointer 12361 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12362 /// compared to a null pointer 12363 /// \param IsEqual True when the comparison is equal to a null pointer 12364 /// \param Range Extra SourceRange to highlight in the diagnostic 12365 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12366 Expr::NullPointerConstantKind NullKind, 12367 bool IsEqual, SourceRange Range) { 12368 if (!E) 12369 return; 12370 12371 // Don't warn inside macros. 12372 if (E->getExprLoc().isMacroID()) { 12373 const SourceManager &SM = getSourceManager(); 12374 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12375 IsInAnyMacroBody(SM, Range.getBegin())) 12376 return; 12377 } 12378 E = E->IgnoreImpCasts(); 12379 12380 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12381 12382 if (isa<CXXThisExpr>(E)) { 12383 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12384 : diag::warn_this_bool_conversion; 12385 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12386 return; 12387 } 12388 12389 bool IsAddressOf = false; 12390 12391 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12392 if (UO->getOpcode() != UO_AddrOf) 12393 return; 12394 IsAddressOf = true; 12395 E = UO->getSubExpr(); 12396 } 12397 12398 if (IsAddressOf) { 12399 unsigned DiagID = IsCompare 12400 ? diag::warn_address_of_reference_null_compare 12401 : diag::warn_address_of_reference_bool_conversion; 12402 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12403 << IsEqual; 12404 if (CheckForReference(*this, E, PD)) { 12405 return; 12406 } 12407 } 12408 12409 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12410 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12411 std::string Str; 12412 llvm::raw_string_ostream S(Str); 12413 E->printPretty(S, nullptr, getPrintingPolicy()); 12414 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12415 : diag::warn_cast_nonnull_to_bool; 12416 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12417 << E->getSourceRange() << Range << IsEqual; 12418 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12419 }; 12420 12421 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12422 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12423 if (auto *Callee = Call->getDirectCallee()) { 12424 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12425 ComplainAboutNonnullParamOrCall(A); 12426 return; 12427 } 12428 } 12429 } 12430 12431 // Expect to find a single Decl. Skip anything more complicated. 12432 ValueDecl *D = nullptr; 12433 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12434 D = R->getDecl(); 12435 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12436 D = M->getMemberDecl(); 12437 } 12438 12439 // Weak Decls can be null. 12440 if (!D || D->isWeak()) 12441 return; 12442 12443 // Check for parameter decl with nonnull attribute 12444 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12445 if (getCurFunction() && 12446 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12447 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12448 ComplainAboutNonnullParamOrCall(A); 12449 return; 12450 } 12451 12452 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12453 // Skip function template not specialized yet. 12454 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12455 return; 12456 auto ParamIter = llvm::find(FD->parameters(), PV); 12457 assert(ParamIter != FD->param_end()); 12458 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12459 12460 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12461 if (!NonNull->args_size()) { 12462 ComplainAboutNonnullParamOrCall(NonNull); 12463 return; 12464 } 12465 12466 for (const ParamIdx &ArgNo : NonNull->args()) { 12467 if (ArgNo.getASTIndex() == ParamNo) { 12468 ComplainAboutNonnullParamOrCall(NonNull); 12469 return; 12470 } 12471 } 12472 } 12473 } 12474 } 12475 } 12476 12477 QualType T = D->getType(); 12478 const bool IsArray = T->isArrayType(); 12479 const bool IsFunction = T->isFunctionType(); 12480 12481 // Address of function is used to silence the function warning. 12482 if (IsAddressOf && IsFunction) { 12483 return; 12484 } 12485 12486 // Found nothing. 12487 if (!IsAddressOf && !IsFunction && !IsArray) 12488 return; 12489 12490 // Pretty print the expression for the diagnostic. 12491 std::string Str; 12492 llvm::raw_string_ostream S(Str); 12493 E->printPretty(S, nullptr, getPrintingPolicy()); 12494 12495 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12496 : diag::warn_impcast_pointer_to_bool; 12497 enum { 12498 AddressOf, 12499 FunctionPointer, 12500 ArrayPointer 12501 } DiagType; 12502 if (IsAddressOf) 12503 DiagType = AddressOf; 12504 else if (IsFunction) 12505 DiagType = FunctionPointer; 12506 else if (IsArray) 12507 DiagType = ArrayPointer; 12508 else 12509 llvm_unreachable("Could not determine diagnostic."); 12510 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12511 << Range << IsEqual; 12512 12513 if (!IsFunction) 12514 return; 12515 12516 // Suggest '&' to silence the function warning. 12517 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12518 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12519 12520 // Check to see if '()' fixit should be emitted. 12521 QualType ReturnType; 12522 UnresolvedSet<4> NonTemplateOverloads; 12523 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12524 if (ReturnType.isNull()) 12525 return; 12526 12527 if (IsCompare) { 12528 // There are two cases here. If there is null constant, the only suggest 12529 // for a pointer return type. If the null is 0, then suggest if the return 12530 // type is a pointer or an integer type. 12531 if (!ReturnType->isPointerType()) { 12532 if (NullKind == Expr::NPCK_ZeroExpression || 12533 NullKind == Expr::NPCK_ZeroLiteral) { 12534 if (!ReturnType->isIntegerType()) 12535 return; 12536 } else { 12537 return; 12538 } 12539 } 12540 } else { // !IsCompare 12541 // For function to bool, only suggest if the function pointer has bool 12542 // return type. 12543 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12544 return; 12545 } 12546 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12547 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12548 } 12549 12550 /// Diagnoses "dangerous" implicit conversions within the given 12551 /// expression (which is a full expression). Implements -Wconversion 12552 /// and -Wsign-compare. 12553 /// 12554 /// \param CC the "context" location of the implicit conversion, i.e. 12555 /// the most location of the syntactic entity requiring the implicit 12556 /// conversion 12557 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12558 // Don't diagnose in unevaluated contexts. 12559 if (isUnevaluatedContext()) 12560 return; 12561 12562 // Don't diagnose for value- or type-dependent expressions. 12563 if (E->isTypeDependent() || E->isValueDependent()) 12564 return; 12565 12566 // Check for array bounds violations in cases where the check isn't triggered 12567 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12568 // ArraySubscriptExpr is on the RHS of a variable initialization. 12569 CheckArrayAccess(E); 12570 12571 // This is not the right CC for (e.g.) a variable initialization. 12572 AnalyzeImplicitConversions(*this, E, CC); 12573 } 12574 12575 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12576 /// Input argument E is a logical expression. 12577 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12578 ::CheckBoolLikeConversion(*this, E, CC); 12579 } 12580 12581 /// Diagnose when expression is an integer constant expression and its evaluation 12582 /// results in integer overflow 12583 void Sema::CheckForIntOverflow (Expr *E) { 12584 // Use a work list to deal with nested struct initializers. 12585 SmallVector<Expr *, 2> Exprs(1, E); 12586 12587 do { 12588 Expr *OriginalE = Exprs.pop_back_val(); 12589 Expr *E = OriginalE->IgnoreParenCasts(); 12590 12591 if (isa<BinaryOperator>(E)) { 12592 E->EvaluateForOverflow(Context); 12593 continue; 12594 } 12595 12596 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12597 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12598 else if (isa<ObjCBoxedExpr>(OriginalE)) 12599 E->EvaluateForOverflow(Context); 12600 else if (auto Call = dyn_cast<CallExpr>(E)) 12601 Exprs.append(Call->arg_begin(), Call->arg_end()); 12602 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12603 Exprs.append(Message->arg_begin(), Message->arg_end()); 12604 } while (!Exprs.empty()); 12605 } 12606 12607 namespace { 12608 12609 /// Visitor for expressions which looks for unsequenced operations on the 12610 /// same object. 12611 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12612 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12613 12614 /// A tree of sequenced regions within an expression. Two regions are 12615 /// unsequenced if one is an ancestor or a descendent of the other. When we 12616 /// finish processing an expression with sequencing, such as a comma 12617 /// expression, we fold its tree nodes into its parent, since they are 12618 /// unsequenced with respect to nodes we will visit later. 12619 class SequenceTree { 12620 struct Value { 12621 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12622 unsigned Parent : 31; 12623 unsigned Merged : 1; 12624 }; 12625 SmallVector<Value, 8> Values; 12626 12627 public: 12628 /// A region within an expression which may be sequenced with respect 12629 /// to some other region. 12630 class Seq { 12631 friend class SequenceTree; 12632 12633 unsigned Index; 12634 12635 explicit Seq(unsigned N) : Index(N) {} 12636 12637 public: 12638 Seq() : Index(0) {} 12639 }; 12640 12641 SequenceTree() { Values.push_back(Value(0)); } 12642 Seq root() const { return Seq(0); } 12643 12644 /// Create a new sequence of operations, which is an unsequenced 12645 /// subset of \p Parent. This sequence of operations is sequenced with 12646 /// respect to other children of \p Parent. 12647 Seq allocate(Seq Parent) { 12648 Values.push_back(Value(Parent.Index)); 12649 return Seq(Values.size() - 1); 12650 } 12651 12652 /// Merge a sequence of operations into its parent. 12653 void merge(Seq S) { 12654 Values[S.Index].Merged = true; 12655 } 12656 12657 /// Determine whether two operations are unsequenced. This operation 12658 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12659 /// should have been merged into its parent as appropriate. 12660 bool isUnsequenced(Seq Cur, Seq Old) { 12661 unsigned C = representative(Cur.Index); 12662 unsigned Target = representative(Old.Index); 12663 while (C >= Target) { 12664 if (C == Target) 12665 return true; 12666 C = Values[C].Parent; 12667 } 12668 return false; 12669 } 12670 12671 private: 12672 /// Pick a representative for a sequence. 12673 unsigned representative(unsigned K) { 12674 if (Values[K].Merged) 12675 // Perform path compression as we go. 12676 return Values[K].Parent = representative(Values[K].Parent); 12677 return K; 12678 } 12679 }; 12680 12681 /// An object for which we can track unsequenced uses. 12682 using Object = const NamedDecl *; 12683 12684 /// Different flavors of object usage which we track. We only track the 12685 /// least-sequenced usage of each kind. 12686 enum UsageKind { 12687 /// A read of an object. Multiple unsequenced reads are OK. 12688 UK_Use, 12689 12690 /// A modification of an object which is sequenced before the value 12691 /// computation of the expression, such as ++n in C++. 12692 UK_ModAsValue, 12693 12694 /// A modification of an object which is not sequenced before the value 12695 /// computation of the expression, such as n++. 12696 UK_ModAsSideEffect, 12697 12698 UK_Count = UK_ModAsSideEffect + 1 12699 }; 12700 12701 /// Bundle together a sequencing region and the expression corresponding 12702 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12703 struct Usage { 12704 const Expr *UsageExpr; 12705 SequenceTree::Seq Seq; 12706 12707 Usage() : UsageExpr(nullptr), Seq() {} 12708 }; 12709 12710 struct UsageInfo { 12711 Usage Uses[UK_Count]; 12712 12713 /// Have we issued a diagnostic for this object already? 12714 bool Diagnosed; 12715 12716 UsageInfo() : Uses(), Diagnosed(false) {} 12717 }; 12718 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12719 12720 Sema &SemaRef; 12721 12722 /// Sequenced regions within the expression. 12723 SequenceTree Tree; 12724 12725 /// Declaration modifications and references which we have seen. 12726 UsageInfoMap UsageMap; 12727 12728 /// The region we are currently within. 12729 SequenceTree::Seq Region; 12730 12731 /// Filled in with declarations which were modified as a side-effect 12732 /// (that is, post-increment operations). 12733 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12734 12735 /// Expressions to check later. We defer checking these to reduce 12736 /// stack usage. 12737 SmallVectorImpl<const Expr *> &WorkList; 12738 12739 /// RAII object wrapping the visitation of a sequenced subexpression of an 12740 /// expression. At the end of this process, the side-effects of the evaluation 12741 /// become sequenced with respect to the value computation of the result, so 12742 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12743 /// UK_ModAsValue. 12744 struct SequencedSubexpression { 12745 SequencedSubexpression(SequenceChecker &Self) 12746 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12747 Self.ModAsSideEffect = &ModAsSideEffect; 12748 } 12749 12750 ~SequencedSubexpression() { 12751 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12752 // Add a new usage with usage kind UK_ModAsValue, and then restore 12753 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12754 // the previous one was empty). 12755 UsageInfo &UI = Self.UsageMap[M.first]; 12756 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12757 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12758 SideEffectUsage = M.second; 12759 } 12760 Self.ModAsSideEffect = OldModAsSideEffect; 12761 } 12762 12763 SequenceChecker &Self; 12764 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12765 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12766 }; 12767 12768 /// RAII object wrapping the visitation of a subexpression which we might 12769 /// choose to evaluate as a constant. If any subexpression is evaluated and 12770 /// found to be non-constant, this allows us to suppress the evaluation of 12771 /// the outer expression. 12772 class EvaluationTracker { 12773 public: 12774 EvaluationTracker(SequenceChecker &Self) 12775 : Self(Self), Prev(Self.EvalTracker) { 12776 Self.EvalTracker = this; 12777 } 12778 12779 ~EvaluationTracker() { 12780 Self.EvalTracker = Prev; 12781 if (Prev) 12782 Prev->EvalOK &= EvalOK; 12783 } 12784 12785 bool evaluate(const Expr *E, bool &Result) { 12786 if (!EvalOK || E->isValueDependent()) 12787 return false; 12788 EvalOK = E->EvaluateAsBooleanCondition( 12789 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12790 return EvalOK; 12791 } 12792 12793 private: 12794 SequenceChecker &Self; 12795 EvaluationTracker *Prev; 12796 bool EvalOK = true; 12797 } *EvalTracker = nullptr; 12798 12799 /// Find the object which is produced by the specified expression, 12800 /// if any. 12801 Object getObject(const Expr *E, bool Mod) const { 12802 E = E->IgnoreParenCasts(); 12803 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12804 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12805 return getObject(UO->getSubExpr(), Mod); 12806 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12807 if (BO->getOpcode() == BO_Comma) 12808 return getObject(BO->getRHS(), Mod); 12809 if (Mod && BO->isAssignmentOp()) 12810 return getObject(BO->getLHS(), Mod); 12811 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12812 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12813 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12814 return ME->getMemberDecl(); 12815 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12816 // FIXME: If this is a reference, map through to its value. 12817 return DRE->getDecl(); 12818 return nullptr; 12819 } 12820 12821 /// Note that an object \p O was modified or used by an expression 12822 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12823 /// the object \p O as obtained via the \p UsageMap. 12824 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12825 // Get the old usage for the given object and usage kind. 12826 Usage &U = UI.Uses[UK]; 12827 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12828 // If we have a modification as side effect and are in a sequenced 12829 // subexpression, save the old Usage so that we can restore it later 12830 // in SequencedSubexpression::~SequencedSubexpression. 12831 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12832 ModAsSideEffect->push_back(std::make_pair(O, U)); 12833 // Then record the new usage with the current sequencing region. 12834 U.UsageExpr = UsageExpr; 12835 U.Seq = Region; 12836 } 12837 } 12838 12839 /// Check whether a modification or use of an object \p O in an expression 12840 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12841 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12842 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12843 /// usage and false we are checking for a mod-use unsequenced usage. 12844 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12845 UsageKind OtherKind, bool IsModMod) { 12846 if (UI.Diagnosed) 12847 return; 12848 12849 const Usage &U = UI.Uses[OtherKind]; 12850 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12851 return; 12852 12853 const Expr *Mod = U.UsageExpr; 12854 const Expr *ModOrUse = UsageExpr; 12855 if (OtherKind == UK_Use) 12856 std::swap(Mod, ModOrUse); 12857 12858 SemaRef.DiagRuntimeBehavior( 12859 Mod->getExprLoc(), {Mod, ModOrUse}, 12860 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12861 : diag::warn_unsequenced_mod_use) 12862 << O << SourceRange(ModOrUse->getExprLoc())); 12863 UI.Diagnosed = true; 12864 } 12865 12866 // A note on note{Pre, Post}{Use, Mod}: 12867 // 12868 // (It helps to follow the algorithm with an expression such as 12869 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12870 // operations before C++17 and both are well-defined in C++17). 12871 // 12872 // When visiting a node which uses/modify an object we first call notePreUse 12873 // or notePreMod before visiting its sub-expression(s). At this point the 12874 // children of the current node have not yet been visited and so the eventual 12875 // uses/modifications resulting from the children of the current node have not 12876 // been recorded yet. 12877 // 12878 // We then visit the children of the current node. After that notePostUse or 12879 // notePostMod is called. These will 1) detect an unsequenced modification 12880 // as side effect (as in "k++ + k") and 2) add a new usage with the 12881 // appropriate usage kind. 12882 // 12883 // We also have to be careful that some operation sequences modification as 12884 // side effect as well (for example: || or ,). To account for this we wrap 12885 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12886 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12887 // which record usages which are modifications as side effect, and then 12888 // downgrade them (or more accurately restore the previous usage which was a 12889 // modification as side effect) when exiting the scope of the sequenced 12890 // subexpression. 12891 12892 void notePreUse(Object O, const Expr *UseExpr) { 12893 UsageInfo &UI = UsageMap[O]; 12894 // Uses conflict with other modifications. 12895 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12896 } 12897 12898 void notePostUse(Object O, const Expr *UseExpr) { 12899 UsageInfo &UI = UsageMap[O]; 12900 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12901 /*IsModMod=*/false); 12902 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12903 } 12904 12905 void notePreMod(Object O, const Expr *ModExpr) { 12906 UsageInfo &UI = UsageMap[O]; 12907 // Modifications conflict with other modifications and with uses. 12908 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12909 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12910 } 12911 12912 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12913 UsageInfo &UI = UsageMap[O]; 12914 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12915 /*IsModMod=*/true); 12916 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12917 } 12918 12919 public: 12920 SequenceChecker(Sema &S, const Expr *E, 12921 SmallVectorImpl<const Expr *> &WorkList) 12922 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12923 Visit(E); 12924 // Silence a -Wunused-private-field since WorkList is now unused. 12925 // TODO: Evaluate if it can be used, and if not remove it. 12926 (void)this->WorkList; 12927 } 12928 12929 void VisitStmt(const Stmt *S) { 12930 // Skip all statements which aren't expressions for now. 12931 } 12932 12933 void VisitExpr(const Expr *E) { 12934 // By default, just recurse to evaluated subexpressions. 12935 Base::VisitStmt(E); 12936 } 12937 12938 void VisitCastExpr(const CastExpr *E) { 12939 Object O = Object(); 12940 if (E->getCastKind() == CK_LValueToRValue) 12941 O = getObject(E->getSubExpr(), false); 12942 12943 if (O) 12944 notePreUse(O, E); 12945 VisitExpr(E); 12946 if (O) 12947 notePostUse(O, E); 12948 } 12949 12950 void VisitSequencedExpressions(const Expr *SequencedBefore, 12951 const Expr *SequencedAfter) { 12952 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12953 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12954 SequenceTree::Seq OldRegion = Region; 12955 12956 { 12957 SequencedSubexpression SeqBefore(*this); 12958 Region = BeforeRegion; 12959 Visit(SequencedBefore); 12960 } 12961 12962 Region = AfterRegion; 12963 Visit(SequencedAfter); 12964 12965 Region = OldRegion; 12966 12967 Tree.merge(BeforeRegion); 12968 Tree.merge(AfterRegion); 12969 } 12970 12971 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12972 // C++17 [expr.sub]p1: 12973 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12974 // expression E1 is sequenced before the expression E2. 12975 if (SemaRef.getLangOpts().CPlusPlus17) 12976 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12977 else { 12978 Visit(ASE->getLHS()); 12979 Visit(ASE->getRHS()); 12980 } 12981 } 12982 12983 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12984 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12985 void VisitBinPtrMem(const BinaryOperator *BO) { 12986 // C++17 [expr.mptr.oper]p4: 12987 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12988 // the expression E1 is sequenced before the expression E2. 12989 if (SemaRef.getLangOpts().CPlusPlus17) 12990 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12991 else { 12992 Visit(BO->getLHS()); 12993 Visit(BO->getRHS()); 12994 } 12995 } 12996 12997 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12998 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12999 void VisitBinShlShr(const BinaryOperator *BO) { 13000 // C++17 [expr.shift]p4: 13001 // The expression E1 is sequenced before the expression E2. 13002 if (SemaRef.getLangOpts().CPlusPlus17) 13003 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13004 else { 13005 Visit(BO->getLHS()); 13006 Visit(BO->getRHS()); 13007 } 13008 } 13009 13010 void VisitBinComma(const BinaryOperator *BO) { 13011 // C++11 [expr.comma]p1: 13012 // Every value computation and side effect associated with the left 13013 // expression is sequenced before every value computation and side 13014 // effect associated with the right expression. 13015 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13016 } 13017 13018 void VisitBinAssign(const BinaryOperator *BO) { 13019 SequenceTree::Seq RHSRegion; 13020 SequenceTree::Seq LHSRegion; 13021 if (SemaRef.getLangOpts().CPlusPlus17) { 13022 RHSRegion = Tree.allocate(Region); 13023 LHSRegion = Tree.allocate(Region); 13024 } else { 13025 RHSRegion = Region; 13026 LHSRegion = Region; 13027 } 13028 SequenceTree::Seq OldRegion = Region; 13029 13030 // C++11 [expr.ass]p1: 13031 // [...] the assignment is sequenced after the value computation 13032 // of the right and left operands, [...] 13033 // 13034 // so check it before inspecting the operands and update the 13035 // map afterwards. 13036 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13037 if (O) 13038 notePreMod(O, BO); 13039 13040 if (SemaRef.getLangOpts().CPlusPlus17) { 13041 // C++17 [expr.ass]p1: 13042 // [...] The right operand is sequenced before the left operand. [...] 13043 { 13044 SequencedSubexpression SeqBefore(*this); 13045 Region = RHSRegion; 13046 Visit(BO->getRHS()); 13047 } 13048 13049 Region = LHSRegion; 13050 Visit(BO->getLHS()); 13051 13052 if (O && isa<CompoundAssignOperator>(BO)) 13053 notePostUse(O, BO); 13054 13055 } else { 13056 // C++11 does not specify any sequencing between the LHS and RHS. 13057 Region = LHSRegion; 13058 Visit(BO->getLHS()); 13059 13060 if (O && isa<CompoundAssignOperator>(BO)) 13061 notePostUse(O, BO); 13062 13063 Region = RHSRegion; 13064 Visit(BO->getRHS()); 13065 } 13066 13067 // C++11 [expr.ass]p1: 13068 // the assignment is sequenced [...] before the value computation of the 13069 // assignment expression. 13070 // C11 6.5.16/3 has no such rule. 13071 Region = OldRegion; 13072 if (O) 13073 notePostMod(O, BO, 13074 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13075 : UK_ModAsSideEffect); 13076 if (SemaRef.getLangOpts().CPlusPlus17) { 13077 Tree.merge(RHSRegion); 13078 Tree.merge(LHSRegion); 13079 } 13080 } 13081 13082 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13083 VisitBinAssign(CAO); 13084 } 13085 13086 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13087 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13088 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13089 Object O = getObject(UO->getSubExpr(), true); 13090 if (!O) 13091 return VisitExpr(UO); 13092 13093 notePreMod(O, UO); 13094 Visit(UO->getSubExpr()); 13095 // C++11 [expr.pre.incr]p1: 13096 // the expression ++x is equivalent to x+=1 13097 notePostMod(O, UO, 13098 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13099 : UK_ModAsSideEffect); 13100 } 13101 13102 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13103 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13104 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13105 Object O = getObject(UO->getSubExpr(), true); 13106 if (!O) 13107 return VisitExpr(UO); 13108 13109 notePreMod(O, UO); 13110 Visit(UO->getSubExpr()); 13111 notePostMod(O, UO, UK_ModAsSideEffect); 13112 } 13113 13114 void VisitBinLOr(const BinaryOperator *BO) { 13115 // C++11 [expr.log.or]p2: 13116 // If the second expression is evaluated, every value computation and 13117 // side effect associated with the first expression is sequenced before 13118 // every value computation and side effect associated with the 13119 // second expression. 13120 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13121 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13122 SequenceTree::Seq OldRegion = Region; 13123 13124 EvaluationTracker Eval(*this); 13125 { 13126 SequencedSubexpression Sequenced(*this); 13127 Region = LHSRegion; 13128 Visit(BO->getLHS()); 13129 } 13130 13131 // C++11 [expr.log.or]p1: 13132 // [...] the second operand is not evaluated if the first operand 13133 // evaluates to true. 13134 bool EvalResult = false; 13135 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13136 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13137 if (ShouldVisitRHS) { 13138 Region = RHSRegion; 13139 Visit(BO->getRHS()); 13140 } 13141 13142 Region = OldRegion; 13143 Tree.merge(LHSRegion); 13144 Tree.merge(RHSRegion); 13145 } 13146 13147 void VisitBinLAnd(const BinaryOperator *BO) { 13148 // C++11 [expr.log.and]p2: 13149 // If the second expression is evaluated, every value computation and 13150 // side effect associated with the first expression is sequenced before 13151 // every value computation and side effect associated with the 13152 // second expression. 13153 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13154 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13155 SequenceTree::Seq OldRegion = Region; 13156 13157 EvaluationTracker Eval(*this); 13158 { 13159 SequencedSubexpression Sequenced(*this); 13160 Region = LHSRegion; 13161 Visit(BO->getLHS()); 13162 } 13163 13164 // C++11 [expr.log.and]p1: 13165 // [...] the second operand is not evaluated if the first operand is false. 13166 bool EvalResult = false; 13167 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13168 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13169 if (ShouldVisitRHS) { 13170 Region = RHSRegion; 13171 Visit(BO->getRHS()); 13172 } 13173 13174 Region = OldRegion; 13175 Tree.merge(LHSRegion); 13176 Tree.merge(RHSRegion); 13177 } 13178 13179 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13180 // C++11 [expr.cond]p1: 13181 // [...] Every value computation and side effect associated with the first 13182 // expression is sequenced before every value computation and side effect 13183 // associated with the second or third expression. 13184 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13185 13186 // No sequencing is specified between the true and false expression. 13187 // However since exactly one of both is going to be evaluated we can 13188 // consider them to be sequenced. This is needed to avoid warning on 13189 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13190 // both the true and false expressions because we can't evaluate x. 13191 // This will still allow us to detect an expression like (pre C++17) 13192 // "(x ? y += 1 : y += 2) = y". 13193 // 13194 // We don't wrap the visitation of the true and false expression with 13195 // SequencedSubexpression because we don't want to downgrade modifications 13196 // as side effect in the true and false expressions after the visition 13197 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13198 // not warn between the two "y++", but we should warn between the "y++" 13199 // and the "y". 13200 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13201 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13202 SequenceTree::Seq OldRegion = Region; 13203 13204 EvaluationTracker Eval(*this); 13205 { 13206 SequencedSubexpression Sequenced(*this); 13207 Region = ConditionRegion; 13208 Visit(CO->getCond()); 13209 } 13210 13211 // C++11 [expr.cond]p1: 13212 // [...] The first expression is contextually converted to bool (Clause 4). 13213 // It is evaluated and if it is true, the result of the conditional 13214 // expression is the value of the second expression, otherwise that of the 13215 // third expression. Only one of the second and third expressions is 13216 // evaluated. [...] 13217 bool EvalResult = false; 13218 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13219 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13220 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13221 if (ShouldVisitTrueExpr) { 13222 Region = TrueRegion; 13223 Visit(CO->getTrueExpr()); 13224 } 13225 if (ShouldVisitFalseExpr) { 13226 Region = FalseRegion; 13227 Visit(CO->getFalseExpr()); 13228 } 13229 13230 Region = OldRegion; 13231 Tree.merge(ConditionRegion); 13232 Tree.merge(TrueRegion); 13233 Tree.merge(FalseRegion); 13234 } 13235 13236 void VisitCallExpr(const CallExpr *CE) { 13237 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13238 13239 if (CE->isUnevaluatedBuiltinCall(Context)) 13240 return; 13241 13242 // C++11 [intro.execution]p15: 13243 // When calling a function [...], every value computation and side effect 13244 // associated with any argument expression, or with the postfix expression 13245 // designating the called function, is sequenced before execution of every 13246 // expression or statement in the body of the function [and thus before 13247 // the value computation of its result]. 13248 SequencedSubexpression Sequenced(*this); 13249 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13250 // C++17 [expr.call]p5 13251 // The postfix-expression is sequenced before each expression in the 13252 // expression-list and any default argument. [...] 13253 SequenceTree::Seq CalleeRegion; 13254 SequenceTree::Seq OtherRegion; 13255 if (SemaRef.getLangOpts().CPlusPlus17) { 13256 CalleeRegion = Tree.allocate(Region); 13257 OtherRegion = Tree.allocate(Region); 13258 } else { 13259 CalleeRegion = Region; 13260 OtherRegion = Region; 13261 } 13262 SequenceTree::Seq OldRegion = Region; 13263 13264 // Visit the callee expression first. 13265 Region = CalleeRegion; 13266 if (SemaRef.getLangOpts().CPlusPlus17) { 13267 SequencedSubexpression Sequenced(*this); 13268 Visit(CE->getCallee()); 13269 } else { 13270 Visit(CE->getCallee()); 13271 } 13272 13273 // Then visit the argument expressions. 13274 Region = OtherRegion; 13275 for (const Expr *Argument : CE->arguments()) 13276 Visit(Argument); 13277 13278 Region = OldRegion; 13279 if (SemaRef.getLangOpts().CPlusPlus17) { 13280 Tree.merge(CalleeRegion); 13281 Tree.merge(OtherRegion); 13282 } 13283 }); 13284 } 13285 13286 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13287 // C++17 [over.match.oper]p2: 13288 // [...] the operator notation is first transformed to the equivalent 13289 // function-call notation as summarized in Table 12 (where @ denotes one 13290 // of the operators covered in the specified subclause). However, the 13291 // operands are sequenced in the order prescribed for the built-in 13292 // operator (Clause 8). 13293 // 13294 // From the above only overloaded binary operators and overloaded call 13295 // operators have sequencing rules in C++17 that we need to handle 13296 // separately. 13297 if (!SemaRef.getLangOpts().CPlusPlus17 || 13298 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13299 return VisitCallExpr(CXXOCE); 13300 13301 enum { 13302 NoSequencing, 13303 LHSBeforeRHS, 13304 RHSBeforeLHS, 13305 LHSBeforeRest 13306 } SequencingKind; 13307 switch (CXXOCE->getOperator()) { 13308 case OO_Equal: 13309 case OO_PlusEqual: 13310 case OO_MinusEqual: 13311 case OO_StarEqual: 13312 case OO_SlashEqual: 13313 case OO_PercentEqual: 13314 case OO_CaretEqual: 13315 case OO_AmpEqual: 13316 case OO_PipeEqual: 13317 case OO_LessLessEqual: 13318 case OO_GreaterGreaterEqual: 13319 SequencingKind = RHSBeforeLHS; 13320 break; 13321 13322 case OO_LessLess: 13323 case OO_GreaterGreater: 13324 case OO_AmpAmp: 13325 case OO_PipePipe: 13326 case OO_Comma: 13327 case OO_ArrowStar: 13328 case OO_Subscript: 13329 SequencingKind = LHSBeforeRHS; 13330 break; 13331 13332 case OO_Call: 13333 SequencingKind = LHSBeforeRest; 13334 break; 13335 13336 default: 13337 SequencingKind = NoSequencing; 13338 break; 13339 } 13340 13341 if (SequencingKind == NoSequencing) 13342 return VisitCallExpr(CXXOCE); 13343 13344 // This is a call, so all subexpressions are sequenced before the result. 13345 SequencedSubexpression Sequenced(*this); 13346 13347 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13348 assert(SemaRef.getLangOpts().CPlusPlus17 && 13349 "Should only get there with C++17 and above!"); 13350 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13351 "Should only get there with an overloaded binary operator" 13352 " or an overloaded call operator!"); 13353 13354 if (SequencingKind == LHSBeforeRest) { 13355 assert(CXXOCE->getOperator() == OO_Call && 13356 "We should only have an overloaded call operator here!"); 13357 13358 // This is very similar to VisitCallExpr, except that we only have the 13359 // C++17 case. The postfix-expression is the first argument of the 13360 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13361 // are in the following arguments. 13362 // 13363 // Note that we intentionally do not visit the callee expression since 13364 // it is just a decayed reference to a function. 13365 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13366 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13367 SequenceTree::Seq OldRegion = Region; 13368 13369 assert(CXXOCE->getNumArgs() >= 1 && 13370 "An overloaded call operator must have at least one argument" 13371 " for the postfix-expression!"); 13372 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13373 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13374 CXXOCE->getNumArgs() - 1); 13375 13376 // Visit the postfix-expression first. 13377 { 13378 Region = PostfixExprRegion; 13379 SequencedSubexpression Sequenced(*this); 13380 Visit(PostfixExpr); 13381 } 13382 13383 // Then visit the argument expressions. 13384 Region = ArgsRegion; 13385 for (const Expr *Arg : Args) 13386 Visit(Arg); 13387 13388 Region = OldRegion; 13389 Tree.merge(PostfixExprRegion); 13390 Tree.merge(ArgsRegion); 13391 } else { 13392 assert(CXXOCE->getNumArgs() == 2 && 13393 "Should only have two arguments here!"); 13394 assert((SequencingKind == LHSBeforeRHS || 13395 SequencingKind == RHSBeforeLHS) && 13396 "Unexpected sequencing kind!"); 13397 13398 // We do not visit the callee expression since it is just a decayed 13399 // reference to a function. 13400 const Expr *E1 = CXXOCE->getArg(0); 13401 const Expr *E2 = CXXOCE->getArg(1); 13402 if (SequencingKind == RHSBeforeLHS) 13403 std::swap(E1, E2); 13404 13405 return VisitSequencedExpressions(E1, E2); 13406 } 13407 }); 13408 } 13409 13410 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13411 // This is a call, so all subexpressions are sequenced before the result. 13412 SequencedSubexpression Sequenced(*this); 13413 13414 if (!CCE->isListInitialization()) 13415 return VisitExpr(CCE); 13416 13417 // In C++11, list initializations are sequenced. 13418 SmallVector<SequenceTree::Seq, 32> Elts; 13419 SequenceTree::Seq Parent = Region; 13420 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13421 E = CCE->arg_end(); 13422 I != E; ++I) { 13423 Region = Tree.allocate(Parent); 13424 Elts.push_back(Region); 13425 Visit(*I); 13426 } 13427 13428 // Forget that the initializers are sequenced. 13429 Region = Parent; 13430 for (unsigned I = 0; I < Elts.size(); ++I) 13431 Tree.merge(Elts[I]); 13432 } 13433 13434 void VisitInitListExpr(const InitListExpr *ILE) { 13435 if (!SemaRef.getLangOpts().CPlusPlus11) 13436 return VisitExpr(ILE); 13437 13438 // In C++11, list initializations are sequenced. 13439 SmallVector<SequenceTree::Seq, 32> Elts; 13440 SequenceTree::Seq Parent = Region; 13441 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13442 const Expr *E = ILE->getInit(I); 13443 if (!E) 13444 continue; 13445 Region = Tree.allocate(Parent); 13446 Elts.push_back(Region); 13447 Visit(E); 13448 } 13449 13450 // Forget that the initializers are sequenced. 13451 Region = Parent; 13452 for (unsigned I = 0; I < Elts.size(); ++I) 13453 Tree.merge(Elts[I]); 13454 } 13455 }; 13456 13457 } // namespace 13458 13459 void Sema::CheckUnsequencedOperations(const Expr *E) { 13460 SmallVector<const Expr *, 8> WorkList; 13461 WorkList.push_back(E); 13462 while (!WorkList.empty()) { 13463 const Expr *Item = WorkList.pop_back_val(); 13464 SequenceChecker(*this, Item, WorkList); 13465 } 13466 } 13467 13468 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13469 bool IsConstexpr) { 13470 llvm::SaveAndRestore<bool> ConstantContext( 13471 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13472 CheckImplicitConversions(E, CheckLoc); 13473 if (!E->isInstantiationDependent()) 13474 CheckUnsequencedOperations(E); 13475 if (!IsConstexpr && !E->isValueDependent()) 13476 CheckForIntOverflow(E); 13477 DiagnoseMisalignedMembers(); 13478 } 13479 13480 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13481 FieldDecl *BitField, 13482 Expr *Init) { 13483 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13484 } 13485 13486 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13487 SourceLocation Loc) { 13488 if (!PType->isVariablyModifiedType()) 13489 return; 13490 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13491 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13492 return; 13493 } 13494 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13495 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13496 return; 13497 } 13498 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13499 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13500 return; 13501 } 13502 13503 const ArrayType *AT = S.Context.getAsArrayType(PType); 13504 if (!AT) 13505 return; 13506 13507 if (AT->getSizeModifier() != ArrayType::Star) { 13508 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13509 return; 13510 } 13511 13512 S.Diag(Loc, diag::err_array_star_in_function_definition); 13513 } 13514 13515 /// CheckParmsForFunctionDef - Check that the parameters of the given 13516 /// function are appropriate for the definition of a function. This 13517 /// takes care of any checks that cannot be performed on the 13518 /// declaration itself, e.g., that the types of each of the function 13519 /// parameters are complete. 13520 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13521 bool CheckParameterNames) { 13522 bool HasInvalidParm = false; 13523 for (ParmVarDecl *Param : Parameters) { 13524 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13525 // function declarator that is part of a function definition of 13526 // that function shall not have incomplete type. 13527 // 13528 // This is also C++ [dcl.fct]p6. 13529 if (!Param->isInvalidDecl() && 13530 RequireCompleteType(Param->getLocation(), Param->getType(), 13531 diag::err_typecheck_decl_incomplete_type)) { 13532 Param->setInvalidDecl(); 13533 HasInvalidParm = true; 13534 } 13535 13536 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13537 // declaration of each parameter shall include an identifier. 13538 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13539 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13540 // Diagnose this as an extension in C17 and earlier. 13541 if (!getLangOpts().C2x) 13542 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13543 } 13544 13545 // C99 6.7.5.3p12: 13546 // If the function declarator is not part of a definition of that 13547 // function, parameters may have incomplete type and may use the [*] 13548 // notation in their sequences of declarator specifiers to specify 13549 // variable length array types. 13550 QualType PType = Param->getOriginalType(); 13551 // FIXME: This diagnostic should point the '[*]' if source-location 13552 // information is added for it. 13553 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13554 13555 // If the parameter is a c++ class type and it has to be destructed in the 13556 // callee function, declare the destructor so that it can be called by the 13557 // callee function. Do not perform any direct access check on the dtor here. 13558 if (!Param->isInvalidDecl()) { 13559 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13560 if (!ClassDecl->isInvalidDecl() && 13561 !ClassDecl->hasIrrelevantDestructor() && 13562 !ClassDecl->isDependentContext() && 13563 ClassDecl->isParamDestroyedInCallee()) { 13564 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13565 MarkFunctionReferenced(Param->getLocation(), Destructor); 13566 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13567 } 13568 } 13569 } 13570 13571 // Parameters with the pass_object_size attribute only need to be marked 13572 // constant at function definitions. Because we lack information about 13573 // whether we're on a declaration or definition when we're instantiating the 13574 // attribute, we need to check for constness here. 13575 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13576 if (!Param->getType().isConstQualified()) 13577 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13578 << Attr->getSpelling() << 1; 13579 13580 // Check for parameter names shadowing fields from the class. 13581 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13582 // The owning context for the parameter should be the function, but we 13583 // want to see if this function's declaration context is a record. 13584 DeclContext *DC = Param->getDeclContext(); 13585 if (DC && DC->isFunctionOrMethod()) { 13586 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13587 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13588 RD, /*DeclIsField*/ false); 13589 } 13590 } 13591 } 13592 13593 return HasInvalidParm; 13594 } 13595 13596 Optional<std::pair<CharUnits, CharUnits>> 13597 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13598 13599 /// Compute the alignment and offset of the base class object given the 13600 /// derived-to-base cast expression and the alignment and offset of the derived 13601 /// class object. 13602 static std::pair<CharUnits, CharUnits> 13603 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13604 CharUnits BaseAlignment, CharUnits Offset, 13605 ASTContext &Ctx) { 13606 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13607 ++PathI) { 13608 const CXXBaseSpecifier *Base = *PathI; 13609 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13610 if (Base->isVirtual()) { 13611 // The complete object may have a lower alignment than the non-virtual 13612 // alignment of the base, in which case the base may be misaligned. Choose 13613 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13614 // conservative lower bound of the complete object alignment. 13615 CharUnits NonVirtualAlignment = 13616 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13617 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13618 Offset = CharUnits::Zero(); 13619 } else { 13620 const ASTRecordLayout &RL = 13621 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13622 Offset += RL.getBaseClassOffset(BaseDecl); 13623 } 13624 DerivedType = Base->getType(); 13625 } 13626 13627 return std::make_pair(BaseAlignment, Offset); 13628 } 13629 13630 /// Compute the alignment and offset of a binary additive operator. 13631 static Optional<std::pair<CharUnits, CharUnits>> 13632 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13633 bool IsSub, ASTContext &Ctx) { 13634 QualType PointeeType = PtrE->getType()->getPointeeType(); 13635 13636 if (!PointeeType->isConstantSizeType()) 13637 return llvm::None; 13638 13639 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13640 13641 if (!P) 13642 return llvm::None; 13643 13644 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13645 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13646 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13647 if (IsSub) 13648 Offset = -Offset; 13649 return std::make_pair(P->first, P->second + Offset); 13650 } 13651 13652 // If the integer expression isn't a constant expression, compute the lower 13653 // bound of the alignment using the alignment and offset of the pointer 13654 // expression and the element size. 13655 return std::make_pair( 13656 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13657 CharUnits::Zero()); 13658 } 13659 13660 /// This helper function takes an lvalue expression and returns the alignment of 13661 /// a VarDecl and a constant offset from the VarDecl. 13662 Optional<std::pair<CharUnits, CharUnits>> 13663 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13664 E = E->IgnoreParens(); 13665 switch (E->getStmtClass()) { 13666 default: 13667 break; 13668 case Stmt::CStyleCastExprClass: 13669 case Stmt::CXXStaticCastExprClass: 13670 case Stmt::ImplicitCastExprClass: { 13671 auto *CE = cast<CastExpr>(E); 13672 const Expr *From = CE->getSubExpr(); 13673 switch (CE->getCastKind()) { 13674 default: 13675 break; 13676 case CK_NoOp: 13677 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13678 case CK_UncheckedDerivedToBase: 13679 case CK_DerivedToBase: { 13680 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13681 if (!P) 13682 break; 13683 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13684 P->second, Ctx); 13685 } 13686 } 13687 break; 13688 } 13689 case Stmt::ArraySubscriptExprClass: { 13690 auto *ASE = cast<ArraySubscriptExpr>(E); 13691 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13692 false, Ctx); 13693 } 13694 case Stmt::DeclRefExprClass: { 13695 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13696 // FIXME: If VD is captured by copy or is an escaping __block variable, 13697 // use the alignment of VD's type. 13698 if (!VD->getType()->isReferenceType()) 13699 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13700 if (VD->hasInit()) 13701 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13702 } 13703 break; 13704 } 13705 case Stmt::MemberExprClass: { 13706 auto *ME = cast<MemberExpr>(E); 13707 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13708 if (!FD || FD->getType()->isReferenceType()) 13709 break; 13710 Optional<std::pair<CharUnits, CharUnits>> P; 13711 if (ME->isArrow()) 13712 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 13713 else 13714 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13715 if (!P) 13716 break; 13717 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13718 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13719 return std::make_pair(P->first, 13720 P->second + CharUnits::fromQuantity(Offset)); 13721 } 13722 case Stmt::UnaryOperatorClass: { 13723 auto *UO = cast<UnaryOperator>(E); 13724 switch (UO->getOpcode()) { 13725 default: 13726 break; 13727 case UO_Deref: 13728 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13729 } 13730 break; 13731 } 13732 case Stmt::BinaryOperatorClass: { 13733 auto *BO = cast<BinaryOperator>(E); 13734 auto Opcode = BO->getOpcode(); 13735 switch (Opcode) { 13736 default: 13737 break; 13738 case BO_Comma: 13739 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13740 } 13741 break; 13742 } 13743 } 13744 return llvm::None; 13745 } 13746 13747 /// This helper function takes a pointer expression and returns the alignment of 13748 /// a VarDecl and a constant offset from the VarDecl. 13749 Optional<std::pair<CharUnits, CharUnits>> 13750 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13751 E = E->IgnoreParens(); 13752 switch (E->getStmtClass()) { 13753 default: 13754 break; 13755 case Stmt::CStyleCastExprClass: 13756 case Stmt::CXXStaticCastExprClass: 13757 case Stmt::ImplicitCastExprClass: { 13758 auto *CE = cast<CastExpr>(E); 13759 const Expr *From = CE->getSubExpr(); 13760 switch (CE->getCastKind()) { 13761 default: 13762 break; 13763 case CK_NoOp: 13764 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13765 case CK_ArrayToPointerDecay: 13766 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13767 case CK_UncheckedDerivedToBase: 13768 case CK_DerivedToBase: { 13769 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13770 if (!P) 13771 break; 13772 return getDerivedToBaseAlignmentAndOffset( 13773 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13774 } 13775 } 13776 break; 13777 } 13778 case Stmt::CXXThisExprClass: { 13779 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 13780 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 13781 return std::make_pair(Alignment, CharUnits::Zero()); 13782 } 13783 case Stmt::UnaryOperatorClass: { 13784 auto *UO = cast<UnaryOperator>(E); 13785 if (UO->getOpcode() == UO_AddrOf) 13786 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13787 break; 13788 } 13789 case Stmt::BinaryOperatorClass: { 13790 auto *BO = cast<BinaryOperator>(E); 13791 auto Opcode = BO->getOpcode(); 13792 switch (Opcode) { 13793 default: 13794 break; 13795 case BO_Add: 13796 case BO_Sub: { 13797 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13798 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13799 std::swap(LHS, RHS); 13800 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13801 Ctx); 13802 } 13803 case BO_Comma: 13804 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13805 } 13806 break; 13807 } 13808 } 13809 return llvm::None; 13810 } 13811 13812 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13813 // See if we can compute the alignment of a VarDecl and an offset from it. 13814 Optional<std::pair<CharUnits, CharUnits>> P = 13815 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13816 13817 if (P) 13818 return P->first.alignmentAtOffset(P->second); 13819 13820 // If that failed, return the type's alignment. 13821 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13822 } 13823 13824 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13825 /// pointer cast increases the alignment requirements. 13826 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13827 // This is actually a lot of work to potentially be doing on every 13828 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13829 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13830 return; 13831 13832 // Ignore dependent types. 13833 if (T->isDependentType() || Op->getType()->isDependentType()) 13834 return; 13835 13836 // Require that the destination be a pointer type. 13837 const PointerType *DestPtr = T->getAs<PointerType>(); 13838 if (!DestPtr) return; 13839 13840 // If the destination has alignment 1, we're done. 13841 QualType DestPointee = DestPtr->getPointeeType(); 13842 if (DestPointee->isIncompleteType()) return; 13843 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13844 if (DestAlign.isOne()) return; 13845 13846 // Require that the source be a pointer type. 13847 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13848 if (!SrcPtr) return; 13849 QualType SrcPointee = SrcPtr->getPointeeType(); 13850 13851 // Explicitly allow casts from cv void*. We already implicitly 13852 // allowed casts to cv void*, since they have alignment 1. 13853 // Also allow casts involving incomplete types, which implicitly 13854 // includes 'void'. 13855 if (SrcPointee->isIncompleteType()) return; 13856 13857 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13858 13859 if (SrcAlign >= DestAlign) return; 13860 13861 Diag(TRange.getBegin(), diag::warn_cast_align) 13862 << Op->getType() << T 13863 << static_cast<unsigned>(SrcAlign.getQuantity()) 13864 << static_cast<unsigned>(DestAlign.getQuantity()) 13865 << TRange << Op->getSourceRange(); 13866 } 13867 13868 /// Check whether this array fits the idiom of a size-one tail padded 13869 /// array member of a struct. 13870 /// 13871 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13872 /// commonly used to emulate flexible arrays in C89 code. 13873 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13874 const NamedDecl *ND) { 13875 if (Size != 1 || !ND) return false; 13876 13877 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13878 if (!FD) return false; 13879 13880 // Don't consider sizes resulting from macro expansions or template argument 13881 // substitution to form C89 tail-padded arrays. 13882 13883 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13884 while (TInfo) { 13885 TypeLoc TL = TInfo->getTypeLoc(); 13886 // Look through typedefs. 13887 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13888 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13889 TInfo = TDL->getTypeSourceInfo(); 13890 continue; 13891 } 13892 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13893 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13894 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13895 return false; 13896 } 13897 break; 13898 } 13899 13900 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13901 if (!RD) return false; 13902 if (RD->isUnion()) return false; 13903 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13904 if (!CRD->isStandardLayout()) return false; 13905 } 13906 13907 // See if this is the last field decl in the record. 13908 const Decl *D = FD; 13909 while ((D = D->getNextDeclInContext())) 13910 if (isa<FieldDecl>(D)) 13911 return false; 13912 return true; 13913 } 13914 13915 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13916 const ArraySubscriptExpr *ASE, 13917 bool AllowOnePastEnd, bool IndexNegated) { 13918 // Already diagnosed by the constant evaluator. 13919 if (isConstantEvaluated()) 13920 return; 13921 13922 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13923 if (IndexExpr->isValueDependent()) 13924 return; 13925 13926 const Type *EffectiveType = 13927 BaseExpr->getType()->getPointeeOrArrayElementType(); 13928 BaseExpr = BaseExpr->IgnoreParenCasts(); 13929 const ConstantArrayType *ArrayTy = 13930 Context.getAsConstantArrayType(BaseExpr->getType()); 13931 13932 if (!ArrayTy) 13933 return; 13934 13935 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13936 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13937 return; 13938 13939 Expr::EvalResult Result; 13940 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13941 return; 13942 13943 llvm::APSInt index = Result.Val.getInt(); 13944 if (IndexNegated) 13945 index = -index; 13946 13947 const NamedDecl *ND = nullptr; 13948 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13949 ND = DRE->getDecl(); 13950 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13951 ND = ME->getMemberDecl(); 13952 13953 if (index.isUnsigned() || !index.isNegative()) { 13954 // It is possible that the type of the base expression after 13955 // IgnoreParenCasts is incomplete, even though the type of the base 13956 // expression before IgnoreParenCasts is complete (see PR39746 for an 13957 // example). In this case we have no information about whether the array 13958 // access exceeds the array bounds. However we can still diagnose an array 13959 // access which precedes the array bounds. 13960 if (BaseType->isIncompleteType()) 13961 return; 13962 13963 llvm::APInt size = ArrayTy->getSize(); 13964 if (!size.isStrictlyPositive()) 13965 return; 13966 13967 if (BaseType != EffectiveType) { 13968 // Make sure we're comparing apples to apples when comparing index to size 13969 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13970 uint64_t array_typesize = Context.getTypeSize(BaseType); 13971 // Handle ptrarith_typesize being zero, such as when casting to void* 13972 if (!ptrarith_typesize) ptrarith_typesize = 1; 13973 if (ptrarith_typesize != array_typesize) { 13974 // There's a cast to a different size type involved 13975 uint64_t ratio = array_typesize / ptrarith_typesize; 13976 // TODO: Be smarter about handling cases where array_typesize is not a 13977 // multiple of ptrarith_typesize 13978 if (ptrarith_typesize * ratio == array_typesize) 13979 size *= llvm::APInt(size.getBitWidth(), ratio); 13980 } 13981 } 13982 13983 if (size.getBitWidth() > index.getBitWidth()) 13984 index = index.zext(size.getBitWidth()); 13985 else if (size.getBitWidth() < index.getBitWidth()) 13986 size = size.zext(index.getBitWidth()); 13987 13988 // For array subscripting the index must be less than size, but for pointer 13989 // arithmetic also allow the index (offset) to be equal to size since 13990 // computing the next address after the end of the array is legal and 13991 // commonly done e.g. in C++ iterators and range-based for loops. 13992 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13993 return; 13994 13995 // Also don't warn for arrays of size 1 which are members of some 13996 // structure. These are often used to approximate flexible arrays in C89 13997 // code. 13998 if (IsTailPaddedMemberArray(*this, size, ND)) 13999 return; 14000 14001 // Suppress the warning if the subscript expression (as identified by the 14002 // ']' location) and the index expression are both from macro expansions 14003 // within a system header. 14004 if (ASE) { 14005 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14006 ASE->getRBracketLoc()); 14007 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14008 SourceLocation IndexLoc = 14009 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14010 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14011 return; 14012 } 14013 } 14014 14015 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14016 if (ASE) 14017 DiagID = diag::warn_array_index_exceeds_bounds; 14018 14019 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14020 PDiag(DiagID) << index.toString(10, true) 14021 << size.toString(10, true) 14022 << (unsigned)size.getLimitedValue(~0U) 14023 << IndexExpr->getSourceRange()); 14024 } else { 14025 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14026 if (!ASE) { 14027 DiagID = diag::warn_ptr_arith_precedes_bounds; 14028 if (index.isNegative()) index = -index; 14029 } 14030 14031 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14032 PDiag(DiagID) << index.toString(10, true) 14033 << IndexExpr->getSourceRange()); 14034 } 14035 14036 if (!ND) { 14037 // Try harder to find a NamedDecl to point at in the note. 14038 while (const ArraySubscriptExpr *ASE = 14039 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14040 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14041 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14042 ND = DRE->getDecl(); 14043 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14044 ND = ME->getMemberDecl(); 14045 } 14046 14047 if (ND) 14048 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14049 PDiag(diag::note_array_declared_here) << ND); 14050 } 14051 14052 void Sema::CheckArrayAccess(const Expr *expr) { 14053 int AllowOnePastEnd = 0; 14054 while (expr) { 14055 expr = expr->IgnoreParenImpCasts(); 14056 switch (expr->getStmtClass()) { 14057 case Stmt::ArraySubscriptExprClass: { 14058 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14059 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14060 AllowOnePastEnd > 0); 14061 expr = ASE->getBase(); 14062 break; 14063 } 14064 case Stmt::MemberExprClass: { 14065 expr = cast<MemberExpr>(expr)->getBase(); 14066 break; 14067 } 14068 case Stmt::OMPArraySectionExprClass: { 14069 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14070 if (ASE->getLowerBound()) 14071 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14072 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14073 return; 14074 } 14075 case Stmt::UnaryOperatorClass: { 14076 // Only unwrap the * and & unary operators 14077 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14078 expr = UO->getSubExpr(); 14079 switch (UO->getOpcode()) { 14080 case UO_AddrOf: 14081 AllowOnePastEnd++; 14082 break; 14083 case UO_Deref: 14084 AllowOnePastEnd--; 14085 break; 14086 default: 14087 return; 14088 } 14089 break; 14090 } 14091 case Stmt::ConditionalOperatorClass: { 14092 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14093 if (const Expr *lhs = cond->getLHS()) 14094 CheckArrayAccess(lhs); 14095 if (const Expr *rhs = cond->getRHS()) 14096 CheckArrayAccess(rhs); 14097 return; 14098 } 14099 case Stmt::CXXOperatorCallExprClass: { 14100 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14101 for (const auto *Arg : OCE->arguments()) 14102 CheckArrayAccess(Arg); 14103 return; 14104 } 14105 default: 14106 return; 14107 } 14108 } 14109 } 14110 14111 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14112 14113 namespace { 14114 14115 struct RetainCycleOwner { 14116 VarDecl *Variable = nullptr; 14117 SourceRange Range; 14118 SourceLocation Loc; 14119 bool Indirect = false; 14120 14121 RetainCycleOwner() = default; 14122 14123 void setLocsFrom(Expr *e) { 14124 Loc = e->getExprLoc(); 14125 Range = e->getSourceRange(); 14126 } 14127 }; 14128 14129 } // namespace 14130 14131 /// Consider whether capturing the given variable can possibly lead to 14132 /// a retain cycle. 14133 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14134 // In ARC, it's captured strongly iff the variable has __strong 14135 // lifetime. In MRR, it's captured strongly if the variable is 14136 // __block and has an appropriate type. 14137 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14138 return false; 14139 14140 owner.Variable = var; 14141 if (ref) 14142 owner.setLocsFrom(ref); 14143 return true; 14144 } 14145 14146 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14147 while (true) { 14148 e = e->IgnoreParens(); 14149 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14150 switch (cast->getCastKind()) { 14151 case CK_BitCast: 14152 case CK_LValueBitCast: 14153 case CK_LValueToRValue: 14154 case CK_ARCReclaimReturnedObject: 14155 e = cast->getSubExpr(); 14156 continue; 14157 14158 default: 14159 return false; 14160 } 14161 } 14162 14163 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14164 ObjCIvarDecl *ivar = ref->getDecl(); 14165 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14166 return false; 14167 14168 // Try to find a retain cycle in the base. 14169 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14170 return false; 14171 14172 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14173 owner.Indirect = true; 14174 return true; 14175 } 14176 14177 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14178 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14179 if (!var) return false; 14180 return considerVariable(var, ref, owner); 14181 } 14182 14183 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14184 if (member->isArrow()) return false; 14185 14186 // Don't count this as an indirect ownership. 14187 e = member->getBase(); 14188 continue; 14189 } 14190 14191 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14192 // Only pay attention to pseudo-objects on property references. 14193 ObjCPropertyRefExpr *pre 14194 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14195 ->IgnoreParens()); 14196 if (!pre) return false; 14197 if (pre->isImplicitProperty()) return false; 14198 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14199 if (!property->isRetaining() && 14200 !(property->getPropertyIvarDecl() && 14201 property->getPropertyIvarDecl()->getType() 14202 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14203 return false; 14204 14205 owner.Indirect = true; 14206 if (pre->isSuperReceiver()) { 14207 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14208 if (!owner.Variable) 14209 return false; 14210 owner.Loc = pre->getLocation(); 14211 owner.Range = pre->getSourceRange(); 14212 return true; 14213 } 14214 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14215 ->getSourceExpr()); 14216 continue; 14217 } 14218 14219 // Array ivars? 14220 14221 return false; 14222 } 14223 } 14224 14225 namespace { 14226 14227 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14228 ASTContext &Context; 14229 VarDecl *Variable; 14230 Expr *Capturer = nullptr; 14231 bool VarWillBeReased = false; 14232 14233 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14234 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14235 Context(Context), Variable(variable) {} 14236 14237 void VisitDeclRefExpr(DeclRefExpr *ref) { 14238 if (ref->getDecl() == Variable && !Capturer) 14239 Capturer = ref; 14240 } 14241 14242 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14243 if (Capturer) return; 14244 Visit(ref->getBase()); 14245 if (Capturer && ref->isFreeIvar()) 14246 Capturer = ref; 14247 } 14248 14249 void VisitBlockExpr(BlockExpr *block) { 14250 // Look inside nested blocks 14251 if (block->getBlockDecl()->capturesVariable(Variable)) 14252 Visit(block->getBlockDecl()->getBody()); 14253 } 14254 14255 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14256 if (Capturer) return; 14257 if (OVE->getSourceExpr()) 14258 Visit(OVE->getSourceExpr()); 14259 } 14260 14261 void VisitBinaryOperator(BinaryOperator *BinOp) { 14262 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14263 return; 14264 Expr *LHS = BinOp->getLHS(); 14265 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14266 if (DRE->getDecl() != Variable) 14267 return; 14268 if (Expr *RHS = BinOp->getRHS()) { 14269 RHS = RHS->IgnoreParenCasts(); 14270 Optional<llvm::APSInt> Value; 14271 VarWillBeReased = 14272 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14273 *Value == 0); 14274 } 14275 } 14276 } 14277 }; 14278 14279 } // namespace 14280 14281 /// Check whether the given argument is a block which captures a 14282 /// variable. 14283 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14284 assert(owner.Variable && owner.Loc.isValid()); 14285 14286 e = e->IgnoreParenCasts(); 14287 14288 // Look through [^{...} copy] and Block_copy(^{...}). 14289 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14290 Selector Cmd = ME->getSelector(); 14291 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14292 e = ME->getInstanceReceiver(); 14293 if (!e) 14294 return nullptr; 14295 e = e->IgnoreParenCasts(); 14296 } 14297 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14298 if (CE->getNumArgs() == 1) { 14299 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14300 if (Fn) { 14301 const IdentifierInfo *FnI = Fn->getIdentifier(); 14302 if (FnI && FnI->isStr("_Block_copy")) { 14303 e = CE->getArg(0)->IgnoreParenCasts(); 14304 } 14305 } 14306 } 14307 } 14308 14309 BlockExpr *block = dyn_cast<BlockExpr>(e); 14310 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14311 return nullptr; 14312 14313 FindCaptureVisitor visitor(S.Context, owner.Variable); 14314 visitor.Visit(block->getBlockDecl()->getBody()); 14315 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14316 } 14317 14318 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14319 RetainCycleOwner &owner) { 14320 assert(capturer); 14321 assert(owner.Variable && owner.Loc.isValid()); 14322 14323 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14324 << owner.Variable << capturer->getSourceRange(); 14325 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14326 << owner.Indirect << owner.Range; 14327 } 14328 14329 /// Check for a keyword selector that starts with the word 'add' or 14330 /// 'set'. 14331 static bool isSetterLikeSelector(Selector sel) { 14332 if (sel.isUnarySelector()) return false; 14333 14334 StringRef str = sel.getNameForSlot(0); 14335 while (!str.empty() && str.front() == '_') str = str.substr(1); 14336 if (str.startswith("set")) 14337 str = str.substr(3); 14338 else if (str.startswith("add")) { 14339 // Specially allow 'addOperationWithBlock:'. 14340 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14341 return false; 14342 str = str.substr(3); 14343 } 14344 else 14345 return false; 14346 14347 if (str.empty()) return true; 14348 return !isLowercase(str.front()); 14349 } 14350 14351 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14352 ObjCMessageExpr *Message) { 14353 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14354 Message->getReceiverInterface(), 14355 NSAPI::ClassId_NSMutableArray); 14356 if (!IsMutableArray) { 14357 return None; 14358 } 14359 14360 Selector Sel = Message->getSelector(); 14361 14362 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14363 S.NSAPIObj->getNSArrayMethodKind(Sel); 14364 if (!MKOpt) { 14365 return None; 14366 } 14367 14368 NSAPI::NSArrayMethodKind MK = *MKOpt; 14369 14370 switch (MK) { 14371 case NSAPI::NSMutableArr_addObject: 14372 case NSAPI::NSMutableArr_insertObjectAtIndex: 14373 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14374 return 0; 14375 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14376 return 1; 14377 14378 default: 14379 return None; 14380 } 14381 14382 return None; 14383 } 14384 14385 static 14386 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14387 ObjCMessageExpr *Message) { 14388 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14389 Message->getReceiverInterface(), 14390 NSAPI::ClassId_NSMutableDictionary); 14391 if (!IsMutableDictionary) { 14392 return None; 14393 } 14394 14395 Selector Sel = Message->getSelector(); 14396 14397 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14398 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14399 if (!MKOpt) { 14400 return None; 14401 } 14402 14403 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14404 14405 switch (MK) { 14406 case NSAPI::NSMutableDict_setObjectForKey: 14407 case NSAPI::NSMutableDict_setValueForKey: 14408 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14409 return 0; 14410 14411 default: 14412 return None; 14413 } 14414 14415 return None; 14416 } 14417 14418 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14419 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14420 Message->getReceiverInterface(), 14421 NSAPI::ClassId_NSMutableSet); 14422 14423 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14424 Message->getReceiverInterface(), 14425 NSAPI::ClassId_NSMutableOrderedSet); 14426 if (!IsMutableSet && !IsMutableOrderedSet) { 14427 return None; 14428 } 14429 14430 Selector Sel = Message->getSelector(); 14431 14432 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14433 if (!MKOpt) { 14434 return None; 14435 } 14436 14437 NSAPI::NSSetMethodKind MK = *MKOpt; 14438 14439 switch (MK) { 14440 case NSAPI::NSMutableSet_addObject: 14441 case NSAPI::NSOrderedSet_setObjectAtIndex: 14442 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14443 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14444 return 0; 14445 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14446 return 1; 14447 } 14448 14449 return None; 14450 } 14451 14452 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14453 if (!Message->isInstanceMessage()) { 14454 return; 14455 } 14456 14457 Optional<int> ArgOpt; 14458 14459 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14460 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14461 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14462 return; 14463 } 14464 14465 int ArgIndex = *ArgOpt; 14466 14467 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14468 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14469 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14470 } 14471 14472 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14473 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14474 if (ArgRE->isObjCSelfExpr()) { 14475 Diag(Message->getSourceRange().getBegin(), 14476 diag::warn_objc_circular_container) 14477 << ArgRE->getDecl() << StringRef("'super'"); 14478 } 14479 } 14480 } else { 14481 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14482 14483 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14484 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14485 } 14486 14487 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14488 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14489 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14490 ValueDecl *Decl = ReceiverRE->getDecl(); 14491 Diag(Message->getSourceRange().getBegin(), 14492 diag::warn_objc_circular_container) 14493 << Decl << Decl; 14494 if (!ArgRE->isObjCSelfExpr()) { 14495 Diag(Decl->getLocation(), 14496 diag::note_objc_circular_container_declared_here) 14497 << Decl; 14498 } 14499 } 14500 } 14501 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14502 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14503 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14504 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14505 Diag(Message->getSourceRange().getBegin(), 14506 diag::warn_objc_circular_container) 14507 << Decl << Decl; 14508 Diag(Decl->getLocation(), 14509 diag::note_objc_circular_container_declared_here) 14510 << Decl; 14511 } 14512 } 14513 } 14514 } 14515 } 14516 14517 /// Check a message send to see if it's likely to cause a retain cycle. 14518 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14519 // Only check instance methods whose selector looks like a setter. 14520 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14521 return; 14522 14523 // Try to find a variable that the receiver is strongly owned by. 14524 RetainCycleOwner owner; 14525 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14526 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14527 return; 14528 } else { 14529 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14530 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14531 owner.Loc = msg->getSuperLoc(); 14532 owner.Range = msg->getSuperLoc(); 14533 } 14534 14535 // Check whether the receiver is captured by any of the arguments. 14536 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14537 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14538 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14539 // noescape blocks should not be retained by the method. 14540 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14541 continue; 14542 return diagnoseRetainCycle(*this, capturer, owner); 14543 } 14544 } 14545 } 14546 14547 /// Check a property assign to see if it's likely to cause a retain cycle. 14548 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14549 RetainCycleOwner owner; 14550 if (!findRetainCycleOwner(*this, receiver, owner)) 14551 return; 14552 14553 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14554 diagnoseRetainCycle(*this, capturer, owner); 14555 } 14556 14557 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14558 RetainCycleOwner Owner; 14559 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14560 return; 14561 14562 // Because we don't have an expression for the variable, we have to set the 14563 // location explicitly here. 14564 Owner.Loc = Var->getLocation(); 14565 Owner.Range = Var->getSourceRange(); 14566 14567 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14568 diagnoseRetainCycle(*this, Capturer, Owner); 14569 } 14570 14571 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14572 Expr *RHS, bool isProperty) { 14573 // Check if RHS is an Objective-C object literal, which also can get 14574 // immediately zapped in a weak reference. Note that we explicitly 14575 // allow ObjCStringLiterals, since those are designed to never really die. 14576 RHS = RHS->IgnoreParenImpCasts(); 14577 14578 // This enum needs to match with the 'select' in 14579 // warn_objc_arc_literal_assign (off-by-1). 14580 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14581 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14582 return false; 14583 14584 S.Diag(Loc, diag::warn_arc_literal_assign) 14585 << (unsigned) Kind 14586 << (isProperty ? 0 : 1) 14587 << RHS->getSourceRange(); 14588 14589 return true; 14590 } 14591 14592 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14593 Qualifiers::ObjCLifetime LT, 14594 Expr *RHS, bool isProperty) { 14595 // Strip off any implicit cast added to get to the one ARC-specific. 14596 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14597 if (cast->getCastKind() == CK_ARCConsumeObject) { 14598 S.Diag(Loc, diag::warn_arc_retained_assign) 14599 << (LT == Qualifiers::OCL_ExplicitNone) 14600 << (isProperty ? 0 : 1) 14601 << RHS->getSourceRange(); 14602 return true; 14603 } 14604 RHS = cast->getSubExpr(); 14605 } 14606 14607 if (LT == Qualifiers::OCL_Weak && 14608 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14609 return true; 14610 14611 return false; 14612 } 14613 14614 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14615 QualType LHS, Expr *RHS) { 14616 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14617 14618 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14619 return false; 14620 14621 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14622 return true; 14623 14624 return false; 14625 } 14626 14627 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14628 Expr *LHS, Expr *RHS) { 14629 QualType LHSType; 14630 // PropertyRef on LHS type need be directly obtained from 14631 // its declaration as it has a PseudoType. 14632 ObjCPropertyRefExpr *PRE 14633 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14634 if (PRE && !PRE->isImplicitProperty()) { 14635 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14636 if (PD) 14637 LHSType = PD->getType(); 14638 } 14639 14640 if (LHSType.isNull()) 14641 LHSType = LHS->getType(); 14642 14643 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14644 14645 if (LT == Qualifiers::OCL_Weak) { 14646 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14647 getCurFunction()->markSafeWeakUse(LHS); 14648 } 14649 14650 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14651 return; 14652 14653 // FIXME. Check for other life times. 14654 if (LT != Qualifiers::OCL_None) 14655 return; 14656 14657 if (PRE) { 14658 if (PRE->isImplicitProperty()) 14659 return; 14660 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14661 if (!PD) 14662 return; 14663 14664 unsigned Attributes = PD->getPropertyAttributes(); 14665 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14666 // when 'assign' attribute was not explicitly specified 14667 // by user, ignore it and rely on property type itself 14668 // for lifetime info. 14669 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14670 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14671 LHSType->isObjCRetainableType()) 14672 return; 14673 14674 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14675 if (cast->getCastKind() == CK_ARCConsumeObject) { 14676 Diag(Loc, diag::warn_arc_retained_property_assign) 14677 << RHS->getSourceRange(); 14678 return; 14679 } 14680 RHS = cast->getSubExpr(); 14681 } 14682 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14683 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14684 return; 14685 } 14686 } 14687 } 14688 14689 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14690 14691 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14692 SourceLocation StmtLoc, 14693 const NullStmt *Body) { 14694 // Do not warn if the body is a macro that expands to nothing, e.g: 14695 // 14696 // #define CALL(x) 14697 // if (condition) 14698 // CALL(0); 14699 if (Body->hasLeadingEmptyMacro()) 14700 return false; 14701 14702 // Get line numbers of statement and body. 14703 bool StmtLineInvalid; 14704 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14705 &StmtLineInvalid); 14706 if (StmtLineInvalid) 14707 return false; 14708 14709 bool BodyLineInvalid; 14710 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14711 &BodyLineInvalid); 14712 if (BodyLineInvalid) 14713 return false; 14714 14715 // Warn if null statement and body are on the same line. 14716 if (StmtLine != BodyLine) 14717 return false; 14718 14719 return true; 14720 } 14721 14722 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14723 const Stmt *Body, 14724 unsigned DiagID) { 14725 // Since this is a syntactic check, don't emit diagnostic for template 14726 // instantiations, this just adds noise. 14727 if (CurrentInstantiationScope) 14728 return; 14729 14730 // The body should be a null statement. 14731 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14732 if (!NBody) 14733 return; 14734 14735 // Do the usual checks. 14736 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14737 return; 14738 14739 Diag(NBody->getSemiLoc(), DiagID); 14740 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14741 } 14742 14743 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14744 const Stmt *PossibleBody) { 14745 assert(!CurrentInstantiationScope); // Ensured by caller 14746 14747 SourceLocation StmtLoc; 14748 const Stmt *Body; 14749 unsigned DiagID; 14750 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14751 StmtLoc = FS->getRParenLoc(); 14752 Body = FS->getBody(); 14753 DiagID = diag::warn_empty_for_body; 14754 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14755 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14756 Body = WS->getBody(); 14757 DiagID = diag::warn_empty_while_body; 14758 } else 14759 return; // Neither `for' nor `while'. 14760 14761 // The body should be a null statement. 14762 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14763 if (!NBody) 14764 return; 14765 14766 // Skip expensive checks if diagnostic is disabled. 14767 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14768 return; 14769 14770 // Do the usual checks. 14771 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14772 return; 14773 14774 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14775 // noise level low, emit diagnostics only if for/while is followed by a 14776 // CompoundStmt, e.g.: 14777 // for (int i = 0; i < n; i++); 14778 // { 14779 // a(i); 14780 // } 14781 // or if for/while is followed by a statement with more indentation 14782 // than for/while itself: 14783 // for (int i = 0; i < n; i++); 14784 // a(i); 14785 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14786 if (!ProbableTypo) { 14787 bool BodyColInvalid; 14788 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14789 PossibleBody->getBeginLoc(), &BodyColInvalid); 14790 if (BodyColInvalid) 14791 return; 14792 14793 bool StmtColInvalid; 14794 unsigned StmtCol = 14795 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14796 if (StmtColInvalid) 14797 return; 14798 14799 if (BodyCol > StmtCol) 14800 ProbableTypo = true; 14801 } 14802 14803 if (ProbableTypo) { 14804 Diag(NBody->getSemiLoc(), DiagID); 14805 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14806 } 14807 } 14808 14809 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14810 14811 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14812 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14813 SourceLocation OpLoc) { 14814 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14815 return; 14816 14817 if (inTemplateInstantiation()) 14818 return; 14819 14820 // Strip parens and casts away. 14821 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14822 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14823 14824 // Check for a call expression 14825 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14826 if (!CE || CE->getNumArgs() != 1) 14827 return; 14828 14829 // Check for a call to std::move 14830 if (!CE->isCallToStdMove()) 14831 return; 14832 14833 // Get argument from std::move 14834 RHSExpr = CE->getArg(0); 14835 14836 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14837 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14838 14839 // Two DeclRefExpr's, check that the decls are the same. 14840 if (LHSDeclRef && RHSDeclRef) { 14841 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14842 return; 14843 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14844 RHSDeclRef->getDecl()->getCanonicalDecl()) 14845 return; 14846 14847 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14848 << LHSExpr->getSourceRange() 14849 << RHSExpr->getSourceRange(); 14850 return; 14851 } 14852 14853 // Member variables require a different approach to check for self moves. 14854 // MemberExpr's are the same if every nested MemberExpr refers to the same 14855 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14856 // the base Expr's are CXXThisExpr's. 14857 const Expr *LHSBase = LHSExpr; 14858 const Expr *RHSBase = RHSExpr; 14859 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14860 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14861 if (!LHSME || !RHSME) 14862 return; 14863 14864 while (LHSME && RHSME) { 14865 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14866 RHSME->getMemberDecl()->getCanonicalDecl()) 14867 return; 14868 14869 LHSBase = LHSME->getBase(); 14870 RHSBase = RHSME->getBase(); 14871 LHSME = dyn_cast<MemberExpr>(LHSBase); 14872 RHSME = dyn_cast<MemberExpr>(RHSBase); 14873 } 14874 14875 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14876 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14877 if (LHSDeclRef && RHSDeclRef) { 14878 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14879 return; 14880 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14881 RHSDeclRef->getDecl()->getCanonicalDecl()) 14882 return; 14883 14884 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14885 << LHSExpr->getSourceRange() 14886 << RHSExpr->getSourceRange(); 14887 return; 14888 } 14889 14890 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14891 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14892 << LHSExpr->getSourceRange() 14893 << RHSExpr->getSourceRange(); 14894 } 14895 14896 //===--- Layout compatibility ----------------------------------------------// 14897 14898 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14899 14900 /// Check if two enumeration types are layout-compatible. 14901 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14902 // C++11 [dcl.enum] p8: 14903 // Two enumeration types are layout-compatible if they have the same 14904 // underlying type. 14905 return ED1->isComplete() && ED2->isComplete() && 14906 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14907 } 14908 14909 /// Check if two fields are layout-compatible. 14910 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14911 FieldDecl *Field2) { 14912 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14913 return false; 14914 14915 if (Field1->isBitField() != Field2->isBitField()) 14916 return false; 14917 14918 if (Field1->isBitField()) { 14919 // Make sure that the bit-fields are the same length. 14920 unsigned Bits1 = Field1->getBitWidthValue(C); 14921 unsigned Bits2 = Field2->getBitWidthValue(C); 14922 14923 if (Bits1 != Bits2) 14924 return false; 14925 } 14926 14927 return true; 14928 } 14929 14930 /// Check if two standard-layout structs are layout-compatible. 14931 /// (C++11 [class.mem] p17) 14932 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14933 RecordDecl *RD2) { 14934 // If both records are C++ classes, check that base classes match. 14935 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14936 // If one of records is a CXXRecordDecl we are in C++ mode, 14937 // thus the other one is a CXXRecordDecl, too. 14938 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14939 // Check number of base classes. 14940 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14941 return false; 14942 14943 // Check the base classes. 14944 for (CXXRecordDecl::base_class_const_iterator 14945 Base1 = D1CXX->bases_begin(), 14946 BaseEnd1 = D1CXX->bases_end(), 14947 Base2 = D2CXX->bases_begin(); 14948 Base1 != BaseEnd1; 14949 ++Base1, ++Base2) { 14950 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14951 return false; 14952 } 14953 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14954 // If only RD2 is a C++ class, it should have zero base classes. 14955 if (D2CXX->getNumBases() > 0) 14956 return false; 14957 } 14958 14959 // Check the fields. 14960 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14961 Field2End = RD2->field_end(), 14962 Field1 = RD1->field_begin(), 14963 Field1End = RD1->field_end(); 14964 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14965 if (!isLayoutCompatible(C, *Field1, *Field2)) 14966 return false; 14967 } 14968 if (Field1 != Field1End || Field2 != Field2End) 14969 return false; 14970 14971 return true; 14972 } 14973 14974 /// Check if two standard-layout unions are layout-compatible. 14975 /// (C++11 [class.mem] p18) 14976 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14977 RecordDecl *RD2) { 14978 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14979 for (auto *Field2 : RD2->fields()) 14980 UnmatchedFields.insert(Field2); 14981 14982 for (auto *Field1 : RD1->fields()) { 14983 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14984 I = UnmatchedFields.begin(), 14985 E = UnmatchedFields.end(); 14986 14987 for ( ; I != E; ++I) { 14988 if (isLayoutCompatible(C, Field1, *I)) { 14989 bool Result = UnmatchedFields.erase(*I); 14990 (void) Result; 14991 assert(Result); 14992 break; 14993 } 14994 } 14995 if (I == E) 14996 return false; 14997 } 14998 14999 return UnmatchedFields.empty(); 15000 } 15001 15002 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15003 RecordDecl *RD2) { 15004 if (RD1->isUnion() != RD2->isUnion()) 15005 return false; 15006 15007 if (RD1->isUnion()) 15008 return isLayoutCompatibleUnion(C, RD1, RD2); 15009 else 15010 return isLayoutCompatibleStruct(C, RD1, RD2); 15011 } 15012 15013 /// Check if two types are layout-compatible in C++11 sense. 15014 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15015 if (T1.isNull() || T2.isNull()) 15016 return false; 15017 15018 // C++11 [basic.types] p11: 15019 // If two types T1 and T2 are the same type, then T1 and T2 are 15020 // layout-compatible types. 15021 if (C.hasSameType(T1, T2)) 15022 return true; 15023 15024 T1 = T1.getCanonicalType().getUnqualifiedType(); 15025 T2 = T2.getCanonicalType().getUnqualifiedType(); 15026 15027 const Type::TypeClass TC1 = T1->getTypeClass(); 15028 const Type::TypeClass TC2 = T2->getTypeClass(); 15029 15030 if (TC1 != TC2) 15031 return false; 15032 15033 if (TC1 == Type::Enum) { 15034 return isLayoutCompatible(C, 15035 cast<EnumType>(T1)->getDecl(), 15036 cast<EnumType>(T2)->getDecl()); 15037 } else if (TC1 == Type::Record) { 15038 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15039 return false; 15040 15041 return isLayoutCompatible(C, 15042 cast<RecordType>(T1)->getDecl(), 15043 cast<RecordType>(T2)->getDecl()); 15044 } 15045 15046 return false; 15047 } 15048 15049 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15050 15051 /// Given a type tag expression find the type tag itself. 15052 /// 15053 /// \param TypeExpr Type tag expression, as it appears in user's code. 15054 /// 15055 /// \param VD Declaration of an identifier that appears in a type tag. 15056 /// 15057 /// \param MagicValue Type tag magic value. 15058 /// 15059 /// \param isConstantEvaluated wether the evalaution should be performed in 15060 15061 /// constant context. 15062 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15063 const ValueDecl **VD, uint64_t *MagicValue, 15064 bool isConstantEvaluated) { 15065 while(true) { 15066 if (!TypeExpr) 15067 return false; 15068 15069 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15070 15071 switch (TypeExpr->getStmtClass()) { 15072 case Stmt::UnaryOperatorClass: { 15073 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15074 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15075 TypeExpr = UO->getSubExpr(); 15076 continue; 15077 } 15078 return false; 15079 } 15080 15081 case Stmt::DeclRefExprClass: { 15082 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15083 *VD = DRE->getDecl(); 15084 return true; 15085 } 15086 15087 case Stmt::IntegerLiteralClass: { 15088 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15089 llvm::APInt MagicValueAPInt = IL->getValue(); 15090 if (MagicValueAPInt.getActiveBits() <= 64) { 15091 *MagicValue = MagicValueAPInt.getZExtValue(); 15092 return true; 15093 } else 15094 return false; 15095 } 15096 15097 case Stmt::BinaryConditionalOperatorClass: 15098 case Stmt::ConditionalOperatorClass: { 15099 const AbstractConditionalOperator *ACO = 15100 cast<AbstractConditionalOperator>(TypeExpr); 15101 bool Result; 15102 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15103 isConstantEvaluated)) { 15104 if (Result) 15105 TypeExpr = ACO->getTrueExpr(); 15106 else 15107 TypeExpr = ACO->getFalseExpr(); 15108 continue; 15109 } 15110 return false; 15111 } 15112 15113 case Stmt::BinaryOperatorClass: { 15114 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15115 if (BO->getOpcode() == BO_Comma) { 15116 TypeExpr = BO->getRHS(); 15117 continue; 15118 } 15119 return false; 15120 } 15121 15122 default: 15123 return false; 15124 } 15125 } 15126 } 15127 15128 /// Retrieve the C type corresponding to type tag TypeExpr. 15129 /// 15130 /// \param TypeExpr Expression that specifies a type tag. 15131 /// 15132 /// \param MagicValues Registered magic values. 15133 /// 15134 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15135 /// kind. 15136 /// 15137 /// \param TypeInfo Information about the corresponding C type. 15138 /// 15139 /// \param isConstantEvaluated wether the evalaution should be performed in 15140 /// constant context. 15141 /// 15142 /// \returns true if the corresponding C type was found. 15143 static bool GetMatchingCType( 15144 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15145 const ASTContext &Ctx, 15146 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15147 *MagicValues, 15148 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15149 bool isConstantEvaluated) { 15150 FoundWrongKind = false; 15151 15152 // Variable declaration that has type_tag_for_datatype attribute. 15153 const ValueDecl *VD = nullptr; 15154 15155 uint64_t MagicValue; 15156 15157 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15158 return false; 15159 15160 if (VD) { 15161 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15162 if (I->getArgumentKind() != ArgumentKind) { 15163 FoundWrongKind = true; 15164 return false; 15165 } 15166 TypeInfo.Type = I->getMatchingCType(); 15167 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15168 TypeInfo.MustBeNull = I->getMustBeNull(); 15169 return true; 15170 } 15171 return false; 15172 } 15173 15174 if (!MagicValues) 15175 return false; 15176 15177 llvm::DenseMap<Sema::TypeTagMagicValue, 15178 Sema::TypeTagData>::const_iterator I = 15179 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15180 if (I == MagicValues->end()) 15181 return false; 15182 15183 TypeInfo = I->second; 15184 return true; 15185 } 15186 15187 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15188 uint64_t MagicValue, QualType Type, 15189 bool LayoutCompatible, 15190 bool MustBeNull) { 15191 if (!TypeTagForDatatypeMagicValues) 15192 TypeTagForDatatypeMagicValues.reset( 15193 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15194 15195 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15196 (*TypeTagForDatatypeMagicValues)[Magic] = 15197 TypeTagData(Type, LayoutCompatible, MustBeNull); 15198 } 15199 15200 static bool IsSameCharType(QualType T1, QualType T2) { 15201 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15202 if (!BT1) 15203 return false; 15204 15205 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15206 if (!BT2) 15207 return false; 15208 15209 BuiltinType::Kind T1Kind = BT1->getKind(); 15210 BuiltinType::Kind T2Kind = BT2->getKind(); 15211 15212 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15213 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15214 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15215 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15216 } 15217 15218 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15219 const ArrayRef<const Expr *> ExprArgs, 15220 SourceLocation CallSiteLoc) { 15221 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15222 bool IsPointerAttr = Attr->getIsPointer(); 15223 15224 // Retrieve the argument representing the 'type_tag'. 15225 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15226 if (TypeTagIdxAST >= ExprArgs.size()) { 15227 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15228 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15229 return; 15230 } 15231 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15232 bool FoundWrongKind; 15233 TypeTagData TypeInfo; 15234 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15235 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15236 TypeInfo, isConstantEvaluated())) { 15237 if (FoundWrongKind) 15238 Diag(TypeTagExpr->getExprLoc(), 15239 diag::warn_type_tag_for_datatype_wrong_kind) 15240 << TypeTagExpr->getSourceRange(); 15241 return; 15242 } 15243 15244 // Retrieve the argument representing the 'arg_idx'. 15245 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15246 if (ArgumentIdxAST >= ExprArgs.size()) { 15247 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15248 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15249 return; 15250 } 15251 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15252 if (IsPointerAttr) { 15253 // Skip implicit cast of pointer to `void *' (as a function argument). 15254 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15255 if (ICE->getType()->isVoidPointerType() && 15256 ICE->getCastKind() == CK_BitCast) 15257 ArgumentExpr = ICE->getSubExpr(); 15258 } 15259 QualType ArgumentType = ArgumentExpr->getType(); 15260 15261 // Passing a `void*' pointer shouldn't trigger a warning. 15262 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15263 return; 15264 15265 if (TypeInfo.MustBeNull) { 15266 // Type tag with matching void type requires a null pointer. 15267 if (!ArgumentExpr->isNullPointerConstant(Context, 15268 Expr::NPC_ValueDependentIsNotNull)) { 15269 Diag(ArgumentExpr->getExprLoc(), 15270 diag::warn_type_safety_null_pointer_required) 15271 << ArgumentKind->getName() 15272 << ArgumentExpr->getSourceRange() 15273 << TypeTagExpr->getSourceRange(); 15274 } 15275 return; 15276 } 15277 15278 QualType RequiredType = TypeInfo.Type; 15279 if (IsPointerAttr) 15280 RequiredType = Context.getPointerType(RequiredType); 15281 15282 bool mismatch = false; 15283 if (!TypeInfo.LayoutCompatible) { 15284 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15285 15286 // C++11 [basic.fundamental] p1: 15287 // Plain char, signed char, and unsigned char are three distinct types. 15288 // 15289 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15290 // char' depending on the current char signedness mode. 15291 if (mismatch) 15292 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15293 RequiredType->getPointeeType())) || 15294 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15295 mismatch = false; 15296 } else 15297 if (IsPointerAttr) 15298 mismatch = !isLayoutCompatible(Context, 15299 ArgumentType->getPointeeType(), 15300 RequiredType->getPointeeType()); 15301 else 15302 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15303 15304 if (mismatch) 15305 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15306 << ArgumentType << ArgumentKind 15307 << TypeInfo.LayoutCompatible << RequiredType 15308 << ArgumentExpr->getSourceRange() 15309 << TypeTagExpr->getSourceRange(); 15310 } 15311 15312 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15313 CharUnits Alignment) { 15314 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15315 } 15316 15317 void Sema::DiagnoseMisalignedMembers() { 15318 for (MisalignedMember &m : MisalignedMembers) { 15319 const NamedDecl *ND = m.RD; 15320 if (ND->getName().empty()) { 15321 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15322 ND = TD; 15323 } 15324 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15325 << m.MD << ND << m.E->getSourceRange(); 15326 } 15327 MisalignedMembers.clear(); 15328 } 15329 15330 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15331 E = E->IgnoreParens(); 15332 if (!T->isPointerType() && !T->isIntegerType()) 15333 return; 15334 if (isa<UnaryOperator>(E) && 15335 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15336 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15337 if (isa<MemberExpr>(Op)) { 15338 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15339 if (MA != MisalignedMembers.end() && 15340 (T->isIntegerType() || 15341 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15342 Context.getTypeAlignInChars( 15343 T->getPointeeType()) <= MA->Alignment)))) 15344 MisalignedMembers.erase(MA); 15345 } 15346 } 15347 } 15348 15349 void Sema::RefersToMemberWithReducedAlignment( 15350 Expr *E, 15351 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15352 Action) { 15353 const auto *ME = dyn_cast<MemberExpr>(E); 15354 if (!ME) 15355 return; 15356 15357 // No need to check expressions with an __unaligned-qualified type. 15358 if (E->getType().getQualifiers().hasUnaligned()) 15359 return; 15360 15361 // For a chain of MemberExpr like "a.b.c.d" this list 15362 // will keep FieldDecl's like [d, c, b]. 15363 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15364 const MemberExpr *TopME = nullptr; 15365 bool AnyIsPacked = false; 15366 do { 15367 QualType BaseType = ME->getBase()->getType(); 15368 if (BaseType->isDependentType()) 15369 return; 15370 if (ME->isArrow()) 15371 BaseType = BaseType->getPointeeType(); 15372 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15373 if (RD->isInvalidDecl()) 15374 return; 15375 15376 ValueDecl *MD = ME->getMemberDecl(); 15377 auto *FD = dyn_cast<FieldDecl>(MD); 15378 // We do not care about non-data members. 15379 if (!FD || FD->isInvalidDecl()) 15380 return; 15381 15382 AnyIsPacked = 15383 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15384 ReverseMemberChain.push_back(FD); 15385 15386 TopME = ME; 15387 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15388 } while (ME); 15389 assert(TopME && "We did not compute a topmost MemberExpr!"); 15390 15391 // Not the scope of this diagnostic. 15392 if (!AnyIsPacked) 15393 return; 15394 15395 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15396 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15397 // TODO: The innermost base of the member expression may be too complicated. 15398 // For now, just disregard these cases. This is left for future 15399 // improvement. 15400 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15401 return; 15402 15403 // Alignment expected by the whole expression. 15404 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15405 15406 // No need to do anything else with this case. 15407 if (ExpectedAlignment.isOne()) 15408 return; 15409 15410 // Synthesize offset of the whole access. 15411 CharUnits Offset; 15412 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15413 I++) { 15414 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15415 } 15416 15417 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15418 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15419 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15420 15421 // The base expression of the innermost MemberExpr may give 15422 // stronger guarantees than the class containing the member. 15423 if (DRE && !TopME->isArrow()) { 15424 const ValueDecl *VD = DRE->getDecl(); 15425 if (!VD->getType()->isReferenceType()) 15426 CompleteObjectAlignment = 15427 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15428 } 15429 15430 // Check if the synthesized offset fulfills the alignment. 15431 if (Offset % ExpectedAlignment != 0 || 15432 // It may fulfill the offset it but the effective alignment may still be 15433 // lower than the expected expression alignment. 15434 CompleteObjectAlignment < ExpectedAlignment) { 15435 // If this happens, we want to determine a sensible culprit of this. 15436 // Intuitively, watching the chain of member expressions from right to 15437 // left, we start with the required alignment (as required by the field 15438 // type) but some packed attribute in that chain has reduced the alignment. 15439 // It may happen that another packed structure increases it again. But if 15440 // we are here such increase has not been enough. So pointing the first 15441 // FieldDecl that either is packed or else its RecordDecl is, 15442 // seems reasonable. 15443 FieldDecl *FD = nullptr; 15444 CharUnits Alignment; 15445 for (FieldDecl *FDI : ReverseMemberChain) { 15446 if (FDI->hasAttr<PackedAttr>() || 15447 FDI->getParent()->hasAttr<PackedAttr>()) { 15448 FD = FDI; 15449 Alignment = std::min( 15450 Context.getTypeAlignInChars(FD->getType()), 15451 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15452 break; 15453 } 15454 } 15455 assert(FD && "We did not find a packed FieldDecl!"); 15456 Action(E, FD->getParent(), FD, Alignment); 15457 } 15458 } 15459 15460 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15461 using namespace std::placeholders; 15462 15463 RefersToMemberWithReducedAlignment( 15464 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15465 _2, _3, _4)); 15466 } 15467 15468 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15469 ExprResult CallResult) { 15470 if (checkArgCount(*this, TheCall, 1)) 15471 return ExprError(); 15472 15473 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15474 if (MatrixArg.isInvalid()) 15475 return MatrixArg; 15476 Expr *Matrix = MatrixArg.get(); 15477 15478 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15479 if (!MType) { 15480 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15481 return ExprError(); 15482 } 15483 15484 // Create returned matrix type by swapping rows and columns of the argument 15485 // matrix type. 15486 QualType ResultType = Context.getConstantMatrixType( 15487 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15488 15489 // Change the return type to the type of the returned matrix. 15490 TheCall->setType(ResultType); 15491 15492 // Update call argument to use the possibly converted matrix argument. 15493 TheCall->setArg(0, Matrix); 15494 return CallResult; 15495 } 15496 15497 // Get and verify the matrix dimensions. 15498 static llvm::Optional<unsigned> 15499 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15500 SourceLocation ErrorPos; 15501 Optional<llvm::APSInt> Value = 15502 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15503 if (!Value) { 15504 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15505 << Name; 15506 return {}; 15507 } 15508 uint64_t Dim = Value->getZExtValue(); 15509 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15510 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15511 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15512 return {}; 15513 } 15514 return Dim; 15515 } 15516 15517 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15518 ExprResult CallResult) { 15519 if (!getLangOpts().MatrixTypes) { 15520 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15521 return ExprError(); 15522 } 15523 15524 if (checkArgCount(*this, TheCall, 4)) 15525 return ExprError(); 15526 15527 unsigned PtrArgIdx = 0; 15528 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15529 Expr *RowsExpr = TheCall->getArg(1); 15530 Expr *ColumnsExpr = TheCall->getArg(2); 15531 Expr *StrideExpr = TheCall->getArg(3); 15532 15533 bool ArgError = false; 15534 15535 // Check pointer argument. 15536 { 15537 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15538 if (PtrConv.isInvalid()) 15539 return PtrConv; 15540 PtrExpr = PtrConv.get(); 15541 TheCall->setArg(0, PtrExpr); 15542 if (PtrExpr->isTypeDependent()) { 15543 TheCall->setType(Context.DependentTy); 15544 return TheCall; 15545 } 15546 } 15547 15548 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15549 QualType ElementTy; 15550 if (!PtrTy) { 15551 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15552 << PtrArgIdx + 1; 15553 ArgError = true; 15554 } else { 15555 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15556 15557 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15558 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15559 << PtrArgIdx + 1; 15560 ArgError = true; 15561 } 15562 } 15563 15564 // Apply default Lvalue conversions and convert the expression to size_t. 15565 auto ApplyArgumentConversions = [this](Expr *E) { 15566 ExprResult Conv = DefaultLvalueConversion(E); 15567 if (Conv.isInvalid()) 15568 return Conv; 15569 15570 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15571 }; 15572 15573 // Apply conversion to row and column expressions. 15574 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15575 if (!RowsConv.isInvalid()) { 15576 RowsExpr = RowsConv.get(); 15577 TheCall->setArg(1, RowsExpr); 15578 } else 15579 RowsExpr = nullptr; 15580 15581 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15582 if (!ColumnsConv.isInvalid()) { 15583 ColumnsExpr = ColumnsConv.get(); 15584 TheCall->setArg(2, ColumnsExpr); 15585 } else 15586 ColumnsExpr = nullptr; 15587 15588 // If any any part of the result matrix type is still pending, just use 15589 // Context.DependentTy, until all parts are resolved. 15590 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15591 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15592 TheCall->setType(Context.DependentTy); 15593 return CallResult; 15594 } 15595 15596 // Check row and column dimenions. 15597 llvm::Optional<unsigned> MaybeRows; 15598 if (RowsExpr) 15599 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15600 15601 llvm::Optional<unsigned> MaybeColumns; 15602 if (ColumnsExpr) 15603 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15604 15605 // Check stride argument. 15606 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15607 if (StrideConv.isInvalid()) 15608 return ExprError(); 15609 StrideExpr = StrideConv.get(); 15610 TheCall->setArg(3, StrideExpr); 15611 15612 if (MaybeRows) { 15613 if (Optional<llvm::APSInt> Value = 15614 StrideExpr->getIntegerConstantExpr(Context)) { 15615 uint64_t Stride = Value->getZExtValue(); 15616 if (Stride < *MaybeRows) { 15617 Diag(StrideExpr->getBeginLoc(), 15618 diag::err_builtin_matrix_stride_too_small); 15619 ArgError = true; 15620 } 15621 } 15622 } 15623 15624 if (ArgError || !MaybeRows || !MaybeColumns) 15625 return ExprError(); 15626 15627 TheCall->setType( 15628 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15629 return CallResult; 15630 } 15631 15632 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15633 ExprResult CallResult) { 15634 if (checkArgCount(*this, TheCall, 3)) 15635 return ExprError(); 15636 15637 unsigned PtrArgIdx = 1; 15638 Expr *MatrixExpr = TheCall->getArg(0); 15639 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15640 Expr *StrideExpr = TheCall->getArg(2); 15641 15642 bool ArgError = false; 15643 15644 { 15645 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15646 if (MatrixConv.isInvalid()) 15647 return MatrixConv; 15648 MatrixExpr = MatrixConv.get(); 15649 TheCall->setArg(0, MatrixExpr); 15650 } 15651 if (MatrixExpr->isTypeDependent()) { 15652 TheCall->setType(Context.DependentTy); 15653 return TheCall; 15654 } 15655 15656 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15657 if (!MatrixTy) { 15658 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15659 ArgError = true; 15660 } 15661 15662 { 15663 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15664 if (PtrConv.isInvalid()) 15665 return PtrConv; 15666 PtrExpr = PtrConv.get(); 15667 TheCall->setArg(1, PtrExpr); 15668 if (PtrExpr->isTypeDependent()) { 15669 TheCall->setType(Context.DependentTy); 15670 return TheCall; 15671 } 15672 } 15673 15674 // Check pointer argument. 15675 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15676 if (!PtrTy) { 15677 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15678 << PtrArgIdx + 1; 15679 ArgError = true; 15680 } else { 15681 QualType ElementTy = PtrTy->getPointeeType(); 15682 if (ElementTy.isConstQualified()) { 15683 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15684 ArgError = true; 15685 } 15686 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15687 if (MatrixTy && 15688 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15689 Diag(PtrExpr->getBeginLoc(), 15690 diag::err_builtin_matrix_pointer_arg_mismatch) 15691 << ElementTy << MatrixTy->getElementType(); 15692 ArgError = true; 15693 } 15694 } 15695 15696 // Apply default Lvalue conversions and convert the stride expression to 15697 // size_t. 15698 { 15699 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15700 if (StrideConv.isInvalid()) 15701 return StrideConv; 15702 15703 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15704 if (StrideConv.isInvalid()) 15705 return StrideConv; 15706 StrideExpr = StrideConv.get(); 15707 TheCall->setArg(2, StrideExpr); 15708 } 15709 15710 // Check stride argument. 15711 if (MatrixTy) { 15712 if (Optional<llvm::APSInt> Value = 15713 StrideExpr->getIntegerConstantExpr(Context)) { 15714 uint64_t Stride = Value->getZExtValue(); 15715 if (Stride < MatrixTy->getNumRows()) { 15716 Diag(StrideExpr->getBeginLoc(), 15717 diag::err_builtin_matrix_stride_too_small); 15718 ArgError = true; 15719 } 15720 } 15721 } 15722 15723 if (ArgError) 15724 return ExprError(); 15725 15726 return CallResult; 15727 } 15728