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 isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2574 QualType VectorTy, QualType EltTy) { 2575 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2576 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2577 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2578 << Call->getSourceRange() << VectorEltTy << EltTy; 2579 return false; 2580 } 2581 return true; 2582 } 2583 2584 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2585 QualType ArgType = Arg->getType(); 2586 if (ArgType->getAsPlaceholderType()) 2587 return false; 2588 2589 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2590 // format: 2591 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2592 // 2. <type> var; 2593 // __builtin_preserve_type_info(var, flag); 2594 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2595 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2596 return false; 2597 2598 // Typedef type. 2599 if (ArgType->getAs<TypedefType>()) 2600 return true; 2601 2602 // Record type or Enum type. 2603 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2604 if (const auto *RT = Ty->getAs<RecordType>()) { 2605 if (!RT->getDecl()->getDeclName().isEmpty()) 2606 return true; 2607 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2608 if (!ET->getDecl()->getDeclName().isEmpty()) 2609 return true; 2610 } 2611 2612 return false; 2613 } 2614 2615 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2616 QualType ArgType = Arg->getType(); 2617 if (ArgType->getAsPlaceholderType()) 2618 return false; 2619 2620 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2621 // format: 2622 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2623 // flag); 2624 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2625 if (!UO) 2626 return false; 2627 2628 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2629 if (!CE || CE->getCastKind() != CK_IntegralToPointer) 2630 return false; 2631 2632 // The integer must be from an EnumConstantDecl. 2633 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2634 if (!DR) 2635 return false; 2636 2637 const EnumConstantDecl *Enumerator = 2638 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2639 if (!Enumerator) 2640 return false; 2641 2642 // The type must be EnumType. 2643 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2644 const auto *ET = Ty->getAs<EnumType>(); 2645 if (!ET) 2646 return false; 2647 2648 // The enum value must be supported. 2649 for (auto *EDI : ET->getDecl()->enumerators()) { 2650 if (EDI == Enumerator) 2651 return true; 2652 } 2653 2654 return false; 2655 } 2656 2657 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2658 CallExpr *TheCall) { 2659 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2660 BuiltinID == BPF::BI__builtin_btf_type_id || 2661 BuiltinID == BPF::BI__builtin_preserve_type_info || 2662 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2663 "unexpected BPF builtin"); 2664 2665 if (checkArgCount(*this, TheCall, 2)) 2666 return true; 2667 2668 // The second argument needs to be a constant int 2669 Expr *Arg = TheCall->getArg(1); 2670 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2671 diag::kind kind; 2672 if (!Value) { 2673 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2674 kind = diag::err_preserve_field_info_not_const; 2675 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2676 kind = diag::err_btf_type_id_not_const; 2677 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2678 kind = diag::err_preserve_type_info_not_const; 2679 else 2680 kind = diag::err_preserve_enum_value_not_const; 2681 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2682 return true; 2683 } 2684 2685 // The first argument 2686 Arg = TheCall->getArg(0); 2687 bool InvalidArg = false; 2688 bool ReturnUnsignedInt = true; 2689 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2690 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2691 InvalidArg = true; 2692 kind = diag::err_preserve_field_info_not_field; 2693 } 2694 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2695 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2696 InvalidArg = true; 2697 kind = diag::err_preserve_type_info_invalid; 2698 } 2699 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2700 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2701 InvalidArg = true; 2702 kind = diag::err_preserve_enum_value_invalid; 2703 } 2704 ReturnUnsignedInt = false; 2705 } 2706 2707 if (InvalidArg) { 2708 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2709 return true; 2710 } 2711 2712 if (ReturnUnsignedInt) 2713 TheCall->setType(Context.UnsignedIntTy); 2714 else 2715 TheCall->setType(Context.UnsignedLongTy); 2716 return false; 2717 } 2718 2719 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2720 struct ArgInfo { 2721 uint8_t OpNum; 2722 bool IsSigned; 2723 uint8_t BitWidth; 2724 uint8_t Align; 2725 }; 2726 struct BuiltinInfo { 2727 unsigned BuiltinID; 2728 ArgInfo Infos[2]; 2729 }; 2730 2731 static BuiltinInfo Infos[] = { 2732 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2733 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2734 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2735 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2736 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2737 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2738 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2739 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2740 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2741 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2742 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2743 2744 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2755 2756 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2808 {{ 1, false, 6, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2816 {{ 1, false, 5, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2823 { 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2825 { 2, false, 6, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2827 { 3, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2829 { 3, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2846 {{ 2, false, 4, 0 }, 2847 { 3, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2849 {{ 2, false, 4, 0 }, 2850 { 3, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2852 {{ 2, false, 4, 0 }, 2853 { 3, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2855 {{ 2, false, 4, 0 }, 2856 { 3, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2868 { 2, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2870 { 2, false, 6, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2880 {{ 1, false, 4, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2883 {{ 1, false, 4, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2904 {{ 3, false, 1, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2909 {{ 3, false, 1, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2914 {{ 3, false, 1, 0 }} }, 2915 }; 2916 2917 // Use a dynamically initialized static to sort the table exactly once on 2918 // first run. 2919 static const bool SortOnce = 2920 (llvm::sort(Infos, 2921 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2922 return LHS.BuiltinID < RHS.BuiltinID; 2923 }), 2924 true); 2925 (void)SortOnce; 2926 2927 const BuiltinInfo *F = llvm::partition_point( 2928 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2929 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2930 return false; 2931 2932 bool Error = false; 2933 2934 for (const ArgInfo &A : F->Infos) { 2935 // Ignore empty ArgInfo elements. 2936 if (A.BitWidth == 0) 2937 continue; 2938 2939 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2940 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2941 if (!A.Align) { 2942 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2943 } else { 2944 unsigned M = 1 << A.Align; 2945 Min *= M; 2946 Max *= M; 2947 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2948 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2949 } 2950 } 2951 return Error; 2952 } 2953 2954 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2955 CallExpr *TheCall) { 2956 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2957 } 2958 2959 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2960 unsigned BuiltinID, CallExpr *TheCall) { 2961 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2962 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2963 } 2964 2965 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2966 CallExpr *TheCall) { 2967 2968 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2969 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2970 if (!TI.hasFeature("dsp")) 2971 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2972 } 2973 2974 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2975 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2976 if (!TI.hasFeature("dspr2")) 2977 return Diag(TheCall->getBeginLoc(), 2978 diag::err_mips_builtin_requires_dspr2); 2979 } 2980 2981 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2982 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2983 if (!TI.hasFeature("msa")) 2984 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2985 } 2986 2987 return false; 2988 } 2989 2990 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2991 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2992 // ordering for DSP is unspecified. MSA is ordered by the data format used 2993 // by the underlying instruction i.e., df/m, df/n and then by size. 2994 // 2995 // FIXME: The size tests here should instead be tablegen'd along with the 2996 // definitions from include/clang/Basic/BuiltinsMips.def. 2997 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2998 // be too. 2999 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3000 unsigned i = 0, l = 0, u = 0, m = 0; 3001 switch (BuiltinID) { 3002 default: return false; 3003 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3004 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3005 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3006 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3007 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3008 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3009 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3010 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3011 // df/m field. 3012 // These intrinsics take an unsigned 3 bit immediate. 3013 case Mips::BI__builtin_msa_bclri_b: 3014 case Mips::BI__builtin_msa_bnegi_b: 3015 case Mips::BI__builtin_msa_bseti_b: 3016 case Mips::BI__builtin_msa_sat_s_b: 3017 case Mips::BI__builtin_msa_sat_u_b: 3018 case Mips::BI__builtin_msa_slli_b: 3019 case Mips::BI__builtin_msa_srai_b: 3020 case Mips::BI__builtin_msa_srari_b: 3021 case Mips::BI__builtin_msa_srli_b: 3022 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3023 case Mips::BI__builtin_msa_binsli_b: 3024 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3025 // These intrinsics take an unsigned 4 bit immediate. 3026 case Mips::BI__builtin_msa_bclri_h: 3027 case Mips::BI__builtin_msa_bnegi_h: 3028 case Mips::BI__builtin_msa_bseti_h: 3029 case Mips::BI__builtin_msa_sat_s_h: 3030 case Mips::BI__builtin_msa_sat_u_h: 3031 case Mips::BI__builtin_msa_slli_h: 3032 case Mips::BI__builtin_msa_srai_h: 3033 case Mips::BI__builtin_msa_srari_h: 3034 case Mips::BI__builtin_msa_srli_h: 3035 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3036 case Mips::BI__builtin_msa_binsli_h: 3037 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3038 // These intrinsics take an unsigned 5 bit immediate. 3039 // The first block of intrinsics actually have an unsigned 5 bit field, 3040 // not a df/n field. 3041 case Mips::BI__builtin_msa_cfcmsa: 3042 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3043 case Mips::BI__builtin_msa_clei_u_b: 3044 case Mips::BI__builtin_msa_clei_u_h: 3045 case Mips::BI__builtin_msa_clei_u_w: 3046 case Mips::BI__builtin_msa_clei_u_d: 3047 case Mips::BI__builtin_msa_clti_u_b: 3048 case Mips::BI__builtin_msa_clti_u_h: 3049 case Mips::BI__builtin_msa_clti_u_w: 3050 case Mips::BI__builtin_msa_clti_u_d: 3051 case Mips::BI__builtin_msa_maxi_u_b: 3052 case Mips::BI__builtin_msa_maxi_u_h: 3053 case Mips::BI__builtin_msa_maxi_u_w: 3054 case Mips::BI__builtin_msa_maxi_u_d: 3055 case Mips::BI__builtin_msa_mini_u_b: 3056 case Mips::BI__builtin_msa_mini_u_h: 3057 case Mips::BI__builtin_msa_mini_u_w: 3058 case Mips::BI__builtin_msa_mini_u_d: 3059 case Mips::BI__builtin_msa_addvi_b: 3060 case Mips::BI__builtin_msa_addvi_h: 3061 case Mips::BI__builtin_msa_addvi_w: 3062 case Mips::BI__builtin_msa_addvi_d: 3063 case Mips::BI__builtin_msa_bclri_w: 3064 case Mips::BI__builtin_msa_bnegi_w: 3065 case Mips::BI__builtin_msa_bseti_w: 3066 case Mips::BI__builtin_msa_sat_s_w: 3067 case Mips::BI__builtin_msa_sat_u_w: 3068 case Mips::BI__builtin_msa_slli_w: 3069 case Mips::BI__builtin_msa_srai_w: 3070 case Mips::BI__builtin_msa_srari_w: 3071 case Mips::BI__builtin_msa_srli_w: 3072 case Mips::BI__builtin_msa_srlri_w: 3073 case Mips::BI__builtin_msa_subvi_b: 3074 case Mips::BI__builtin_msa_subvi_h: 3075 case Mips::BI__builtin_msa_subvi_w: 3076 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3077 case Mips::BI__builtin_msa_binsli_w: 3078 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3079 // These intrinsics take an unsigned 6 bit immediate. 3080 case Mips::BI__builtin_msa_bclri_d: 3081 case Mips::BI__builtin_msa_bnegi_d: 3082 case Mips::BI__builtin_msa_bseti_d: 3083 case Mips::BI__builtin_msa_sat_s_d: 3084 case Mips::BI__builtin_msa_sat_u_d: 3085 case Mips::BI__builtin_msa_slli_d: 3086 case Mips::BI__builtin_msa_srai_d: 3087 case Mips::BI__builtin_msa_srari_d: 3088 case Mips::BI__builtin_msa_srli_d: 3089 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3090 case Mips::BI__builtin_msa_binsli_d: 3091 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3092 // These intrinsics take a signed 5 bit immediate. 3093 case Mips::BI__builtin_msa_ceqi_b: 3094 case Mips::BI__builtin_msa_ceqi_h: 3095 case Mips::BI__builtin_msa_ceqi_w: 3096 case Mips::BI__builtin_msa_ceqi_d: 3097 case Mips::BI__builtin_msa_clti_s_b: 3098 case Mips::BI__builtin_msa_clti_s_h: 3099 case Mips::BI__builtin_msa_clti_s_w: 3100 case Mips::BI__builtin_msa_clti_s_d: 3101 case Mips::BI__builtin_msa_clei_s_b: 3102 case Mips::BI__builtin_msa_clei_s_h: 3103 case Mips::BI__builtin_msa_clei_s_w: 3104 case Mips::BI__builtin_msa_clei_s_d: 3105 case Mips::BI__builtin_msa_maxi_s_b: 3106 case Mips::BI__builtin_msa_maxi_s_h: 3107 case Mips::BI__builtin_msa_maxi_s_w: 3108 case Mips::BI__builtin_msa_maxi_s_d: 3109 case Mips::BI__builtin_msa_mini_s_b: 3110 case Mips::BI__builtin_msa_mini_s_h: 3111 case Mips::BI__builtin_msa_mini_s_w: 3112 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3113 // These intrinsics take an unsigned 8 bit immediate. 3114 case Mips::BI__builtin_msa_andi_b: 3115 case Mips::BI__builtin_msa_nori_b: 3116 case Mips::BI__builtin_msa_ori_b: 3117 case Mips::BI__builtin_msa_shf_b: 3118 case Mips::BI__builtin_msa_shf_h: 3119 case Mips::BI__builtin_msa_shf_w: 3120 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3121 case Mips::BI__builtin_msa_bseli_b: 3122 case Mips::BI__builtin_msa_bmnzi_b: 3123 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3124 // df/n format 3125 // These intrinsics take an unsigned 4 bit immediate. 3126 case Mips::BI__builtin_msa_copy_s_b: 3127 case Mips::BI__builtin_msa_copy_u_b: 3128 case Mips::BI__builtin_msa_insve_b: 3129 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3130 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3131 // These intrinsics take an unsigned 3 bit immediate. 3132 case Mips::BI__builtin_msa_copy_s_h: 3133 case Mips::BI__builtin_msa_copy_u_h: 3134 case Mips::BI__builtin_msa_insve_h: 3135 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3136 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3137 // These intrinsics take an unsigned 2 bit immediate. 3138 case Mips::BI__builtin_msa_copy_s_w: 3139 case Mips::BI__builtin_msa_copy_u_w: 3140 case Mips::BI__builtin_msa_insve_w: 3141 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3142 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3143 // These intrinsics take an unsigned 1 bit immediate. 3144 case Mips::BI__builtin_msa_copy_s_d: 3145 case Mips::BI__builtin_msa_copy_u_d: 3146 case Mips::BI__builtin_msa_insve_d: 3147 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3148 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3149 // Memory offsets and immediate loads. 3150 // These intrinsics take a signed 10 bit immediate. 3151 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3152 case Mips::BI__builtin_msa_ldi_h: 3153 case Mips::BI__builtin_msa_ldi_w: 3154 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3155 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3156 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3157 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3158 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3159 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3160 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3161 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3162 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3163 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3164 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3165 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3166 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3167 } 3168 3169 if (!m) 3170 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3171 3172 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3173 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3174 } 3175 3176 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3177 CallExpr *TheCall) { 3178 unsigned i = 0, l = 0, u = 0; 3179 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3180 BuiltinID == PPC::BI__builtin_divdeu || 3181 BuiltinID == PPC::BI__builtin_bpermd; 3182 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3183 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3184 BuiltinID == PPC::BI__builtin_divweu || 3185 BuiltinID == PPC::BI__builtin_divde || 3186 BuiltinID == PPC::BI__builtin_divdeu; 3187 3188 if (Is64BitBltin && !IsTarget64Bit) 3189 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3190 << TheCall->getSourceRange(); 3191 3192 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3193 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3194 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3195 << TheCall->getSourceRange(); 3196 3197 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3198 if (!TI.hasFeature("vsx")) 3199 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3200 << TheCall->getSourceRange(); 3201 return false; 3202 }; 3203 3204 switch (BuiltinID) { 3205 default: return false; 3206 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3207 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3208 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3209 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3210 case PPC::BI__builtin_altivec_dss: 3211 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3212 case PPC::BI__builtin_tbegin: 3213 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3214 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3215 case PPC::BI__builtin_tabortwc: 3216 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3217 case PPC::BI__builtin_tabortwci: 3218 case PPC::BI__builtin_tabortdci: 3219 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3220 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3221 case PPC::BI__builtin_altivec_dst: 3222 case PPC::BI__builtin_altivec_dstt: 3223 case PPC::BI__builtin_altivec_dstst: 3224 case PPC::BI__builtin_altivec_dststt: 3225 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3226 case PPC::BI__builtin_vsx_xxpermdi: 3227 case PPC::BI__builtin_vsx_xxsldwi: 3228 return SemaBuiltinVSX(TheCall); 3229 case PPC::BI__builtin_unpack_vector_int128: 3230 return SemaVSXCheck(TheCall) || 3231 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3232 case PPC::BI__builtin_pack_vector_int128: 3233 return SemaVSXCheck(TheCall); 3234 case PPC::BI__builtin_altivec_vgnb: 3235 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3236 case PPC::BI__builtin_altivec_vec_replace_elt: 3237 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3238 QualType VecTy = TheCall->getArg(0)->getType(); 3239 QualType EltTy = TheCall->getArg(1)->getType(); 3240 unsigned Width = Context.getIntWidth(EltTy); 3241 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3242 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3243 } 3244 case PPC::BI__builtin_vsx_xxeval: 3245 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3246 case PPC::BI__builtin_altivec_vsldbi: 3247 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3248 case PPC::BI__builtin_altivec_vsrdbi: 3249 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3250 case PPC::BI__builtin_vsx_xxpermx: 3251 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3252 } 3253 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3254 } 3255 3256 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3257 CallExpr *TheCall) { 3258 // position of memory order and scope arguments in the builtin 3259 unsigned OrderIndex, ScopeIndex; 3260 switch (BuiltinID) { 3261 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3262 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3263 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3264 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3265 OrderIndex = 2; 3266 ScopeIndex = 3; 3267 break; 3268 case AMDGPU::BI__builtin_amdgcn_fence: 3269 OrderIndex = 0; 3270 ScopeIndex = 1; 3271 break; 3272 default: 3273 return false; 3274 } 3275 3276 ExprResult Arg = TheCall->getArg(OrderIndex); 3277 auto ArgExpr = Arg.get(); 3278 Expr::EvalResult ArgResult; 3279 3280 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3281 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3282 << ArgExpr->getType(); 3283 int ord = ArgResult.Val.getInt().getZExtValue(); 3284 3285 // Check valididty of memory ordering as per C11 / C++11's memody model. 3286 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3287 case llvm::AtomicOrderingCABI::acquire: 3288 case llvm::AtomicOrderingCABI::release: 3289 case llvm::AtomicOrderingCABI::acq_rel: 3290 case llvm::AtomicOrderingCABI::seq_cst: 3291 break; 3292 default: { 3293 return Diag(ArgExpr->getBeginLoc(), 3294 diag::warn_atomic_op_has_invalid_memory_order) 3295 << ArgExpr->getSourceRange(); 3296 } 3297 } 3298 3299 Arg = TheCall->getArg(ScopeIndex); 3300 ArgExpr = Arg.get(); 3301 Expr::EvalResult ArgResult1; 3302 // Check that sync scope is a constant literal 3303 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3304 Context)) 3305 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3306 << ArgExpr->getType(); 3307 3308 return false; 3309 } 3310 3311 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3312 CallExpr *TheCall) { 3313 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3314 Expr *Arg = TheCall->getArg(0); 3315 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3316 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3317 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3318 << Arg->getSourceRange(); 3319 } 3320 3321 // For intrinsics which take an immediate value as part of the instruction, 3322 // range check them here. 3323 unsigned i = 0, l = 0, u = 0; 3324 switch (BuiltinID) { 3325 default: return false; 3326 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3327 case SystemZ::BI__builtin_s390_verimb: 3328 case SystemZ::BI__builtin_s390_verimh: 3329 case SystemZ::BI__builtin_s390_verimf: 3330 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3331 case SystemZ::BI__builtin_s390_vfaeb: 3332 case SystemZ::BI__builtin_s390_vfaeh: 3333 case SystemZ::BI__builtin_s390_vfaef: 3334 case SystemZ::BI__builtin_s390_vfaebs: 3335 case SystemZ::BI__builtin_s390_vfaehs: 3336 case SystemZ::BI__builtin_s390_vfaefs: 3337 case SystemZ::BI__builtin_s390_vfaezb: 3338 case SystemZ::BI__builtin_s390_vfaezh: 3339 case SystemZ::BI__builtin_s390_vfaezf: 3340 case SystemZ::BI__builtin_s390_vfaezbs: 3341 case SystemZ::BI__builtin_s390_vfaezhs: 3342 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3343 case SystemZ::BI__builtin_s390_vfisb: 3344 case SystemZ::BI__builtin_s390_vfidb: 3345 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3346 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3347 case SystemZ::BI__builtin_s390_vftcisb: 3348 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3349 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3350 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3351 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3352 case SystemZ::BI__builtin_s390_vstrcb: 3353 case SystemZ::BI__builtin_s390_vstrch: 3354 case SystemZ::BI__builtin_s390_vstrcf: 3355 case SystemZ::BI__builtin_s390_vstrczb: 3356 case SystemZ::BI__builtin_s390_vstrczh: 3357 case SystemZ::BI__builtin_s390_vstrczf: 3358 case SystemZ::BI__builtin_s390_vstrcbs: 3359 case SystemZ::BI__builtin_s390_vstrchs: 3360 case SystemZ::BI__builtin_s390_vstrcfs: 3361 case SystemZ::BI__builtin_s390_vstrczbs: 3362 case SystemZ::BI__builtin_s390_vstrczhs: 3363 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3364 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3365 case SystemZ::BI__builtin_s390_vfminsb: 3366 case SystemZ::BI__builtin_s390_vfmaxsb: 3367 case SystemZ::BI__builtin_s390_vfmindb: 3368 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3369 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3370 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3371 } 3372 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3373 } 3374 3375 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3376 /// This checks that the target supports __builtin_cpu_supports and 3377 /// that the string argument is constant and valid. 3378 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3379 CallExpr *TheCall) { 3380 Expr *Arg = TheCall->getArg(0); 3381 3382 // Check if the argument is a string literal. 3383 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3384 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3385 << Arg->getSourceRange(); 3386 3387 // Check the contents of the string. 3388 StringRef Feature = 3389 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3390 if (!TI.validateCpuSupports(Feature)) 3391 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3392 << Arg->getSourceRange(); 3393 return false; 3394 } 3395 3396 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3397 /// This checks that the target supports __builtin_cpu_is and 3398 /// that the string argument is constant and valid. 3399 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3400 Expr *Arg = TheCall->getArg(0); 3401 3402 // Check if the argument is a string literal. 3403 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3404 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3405 << Arg->getSourceRange(); 3406 3407 // Check the contents of the string. 3408 StringRef Feature = 3409 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3410 if (!TI.validateCpuIs(Feature)) 3411 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3412 << Arg->getSourceRange(); 3413 return false; 3414 } 3415 3416 // Check if the rounding mode is legal. 3417 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3418 // Indicates if this instruction has rounding control or just SAE. 3419 bool HasRC = false; 3420 3421 unsigned ArgNum = 0; 3422 switch (BuiltinID) { 3423 default: 3424 return false; 3425 case X86::BI__builtin_ia32_vcvttsd2si32: 3426 case X86::BI__builtin_ia32_vcvttsd2si64: 3427 case X86::BI__builtin_ia32_vcvttsd2usi32: 3428 case X86::BI__builtin_ia32_vcvttsd2usi64: 3429 case X86::BI__builtin_ia32_vcvttss2si32: 3430 case X86::BI__builtin_ia32_vcvttss2si64: 3431 case X86::BI__builtin_ia32_vcvttss2usi32: 3432 case X86::BI__builtin_ia32_vcvttss2usi64: 3433 ArgNum = 1; 3434 break; 3435 case X86::BI__builtin_ia32_maxpd512: 3436 case X86::BI__builtin_ia32_maxps512: 3437 case X86::BI__builtin_ia32_minpd512: 3438 case X86::BI__builtin_ia32_minps512: 3439 ArgNum = 2; 3440 break; 3441 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3442 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3443 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3444 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3445 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3446 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3447 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3448 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3449 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3450 case X86::BI__builtin_ia32_exp2pd_mask: 3451 case X86::BI__builtin_ia32_exp2ps_mask: 3452 case X86::BI__builtin_ia32_getexppd512_mask: 3453 case X86::BI__builtin_ia32_getexpps512_mask: 3454 case X86::BI__builtin_ia32_rcp28pd_mask: 3455 case X86::BI__builtin_ia32_rcp28ps_mask: 3456 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3457 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3458 case X86::BI__builtin_ia32_vcomisd: 3459 case X86::BI__builtin_ia32_vcomiss: 3460 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3461 ArgNum = 3; 3462 break; 3463 case X86::BI__builtin_ia32_cmppd512_mask: 3464 case X86::BI__builtin_ia32_cmpps512_mask: 3465 case X86::BI__builtin_ia32_cmpsd_mask: 3466 case X86::BI__builtin_ia32_cmpss_mask: 3467 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3468 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3469 case X86::BI__builtin_ia32_getexpss128_round_mask: 3470 case X86::BI__builtin_ia32_getmantpd512_mask: 3471 case X86::BI__builtin_ia32_getmantps512_mask: 3472 case X86::BI__builtin_ia32_maxsd_round_mask: 3473 case X86::BI__builtin_ia32_maxss_round_mask: 3474 case X86::BI__builtin_ia32_minsd_round_mask: 3475 case X86::BI__builtin_ia32_minss_round_mask: 3476 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3477 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3478 case X86::BI__builtin_ia32_reducepd512_mask: 3479 case X86::BI__builtin_ia32_reduceps512_mask: 3480 case X86::BI__builtin_ia32_rndscalepd_mask: 3481 case X86::BI__builtin_ia32_rndscaleps_mask: 3482 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3483 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3484 ArgNum = 4; 3485 break; 3486 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3487 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3488 case X86::BI__builtin_ia32_fixupimmps512_mask: 3489 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3490 case X86::BI__builtin_ia32_fixupimmsd_mask: 3491 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3492 case X86::BI__builtin_ia32_fixupimmss_mask: 3493 case X86::BI__builtin_ia32_fixupimmss_maskz: 3494 case X86::BI__builtin_ia32_getmantsd_round_mask: 3495 case X86::BI__builtin_ia32_getmantss_round_mask: 3496 case X86::BI__builtin_ia32_rangepd512_mask: 3497 case X86::BI__builtin_ia32_rangeps512_mask: 3498 case X86::BI__builtin_ia32_rangesd128_round_mask: 3499 case X86::BI__builtin_ia32_rangess128_round_mask: 3500 case X86::BI__builtin_ia32_reducesd_mask: 3501 case X86::BI__builtin_ia32_reducess_mask: 3502 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3503 case X86::BI__builtin_ia32_rndscaless_round_mask: 3504 ArgNum = 5; 3505 break; 3506 case X86::BI__builtin_ia32_vcvtsd2si64: 3507 case X86::BI__builtin_ia32_vcvtsd2si32: 3508 case X86::BI__builtin_ia32_vcvtsd2usi32: 3509 case X86::BI__builtin_ia32_vcvtsd2usi64: 3510 case X86::BI__builtin_ia32_vcvtss2si32: 3511 case X86::BI__builtin_ia32_vcvtss2si64: 3512 case X86::BI__builtin_ia32_vcvtss2usi32: 3513 case X86::BI__builtin_ia32_vcvtss2usi64: 3514 case X86::BI__builtin_ia32_sqrtpd512: 3515 case X86::BI__builtin_ia32_sqrtps512: 3516 ArgNum = 1; 3517 HasRC = true; 3518 break; 3519 case X86::BI__builtin_ia32_addpd512: 3520 case X86::BI__builtin_ia32_addps512: 3521 case X86::BI__builtin_ia32_divpd512: 3522 case X86::BI__builtin_ia32_divps512: 3523 case X86::BI__builtin_ia32_mulpd512: 3524 case X86::BI__builtin_ia32_mulps512: 3525 case X86::BI__builtin_ia32_subpd512: 3526 case X86::BI__builtin_ia32_subps512: 3527 case X86::BI__builtin_ia32_cvtsi2sd64: 3528 case X86::BI__builtin_ia32_cvtsi2ss32: 3529 case X86::BI__builtin_ia32_cvtsi2ss64: 3530 case X86::BI__builtin_ia32_cvtusi2sd64: 3531 case X86::BI__builtin_ia32_cvtusi2ss32: 3532 case X86::BI__builtin_ia32_cvtusi2ss64: 3533 ArgNum = 2; 3534 HasRC = true; 3535 break; 3536 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3537 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3538 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3539 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3540 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3541 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3542 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3543 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3544 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3545 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3546 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3547 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3548 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3549 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3550 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3551 ArgNum = 3; 3552 HasRC = true; 3553 break; 3554 case X86::BI__builtin_ia32_addss_round_mask: 3555 case X86::BI__builtin_ia32_addsd_round_mask: 3556 case X86::BI__builtin_ia32_divss_round_mask: 3557 case X86::BI__builtin_ia32_divsd_round_mask: 3558 case X86::BI__builtin_ia32_mulss_round_mask: 3559 case X86::BI__builtin_ia32_mulsd_round_mask: 3560 case X86::BI__builtin_ia32_subss_round_mask: 3561 case X86::BI__builtin_ia32_subsd_round_mask: 3562 case X86::BI__builtin_ia32_scalefpd512_mask: 3563 case X86::BI__builtin_ia32_scalefps512_mask: 3564 case X86::BI__builtin_ia32_scalefsd_round_mask: 3565 case X86::BI__builtin_ia32_scalefss_round_mask: 3566 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3567 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3568 case X86::BI__builtin_ia32_sqrtss_round_mask: 3569 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3570 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3571 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3572 case X86::BI__builtin_ia32_vfmaddss3_mask: 3573 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3574 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3575 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3576 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3577 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3578 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3579 case X86::BI__builtin_ia32_vfmaddps512_mask: 3580 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3581 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3582 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3583 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3584 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3585 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3586 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3587 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3588 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3589 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3590 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3591 ArgNum = 4; 3592 HasRC = true; 3593 break; 3594 } 3595 3596 llvm::APSInt Result; 3597 3598 // We can't check the value of a dependent argument. 3599 Expr *Arg = TheCall->getArg(ArgNum); 3600 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3601 return false; 3602 3603 // Check constant-ness first. 3604 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3605 return true; 3606 3607 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3608 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3609 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3610 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3611 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3612 Result == 8/*ROUND_NO_EXC*/ || 3613 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3614 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3615 return false; 3616 3617 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3618 << Arg->getSourceRange(); 3619 } 3620 3621 // Check if the gather/scatter scale is legal. 3622 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3623 CallExpr *TheCall) { 3624 unsigned ArgNum = 0; 3625 switch (BuiltinID) { 3626 default: 3627 return false; 3628 case X86::BI__builtin_ia32_gatherpfdpd: 3629 case X86::BI__builtin_ia32_gatherpfdps: 3630 case X86::BI__builtin_ia32_gatherpfqpd: 3631 case X86::BI__builtin_ia32_gatherpfqps: 3632 case X86::BI__builtin_ia32_scatterpfdpd: 3633 case X86::BI__builtin_ia32_scatterpfdps: 3634 case X86::BI__builtin_ia32_scatterpfqpd: 3635 case X86::BI__builtin_ia32_scatterpfqps: 3636 ArgNum = 3; 3637 break; 3638 case X86::BI__builtin_ia32_gatherd_pd: 3639 case X86::BI__builtin_ia32_gatherd_pd256: 3640 case X86::BI__builtin_ia32_gatherq_pd: 3641 case X86::BI__builtin_ia32_gatherq_pd256: 3642 case X86::BI__builtin_ia32_gatherd_ps: 3643 case X86::BI__builtin_ia32_gatherd_ps256: 3644 case X86::BI__builtin_ia32_gatherq_ps: 3645 case X86::BI__builtin_ia32_gatherq_ps256: 3646 case X86::BI__builtin_ia32_gatherd_q: 3647 case X86::BI__builtin_ia32_gatherd_q256: 3648 case X86::BI__builtin_ia32_gatherq_q: 3649 case X86::BI__builtin_ia32_gatherq_q256: 3650 case X86::BI__builtin_ia32_gatherd_d: 3651 case X86::BI__builtin_ia32_gatherd_d256: 3652 case X86::BI__builtin_ia32_gatherq_d: 3653 case X86::BI__builtin_ia32_gatherq_d256: 3654 case X86::BI__builtin_ia32_gather3div2df: 3655 case X86::BI__builtin_ia32_gather3div2di: 3656 case X86::BI__builtin_ia32_gather3div4df: 3657 case X86::BI__builtin_ia32_gather3div4di: 3658 case X86::BI__builtin_ia32_gather3div4sf: 3659 case X86::BI__builtin_ia32_gather3div4si: 3660 case X86::BI__builtin_ia32_gather3div8sf: 3661 case X86::BI__builtin_ia32_gather3div8si: 3662 case X86::BI__builtin_ia32_gather3siv2df: 3663 case X86::BI__builtin_ia32_gather3siv2di: 3664 case X86::BI__builtin_ia32_gather3siv4df: 3665 case X86::BI__builtin_ia32_gather3siv4di: 3666 case X86::BI__builtin_ia32_gather3siv4sf: 3667 case X86::BI__builtin_ia32_gather3siv4si: 3668 case X86::BI__builtin_ia32_gather3siv8sf: 3669 case X86::BI__builtin_ia32_gather3siv8si: 3670 case X86::BI__builtin_ia32_gathersiv8df: 3671 case X86::BI__builtin_ia32_gathersiv16sf: 3672 case X86::BI__builtin_ia32_gatherdiv8df: 3673 case X86::BI__builtin_ia32_gatherdiv16sf: 3674 case X86::BI__builtin_ia32_gathersiv8di: 3675 case X86::BI__builtin_ia32_gathersiv16si: 3676 case X86::BI__builtin_ia32_gatherdiv8di: 3677 case X86::BI__builtin_ia32_gatherdiv16si: 3678 case X86::BI__builtin_ia32_scatterdiv2df: 3679 case X86::BI__builtin_ia32_scatterdiv2di: 3680 case X86::BI__builtin_ia32_scatterdiv4df: 3681 case X86::BI__builtin_ia32_scatterdiv4di: 3682 case X86::BI__builtin_ia32_scatterdiv4sf: 3683 case X86::BI__builtin_ia32_scatterdiv4si: 3684 case X86::BI__builtin_ia32_scatterdiv8sf: 3685 case X86::BI__builtin_ia32_scatterdiv8si: 3686 case X86::BI__builtin_ia32_scattersiv2df: 3687 case X86::BI__builtin_ia32_scattersiv2di: 3688 case X86::BI__builtin_ia32_scattersiv4df: 3689 case X86::BI__builtin_ia32_scattersiv4di: 3690 case X86::BI__builtin_ia32_scattersiv4sf: 3691 case X86::BI__builtin_ia32_scattersiv4si: 3692 case X86::BI__builtin_ia32_scattersiv8sf: 3693 case X86::BI__builtin_ia32_scattersiv8si: 3694 case X86::BI__builtin_ia32_scattersiv8df: 3695 case X86::BI__builtin_ia32_scattersiv16sf: 3696 case X86::BI__builtin_ia32_scatterdiv8df: 3697 case X86::BI__builtin_ia32_scatterdiv16sf: 3698 case X86::BI__builtin_ia32_scattersiv8di: 3699 case X86::BI__builtin_ia32_scattersiv16si: 3700 case X86::BI__builtin_ia32_scatterdiv8di: 3701 case X86::BI__builtin_ia32_scatterdiv16si: 3702 ArgNum = 4; 3703 break; 3704 } 3705 3706 llvm::APSInt Result; 3707 3708 // We can't check the value of a dependent argument. 3709 Expr *Arg = TheCall->getArg(ArgNum); 3710 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3711 return false; 3712 3713 // Check constant-ness first. 3714 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3715 return true; 3716 3717 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3718 return false; 3719 3720 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3721 << Arg->getSourceRange(); 3722 } 3723 3724 enum { TileRegLow = 0, TileRegHigh = 7 }; 3725 3726 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3727 ArrayRef<int> ArgNums) { 3728 for (int ArgNum : ArgNums) { 3729 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3730 return true; 3731 } 3732 return false; 3733 } 3734 3735 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3736 ArrayRef<int> ArgNums) { 3737 // Because the max number of tile register is TileRegHigh + 1, so here we use 3738 // each bit to represent the usage of them in bitset. 3739 std::bitset<TileRegHigh + 1> ArgValues; 3740 for (int ArgNum : ArgNums) { 3741 Expr *Arg = TheCall->getArg(ArgNum); 3742 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3743 continue; 3744 3745 llvm::APSInt Result; 3746 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3747 return true; 3748 int ArgExtValue = Result.getExtValue(); 3749 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3750 "Incorrect tile register num."); 3751 if (ArgValues.test(ArgExtValue)) 3752 return Diag(TheCall->getBeginLoc(), 3753 diag::err_x86_builtin_tile_arg_duplicate) 3754 << TheCall->getArg(ArgNum)->getSourceRange(); 3755 ArgValues.set(ArgExtValue); 3756 } 3757 return false; 3758 } 3759 3760 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3761 ArrayRef<int> ArgNums) { 3762 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3763 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3764 } 3765 3766 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3767 switch (BuiltinID) { 3768 default: 3769 return false; 3770 case X86::BI__builtin_ia32_tileloadd64: 3771 case X86::BI__builtin_ia32_tileloaddt164: 3772 case X86::BI__builtin_ia32_tilestored64: 3773 case X86::BI__builtin_ia32_tilezero: 3774 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3775 case X86::BI__builtin_ia32_tdpbssd: 3776 case X86::BI__builtin_ia32_tdpbsud: 3777 case X86::BI__builtin_ia32_tdpbusd: 3778 case X86::BI__builtin_ia32_tdpbuud: 3779 case X86::BI__builtin_ia32_tdpbf16ps: 3780 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3781 } 3782 } 3783 static bool isX86_32Builtin(unsigned BuiltinID) { 3784 // These builtins only work on x86-32 targets. 3785 switch (BuiltinID) { 3786 case X86::BI__builtin_ia32_readeflags_u32: 3787 case X86::BI__builtin_ia32_writeeflags_u32: 3788 return true; 3789 } 3790 3791 return false; 3792 } 3793 3794 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3795 CallExpr *TheCall) { 3796 if (BuiltinID == X86::BI__builtin_cpu_supports) 3797 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3798 3799 if (BuiltinID == X86::BI__builtin_cpu_is) 3800 return SemaBuiltinCpuIs(*this, TI, TheCall); 3801 3802 // Check for 32-bit only builtins on a 64-bit target. 3803 const llvm::Triple &TT = TI.getTriple(); 3804 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3805 return Diag(TheCall->getCallee()->getBeginLoc(), 3806 diag::err_32_bit_builtin_64_bit_tgt); 3807 3808 // If the intrinsic has rounding or SAE make sure its valid. 3809 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3810 return true; 3811 3812 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3813 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3814 return true; 3815 3816 // If the intrinsic has a tile arguments, make sure they are valid. 3817 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3818 return true; 3819 3820 // For intrinsics which take an immediate value as part of the instruction, 3821 // range check them here. 3822 int i = 0, l = 0, u = 0; 3823 switch (BuiltinID) { 3824 default: 3825 return false; 3826 case X86::BI__builtin_ia32_vec_ext_v2si: 3827 case X86::BI__builtin_ia32_vec_ext_v2di: 3828 case X86::BI__builtin_ia32_vextractf128_pd256: 3829 case X86::BI__builtin_ia32_vextractf128_ps256: 3830 case X86::BI__builtin_ia32_vextractf128_si256: 3831 case X86::BI__builtin_ia32_extract128i256: 3832 case X86::BI__builtin_ia32_extractf64x4_mask: 3833 case X86::BI__builtin_ia32_extracti64x4_mask: 3834 case X86::BI__builtin_ia32_extractf32x8_mask: 3835 case X86::BI__builtin_ia32_extracti32x8_mask: 3836 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3837 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3838 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3839 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3840 i = 1; l = 0; u = 1; 3841 break; 3842 case X86::BI__builtin_ia32_vec_set_v2di: 3843 case X86::BI__builtin_ia32_vinsertf128_pd256: 3844 case X86::BI__builtin_ia32_vinsertf128_ps256: 3845 case X86::BI__builtin_ia32_vinsertf128_si256: 3846 case X86::BI__builtin_ia32_insert128i256: 3847 case X86::BI__builtin_ia32_insertf32x8: 3848 case X86::BI__builtin_ia32_inserti32x8: 3849 case X86::BI__builtin_ia32_insertf64x4: 3850 case X86::BI__builtin_ia32_inserti64x4: 3851 case X86::BI__builtin_ia32_insertf64x2_256: 3852 case X86::BI__builtin_ia32_inserti64x2_256: 3853 case X86::BI__builtin_ia32_insertf32x4_256: 3854 case X86::BI__builtin_ia32_inserti32x4_256: 3855 i = 2; l = 0; u = 1; 3856 break; 3857 case X86::BI__builtin_ia32_vpermilpd: 3858 case X86::BI__builtin_ia32_vec_ext_v4hi: 3859 case X86::BI__builtin_ia32_vec_ext_v4si: 3860 case X86::BI__builtin_ia32_vec_ext_v4sf: 3861 case X86::BI__builtin_ia32_vec_ext_v4di: 3862 case X86::BI__builtin_ia32_extractf32x4_mask: 3863 case X86::BI__builtin_ia32_extracti32x4_mask: 3864 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3865 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3866 i = 1; l = 0; u = 3; 3867 break; 3868 case X86::BI_mm_prefetch: 3869 case X86::BI__builtin_ia32_vec_ext_v8hi: 3870 case X86::BI__builtin_ia32_vec_ext_v8si: 3871 i = 1; l = 0; u = 7; 3872 break; 3873 case X86::BI__builtin_ia32_sha1rnds4: 3874 case X86::BI__builtin_ia32_blendpd: 3875 case X86::BI__builtin_ia32_shufpd: 3876 case X86::BI__builtin_ia32_vec_set_v4hi: 3877 case X86::BI__builtin_ia32_vec_set_v4si: 3878 case X86::BI__builtin_ia32_vec_set_v4di: 3879 case X86::BI__builtin_ia32_shuf_f32x4_256: 3880 case X86::BI__builtin_ia32_shuf_f64x2_256: 3881 case X86::BI__builtin_ia32_shuf_i32x4_256: 3882 case X86::BI__builtin_ia32_shuf_i64x2_256: 3883 case X86::BI__builtin_ia32_insertf64x2_512: 3884 case X86::BI__builtin_ia32_inserti64x2_512: 3885 case X86::BI__builtin_ia32_insertf32x4: 3886 case X86::BI__builtin_ia32_inserti32x4: 3887 i = 2; l = 0; u = 3; 3888 break; 3889 case X86::BI__builtin_ia32_vpermil2pd: 3890 case X86::BI__builtin_ia32_vpermil2pd256: 3891 case X86::BI__builtin_ia32_vpermil2ps: 3892 case X86::BI__builtin_ia32_vpermil2ps256: 3893 i = 3; l = 0; u = 3; 3894 break; 3895 case X86::BI__builtin_ia32_cmpb128_mask: 3896 case X86::BI__builtin_ia32_cmpw128_mask: 3897 case X86::BI__builtin_ia32_cmpd128_mask: 3898 case X86::BI__builtin_ia32_cmpq128_mask: 3899 case X86::BI__builtin_ia32_cmpb256_mask: 3900 case X86::BI__builtin_ia32_cmpw256_mask: 3901 case X86::BI__builtin_ia32_cmpd256_mask: 3902 case X86::BI__builtin_ia32_cmpq256_mask: 3903 case X86::BI__builtin_ia32_cmpb512_mask: 3904 case X86::BI__builtin_ia32_cmpw512_mask: 3905 case X86::BI__builtin_ia32_cmpd512_mask: 3906 case X86::BI__builtin_ia32_cmpq512_mask: 3907 case X86::BI__builtin_ia32_ucmpb128_mask: 3908 case X86::BI__builtin_ia32_ucmpw128_mask: 3909 case X86::BI__builtin_ia32_ucmpd128_mask: 3910 case X86::BI__builtin_ia32_ucmpq128_mask: 3911 case X86::BI__builtin_ia32_ucmpb256_mask: 3912 case X86::BI__builtin_ia32_ucmpw256_mask: 3913 case X86::BI__builtin_ia32_ucmpd256_mask: 3914 case X86::BI__builtin_ia32_ucmpq256_mask: 3915 case X86::BI__builtin_ia32_ucmpb512_mask: 3916 case X86::BI__builtin_ia32_ucmpw512_mask: 3917 case X86::BI__builtin_ia32_ucmpd512_mask: 3918 case X86::BI__builtin_ia32_ucmpq512_mask: 3919 case X86::BI__builtin_ia32_vpcomub: 3920 case X86::BI__builtin_ia32_vpcomuw: 3921 case X86::BI__builtin_ia32_vpcomud: 3922 case X86::BI__builtin_ia32_vpcomuq: 3923 case X86::BI__builtin_ia32_vpcomb: 3924 case X86::BI__builtin_ia32_vpcomw: 3925 case X86::BI__builtin_ia32_vpcomd: 3926 case X86::BI__builtin_ia32_vpcomq: 3927 case X86::BI__builtin_ia32_vec_set_v8hi: 3928 case X86::BI__builtin_ia32_vec_set_v8si: 3929 i = 2; l = 0; u = 7; 3930 break; 3931 case X86::BI__builtin_ia32_vpermilpd256: 3932 case X86::BI__builtin_ia32_roundps: 3933 case X86::BI__builtin_ia32_roundpd: 3934 case X86::BI__builtin_ia32_roundps256: 3935 case X86::BI__builtin_ia32_roundpd256: 3936 case X86::BI__builtin_ia32_getmantpd128_mask: 3937 case X86::BI__builtin_ia32_getmantpd256_mask: 3938 case X86::BI__builtin_ia32_getmantps128_mask: 3939 case X86::BI__builtin_ia32_getmantps256_mask: 3940 case X86::BI__builtin_ia32_getmantpd512_mask: 3941 case X86::BI__builtin_ia32_getmantps512_mask: 3942 case X86::BI__builtin_ia32_vec_ext_v16qi: 3943 case X86::BI__builtin_ia32_vec_ext_v16hi: 3944 i = 1; l = 0; u = 15; 3945 break; 3946 case X86::BI__builtin_ia32_pblendd128: 3947 case X86::BI__builtin_ia32_blendps: 3948 case X86::BI__builtin_ia32_blendpd256: 3949 case X86::BI__builtin_ia32_shufpd256: 3950 case X86::BI__builtin_ia32_roundss: 3951 case X86::BI__builtin_ia32_roundsd: 3952 case X86::BI__builtin_ia32_rangepd128_mask: 3953 case X86::BI__builtin_ia32_rangepd256_mask: 3954 case X86::BI__builtin_ia32_rangepd512_mask: 3955 case X86::BI__builtin_ia32_rangeps128_mask: 3956 case X86::BI__builtin_ia32_rangeps256_mask: 3957 case X86::BI__builtin_ia32_rangeps512_mask: 3958 case X86::BI__builtin_ia32_getmantsd_round_mask: 3959 case X86::BI__builtin_ia32_getmantss_round_mask: 3960 case X86::BI__builtin_ia32_vec_set_v16qi: 3961 case X86::BI__builtin_ia32_vec_set_v16hi: 3962 i = 2; l = 0; u = 15; 3963 break; 3964 case X86::BI__builtin_ia32_vec_ext_v32qi: 3965 i = 1; l = 0; u = 31; 3966 break; 3967 case X86::BI__builtin_ia32_cmpps: 3968 case X86::BI__builtin_ia32_cmpss: 3969 case X86::BI__builtin_ia32_cmppd: 3970 case X86::BI__builtin_ia32_cmpsd: 3971 case X86::BI__builtin_ia32_cmpps256: 3972 case X86::BI__builtin_ia32_cmppd256: 3973 case X86::BI__builtin_ia32_cmpps128_mask: 3974 case X86::BI__builtin_ia32_cmppd128_mask: 3975 case X86::BI__builtin_ia32_cmpps256_mask: 3976 case X86::BI__builtin_ia32_cmppd256_mask: 3977 case X86::BI__builtin_ia32_cmpps512_mask: 3978 case X86::BI__builtin_ia32_cmppd512_mask: 3979 case X86::BI__builtin_ia32_cmpsd_mask: 3980 case X86::BI__builtin_ia32_cmpss_mask: 3981 case X86::BI__builtin_ia32_vec_set_v32qi: 3982 i = 2; l = 0; u = 31; 3983 break; 3984 case X86::BI__builtin_ia32_permdf256: 3985 case X86::BI__builtin_ia32_permdi256: 3986 case X86::BI__builtin_ia32_permdf512: 3987 case X86::BI__builtin_ia32_permdi512: 3988 case X86::BI__builtin_ia32_vpermilps: 3989 case X86::BI__builtin_ia32_vpermilps256: 3990 case X86::BI__builtin_ia32_vpermilpd512: 3991 case X86::BI__builtin_ia32_vpermilps512: 3992 case X86::BI__builtin_ia32_pshufd: 3993 case X86::BI__builtin_ia32_pshufd256: 3994 case X86::BI__builtin_ia32_pshufd512: 3995 case X86::BI__builtin_ia32_pshufhw: 3996 case X86::BI__builtin_ia32_pshufhw256: 3997 case X86::BI__builtin_ia32_pshufhw512: 3998 case X86::BI__builtin_ia32_pshuflw: 3999 case X86::BI__builtin_ia32_pshuflw256: 4000 case X86::BI__builtin_ia32_pshuflw512: 4001 case X86::BI__builtin_ia32_vcvtps2ph: 4002 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4003 case X86::BI__builtin_ia32_vcvtps2ph256: 4004 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4005 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4006 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4007 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4008 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4009 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4010 case X86::BI__builtin_ia32_rndscaleps_mask: 4011 case X86::BI__builtin_ia32_rndscalepd_mask: 4012 case X86::BI__builtin_ia32_reducepd128_mask: 4013 case X86::BI__builtin_ia32_reducepd256_mask: 4014 case X86::BI__builtin_ia32_reducepd512_mask: 4015 case X86::BI__builtin_ia32_reduceps128_mask: 4016 case X86::BI__builtin_ia32_reduceps256_mask: 4017 case X86::BI__builtin_ia32_reduceps512_mask: 4018 case X86::BI__builtin_ia32_prold512: 4019 case X86::BI__builtin_ia32_prolq512: 4020 case X86::BI__builtin_ia32_prold128: 4021 case X86::BI__builtin_ia32_prold256: 4022 case X86::BI__builtin_ia32_prolq128: 4023 case X86::BI__builtin_ia32_prolq256: 4024 case X86::BI__builtin_ia32_prord512: 4025 case X86::BI__builtin_ia32_prorq512: 4026 case X86::BI__builtin_ia32_prord128: 4027 case X86::BI__builtin_ia32_prord256: 4028 case X86::BI__builtin_ia32_prorq128: 4029 case X86::BI__builtin_ia32_prorq256: 4030 case X86::BI__builtin_ia32_fpclasspd128_mask: 4031 case X86::BI__builtin_ia32_fpclasspd256_mask: 4032 case X86::BI__builtin_ia32_fpclassps128_mask: 4033 case X86::BI__builtin_ia32_fpclassps256_mask: 4034 case X86::BI__builtin_ia32_fpclassps512_mask: 4035 case X86::BI__builtin_ia32_fpclasspd512_mask: 4036 case X86::BI__builtin_ia32_fpclasssd_mask: 4037 case X86::BI__builtin_ia32_fpclassss_mask: 4038 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4039 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4040 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4041 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4042 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4043 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4044 case X86::BI__builtin_ia32_kshiftliqi: 4045 case X86::BI__builtin_ia32_kshiftlihi: 4046 case X86::BI__builtin_ia32_kshiftlisi: 4047 case X86::BI__builtin_ia32_kshiftlidi: 4048 case X86::BI__builtin_ia32_kshiftriqi: 4049 case X86::BI__builtin_ia32_kshiftrihi: 4050 case X86::BI__builtin_ia32_kshiftrisi: 4051 case X86::BI__builtin_ia32_kshiftridi: 4052 i = 1; l = 0; u = 255; 4053 break; 4054 case X86::BI__builtin_ia32_vperm2f128_pd256: 4055 case X86::BI__builtin_ia32_vperm2f128_ps256: 4056 case X86::BI__builtin_ia32_vperm2f128_si256: 4057 case X86::BI__builtin_ia32_permti256: 4058 case X86::BI__builtin_ia32_pblendw128: 4059 case X86::BI__builtin_ia32_pblendw256: 4060 case X86::BI__builtin_ia32_blendps256: 4061 case X86::BI__builtin_ia32_pblendd256: 4062 case X86::BI__builtin_ia32_palignr128: 4063 case X86::BI__builtin_ia32_palignr256: 4064 case X86::BI__builtin_ia32_palignr512: 4065 case X86::BI__builtin_ia32_alignq512: 4066 case X86::BI__builtin_ia32_alignd512: 4067 case X86::BI__builtin_ia32_alignd128: 4068 case X86::BI__builtin_ia32_alignd256: 4069 case X86::BI__builtin_ia32_alignq128: 4070 case X86::BI__builtin_ia32_alignq256: 4071 case X86::BI__builtin_ia32_vcomisd: 4072 case X86::BI__builtin_ia32_vcomiss: 4073 case X86::BI__builtin_ia32_shuf_f32x4: 4074 case X86::BI__builtin_ia32_shuf_f64x2: 4075 case X86::BI__builtin_ia32_shuf_i32x4: 4076 case X86::BI__builtin_ia32_shuf_i64x2: 4077 case X86::BI__builtin_ia32_shufpd512: 4078 case X86::BI__builtin_ia32_shufps: 4079 case X86::BI__builtin_ia32_shufps256: 4080 case X86::BI__builtin_ia32_shufps512: 4081 case X86::BI__builtin_ia32_dbpsadbw128: 4082 case X86::BI__builtin_ia32_dbpsadbw256: 4083 case X86::BI__builtin_ia32_dbpsadbw512: 4084 case X86::BI__builtin_ia32_vpshldd128: 4085 case X86::BI__builtin_ia32_vpshldd256: 4086 case X86::BI__builtin_ia32_vpshldd512: 4087 case X86::BI__builtin_ia32_vpshldq128: 4088 case X86::BI__builtin_ia32_vpshldq256: 4089 case X86::BI__builtin_ia32_vpshldq512: 4090 case X86::BI__builtin_ia32_vpshldw128: 4091 case X86::BI__builtin_ia32_vpshldw256: 4092 case X86::BI__builtin_ia32_vpshldw512: 4093 case X86::BI__builtin_ia32_vpshrdd128: 4094 case X86::BI__builtin_ia32_vpshrdd256: 4095 case X86::BI__builtin_ia32_vpshrdd512: 4096 case X86::BI__builtin_ia32_vpshrdq128: 4097 case X86::BI__builtin_ia32_vpshrdq256: 4098 case X86::BI__builtin_ia32_vpshrdq512: 4099 case X86::BI__builtin_ia32_vpshrdw128: 4100 case X86::BI__builtin_ia32_vpshrdw256: 4101 case X86::BI__builtin_ia32_vpshrdw512: 4102 i = 2; l = 0; u = 255; 4103 break; 4104 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4105 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4106 case X86::BI__builtin_ia32_fixupimmps512_mask: 4107 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4108 case X86::BI__builtin_ia32_fixupimmsd_mask: 4109 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4110 case X86::BI__builtin_ia32_fixupimmss_mask: 4111 case X86::BI__builtin_ia32_fixupimmss_maskz: 4112 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4113 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4114 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4115 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4116 case X86::BI__builtin_ia32_fixupimmps128_mask: 4117 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4118 case X86::BI__builtin_ia32_fixupimmps256_mask: 4119 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4120 case X86::BI__builtin_ia32_pternlogd512_mask: 4121 case X86::BI__builtin_ia32_pternlogd512_maskz: 4122 case X86::BI__builtin_ia32_pternlogq512_mask: 4123 case X86::BI__builtin_ia32_pternlogq512_maskz: 4124 case X86::BI__builtin_ia32_pternlogd128_mask: 4125 case X86::BI__builtin_ia32_pternlogd128_maskz: 4126 case X86::BI__builtin_ia32_pternlogd256_mask: 4127 case X86::BI__builtin_ia32_pternlogd256_maskz: 4128 case X86::BI__builtin_ia32_pternlogq128_mask: 4129 case X86::BI__builtin_ia32_pternlogq128_maskz: 4130 case X86::BI__builtin_ia32_pternlogq256_mask: 4131 case X86::BI__builtin_ia32_pternlogq256_maskz: 4132 i = 3; l = 0; u = 255; 4133 break; 4134 case X86::BI__builtin_ia32_gatherpfdpd: 4135 case X86::BI__builtin_ia32_gatherpfdps: 4136 case X86::BI__builtin_ia32_gatherpfqpd: 4137 case X86::BI__builtin_ia32_gatherpfqps: 4138 case X86::BI__builtin_ia32_scatterpfdpd: 4139 case X86::BI__builtin_ia32_scatterpfdps: 4140 case X86::BI__builtin_ia32_scatterpfqpd: 4141 case X86::BI__builtin_ia32_scatterpfqps: 4142 i = 4; l = 2; u = 3; 4143 break; 4144 case X86::BI__builtin_ia32_reducesd_mask: 4145 case X86::BI__builtin_ia32_reducess_mask: 4146 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4147 case X86::BI__builtin_ia32_rndscaless_round_mask: 4148 i = 4; l = 0; u = 255; 4149 break; 4150 } 4151 4152 // Note that we don't force a hard error on the range check here, allowing 4153 // template-generated or macro-generated dead code to potentially have out-of- 4154 // range values. These need to code generate, but don't need to necessarily 4155 // make any sense. We use a warning that defaults to an error. 4156 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4157 } 4158 4159 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4160 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4161 /// Returns true when the format fits the function and the FormatStringInfo has 4162 /// been populated. 4163 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4164 FormatStringInfo *FSI) { 4165 FSI->HasVAListArg = Format->getFirstArg() == 0; 4166 FSI->FormatIdx = Format->getFormatIdx() - 1; 4167 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4168 4169 // The way the format attribute works in GCC, the implicit this argument 4170 // of member functions is counted. However, it doesn't appear in our own 4171 // lists, so decrement format_idx in that case. 4172 if (IsCXXMember) { 4173 if(FSI->FormatIdx == 0) 4174 return false; 4175 --FSI->FormatIdx; 4176 if (FSI->FirstDataArg != 0) 4177 --FSI->FirstDataArg; 4178 } 4179 return true; 4180 } 4181 4182 /// Checks if a the given expression evaluates to null. 4183 /// 4184 /// Returns true if the value evaluates to null. 4185 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4186 // If the expression has non-null type, it doesn't evaluate to null. 4187 if (auto nullability 4188 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4189 if (*nullability == NullabilityKind::NonNull) 4190 return false; 4191 } 4192 4193 // As a special case, transparent unions initialized with zero are 4194 // considered null for the purposes of the nonnull attribute. 4195 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4196 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4197 if (const CompoundLiteralExpr *CLE = 4198 dyn_cast<CompoundLiteralExpr>(Expr)) 4199 if (const InitListExpr *ILE = 4200 dyn_cast<InitListExpr>(CLE->getInitializer())) 4201 Expr = ILE->getInit(0); 4202 } 4203 4204 bool Result; 4205 return (!Expr->isValueDependent() && 4206 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4207 !Result); 4208 } 4209 4210 static void CheckNonNullArgument(Sema &S, 4211 const Expr *ArgExpr, 4212 SourceLocation CallSiteLoc) { 4213 if (CheckNonNullExpr(S, ArgExpr)) 4214 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4215 S.PDiag(diag::warn_null_arg) 4216 << ArgExpr->getSourceRange()); 4217 } 4218 4219 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4220 FormatStringInfo FSI; 4221 if ((GetFormatStringType(Format) == FST_NSString) && 4222 getFormatStringInfo(Format, false, &FSI)) { 4223 Idx = FSI.FormatIdx; 4224 return true; 4225 } 4226 return false; 4227 } 4228 4229 /// Diagnose use of %s directive in an NSString which is being passed 4230 /// as formatting string to formatting method. 4231 static void 4232 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4233 const NamedDecl *FDecl, 4234 Expr **Args, 4235 unsigned NumArgs) { 4236 unsigned Idx = 0; 4237 bool Format = false; 4238 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4239 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4240 Idx = 2; 4241 Format = true; 4242 } 4243 else 4244 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4245 if (S.GetFormatNSStringIdx(I, Idx)) { 4246 Format = true; 4247 break; 4248 } 4249 } 4250 if (!Format || NumArgs <= Idx) 4251 return; 4252 const Expr *FormatExpr = Args[Idx]; 4253 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4254 FormatExpr = CSCE->getSubExpr(); 4255 const StringLiteral *FormatString; 4256 if (const ObjCStringLiteral *OSL = 4257 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4258 FormatString = OSL->getString(); 4259 else 4260 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4261 if (!FormatString) 4262 return; 4263 if (S.FormatStringHasSArg(FormatString)) { 4264 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4265 << "%s" << 1 << 1; 4266 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4267 << FDecl->getDeclName(); 4268 } 4269 } 4270 4271 /// Determine whether the given type has a non-null nullability annotation. 4272 static bool isNonNullType(ASTContext &ctx, QualType type) { 4273 if (auto nullability = type->getNullability(ctx)) 4274 return *nullability == NullabilityKind::NonNull; 4275 4276 return false; 4277 } 4278 4279 static void CheckNonNullArguments(Sema &S, 4280 const NamedDecl *FDecl, 4281 const FunctionProtoType *Proto, 4282 ArrayRef<const Expr *> Args, 4283 SourceLocation CallSiteLoc) { 4284 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4285 4286 // Already checked by by constant evaluator. 4287 if (S.isConstantEvaluated()) 4288 return; 4289 // Check the attributes attached to the method/function itself. 4290 llvm::SmallBitVector NonNullArgs; 4291 if (FDecl) { 4292 // Handle the nonnull attribute on the function/method declaration itself. 4293 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4294 if (!NonNull->args_size()) { 4295 // Easy case: all pointer arguments are nonnull. 4296 for (const auto *Arg : Args) 4297 if (S.isValidPointerAttrType(Arg->getType())) 4298 CheckNonNullArgument(S, Arg, CallSiteLoc); 4299 return; 4300 } 4301 4302 for (const ParamIdx &Idx : NonNull->args()) { 4303 unsigned IdxAST = Idx.getASTIndex(); 4304 if (IdxAST >= Args.size()) 4305 continue; 4306 if (NonNullArgs.empty()) 4307 NonNullArgs.resize(Args.size()); 4308 NonNullArgs.set(IdxAST); 4309 } 4310 } 4311 } 4312 4313 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4314 // Handle the nonnull attribute on the parameters of the 4315 // function/method. 4316 ArrayRef<ParmVarDecl*> parms; 4317 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4318 parms = FD->parameters(); 4319 else 4320 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4321 4322 unsigned ParamIndex = 0; 4323 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4324 I != E; ++I, ++ParamIndex) { 4325 const ParmVarDecl *PVD = *I; 4326 if (PVD->hasAttr<NonNullAttr>() || 4327 isNonNullType(S.Context, PVD->getType())) { 4328 if (NonNullArgs.empty()) 4329 NonNullArgs.resize(Args.size()); 4330 4331 NonNullArgs.set(ParamIndex); 4332 } 4333 } 4334 } else { 4335 // If we have a non-function, non-method declaration but no 4336 // function prototype, try to dig out the function prototype. 4337 if (!Proto) { 4338 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4339 QualType type = VD->getType().getNonReferenceType(); 4340 if (auto pointerType = type->getAs<PointerType>()) 4341 type = pointerType->getPointeeType(); 4342 else if (auto blockType = type->getAs<BlockPointerType>()) 4343 type = blockType->getPointeeType(); 4344 // FIXME: data member pointers? 4345 4346 // Dig out the function prototype, if there is one. 4347 Proto = type->getAs<FunctionProtoType>(); 4348 } 4349 } 4350 4351 // Fill in non-null argument information from the nullability 4352 // information on the parameter types (if we have them). 4353 if (Proto) { 4354 unsigned Index = 0; 4355 for (auto paramType : Proto->getParamTypes()) { 4356 if (isNonNullType(S.Context, paramType)) { 4357 if (NonNullArgs.empty()) 4358 NonNullArgs.resize(Args.size()); 4359 4360 NonNullArgs.set(Index); 4361 } 4362 4363 ++Index; 4364 } 4365 } 4366 } 4367 4368 // Check for non-null arguments. 4369 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4370 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4371 if (NonNullArgs[ArgIndex]) 4372 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4373 } 4374 } 4375 4376 /// Handles the checks for format strings, non-POD arguments to vararg 4377 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4378 /// attributes. 4379 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4380 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4381 bool IsMemberFunction, SourceLocation Loc, 4382 SourceRange Range, VariadicCallType CallType) { 4383 // FIXME: We should check as much as we can in the template definition. 4384 if (CurContext->isDependentContext()) 4385 return; 4386 4387 // Printf and scanf checking. 4388 llvm::SmallBitVector CheckedVarArgs; 4389 if (FDecl) { 4390 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4391 // Only create vector if there are format attributes. 4392 CheckedVarArgs.resize(Args.size()); 4393 4394 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4395 CheckedVarArgs); 4396 } 4397 } 4398 4399 // Refuse POD arguments that weren't caught by the format string 4400 // checks above. 4401 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4402 if (CallType != VariadicDoesNotApply && 4403 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4404 unsigned NumParams = Proto ? Proto->getNumParams() 4405 : FDecl && isa<FunctionDecl>(FDecl) 4406 ? cast<FunctionDecl>(FDecl)->getNumParams() 4407 : FDecl && isa<ObjCMethodDecl>(FDecl) 4408 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4409 : 0; 4410 4411 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4412 // Args[ArgIdx] can be null in malformed code. 4413 if (const Expr *Arg = Args[ArgIdx]) { 4414 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4415 checkVariadicArgument(Arg, CallType); 4416 } 4417 } 4418 } 4419 4420 if (FDecl || Proto) { 4421 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4422 4423 // Type safety checking. 4424 if (FDecl) { 4425 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4426 CheckArgumentWithTypeTag(I, Args, Loc); 4427 } 4428 } 4429 4430 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4431 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4432 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4433 if (!Arg->isValueDependent()) { 4434 Expr::EvalResult Align; 4435 if (Arg->EvaluateAsInt(Align, Context)) { 4436 const llvm::APSInt &I = Align.Val.getInt(); 4437 if (!I.isPowerOf2()) 4438 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4439 << Arg->getSourceRange(); 4440 4441 if (I > Sema::MaximumAlignment) 4442 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4443 << Arg->getSourceRange() << Sema::MaximumAlignment; 4444 } 4445 } 4446 } 4447 4448 if (FD) 4449 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4450 } 4451 4452 /// CheckConstructorCall - Check a constructor call for correctness and safety 4453 /// properties not enforced by the C type system. 4454 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4455 ArrayRef<const Expr *> Args, 4456 const FunctionProtoType *Proto, 4457 SourceLocation Loc) { 4458 VariadicCallType CallType = 4459 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4460 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4461 Loc, SourceRange(), CallType); 4462 } 4463 4464 /// CheckFunctionCall - Check a direct function call for various correctness 4465 /// and safety properties not strictly enforced by the C type system. 4466 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4467 const FunctionProtoType *Proto) { 4468 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4469 isa<CXXMethodDecl>(FDecl); 4470 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4471 IsMemberOperatorCall; 4472 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4473 TheCall->getCallee()); 4474 Expr** Args = TheCall->getArgs(); 4475 unsigned NumArgs = TheCall->getNumArgs(); 4476 4477 Expr *ImplicitThis = nullptr; 4478 if (IsMemberOperatorCall) { 4479 // If this is a call to a member operator, hide the first argument 4480 // from checkCall. 4481 // FIXME: Our choice of AST representation here is less than ideal. 4482 ImplicitThis = Args[0]; 4483 ++Args; 4484 --NumArgs; 4485 } else if (IsMemberFunction) 4486 ImplicitThis = 4487 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4488 4489 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4490 IsMemberFunction, TheCall->getRParenLoc(), 4491 TheCall->getCallee()->getSourceRange(), CallType); 4492 4493 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4494 // None of the checks below are needed for functions that don't have 4495 // simple names (e.g., C++ conversion functions). 4496 if (!FnInfo) 4497 return false; 4498 4499 CheckAbsoluteValueFunction(TheCall, FDecl); 4500 CheckMaxUnsignedZero(TheCall, FDecl); 4501 4502 if (getLangOpts().ObjC) 4503 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4504 4505 unsigned CMId = FDecl->getMemoryFunctionKind(); 4506 if (CMId == 0) 4507 return false; 4508 4509 // Handle memory setting and copying functions. 4510 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4511 CheckStrlcpycatArguments(TheCall, FnInfo); 4512 else if (CMId == Builtin::BIstrncat) 4513 CheckStrncatArguments(TheCall, FnInfo); 4514 else 4515 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4516 4517 return false; 4518 } 4519 4520 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4521 ArrayRef<const Expr *> Args) { 4522 VariadicCallType CallType = 4523 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4524 4525 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4526 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4527 CallType); 4528 4529 return false; 4530 } 4531 4532 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4533 const FunctionProtoType *Proto) { 4534 QualType Ty; 4535 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4536 Ty = V->getType().getNonReferenceType(); 4537 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4538 Ty = F->getType().getNonReferenceType(); 4539 else 4540 return false; 4541 4542 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4543 !Ty->isFunctionProtoType()) 4544 return false; 4545 4546 VariadicCallType CallType; 4547 if (!Proto || !Proto->isVariadic()) { 4548 CallType = VariadicDoesNotApply; 4549 } else if (Ty->isBlockPointerType()) { 4550 CallType = VariadicBlock; 4551 } else { // Ty->isFunctionPointerType() 4552 CallType = VariadicFunction; 4553 } 4554 4555 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4556 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4557 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4558 TheCall->getCallee()->getSourceRange(), CallType); 4559 4560 return false; 4561 } 4562 4563 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4564 /// such as function pointers returned from functions. 4565 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4566 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4567 TheCall->getCallee()); 4568 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4569 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4570 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4571 TheCall->getCallee()->getSourceRange(), CallType); 4572 4573 return false; 4574 } 4575 4576 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4577 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4578 return false; 4579 4580 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4581 switch (Op) { 4582 case AtomicExpr::AO__c11_atomic_init: 4583 case AtomicExpr::AO__opencl_atomic_init: 4584 llvm_unreachable("There is no ordering argument for an init"); 4585 4586 case AtomicExpr::AO__c11_atomic_load: 4587 case AtomicExpr::AO__opencl_atomic_load: 4588 case AtomicExpr::AO__atomic_load_n: 4589 case AtomicExpr::AO__atomic_load: 4590 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4591 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4592 4593 case AtomicExpr::AO__c11_atomic_store: 4594 case AtomicExpr::AO__opencl_atomic_store: 4595 case AtomicExpr::AO__atomic_store: 4596 case AtomicExpr::AO__atomic_store_n: 4597 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4598 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4599 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4600 4601 default: 4602 return true; 4603 } 4604 } 4605 4606 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4607 AtomicExpr::AtomicOp Op) { 4608 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4609 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4610 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4611 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4612 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4613 Op); 4614 } 4615 4616 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4617 SourceLocation RParenLoc, MultiExprArg Args, 4618 AtomicExpr::AtomicOp Op, 4619 AtomicArgumentOrder ArgOrder) { 4620 // All the non-OpenCL operations take one of the following forms. 4621 // The OpenCL operations take the __c11 forms with one extra argument for 4622 // synchronization scope. 4623 enum { 4624 // C __c11_atomic_init(A *, C) 4625 Init, 4626 4627 // C __c11_atomic_load(A *, int) 4628 Load, 4629 4630 // void __atomic_load(A *, CP, int) 4631 LoadCopy, 4632 4633 // void __atomic_store(A *, CP, int) 4634 Copy, 4635 4636 // C __c11_atomic_add(A *, M, int) 4637 Arithmetic, 4638 4639 // C __atomic_exchange_n(A *, CP, int) 4640 Xchg, 4641 4642 // void __atomic_exchange(A *, C *, CP, int) 4643 GNUXchg, 4644 4645 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4646 C11CmpXchg, 4647 4648 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4649 GNUCmpXchg 4650 } Form = Init; 4651 4652 const unsigned NumForm = GNUCmpXchg + 1; 4653 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4654 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4655 // where: 4656 // C is an appropriate type, 4657 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4658 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4659 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4660 // the int parameters are for orderings. 4661 4662 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4663 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4664 "need to update code for modified forms"); 4665 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4666 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4667 AtomicExpr::AO__atomic_load, 4668 "need to update code for modified C11 atomics"); 4669 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4670 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4671 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4672 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4673 IsOpenCL; 4674 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4675 Op == AtomicExpr::AO__atomic_store_n || 4676 Op == AtomicExpr::AO__atomic_exchange_n || 4677 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4678 bool IsAddSub = false; 4679 4680 switch (Op) { 4681 case AtomicExpr::AO__c11_atomic_init: 4682 case AtomicExpr::AO__opencl_atomic_init: 4683 Form = Init; 4684 break; 4685 4686 case AtomicExpr::AO__c11_atomic_load: 4687 case AtomicExpr::AO__opencl_atomic_load: 4688 case AtomicExpr::AO__atomic_load_n: 4689 Form = Load; 4690 break; 4691 4692 case AtomicExpr::AO__atomic_load: 4693 Form = LoadCopy; 4694 break; 4695 4696 case AtomicExpr::AO__c11_atomic_store: 4697 case AtomicExpr::AO__opencl_atomic_store: 4698 case AtomicExpr::AO__atomic_store: 4699 case AtomicExpr::AO__atomic_store_n: 4700 Form = Copy; 4701 break; 4702 4703 case AtomicExpr::AO__c11_atomic_fetch_add: 4704 case AtomicExpr::AO__c11_atomic_fetch_sub: 4705 case AtomicExpr::AO__opencl_atomic_fetch_add: 4706 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4707 case AtomicExpr::AO__atomic_fetch_add: 4708 case AtomicExpr::AO__atomic_fetch_sub: 4709 case AtomicExpr::AO__atomic_add_fetch: 4710 case AtomicExpr::AO__atomic_sub_fetch: 4711 IsAddSub = true; 4712 LLVM_FALLTHROUGH; 4713 case AtomicExpr::AO__c11_atomic_fetch_and: 4714 case AtomicExpr::AO__c11_atomic_fetch_or: 4715 case AtomicExpr::AO__c11_atomic_fetch_xor: 4716 case AtomicExpr::AO__opencl_atomic_fetch_and: 4717 case AtomicExpr::AO__opencl_atomic_fetch_or: 4718 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4719 case AtomicExpr::AO__atomic_fetch_and: 4720 case AtomicExpr::AO__atomic_fetch_or: 4721 case AtomicExpr::AO__atomic_fetch_xor: 4722 case AtomicExpr::AO__atomic_fetch_nand: 4723 case AtomicExpr::AO__atomic_and_fetch: 4724 case AtomicExpr::AO__atomic_or_fetch: 4725 case AtomicExpr::AO__atomic_xor_fetch: 4726 case AtomicExpr::AO__atomic_nand_fetch: 4727 case AtomicExpr::AO__c11_atomic_fetch_min: 4728 case AtomicExpr::AO__c11_atomic_fetch_max: 4729 case AtomicExpr::AO__opencl_atomic_fetch_min: 4730 case AtomicExpr::AO__opencl_atomic_fetch_max: 4731 case AtomicExpr::AO__atomic_min_fetch: 4732 case AtomicExpr::AO__atomic_max_fetch: 4733 case AtomicExpr::AO__atomic_fetch_min: 4734 case AtomicExpr::AO__atomic_fetch_max: 4735 Form = Arithmetic; 4736 break; 4737 4738 case AtomicExpr::AO__c11_atomic_exchange: 4739 case AtomicExpr::AO__opencl_atomic_exchange: 4740 case AtomicExpr::AO__atomic_exchange_n: 4741 Form = Xchg; 4742 break; 4743 4744 case AtomicExpr::AO__atomic_exchange: 4745 Form = GNUXchg; 4746 break; 4747 4748 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4749 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4750 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4751 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4752 Form = C11CmpXchg; 4753 break; 4754 4755 case AtomicExpr::AO__atomic_compare_exchange: 4756 case AtomicExpr::AO__atomic_compare_exchange_n: 4757 Form = GNUCmpXchg; 4758 break; 4759 } 4760 4761 unsigned AdjustedNumArgs = NumArgs[Form]; 4762 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4763 ++AdjustedNumArgs; 4764 // Check we have the right number of arguments. 4765 if (Args.size() < AdjustedNumArgs) { 4766 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4767 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4768 << ExprRange; 4769 return ExprError(); 4770 } else if (Args.size() > AdjustedNumArgs) { 4771 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4772 diag::err_typecheck_call_too_many_args) 4773 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4774 << ExprRange; 4775 return ExprError(); 4776 } 4777 4778 // Inspect the first argument of the atomic operation. 4779 Expr *Ptr = Args[0]; 4780 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4781 if (ConvertedPtr.isInvalid()) 4782 return ExprError(); 4783 4784 Ptr = ConvertedPtr.get(); 4785 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4786 if (!pointerType) { 4787 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4788 << Ptr->getType() << Ptr->getSourceRange(); 4789 return ExprError(); 4790 } 4791 4792 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4793 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4794 QualType ValType = AtomTy; // 'C' 4795 if (IsC11) { 4796 if (!AtomTy->isAtomicType()) { 4797 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4798 << Ptr->getType() << Ptr->getSourceRange(); 4799 return ExprError(); 4800 } 4801 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4802 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4803 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4804 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4805 << Ptr->getSourceRange(); 4806 return ExprError(); 4807 } 4808 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4809 } else if (Form != Load && Form != LoadCopy) { 4810 if (ValType.isConstQualified()) { 4811 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4812 << Ptr->getType() << Ptr->getSourceRange(); 4813 return ExprError(); 4814 } 4815 } 4816 4817 // For an arithmetic operation, the implied arithmetic must be well-formed. 4818 if (Form == Arithmetic) { 4819 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4820 if (IsAddSub && !ValType->isIntegerType() 4821 && !ValType->isPointerType()) { 4822 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4823 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4824 return ExprError(); 4825 } 4826 if (!IsAddSub && !ValType->isIntegerType()) { 4827 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4828 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4829 return ExprError(); 4830 } 4831 if (IsC11 && ValType->isPointerType() && 4832 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4833 diag::err_incomplete_type)) { 4834 return ExprError(); 4835 } 4836 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4837 // For __atomic_*_n operations, the value type must be a scalar integral or 4838 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4839 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4840 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4841 return ExprError(); 4842 } 4843 4844 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4845 !AtomTy->isScalarType()) { 4846 // For GNU atomics, require a trivially-copyable type. This is not part of 4847 // the GNU atomics specification, but we enforce it for sanity. 4848 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4849 << Ptr->getType() << Ptr->getSourceRange(); 4850 return ExprError(); 4851 } 4852 4853 switch (ValType.getObjCLifetime()) { 4854 case Qualifiers::OCL_None: 4855 case Qualifiers::OCL_ExplicitNone: 4856 // okay 4857 break; 4858 4859 case Qualifiers::OCL_Weak: 4860 case Qualifiers::OCL_Strong: 4861 case Qualifiers::OCL_Autoreleasing: 4862 // FIXME: Can this happen? By this point, ValType should be known 4863 // to be trivially copyable. 4864 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4865 << ValType << Ptr->getSourceRange(); 4866 return ExprError(); 4867 } 4868 4869 // All atomic operations have an overload which takes a pointer to a volatile 4870 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4871 // into the result or the other operands. Similarly atomic_load takes a 4872 // pointer to a const 'A'. 4873 ValType.removeLocalVolatile(); 4874 ValType.removeLocalConst(); 4875 QualType ResultType = ValType; 4876 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4877 Form == Init) 4878 ResultType = Context.VoidTy; 4879 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4880 ResultType = Context.BoolTy; 4881 4882 // The type of a parameter passed 'by value'. In the GNU atomics, such 4883 // arguments are actually passed as pointers. 4884 QualType ByValType = ValType; // 'CP' 4885 bool IsPassedByAddress = false; 4886 if (!IsC11 && !IsN) { 4887 ByValType = Ptr->getType(); 4888 IsPassedByAddress = true; 4889 } 4890 4891 SmallVector<Expr *, 5> APIOrderedArgs; 4892 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4893 APIOrderedArgs.push_back(Args[0]); 4894 switch (Form) { 4895 case Init: 4896 case Load: 4897 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4898 break; 4899 case LoadCopy: 4900 case Copy: 4901 case Arithmetic: 4902 case Xchg: 4903 APIOrderedArgs.push_back(Args[2]); // Val1 4904 APIOrderedArgs.push_back(Args[1]); // Order 4905 break; 4906 case GNUXchg: 4907 APIOrderedArgs.push_back(Args[2]); // Val1 4908 APIOrderedArgs.push_back(Args[3]); // Val2 4909 APIOrderedArgs.push_back(Args[1]); // Order 4910 break; 4911 case C11CmpXchg: 4912 APIOrderedArgs.push_back(Args[2]); // Val1 4913 APIOrderedArgs.push_back(Args[4]); // Val2 4914 APIOrderedArgs.push_back(Args[1]); // Order 4915 APIOrderedArgs.push_back(Args[3]); // OrderFail 4916 break; 4917 case GNUCmpXchg: 4918 APIOrderedArgs.push_back(Args[2]); // Val1 4919 APIOrderedArgs.push_back(Args[4]); // Val2 4920 APIOrderedArgs.push_back(Args[5]); // Weak 4921 APIOrderedArgs.push_back(Args[1]); // Order 4922 APIOrderedArgs.push_back(Args[3]); // OrderFail 4923 break; 4924 } 4925 } else 4926 APIOrderedArgs.append(Args.begin(), Args.end()); 4927 4928 // The first argument's non-CV pointer type is used to deduce the type of 4929 // subsequent arguments, except for: 4930 // - weak flag (always converted to bool) 4931 // - memory order (always converted to int) 4932 // - scope (always converted to int) 4933 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4934 QualType Ty; 4935 if (i < NumVals[Form] + 1) { 4936 switch (i) { 4937 case 0: 4938 // The first argument is always a pointer. It has a fixed type. 4939 // It is always dereferenced, a nullptr is undefined. 4940 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4941 // Nothing else to do: we already know all we want about this pointer. 4942 continue; 4943 case 1: 4944 // The second argument is the non-atomic operand. For arithmetic, this 4945 // is always passed by value, and for a compare_exchange it is always 4946 // passed by address. For the rest, GNU uses by-address and C11 uses 4947 // by-value. 4948 assert(Form != Load); 4949 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4950 Ty = ValType; 4951 else if (Form == Copy || Form == Xchg) { 4952 if (IsPassedByAddress) { 4953 // The value pointer is always dereferenced, a nullptr is undefined. 4954 CheckNonNullArgument(*this, APIOrderedArgs[i], 4955 ExprRange.getBegin()); 4956 } 4957 Ty = ByValType; 4958 } else if (Form == Arithmetic) 4959 Ty = Context.getPointerDiffType(); 4960 else { 4961 Expr *ValArg = APIOrderedArgs[i]; 4962 // The value pointer is always dereferenced, a nullptr is undefined. 4963 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4964 LangAS AS = LangAS::Default; 4965 // Keep address space of non-atomic pointer type. 4966 if (const PointerType *PtrTy = 4967 ValArg->getType()->getAs<PointerType>()) { 4968 AS = PtrTy->getPointeeType().getAddressSpace(); 4969 } 4970 Ty = Context.getPointerType( 4971 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4972 } 4973 break; 4974 case 2: 4975 // The third argument to compare_exchange / GNU exchange is the desired 4976 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4977 if (IsPassedByAddress) 4978 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4979 Ty = ByValType; 4980 break; 4981 case 3: 4982 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4983 Ty = Context.BoolTy; 4984 break; 4985 } 4986 } else { 4987 // The order(s) and scope are always converted to int. 4988 Ty = Context.IntTy; 4989 } 4990 4991 InitializedEntity Entity = 4992 InitializedEntity::InitializeParameter(Context, Ty, false); 4993 ExprResult Arg = APIOrderedArgs[i]; 4994 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4995 if (Arg.isInvalid()) 4996 return true; 4997 APIOrderedArgs[i] = Arg.get(); 4998 } 4999 5000 // Permute the arguments into a 'consistent' order. 5001 SmallVector<Expr*, 5> SubExprs; 5002 SubExprs.push_back(Ptr); 5003 switch (Form) { 5004 case Init: 5005 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5006 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5007 break; 5008 case Load: 5009 SubExprs.push_back(APIOrderedArgs[1]); // Order 5010 break; 5011 case LoadCopy: 5012 case Copy: 5013 case Arithmetic: 5014 case Xchg: 5015 SubExprs.push_back(APIOrderedArgs[2]); // Order 5016 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5017 break; 5018 case GNUXchg: 5019 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5020 SubExprs.push_back(APIOrderedArgs[3]); // Order 5021 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5022 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5023 break; 5024 case C11CmpXchg: 5025 SubExprs.push_back(APIOrderedArgs[3]); // Order 5026 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5027 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5028 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5029 break; 5030 case GNUCmpXchg: 5031 SubExprs.push_back(APIOrderedArgs[4]); // Order 5032 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5033 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5034 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5035 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5036 break; 5037 } 5038 5039 if (SubExprs.size() >= 2 && Form != Init) { 5040 if (Optional<llvm::APSInt> Result = 5041 SubExprs[1]->getIntegerConstantExpr(Context)) 5042 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5043 Diag(SubExprs[1]->getBeginLoc(), 5044 diag::warn_atomic_op_has_invalid_memory_order) 5045 << SubExprs[1]->getSourceRange(); 5046 } 5047 5048 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5049 auto *Scope = Args[Args.size() - 1]; 5050 if (Optional<llvm::APSInt> Result = 5051 Scope->getIntegerConstantExpr(Context)) { 5052 if (!ScopeModel->isValid(Result->getZExtValue())) 5053 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5054 << Scope->getSourceRange(); 5055 } 5056 SubExprs.push_back(Scope); 5057 } 5058 5059 AtomicExpr *AE = new (Context) 5060 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5061 5062 if ((Op == AtomicExpr::AO__c11_atomic_load || 5063 Op == AtomicExpr::AO__c11_atomic_store || 5064 Op == AtomicExpr::AO__opencl_atomic_load || 5065 Op == AtomicExpr::AO__opencl_atomic_store ) && 5066 Context.AtomicUsesUnsupportedLibcall(AE)) 5067 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5068 << ((Op == AtomicExpr::AO__c11_atomic_load || 5069 Op == AtomicExpr::AO__opencl_atomic_load) 5070 ? 0 5071 : 1); 5072 5073 if (ValType->isExtIntType()) { 5074 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5075 return ExprError(); 5076 } 5077 5078 return AE; 5079 } 5080 5081 /// checkBuiltinArgument - Given a call to a builtin function, perform 5082 /// normal type-checking on the given argument, updating the call in 5083 /// place. This is useful when a builtin function requires custom 5084 /// type-checking for some of its arguments but not necessarily all of 5085 /// them. 5086 /// 5087 /// Returns true on error. 5088 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5089 FunctionDecl *Fn = E->getDirectCallee(); 5090 assert(Fn && "builtin call without direct callee!"); 5091 5092 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5093 InitializedEntity Entity = 5094 InitializedEntity::InitializeParameter(S.Context, Param); 5095 5096 ExprResult Arg = E->getArg(0); 5097 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5098 if (Arg.isInvalid()) 5099 return true; 5100 5101 E->setArg(ArgIndex, Arg.get()); 5102 return false; 5103 } 5104 5105 /// We have a call to a function like __sync_fetch_and_add, which is an 5106 /// overloaded function based on the pointer type of its first argument. 5107 /// The main BuildCallExpr routines have already promoted the types of 5108 /// arguments because all of these calls are prototyped as void(...). 5109 /// 5110 /// This function goes through and does final semantic checking for these 5111 /// builtins, as well as generating any warnings. 5112 ExprResult 5113 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5114 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5115 Expr *Callee = TheCall->getCallee(); 5116 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5117 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5118 5119 // Ensure that we have at least one argument to do type inference from. 5120 if (TheCall->getNumArgs() < 1) { 5121 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5122 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5123 return ExprError(); 5124 } 5125 5126 // Inspect the first argument of the atomic builtin. This should always be 5127 // a pointer type, whose element is an integral scalar or pointer type. 5128 // Because it is a pointer type, we don't have to worry about any implicit 5129 // casts here. 5130 // FIXME: We don't allow floating point scalars as input. 5131 Expr *FirstArg = TheCall->getArg(0); 5132 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5133 if (FirstArgResult.isInvalid()) 5134 return ExprError(); 5135 FirstArg = FirstArgResult.get(); 5136 TheCall->setArg(0, FirstArg); 5137 5138 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5139 if (!pointerType) { 5140 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5141 << FirstArg->getType() << FirstArg->getSourceRange(); 5142 return ExprError(); 5143 } 5144 5145 QualType ValType = pointerType->getPointeeType(); 5146 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5147 !ValType->isBlockPointerType()) { 5148 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5149 << FirstArg->getType() << FirstArg->getSourceRange(); 5150 return ExprError(); 5151 } 5152 5153 if (ValType.isConstQualified()) { 5154 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5155 << FirstArg->getType() << FirstArg->getSourceRange(); 5156 return ExprError(); 5157 } 5158 5159 switch (ValType.getObjCLifetime()) { 5160 case Qualifiers::OCL_None: 5161 case Qualifiers::OCL_ExplicitNone: 5162 // okay 5163 break; 5164 5165 case Qualifiers::OCL_Weak: 5166 case Qualifiers::OCL_Strong: 5167 case Qualifiers::OCL_Autoreleasing: 5168 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5169 << ValType << FirstArg->getSourceRange(); 5170 return ExprError(); 5171 } 5172 5173 // Strip any qualifiers off ValType. 5174 ValType = ValType.getUnqualifiedType(); 5175 5176 // The majority of builtins return a value, but a few have special return 5177 // types, so allow them to override appropriately below. 5178 QualType ResultType = ValType; 5179 5180 // We need to figure out which concrete builtin this maps onto. For example, 5181 // __sync_fetch_and_add with a 2 byte object turns into 5182 // __sync_fetch_and_add_2. 5183 #define BUILTIN_ROW(x) \ 5184 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5185 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5186 5187 static const unsigned BuiltinIndices[][5] = { 5188 BUILTIN_ROW(__sync_fetch_and_add), 5189 BUILTIN_ROW(__sync_fetch_and_sub), 5190 BUILTIN_ROW(__sync_fetch_and_or), 5191 BUILTIN_ROW(__sync_fetch_and_and), 5192 BUILTIN_ROW(__sync_fetch_and_xor), 5193 BUILTIN_ROW(__sync_fetch_and_nand), 5194 5195 BUILTIN_ROW(__sync_add_and_fetch), 5196 BUILTIN_ROW(__sync_sub_and_fetch), 5197 BUILTIN_ROW(__sync_and_and_fetch), 5198 BUILTIN_ROW(__sync_or_and_fetch), 5199 BUILTIN_ROW(__sync_xor_and_fetch), 5200 BUILTIN_ROW(__sync_nand_and_fetch), 5201 5202 BUILTIN_ROW(__sync_val_compare_and_swap), 5203 BUILTIN_ROW(__sync_bool_compare_and_swap), 5204 BUILTIN_ROW(__sync_lock_test_and_set), 5205 BUILTIN_ROW(__sync_lock_release), 5206 BUILTIN_ROW(__sync_swap) 5207 }; 5208 #undef BUILTIN_ROW 5209 5210 // Determine the index of the size. 5211 unsigned SizeIndex; 5212 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5213 case 1: SizeIndex = 0; break; 5214 case 2: SizeIndex = 1; break; 5215 case 4: SizeIndex = 2; break; 5216 case 8: SizeIndex = 3; break; 5217 case 16: SizeIndex = 4; break; 5218 default: 5219 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5220 << FirstArg->getType() << FirstArg->getSourceRange(); 5221 return ExprError(); 5222 } 5223 5224 // Each of these builtins has one pointer argument, followed by some number of 5225 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5226 // that we ignore. Find out which row of BuiltinIndices to read from as well 5227 // as the number of fixed args. 5228 unsigned BuiltinID = FDecl->getBuiltinID(); 5229 unsigned BuiltinIndex, NumFixed = 1; 5230 bool WarnAboutSemanticsChange = false; 5231 switch (BuiltinID) { 5232 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5233 case Builtin::BI__sync_fetch_and_add: 5234 case Builtin::BI__sync_fetch_and_add_1: 5235 case Builtin::BI__sync_fetch_and_add_2: 5236 case Builtin::BI__sync_fetch_and_add_4: 5237 case Builtin::BI__sync_fetch_and_add_8: 5238 case Builtin::BI__sync_fetch_and_add_16: 5239 BuiltinIndex = 0; 5240 break; 5241 5242 case Builtin::BI__sync_fetch_and_sub: 5243 case Builtin::BI__sync_fetch_and_sub_1: 5244 case Builtin::BI__sync_fetch_and_sub_2: 5245 case Builtin::BI__sync_fetch_and_sub_4: 5246 case Builtin::BI__sync_fetch_and_sub_8: 5247 case Builtin::BI__sync_fetch_and_sub_16: 5248 BuiltinIndex = 1; 5249 break; 5250 5251 case Builtin::BI__sync_fetch_and_or: 5252 case Builtin::BI__sync_fetch_and_or_1: 5253 case Builtin::BI__sync_fetch_and_or_2: 5254 case Builtin::BI__sync_fetch_and_or_4: 5255 case Builtin::BI__sync_fetch_and_or_8: 5256 case Builtin::BI__sync_fetch_and_or_16: 5257 BuiltinIndex = 2; 5258 break; 5259 5260 case Builtin::BI__sync_fetch_and_and: 5261 case Builtin::BI__sync_fetch_and_and_1: 5262 case Builtin::BI__sync_fetch_and_and_2: 5263 case Builtin::BI__sync_fetch_and_and_4: 5264 case Builtin::BI__sync_fetch_and_and_8: 5265 case Builtin::BI__sync_fetch_and_and_16: 5266 BuiltinIndex = 3; 5267 break; 5268 5269 case Builtin::BI__sync_fetch_and_xor: 5270 case Builtin::BI__sync_fetch_and_xor_1: 5271 case Builtin::BI__sync_fetch_and_xor_2: 5272 case Builtin::BI__sync_fetch_and_xor_4: 5273 case Builtin::BI__sync_fetch_and_xor_8: 5274 case Builtin::BI__sync_fetch_and_xor_16: 5275 BuiltinIndex = 4; 5276 break; 5277 5278 case Builtin::BI__sync_fetch_and_nand: 5279 case Builtin::BI__sync_fetch_and_nand_1: 5280 case Builtin::BI__sync_fetch_and_nand_2: 5281 case Builtin::BI__sync_fetch_and_nand_4: 5282 case Builtin::BI__sync_fetch_and_nand_8: 5283 case Builtin::BI__sync_fetch_and_nand_16: 5284 BuiltinIndex = 5; 5285 WarnAboutSemanticsChange = true; 5286 break; 5287 5288 case Builtin::BI__sync_add_and_fetch: 5289 case Builtin::BI__sync_add_and_fetch_1: 5290 case Builtin::BI__sync_add_and_fetch_2: 5291 case Builtin::BI__sync_add_and_fetch_4: 5292 case Builtin::BI__sync_add_and_fetch_8: 5293 case Builtin::BI__sync_add_and_fetch_16: 5294 BuiltinIndex = 6; 5295 break; 5296 5297 case Builtin::BI__sync_sub_and_fetch: 5298 case Builtin::BI__sync_sub_and_fetch_1: 5299 case Builtin::BI__sync_sub_and_fetch_2: 5300 case Builtin::BI__sync_sub_and_fetch_4: 5301 case Builtin::BI__sync_sub_and_fetch_8: 5302 case Builtin::BI__sync_sub_and_fetch_16: 5303 BuiltinIndex = 7; 5304 break; 5305 5306 case Builtin::BI__sync_and_and_fetch: 5307 case Builtin::BI__sync_and_and_fetch_1: 5308 case Builtin::BI__sync_and_and_fetch_2: 5309 case Builtin::BI__sync_and_and_fetch_4: 5310 case Builtin::BI__sync_and_and_fetch_8: 5311 case Builtin::BI__sync_and_and_fetch_16: 5312 BuiltinIndex = 8; 5313 break; 5314 5315 case Builtin::BI__sync_or_and_fetch: 5316 case Builtin::BI__sync_or_and_fetch_1: 5317 case Builtin::BI__sync_or_and_fetch_2: 5318 case Builtin::BI__sync_or_and_fetch_4: 5319 case Builtin::BI__sync_or_and_fetch_8: 5320 case Builtin::BI__sync_or_and_fetch_16: 5321 BuiltinIndex = 9; 5322 break; 5323 5324 case Builtin::BI__sync_xor_and_fetch: 5325 case Builtin::BI__sync_xor_and_fetch_1: 5326 case Builtin::BI__sync_xor_and_fetch_2: 5327 case Builtin::BI__sync_xor_and_fetch_4: 5328 case Builtin::BI__sync_xor_and_fetch_8: 5329 case Builtin::BI__sync_xor_and_fetch_16: 5330 BuiltinIndex = 10; 5331 break; 5332 5333 case Builtin::BI__sync_nand_and_fetch: 5334 case Builtin::BI__sync_nand_and_fetch_1: 5335 case Builtin::BI__sync_nand_and_fetch_2: 5336 case Builtin::BI__sync_nand_and_fetch_4: 5337 case Builtin::BI__sync_nand_and_fetch_8: 5338 case Builtin::BI__sync_nand_and_fetch_16: 5339 BuiltinIndex = 11; 5340 WarnAboutSemanticsChange = true; 5341 break; 5342 5343 case Builtin::BI__sync_val_compare_and_swap: 5344 case Builtin::BI__sync_val_compare_and_swap_1: 5345 case Builtin::BI__sync_val_compare_and_swap_2: 5346 case Builtin::BI__sync_val_compare_and_swap_4: 5347 case Builtin::BI__sync_val_compare_and_swap_8: 5348 case Builtin::BI__sync_val_compare_and_swap_16: 5349 BuiltinIndex = 12; 5350 NumFixed = 2; 5351 break; 5352 5353 case Builtin::BI__sync_bool_compare_and_swap: 5354 case Builtin::BI__sync_bool_compare_and_swap_1: 5355 case Builtin::BI__sync_bool_compare_and_swap_2: 5356 case Builtin::BI__sync_bool_compare_and_swap_4: 5357 case Builtin::BI__sync_bool_compare_and_swap_8: 5358 case Builtin::BI__sync_bool_compare_and_swap_16: 5359 BuiltinIndex = 13; 5360 NumFixed = 2; 5361 ResultType = Context.BoolTy; 5362 break; 5363 5364 case Builtin::BI__sync_lock_test_and_set: 5365 case Builtin::BI__sync_lock_test_and_set_1: 5366 case Builtin::BI__sync_lock_test_and_set_2: 5367 case Builtin::BI__sync_lock_test_and_set_4: 5368 case Builtin::BI__sync_lock_test_and_set_8: 5369 case Builtin::BI__sync_lock_test_and_set_16: 5370 BuiltinIndex = 14; 5371 break; 5372 5373 case Builtin::BI__sync_lock_release: 5374 case Builtin::BI__sync_lock_release_1: 5375 case Builtin::BI__sync_lock_release_2: 5376 case Builtin::BI__sync_lock_release_4: 5377 case Builtin::BI__sync_lock_release_8: 5378 case Builtin::BI__sync_lock_release_16: 5379 BuiltinIndex = 15; 5380 NumFixed = 0; 5381 ResultType = Context.VoidTy; 5382 break; 5383 5384 case Builtin::BI__sync_swap: 5385 case Builtin::BI__sync_swap_1: 5386 case Builtin::BI__sync_swap_2: 5387 case Builtin::BI__sync_swap_4: 5388 case Builtin::BI__sync_swap_8: 5389 case Builtin::BI__sync_swap_16: 5390 BuiltinIndex = 16; 5391 break; 5392 } 5393 5394 // Now that we know how many fixed arguments we expect, first check that we 5395 // have at least that many. 5396 if (TheCall->getNumArgs() < 1+NumFixed) { 5397 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5398 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5399 << Callee->getSourceRange(); 5400 return ExprError(); 5401 } 5402 5403 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5404 << Callee->getSourceRange(); 5405 5406 if (WarnAboutSemanticsChange) { 5407 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5408 << Callee->getSourceRange(); 5409 } 5410 5411 // Get the decl for the concrete builtin from this, we can tell what the 5412 // concrete integer type we should convert to is. 5413 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5414 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5415 FunctionDecl *NewBuiltinDecl; 5416 if (NewBuiltinID == BuiltinID) 5417 NewBuiltinDecl = FDecl; 5418 else { 5419 // Perform builtin lookup to avoid redeclaring it. 5420 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5421 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5422 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5423 assert(Res.getFoundDecl()); 5424 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5425 if (!NewBuiltinDecl) 5426 return ExprError(); 5427 } 5428 5429 // The first argument --- the pointer --- has a fixed type; we 5430 // deduce the types of the rest of the arguments accordingly. Walk 5431 // the remaining arguments, converting them to the deduced value type. 5432 for (unsigned i = 0; i != NumFixed; ++i) { 5433 ExprResult Arg = TheCall->getArg(i+1); 5434 5435 // GCC does an implicit conversion to the pointer or integer ValType. This 5436 // can fail in some cases (1i -> int**), check for this error case now. 5437 // Initialize the argument. 5438 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5439 ValType, /*consume*/ false); 5440 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5441 if (Arg.isInvalid()) 5442 return ExprError(); 5443 5444 // Okay, we have something that *can* be converted to the right type. Check 5445 // to see if there is a potentially weird extension going on here. This can 5446 // happen when you do an atomic operation on something like an char* and 5447 // pass in 42. The 42 gets converted to char. This is even more strange 5448 // for things like 45.123 -> char, etc. 5449 // FIXME: Do this check. 5450 TheCall->setArg(i+1, Arg.get()); 5451 } 5452 5453 // Create a new DeclRefExpr to refer to the new decl. 5454 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5455 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5456 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5457 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5458 5459 // Set the callee in the CallExpr. 5460 // FIXME: This loses syntactic information. 5461 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5462 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5463 CK_BuiltinFnToFnPtr); 5464 TheCall->setCallee(PromotedCall.get()); 5465 5466 // Change the result type of the call to match the original value type. This 5467 // is arbitrary, but the codegen for these builtins ins design to handle it 5468 // gracefully. 5469 TheCall->setType(ResultType); 5470 5471 // Prohibit use of _ExtInt with atomic builtins. 5472 // The arguments would have already been converted to the first argument's 5473 // type, so only need to check the first argument. 5474 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5475 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5476 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5477 return ExprError(); 5478 } 5479 5480 return TheCallResult; 5481 } 5482 5483 /// SemaBuiltinNontemporalOverloaded - We have a call to 5484 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5485 /// overloaded function based on the pointer type of its last argument. 5486 /// 5487 /// This function goes through and does final semantic checking for these 5488 /// builtins. 5489 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5490 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5491 DeclRefExpr *DRE = 5492 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5493 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5494 unsigned BuiltinID = FDecl->getBuiltinID(); 5495 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5496 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5497 "Unexpected nontemporal load/store builtin!"); 5498 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5499 unsigned numArgs = isStore ? 2 : 1; 5500 5501 // Ensure that we have the proper number of arguments. 5502 if (checkArgCount(*this, TheCall, numArgs)) 5503 return ExprError(); 5504 5505 // Inspect the last argument of the nontemporal builtin. This should always 5506 // be a pointer type, from which we imply the type of the memory access. 5507 // Because it is a pointer type, we don't have to worry about any implicit 5508 // casts here. 5509 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5510 ExprResult PointerArgResult = 5511 DefaultFunctionArrayLvalueConversion(PointerArg); 5512 5513 if (PointerArgResult.isInvalid()) 5514 return ExprError(); 5515 PointerArg = PointerArgResult.get(); 5516 TheCall->setArg(numArgs - 1, PointerArg); 5517 5518 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5519 if (!pointerType) { 5520 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5521 << PointerArg->getType() << PointerArg->getSourceRange(); 5522 return ExprError(); 5523 } 5524 5525 QualType ValType = pointerType->getPointeeType(); 5526 5527 // Strip any qualifiers off ValType. 5528 ValType = ValType.getUnqualifiedType(); 5529 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5530 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5531 !ValType->isVectorType()) { 5532 Diag(DRE->getBeginLoc(), 5533 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5534 << PointerArg->getType() << PointerArg->getSourceRange(); 5535 return ExprError(); 5536 } 5537 5538 if (!isStore) { 5539 TheCall->setType(ValType); 5540 return TheCallResult; 5541 } 5542 5543 ExprResult ValArg = TheCall->getArg(0); 5544 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5545 Context, ValType, /*consume*/ false); 5546 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5547 if (ValArg.isInvalid()) 5548 return ExprError(); 5549 5550 TheCall->setArg(0, ValArg.get()); 5551 TheCall->setType(Context.VoidTy); 5552 return TheCallResult; 5553 } 5554 5555 /// CheckObjCString - Checks that the argument to the builtin 5556 /// CFString constructor is correct 5557 /// Note: It might also make sense to do the UTF-16 conversion here (would 5558 /// simplify the backend). 5559 bool Sema::CheckObjCString(Expr *Arg) { 5560 Arg = Arg->IgnoreParenCasts(); 5561 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5562 5563 if (!Literal || !Literal->isAscii()) { 5564 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5565 << Arg->getSourceRange(); 5566 return true; 5567 } 5568 5569 if (Literal->containsNonAsciiOrNull()) { 5570 StringRef String = Literal->getString(); 5571 unsigned NumBytes = String.size(); 5572 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5573 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5574 llvm::UTF16 *ToPtr = &ToBuf[0]; 5575 5576 llvm::ConversionResult Result = 5577 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5578 ToPtr + NumBytes, llvm::strictConversion); 5579 // Check for conversion failure. 5580 if (Result != llvm::conversionOK) 5581 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5582 << Arg->getSourceRange(); 5583 } 5584 return false; 5585 } 5586 5587 /// CheckObjCString - Checks that the format string argument to the os_log() 5588 /// and os_trace() functions is correct, and converts it to const char *. 5589 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5590 Arg = Arg->IgnoreParenCasts(); 5591 auto *Literal = dyn_cast<StringLiteral>(Arg); 5592 if (!Literal) { 5593 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5594 Literal = ObjcLiteral->getString(); 5595 } 5596 } 5597 5598 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5599 return ExprError( 5600 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5601 << Arg->getSourceRange()); 5602 } 5603 5604 ExprResult Result(Literal); 5605 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5606 InitializedEntity Entity = 5607 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5608 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5609 return Result; 5610 } 5611 5612 /// Check that the user is calling the appropriate va_start builtin for the 5613 /// target and calling convention. 5614 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5615 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5616 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5617 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5618 TT.getArch() == llvm::Triple::aarch64_32); 5619 bool IsWindows = TT.isOSWindows(); 5620 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5621 if (IsX64 || IsAArch64) { 5622 CallingConv CC = CC_C; 5623 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5624 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5625 if (IsMSVAStart) { 5626 // Don't allow this in System V ABI functions. 5627 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5628 return S.Diag(Fn->getBeginLoc(), 5629 diag::err_ms_va_start_used_in_sysv_function); 5630 } else { 5631 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5632 // On x64 Windows, don't allow this in System V ABI functions. 5633 // (Yes, that means there's no corresponding way to support variadic 5634 // System V ABI functions on Windows.) 5635 if ((IsWindows && CC == CC_X86_64SysV) || 5636 (!IsWindows && CC == CC_Win64)) 5637 return S.Diag(Fn->getBeginLoc(), 5638 diag::err_va_start_used_in_wrong_abi_function) 5639 << !IsWindows; 5640 } 5641 return false; 5642 } 5643 5644 if (IsMSVAStart) 5645 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5646 return false; 5647 } 5648 5649 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5650 ParmVarDecl **LastParam = nullptr) { 5651 // Determine whether the current function, block, or obj-c method is variadic 5652 // and get its parameter list. 5653 bool IsVariadic = false; 5654 ArrayRef<ParmVarDecl *> Params; 5655 DeclContext *Caller = S.CurContext; 5656 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5657 IsVariadic = Block->isVariadic(); 5658 Params = Block->parameters(); 5659 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5660 IsVariadic = FD->isVariadic(); 5661 Params = FD->parameters(); 5662 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5663 IsVariadic = MD->isVariadic(); 5664 // FIXME: This isn't correct for methods (results in bogus warning). 5665 Params = MD->parameters(); 5666 } else if (isa<CapturedDecl>(Caller)) { 5667 // We don't support va_start in a CapturedDecl. 5668 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5669 return true; 5670 } else { 5671 // This must be some other declcontext that parses exprs. 5672 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5673 return true; 5674 } 5675 5676 if (!IsVariadic) { 5677 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5678 return true; 5679 } 5680 5681 if (LastParam) 5682 *LastParam = Params.empty() ? nullptr : Params.back(); 5683 5684 return false; 5685 } 5686 5687 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5688 /// for validity. Emit an error and return true on failure; return false 5689 /// on success. 5690 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5691 Expr *Fn = TheCall->getCallee(); 5692 5693 if (checkVAStartABI(*this, BuiltinID, Fn)) 5694 return true; 5695 5696 if (checkArgCount(*this, TheCall, 2)) 5697 return true; 5698 5699 // Type-check the first argument normally. 5700 if (checkBuiltinArgument(*this, TheCall, 0)) 5701 return true; 5702 5703 // Check that the current function is variadic, and get its last parameter. 5704 ParmVarDecl *LastParam; 5705 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5706 return true; 5707 5708 // Verify that the second argument to the builtin is the last argument of the 5709 // current function or method. 5710 bool SecondArgIsLastNamedArgument = false; 5711 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5712 5713 // These are valid if SecondArgIsLastNamedArgument is false after the next 5714 // block. 5715 QualType Type; 5716 SourceLocation ParamLoc; 5717 bool IsCRegister = false; 5718 5719 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5720 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5721 SecondArgIsLastNamedArgument = PV == LastParam; 5722 5723 Type = PV->getType(); 5724 ParamLoc = PV->getLocation(); 5725 IsCRegister = 5726 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5727 } 5728 } 5729 5730 if (!SecondArgIsLastNamedArgument) 5731 Diag(TheCall->getArg(1)->getBeginLoc(), 5732 diag::warn_second_arg_of_va_start_not_last_named_param); 5733 else if (IsCRegister || Type->isReferenceType() || 5734 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5735 // Promotable integers are UB, but enumerations need a bit of 5736 // extra checking to see what their promotable type actually is. 5737 if (!Type->isPromotableIntegerType()) 5738 return false; 5739 if (!Type->isEnumeralType()) 5740 return true; 5741 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5742 return !(ED && 5743 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5744 }()) { 5745 unsigned Reason = 0; 5746 if (Type->isReferenceType()) Reason = 1; 5747 else if (IsCRegister) Reason = 2; 5748 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5749 Diag(ParamLoc, diag::note_parameter_type) << Type; 5750 } 5751 5752 TheCall->setType(Context.VoidTy); 5753 return false; 5754 } 5755 5756 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5757 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5758 // const char *named_addr); 5759 5760 Expr *Func = Call->getCallee(); 5761 5762 if (Call->getNumArgs() < 3) 5763 return Diag(Call->getEndLoc(), 5764 diag::err_typecheck_call_too_few_args_at_least) 5765 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5766 5767 // Type-check the first argument normally. 5768 if (checkBuiltinArgument(*this, Call, 0)) 5769 return true; 5770 5771 // Check that the current function is variadic. 5772 if (checkVAStartIsInVariadicFunction(*this, Func)) 5773 return true; 5774 5775 // __va_start on Windows does not validate the parameter qualifiers 5776 5777 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5778 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5779 5780 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5781 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5782 5783 const QualType &ConstCharPtrTy = 5784 Context.getPointerType(Context.CharTy.withConst()); 5785 if (!Arg1Ty->isPointerType() || 5786 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5787 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5788 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5789 << 0 /* qualifier difference */ 5790 << 3 /* parameter mismatch */ 5791 << 2 << Arg1->getType() << ConstCharPtrTy; 5792 5793 const QualType SizeTy = Context.getSizeType(); 5794 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5795 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5796 << Arg2->getType() << SizeTy << 1 /* different class */ 5797 << 0 /* qualifier difference */ 5798 << 3 /* parameter mismatch */ 5799 << 3 << Arg2->getType() << SizeTy; 5800 5801 return false; 5802 } 5803 5804 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5805 /// friends. This is declared to take (...), so we have to check everything. 5806 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5807 if (checkArgCount(*this, TheCall, 2)) 5808 return true; 5809 5810 ExprResult OrigArg0 = TheCall->getArg(0); 5811 ExprResult OrigArg1 = TheCall->getArg(1); 5812 5813 // Do standard promotions between the two arguments, returning their common 5814 // type. 5815 QualType Res = UsualArithmeticConversions( 5816 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5817 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5818 return true; 5819 5820 // Make sure any conversions are pushed back into the call; this is 5821 // type safe since unordered compare builtins are declared as "_Bool 5822 // foo(...)". 5823 TheCall->setArg(0, OrigArg0.get()); 5824 TheCall->setArg(1, OrigArg1.get()); 5825 5826 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5827 return false; 5828 5829 // If the common type isn't a real floating type, then the arguments were 5830 // invalid for this operation. 5831 if (Res.isNull() || !Res->isRealFloatingType()) 5832 return Diag(OrigArg0.get()->getBeginLoc(), 5833 diag::err_typecheck_call_invalid_ordered_compare) 5834 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5835 << SourceRange(OrigArg0.get()->getBeginLoc(), 5836 OrigArg1.get()->getEndLoc()); 5837 5838 return false; 5839 } 5840 5841 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5842 /// __builtin_isnan and friends. This is declared to take (...), so we have 5843 /// to check everything. We expect the last argument to be a floating point 5844 /// value. 5845 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5846 if (checkArgCount(*this, TheCall, NumArgs)) 5847 return true; 5848 5849 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5850 // on all preceding parameters just being int. Try all of those. 5851 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5852 Expr *Arg = TheCall->getArg(i); 5853 5854 if (Arg->isTypeDependent()) 5855 return false; 5856 5857 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5858 5859 if (Res.isInvalid()) 5860 return true; 5861 TheCall->setArg(i, Res.get()); 5862 } 5863 5864 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5865 5866 if (OrigArg->isTypeDependent()) 5867 return false; 5868 5869 // Usual Unary Conversions will convert half to float, which we want for 5870 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5871 // type how it is, but do normal L->Rvalue conversions. 5872 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5873 OrigArg = UsualUnaryConversions(OrigArg).get(); 5874 else 5875 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5876 TheCall->setArg(NumArgs - 1, OrigArg); 5877 5878 // This operation requires a non-_Complex floating-point number. 5879 if (!OrigArg->getType()->isRealFloatingType()) 5880 return Diag(OrigArg->getBeginLoc(), 5881 diag::err_typecheck_call_invalid_unary_fp) 5882 << OrigArg->getType() << OrigArg->getSourceRange(); 5883 5884 return false; 5885 } 5886 5887 /// Perform semantic analysis for a call to __builtin_complex. 5888 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5889 if (checkArgCount(*this, TheCall, 2)) 5890 return true; 5891 5892 bool Dependent = false; 5893 for (unsigned I = 0; I != 2; ++I) { 5894 Expr *Arg = TheCall->getArg(I); 5895 QualType T = Arg->getType(); 5896 if (T->isDependentType()) { 5897 Dependent = true; 5898 continue; 5899 } 5900 5901 // Despite supporting _Complex int, GCC requires a real floating point type 5902 // for the operands of __builtin_complex. 5903 if (!T->isRealFloatingType()) { 5904 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5905 << Arg->getType() << Arg->getSourceRange(); 5906 } 5907 5908 ExprResult Converted = DefaultLvalueConversion(Arg); 5909 if (Converted.isInvalid()) 5910 return true; 5911 TheCall->setArg(I, Converted.get()); 5912 } 5913 5914 if (Dependent) { 5915 TheCall->setType(Context.DependentTy); 5916 return false; 5917 } 5918 5919 Expr *Real = TheCall->getArg(0); 5920 Expr *Imag = TheCall->getArg(1); 5921 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 5922 return Diag(Real->getBeginLoc(), 5923 diag::err_typecheck_call_different_arg_types) 5924 << Real->getType() << Imag->getType() 5925 << Real->getSourceRange() << Imag->getSourceRange(); 5926 } 5927 5928 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 5929 // don't allow this builtin to form those types either. 5930 // FIXME: Should we allow these types? 5931 if (Real->getType()->isFloat16Type()) 5932 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5933 << "_Float16"; 5934 if (Real->getType()->isHalfType()) 5935 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5936 << "half"; 5937 5938 TheCall->setType(Context.getComplexType(Real->getType())); 5939 return false; 5940 } 5941 5942 // Customized Sema Checking for VSX builtins that have the following signature: 5943 // vector [...] builtinName(vector [...], vector [...], const int); 5944 // Which takes the same type of vectors (any legal vector type) for the first 5945 // two arguments and takes compile time constant for the third argument. 5946 // Example builtins are : 5947 // vector double vec_xxpermdi(vector double, vector double, int); 5948 // vector short vec_xxsldwi(vector short, vector short, int); 5949 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5950 unsigned ExpectedNumArgs = 3; 5951 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 5952 return true; 5953 5954 // Check the third argument is a compile time constant 5955 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 5956 return Diag(TheCall->getBeginLoc(), 5957 diag::err_vsx_builtin_nonconstant_argument) 5958 << 3 /* argument index */ << TheCall->getDirectCallee() 5959 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5960 TheCall->getArg(2)->getEndLoc()); 5961 5962 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5963 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5964 5965 // Check the type of argument 1 and argument 2 are vectors. 5966 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5967 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5968 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5969 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5970 << TheCall->getDirectCallee() 5971 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5972 TheCall->getArg(1)->getEndLoc()); 5973 } 5974 5975 // Check the first two arguments are the same type. 5976 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5977 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5978 << TheCall->getDirectCallee() 5979 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5980 TheCall->getArg(1)->getEndLoc()); 5981 } 5982 5983 // When default clang type checking is turned off and the customized type 5984 // checking is used, the returning type of the function must be explicitly 5985 // set. Otherwise it is _Bool by default. 5986 TheCall->setType(Arg1Ty); 5987 5988 return false; 5989 } 5990 5991 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5992 // This is declared to take (...), so we have to check everything. 5993 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5994 if (TheCall->getNumArgs() < 2) 5995 return ExprError(Diag(TheCall->getEndLoc(), 5996 diag::err_typecheck_call_too_few_args_at_least) 5997 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5998 << TheCall->getSourceRange()); 5999 6000 // Determine which of the following types of shufflevector we're checking: 6001 // 1) unary, vector mask: (lhs, mask) 6002 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6003 QualType resType = TheCall->getArg(0)->getType(); 6004 unsigned numElements = 0; 6005 6006 if (!TheCall->getArg(0)->isTypeDependent() && 6007 !TheCall->getArg(1)->isTypeDependent()) { 6008 QualType LHSType = TheCall->getArg(0)->getType(); 6009 QualType RHSType = TheCall->getArg(1)->getType(); 6010 6011 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6012 return ExprError( 6013 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6014 << TheCall->getDirectCallee() 6015 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6016 TheCall->getArg(1)->getEndLoc())); 6017 6018 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6019 unsigned numResElements = TheCall->getNumArgs() - 2; 6020 6021 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6022 // with mask. If so, verify that RHS is an integer vector type with the 6023 // same number of elts as lhs. 6024 if (TheCall->getNumArgs() == 2) { 6025 if (!RHSType->hasIntegerRepresentation() || 6026 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6027 return ExprError(Diag(TheCall->getBeginLoc(), 6028 diag::err_vec_builtin_incompatible_vector) 6029 << TheCall->getDirectCallee() 6030 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6031 TheCall->getArg(1)->getEndLoc())); 6032 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6033 return ExprError(Diag(TheCall->getBeginLoc(), 6034 diag::err_vec_builtin_incompatible_vector) 6035 << TheCall->getDirectCallee() 6036 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6037 TheCall->getArg(1)->getEndLoc())); 6038 } else if (numElements != numResElements) { 6039 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6040 resType = Context.getVectorType(eltType, numResElements, 6041 VectorType::GenericVector); 6042 } 6043 } 6044 6045 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6046 if (TheCall->getArg(i)->isTypeDependent() || 6047 TheCall->getArg(i)->isValueDependent()) 6048 continue; 6049 6050 Optional<llvm::APSInt> Result; 6051 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6052 return ExprError(Diag(TheCall->getBeginLoc(), 6053 diag::err_shufflevector_nonconstant_argument) 6054 << TheCall->getArg(i)->getSourceRange()); 6055 6056 // Allow -1 which will be translated to undef in the IR. 6057 if (Result->isSigned() && Result->isAllOnesValue()) 6058 continue; 6059 6060 if (Result->getActiveBits() > 64 || 6061 Result->getZExtValue() >= numElements * 2) 6062 return ExprError(Diag(TheCall->getBeginLoc(), 6063 diag::err_shufflevector_argument_too_large) 6064 << TheCall->getArg(i)->getSourceRange()); 6065 } 6066 6067 SmallVector<Expr*, 32> exprs; 6068 6069 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6070 exprs.push_back(TheCall->getArg(i)); 6071 TheCall->setArg(i, nullptr); 6072 } 6073 6074 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6075 TheCall->getCallee()->getBeginLoc(), 6076 TheCall->getRParenLoc()); 6077 } 6078 6079 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6080 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6081 SourceLocation BuiltinLoc, 6082 SourceLocation RParenLoc) { 6083 ExprValueKind VK = VK_RValue; 6084 ExprObjectKind OK = OK_Ordinary; 6085 QualType DstTy = TInfo->getType(); 6086 QualType SrcTy = E->getType(); 6087 6088 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6089 return ExprError(Diag(BuiltinLoc, 6090 diag::err_convertvector_non_vector) 6091 << E->getSourceRange()); 6092 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6093 return ExprError(Diag(BuiltinLoc, 6094 diag::err_convertvector_non_vector_type)); 6095 6096 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6097 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6098 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6099 if (SrcElts != DstElts) 6100 return ExprError(Diag(BuiltinLoc, 6101 diag::err_convertvector_incompatible_vector) 6102 << E->getSourceRange()); 6103 } 6104 6105 return new (Context) 6106 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6107 } 6108 6109 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6110 // This is declared to take (const void*, ...) and can take two 6111 // optional constant int args. 6112 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6113 unsigned NumArgs = TheCall->getNumArgs(); 6114 6115 if (NumArgs > 3) 6116 return Diag(TheCall->getEndLoc(), 6117 diag::err_typecheck_call_too_many_args_at_most) 6118 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6119 6120 // Argument 0 is checked for us and the remaining arguments must be 6121 // constant integers. 6122 for (unsigned i = 1; i != NumArgs; ++i) 6123 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6124 return true; 6125 6126 return false; 6127 } 6128 6129 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6130 // __assume does not evaluate its arguments, and should warn if its argument 6131 // has side effects. 6132 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6133 Expr *Arg = TheCall->getArg(0); 6134 if (Arg->isInstantiationDependent()) return false; 6135 6136 if (Arg->HasSideEffects(Context)) 6137 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6138 << Arg->getSourceRange() 6139 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6140 6141 return false; 6142 } 6143 6144 /// Handle __builtin_alloca_with_align. This is declared 6145 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6146 /// than 8. 6147 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6148 // The alignment must be a constant integer. 6149 Expr *Arg = TheCall->getArg(1); 6150 6151 // We can't check the value of a dependent argument. 6152 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6153 if (const auto *UE = 6154 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6155 if (UE->getKind() == UETT_AlignOf || 6156 UE->getKind() == UETT_PreferredAlignOf) 6157 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6158 << Arg->getSourceRange(); 6159 6160 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6161 6162 if (!Result.isPowerOf2()) 6163 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6164 << Arg->getSourceRange(); 6165 6166 if (Result < Context.getCharWidth()) 6167 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6168 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6169 6170 if (Result > std::numeric_limits<int32_t>::max()) 6171 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6172 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6173 } 6174 6175 return false; 6176 } 6177 6178 /// Handle __builtin_assume_aligned. This is declared 6179 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6180 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6181 unsigned NumArgs = TheCall->getNumArgs(); 6182 6183 if (NumArgs > 3) 6184 return Diag(TheCall->getEndLoc(), 6185 diag::err_typecheck_call_too_many_args_at_most) 6186 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6187 6188 // The alignment must be a constant integer. 6189 Expr *Arg = TheCall->getArg(1); 6190 6191 // We can't check the value of a dependent argument. 6192 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6193 llvm::APSInt Result; 6194 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6195 return true; 6196 6197 if (!Result.isPowerOf2()) 6198 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6199 << Arg->getSourceRange(); 6200 6201 if (Result > Sema::MaximumAlignment) 6202 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6203 << Arg->getSourceRange() << Sema::MaximumAlignment; 6204 } 6205 6206 if (NumArgs > 2) { 6207 ExprResult Arg(TheCall->getArg(2)); 6208 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6209 Context.getSizeType(), false); 6210 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6211 if (Arg.isInvalid()) return true; 6212 TheCall->setArg(2, Arg.get()); 6213 } 6214 6215 return false; 6216 } 6217 6218 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6219 unsigned BuiltinID = 6220 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6221 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6222 6223 unsigned NumArgs = TheCall->getNumArgs(); 6224 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6225 if (NumArgs < NumRequiredArgs) { 6226 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6227 << 0 /* function call */ << NumRequiredArgs << NumArgs 6228 << TheCall->getSourceRange(); 6229 } 6230 if (NumArgs >= NumRequiredArgs + 0x100) { 6231 return Diag(TheCall->getEndLoc(), 6232 diag::err_typecheck_call_too_many_args_at_most) 6233 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6234 << TheCall->getSourceRange(); 6235 } 6236 unsigned i = 0; 6237 6238 // For formatting call, check buffer arg. 6239 if (!IsSizeCall) { 6240 ExprResult Arg(TheCall->getArg(i)); 6241 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6242 Context, Context.VoidPtrTy, false); 6243 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6244 if (Arg.isInvalid()) 6245 return true; 6246 TheCall->setArg(i, Arg.get()); 6247 i++; 6248 } 6249 6250 // Check string literal arg. 6251 unsigned FormatIdx = i; 6252 { 6253 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6254 if (Arg.isInvalid()) 6255 return true; 6256 TheCall->setArg(i, Arg.get()); 6257 i++; 6258 } 6259 6260 // Make sure variadic args are scalar. 6261 unsigned FirstDataArg = i; 6262 while (i < NumArgs) { 6263 ExprResult Arg = DefaultVariadicArgumentPromotion( 6264 TheCall->getArg(i), VariadicFunction, nullptr); 6265 if (Arg.isInvalid()) 6266 return true; 6267 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6268 if (ArgSize.getQuantity() >= 0x100) { 6269 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6270 << i << (int)ArgSize.getQuantity() << 0xff 6271 << TheCall->getSourceRange(); 6272 } 6273 TheCall->setArg(i, Arg.get()); 6274 i++; 6275 } 6276 6277 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6278 // call to avoid duplicate diagnostics. 6279 if (!IsSizeCall) { 6280 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6281 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6282 bool Success = CheckFormatArguments( 6283 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6284 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6285 CheckedVarArgs); 6286 if (!Success) 6287 return true; 6288 } 6289 6290 if (IsSizeCall) { 6291 TheCall->setType(Context.getSizeType()); 6292 } else { 6293 TheCall->setType(Context.VoidPtrTy); 6294 } 6295 return false; 6296 } 6297 6298 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6299 /// TheCall is a constant expression. 6300 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6301 llvm::APSInt &Result) { 6302 Expr *Arg = TheCall->getArg(ArgNum); 6303 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6304 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6305 6306 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6307 6308 Optional<llvm::APSInt> R; 6309 if (!(R = Arg->getIntegerConstantExpr(Context))) 6310 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6311 << FDecl->getDeclName() << Arg->getSourceRange(); 6312 Result = *R; 6313 return false; 6314 } 6315 6316 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6317 /// TheCall is a constant expression in the range [Low, High]. 6318 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6319 int Low, int High, bool RangeIsError) { 6320 if (isConstantEvaluated()) 6321 return false; 6322 llvm::APSInt Result; 6323 6324 // We can't check the value of a dependent argument. 6325 Expr *Arg = TheCall->getArg(ArgNum); 6326 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6327 return false; 6328 6329 // Check constant-ness first. 6330 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6331 return true; 6332 6333 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6334 if (RangeIsError) 6335 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6336 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6337 else 6338 // Defer the warning until we know if the code will be emitted so that 6339 // dead code can ignore this. 6340 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6341 PDiag(diag::warn_argument_invalid_range) 6342 << Result.toString(10) << Low << High 6343 << Arg->getSourceRange()); 6344 } 6345 6346 return false; 6347 } 6348 6349 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6350 /// TheCall is a constant expression is a multiple of Num.. 6351 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6352 unsigned Num) { 6353 llvm::APSInt Result; 6354 6355 // We can't check the value of a dependent argument. 6356 Expr *Arg = TheCall->getArg(ArgNum); 6357 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6358 return false; 6359 6360 // Check constant-ness first. 6361 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6362 return true; 6363 6364 if (Result.getSExtValue() % Num != 0) 6365 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6366 << Num << Arg->getSourceRange(); 6367 6368 return false; 6369 } 6370 6371 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6372 /// constant expression representing a power of 2. 6373 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6374 llvm::APSInt Result; 6375 6376 // We can't check the value of a dependent argument. 6377 Expr *Arg = TheCall->getArg(ArgNum); 6378 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6379 return false; 6380 6381 // Check constant-ness first. 6382 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6383 return true; 6384 6385 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6386 // and only if x is a power of 2. 6387 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6388 return false; 6389 6390 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6391 << Arg->getSourceRange(); 6392 } 6393 6394 static bool IsShiftedByte(llvm::APSInt Value) { 6395 if (Value.isNegative()) 6396 return false; 6397 6398 // Check if it's a shifted byte, by shifting it down 6399 while (true) { 6400 // If the value fits in the bottom byte, the check passes. 6401 if (Value < 0x100) 6402 return true; 6403 6404 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6405 // fails. 6406 if ((Value & 0xFF) != 0) 6407 return false; 6408 6409 // If the bottom 8 bits are all 0, but something above that is nonzero, 6410 // then shifting the value right by 8 bits won't affect whether it's a 6411 // shifted byte or not. So do that, and go round again. 6412 Value >>= 8; 6413 } 6414 } 6415 6416 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6417 /// a constant expression representing an arbitrary byte value shifted left by 6418 /// a multiple of 8 bits. 6419 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6420 unsigned ArgBits) { 6421 llvm::APSInt Result; 6422 6423 // We can't check the value of a dependent argument. 6424 Expr *Arg = TheCall->getArg(ArgNum); 6425 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6426 return false; 6427 6428 // Check constant-ness first. 6429 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6430 return true; 6431 6432 // Truncate to the given size. 6433 Result = Result.getLoBits(ArgBits); 6434 Result.setIsUnsigned(true); 6435 6436 if (IsShiftedByte(Result)) 6437 return false; 6438 6439 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6440 << Arg->getSourceRange(); 6441 } 6442 6443 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6444 /// TheCall is a constant expression representing either a shifted byte value, 6445 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6446 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6447 /// Arm MVE intrinsics. 6448 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6449 int ArgNum, 6450 unsigned ArgBits) { 6451 llvm::APSInt Result; 6452 6453 // We can't check the value of a dependent argument. 6454 Expr *Arg = TheCall->getArg(ArgNum); 6455 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6456 return false; 6457 6458 // Check constant-ness first. 6459 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6460 return true; 6461 6462 // Truncate to the given size. 6463 Result = Result.getLoBits(ArgBits); 6464 Result.setIsUnsigned(true); 6465 6466 // Check to see if it's in either of the required forms. 6467 if (IsShiftedByte(Result) || 6468 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6469 return false; 6470 6471 return Diag(TheCall->getBeginLoc(), 6472 diag::err_argument_not_shifted_byte_or_xxff) 6473 << Arg->getSourceRange(); 6474 } 6475 6476 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6477 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6478 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6479 if (checkArgCount(*this, TheCall, 2)) 6480 return true; 6481 Expr *Arg0 = TheCall->getArg(0); 6482 Expr *Arg1 = TheCall->getArg(1); 6483 6484 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6485 if (FirstArg.isInvalid()) 6486 return true; 6487 QualType FirstArgType = FirstArg.get()->getType(); 6488 if (!FirstArgType->isAnyPointerType()) 6489 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6490 << "first" << FirstArgType << Arg0->getSourceRange(); 6491 TheCall->setArg(0, FirstArg.get()); 6492 6493 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6494 if (SecArg.isInvalid()) 6495 return true; 6496 QualType SecArgType = SecArg.get()->getType(); 6497 if (!SecArgType->isIntegerType()) 6498 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6499 << "second" << SecArgType << Arg1->getSourceRange(); 6500 6501 // Derive the return type from the pointer argument. 6502 TheCall->setType(FirstArgType); 6503 return false; 6504 } 6505 6506 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6507 if (checkArgCount(*this, TheCall, 2)) 6508 return true; 6509 6510 Expr *Arg0 = TheCall->getArg(0); 6511 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6512 if (FirstArg.isInvalid()) 6513 return true; 6514 QualType FirstArgType = FirstArg.get()->getType(); 6515 if (!FirstArgType->isAnyPointerType()) 6516 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6517 << "first" << FirstArgType << Arg0->getSourceRange(); 6518 TheCall->setArg(0, FirstArg.get()); 6519 6520 // Derive the return type from the pointer argument. 6521 TheCall->setType(FirstArgType); 6522 6523 // Second arg must be an constant in range [0,15] 6524 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6525 } 6526 6527 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6528 if (checkArgCount(*this, TheCall, 2)) 6529 return true; 6530 Expr *Arg0 = TheCall->getArg(0); 6531 Expr *Arg1 = TheCall->getArg(1); 6532 6533 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6534 if (FirstArg.isInvalid()) 6535 return true; 6536 QualType FirstArgType = FirstArg.get()->getType(); 6537 if (!FirstArgType->isAnyPointerType()) 6538 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6539 << "first" << FirstArgType << Arg0->getSourceRange(); 6540 6541 QualType SecArgType = Arg1->getType(); 6542 if (!SecArgType->isIntegerType()) 6543 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6544 << "second" << SecArgType << Arg1->getSourceRange(); 6545 TheCall->setType(Context.IntTy); 6546 return false; 6547 } 6548 6549 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6550 BuiltinID == AArch64::BI__builtin_arm_stg) { 6551 if (checkArgCount(*this, TheCall, 1)) 6552 return true; 6553 Expr *Arg0 = TheCall->getArg(0); 6554 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6555 if (FirstArg.isInvalid()) 6556 return true; 6557 6558 QualType FirstArgType = FirstArg.get()->getType(); 6559 if (!FirstArgType->isAnyPointerType()) 6560 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6561 << "first" << FirstArgType << Arg0->getSourceRange(); 6562 TheCall->setArg(0, FirstArg.get()); 6563 6564 // Derive the return type from the pointer argument. 6565 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6566 TheCall->setType(FirstArgType); 6567 return false; 6568 } 6569 6570 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6571 Expr *ArgA = TheCall->getArg(0); 6572 Expr *ArgB = TheCall->getArg(1); 6573 6574 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6575 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6576 6577 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6578 return true; 6579 6580 QualType ArgTypeA = ArgExprA.get()->getType(); 6581 QualType ArgTypeB = ArgExprB.get()->getType(); 6582 6583 auto isNull = [&] (Expr *E) -> bool { 6584 return E->isNullPointerConstant( 6585 Context, Expr::NPC_ValueDependentIsNotNull); }; 6586 6587 // argument should be either a pointer or null 6588 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6589 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6590 << "first" << ArgTypeA << ArgA->getSourceRange(); 6591 6592 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6593 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6594 << "second" << ArgTypeB << ArgB->getSourceRange(); 6595 6596 // Ensure Pointee types are compatible 6597 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6598 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6599 QualType pointeeA = ArgTypeA->getPointeeType(); 6600 QualType pointeeB = ArgTypeB->getPointeeType(); 6601 if (!Context.typesAreCompatible( 6602 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6603 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6604 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6605 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6606 << ArgB->getSourceRange(); 6607 } 6608 } 6609 6610 // at least one argument should be pointer type 6611 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6612 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6613 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6614 6615 if (isNull(ArgA)) // adopt type of the other pointer 6616 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6617 6618 if (isNull(ArgB)) 6619 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6620 6621 TheCall->setArg(0, ArgExprA.get()); 6622 TheCall->setArg(1, ArgExprB.get()); 6623 TheCall->setType(Context.LongLongTy); 6624 return false; 6625 } 6626 assert(false && "Unhandled ARM MTE intrinsic"); 6627 return true; 6628 } 6629 6630 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6631 /// TheCall is an ARM/AArch64 special register string literal. 6632 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6633 int ArgNum, unsigned ExpectedFieldNum, 6634 bool AllowName) { 6635 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6636 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6637 BuiltinID == ARM::BI__builtin_arm_rsr || 6638 BuiltinID == ARM::BI__builtin_arm_rsrp || 6639 BuiltinID == ARM::BI__builtin_arm_wsr || 6640 BuiltinID == ARM::BI__builtin_arm_wsrp; 6641 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6642 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6643 BuiltinID == AArch64::BI__builtin_arm_rsr || 6644 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6645 BuiltinID == AArch64::BI__builtin_arm_wsr || 6646 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6647 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6648 6649 // We can't check the value of a dependent argument. 6650 Expr *Arg = TheCall->getArg(ArgNum); 6651 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6652 return false; 6653 6654 // Check if the argument is a string literal. 6655 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6656 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6657 << Arg->getSourceRange(); 6658 6659 // Check the type of special register given. 6660 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6661 SmallVector<StringRef, 6> Fields; 6662 Reg.split(Fields, ":"); 6663 6664 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6665 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6666 << Arg->getSourceRange(); 6667 6668 // If the string is the name of a register then we cannot check that it is 6669 // valid here but if the string is of one the forms described in ACLE then we 6670 // can check that the supplied fields are integers and within the valid 6671 // ranges. 6672 if (Fields.size() > 1) { 6673 bool FiveFields = Fields.size() == 5; 6674 6675 bool ValidString = true; 6676 if (IsARMBuiltin) { 6677 ValidString &= Fields[0].startswith_lower("cp") || 6678 Fields[0].startswith_lower("p"); 6679 if (ValidString) 6680 Fields[0] = 6681 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6682 6683 ValidString &= Fields[2].startswith_lower("c"); 6684 if (ValidString) 6685 Fields[2] = Fields[2].drop_front(1); 6686 6687 if (FiveFields) { 6688 ValidString &= Fields[3].startswith_lower("c"); 6689 if (ValidString) 6690 Fields[3] = Fields[3].drop_front(1); 6691 } 6692 } 6693 6694 SmallVector<int, 5> Ranges; 6695 if (FiveFields) 6696 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6697 else 6698 Ranges.append({15, 7, 15}); 6699 6700 for (unsigned i=0; i<Fields.size(); ++i) { 6701 int IntField; 6702 ValidString &= !Fields[i].getAsInteger(10, IntField); 6703 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6704 } 6705 6706 if (!ValidString) 6707 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6708 << Arg->getSourceRange(); 6709 } else if (IsAArch64Builtin && Fields.size() == 1) { 6710 // If the register name is one of those that appear in the condition below 6711 // and the special register builtin being used is one of the write builtins, 6712 // then we require that the argument provided for writing to the register 6713 // is an integer constant expression. This is because it will be lowered to 6714 // an MSR (immediate) instruction, so we need to know the immediate at 6715 // compile time. 6716 if (TheCall->getNumArgs() != 2) 6717 return false; 6718 6719 std::string RegLower = Reg.lower(); 6720 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6721 RegLower != "pan" && RegLower != "uao") 6722 return false; 6723 6724 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6725 } 6726 6727 return false; 6728 } 6729 6730 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6731 /// This checks that the target supports __builtin_longjmp and 6732 /// that val is a constant 1. 6733 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6734 if (!Context.getTargetInfo().hasSjLjLowering()) 6735 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6736 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6737 6738 Expr *Arg = TheCall->getArg(1); 6739 llvm::APSInt Result; 6740 6741 // TODO: This is less than ideal. Overload this to take a value. 6742 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6743 return true; 6744 6745 if (Result != 1) 6746 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6747 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6748 6749 return false; 6750 } 6751 6752 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6753 /// This checks that the target supports __builtin_setjmp. 6754 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6755 if (!Context.getTargetInfo().hasSjLjLowering()) 6756 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6757 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6758 return false; 6759 } 6760 6761 namespace { 6762 6763 class UncoveredArgHandler { 6764 enum { Unknown = -1, AllCovered = -2 }; 6765 6766 signed FirstUncoveredArg = Unknown; 6767 SmallVector<const Expr *, 4> DiagnosticExprs; 6768 6769 public: 6770 UncoveredArgHandler() = default; 6771 6772 bool hasUncoveredArg() const { 6773 return (FirstUncoveredArg >= 0); 6774 } 6775 6776 unsigned getUncoveredArg() const { 6777 assert(hasUncoveredArg() && "no uncovered argument"); 6778 return FirstUncoveredArg; 6779 } 6780 6781 void setAllCovered() { 6782 // A string has been found with all arguments covered, so clear out 6783 // the diagnostics. 6784 DiagnosticExprs.clear(); 6785 FirstUncoveredArg = AllCovered; 6786 } 6787 6788 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6789 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6790 6791 // Don't update if a previous string covers all arguments. 6792 if (FirstUncoveredArg == AllCovered) 6793 return; 6794 6795 // UncoveredArgHandler tracks the highest uncovered argument index 6796 // and with it all the strings that match this index. 6797 if (NewFirstUncoveredArg == FirstUncoveredArg) 6798 DiagnosticExprs.push_back(StrExpr); 6799 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6800 DiagnosticExprs.clear(); 6801 DiagnosticExprs.push_back(StrExpr); 6802 FirstUncoveredArg = NewFirstUncoveredArg; 6803 } 6804 } 6805 6806 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6807 }; 6808 6809 enum StringLiteralCheckType { 6810 SLCT_NotALiteral, 6811 SLCT_UncheckedLiteral, 6812 SLCT_CheckedLiteral 6813 }; 6814 6815 } // namespace 6816 6817 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6818 BinaryOperatorKind BinOpKind, 6819 bool AddendIsRight) { 6820 unsigned BitWidth = Offset.getBitWidth(); 6821 unsigned AddendBitWidth = Addend.getBitWidth(); 6822 // There might be negative interim results. 6823 if (Addend.isUnsigned()) { 6824 Addend = Addend.zext(++AddendBitWidth); 6825 Addend.setIsSigned(true); 6826 } 6827 // Adjust the bit width of the APSInts. 6828 if (AddendBitWidth > BitWidth) { 6829 Offset = Offset.sext(AddendBitWidth); 6830 BitWidth = AddendBitWidth; 6831 } else if (BitWidth > AddendBitWidth) { 6832 Addend = Addend.sext(BitWidth); 6833 } 6834 6835 bool Ov = false; 6836 llvm::APSInt ResOffset = Offset; 6837 if (BinOpKind == BO_Add) 6838 ResOffset = Offset.sadd_ov(Addend, Ov); 6839 else { 6840 assert(AddendIsRight && BinOpKind == BO_Sub && 6841 "operator must be add or sub with addend on the right"); 6842 ResOffset = Offset.ssub_ov(Addend, Ov); 6843 } 6844 6845 // We add an offset to a pointer here so we should support an offset as big as 6846 // possible. 6847 if (Ov) { 6848 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6849 "index (intermediate) result too big"); 6850 Offset = Offset.sext(2 * BitWidth); 6851 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6852 return; 6853 } 6854 6855 Offset = ResOffset; 6856 } 6857 6858 namespace { 6859 6860 // This is a wrapper class around StringLiteral to support offsetted string 6861 // literals as format strings. It takes the offset into account when returning 6862 // the string and its length or the source locations to display notes correctly. 6863 class FormatStringLiteral { 6864 const StringLiteral *FExpr; 6865 int64_t Offset; 6866 6867 public: 6868 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6869 : FExpr(fexpr), Offset(Offset) {} 6870 6871 StringRef getString() const { 6872 return FExpr->getString().drop_front(Offset); 6873 } 6874 6875 unsigned getByteLength() const { 6876 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6877 } 6878 6879 unsigned getLength() const { return FExpr->getLength() - Offset; } 6880 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6881 6882 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6883 6884 QualType getType() const { return FExpr->getType(); } 6885 6886 bool isAscii() const { return FExpr->isAscii(); } 6887 bool isWide() const { return FExpr->isWide(); } 6888 bool isUTF8() const { return FExpr->isUTF8(); } 6889 bool isUTF16() const { return FExpr->isUTF16(); } 6890 bool isUTF32() const { return FExpr->isUTF32(); } 6891 bool isPascal() const { return FExpr->isPascal(); } 6892 6893 SourceLocation getLocationOfByte( 6894 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6895 const TargetInfo &Target, unsigned *StartToken = nullptr, 6896 unsigned *StartTokenByteOffset = nullptr) const { 6897 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6898 StartToken, StartTokenByteOffset); 6899 } 6900 6901 SourceLocation getBeginLoc() const LLVM_READONLY { 6902 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6903 } 6904 6905 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6906 }; 6907 6908 } // namespace 6909 6910 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6911 const Expr *OrigFormatExpr, 6912 ArrayRef<const Expr *> Args, 6913 bool HasVAListArg, unsigned format_idx, 6914 unsigned firstDataArg, 6915 Sema::FormatStringType Type, 6916 bool inFunctionCall, 6917 Sema::VariadicCallType CallType, 6918 llvm::SmallBitVector &CheckedVarArgs, 6919 UncoveredArgHandler &UncoveredArg, 6920 bool IgnoreStringsWithoutSpecifiers); 6921 6922 // Determine if an expression is a string literal or constant string. 6923 // If this function returns false on the arguments to a function expecting a 6924 // format string, we will usually need to emit a warning. 6925 // True string literals are then checked by CheckFormatString. 6926 static StringLiteralCheckType 6927 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6928 bool HasVAListArg, unsigned format_idx, 6929 unsigned firstDataArg, Sema::FormatStringType Type, 6930 Sema::VariadicCallType CallType, bool InFunctionCall, 6931 llvm::SmallBitVector &CheckedVarArgs, 6932 UncoveredArgHandler &UncoveredArg, 6933 llvm::APSInt Offset, 6934 bool IgnoreStringsWithoutSpecifiers = false) { 6935 if (S.isConstantEvaluated()) 6936 return SLCT_NotALiteral; 6937 tryAgain: 6938 assert(Offset.isSigned() && "invalid offset"); 6939 6940 if (E->isTypeDependent() || E->isValueDependent()) 6941 return SLCT_NotALiteral; 6942 6943 E = E->IgnoreParenCasts(); 6944 6945 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6946 // Technically -Wformat-nonliteral does not warn about this case. 6947 // The behavior of printf and friends in this case is implementation 6948 // dependent. Ideally if the format string cannot be null then 6949 // it should have a 'nonnull' attribute in the function prototype. 6950 return SLCT_UncheckedLiteral; 6951 6952 switch (E->getStmtClass()) { 6953 case Stmt::BinaryConditionalOperatorClass: 6954 case Stmt::ConditionalOperatorClass: { 6955 // The expression is a literal if both sub-expressions were, and it was 6956 // completely checked only if both sub-expressions were checked. 6957 const AbstractConditionalOperator *C = 6958 cast<AbstractConditionalOperator>(E); 6959 6960 // Determine whether it is necessary to check both sub-expressions, for 6961 // example, because the condition expression is a constant that can be 6962 // evaluated at compile time. 6963 bool CheckLeft = true, CheckRight = true; 6964 6965 bool Cond; 6966 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6967 S.isConstantEvaluated())) { 6968 if (Cond) 6969 CheckRight = false; 6970 else 6971 CheckLeft = false; 6972 } 6973 6974 // We need to maintain the offsets for the right and the left hand side 6975 // separately to check if every possible indexed expression is a valid 6976 // string literal. They might have different offsets for different string 6977 // literals in the end. 6978 StringLiteralCheckType Left; 6979 if (!CheckLeft) 6980 Left = SLCT_UncheckedLiteral; 6981 else { 6982 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6983 HasVAListArg, format_idx, firstDataArg, 6984 Type, CallType, InFunctionCall, 6985 CheckedVarArgs, UncoveredArg, Offset, 6986 IgnoreStringsWithoutSpecifiers); 6987 if (Left == SLCT_NotALiteral || !CheckRight) { 6988 return Left; 6989 } 6990 } 6991 6992 StringLiteralCheckType Right = checkFormatStringExpr( 6993 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6994 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6995 IgnoreStringsWithoutSpecifiers); 6996 6997 return (CheckLeft && Left < Right) ? Left : Right; 6998 } 6999 7000 case Stmt::ImplicitCastExprClass: 7001 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7002 goto tryAgain; 7003 7004 case Stmt::OpaqueValueExprClass: 7005 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7006 E = src; 7007 goto tryAgain; 7008 } 7009 return SLCT_NotALiteral; 7010 7011 case Stmt::PredefinedExprClass: 7012 // While __func__, etc., are technically not string literals, they 7013 // cannot contain format specifiers and thus are not a security 7014 // liability. 7015 return SLCT_UncheckedLiteral; 7016 7017 case Stmt::DeclRefExprClass: { 7018 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7019 7020 // As an exception, do not flag errors for variables binding to 7021 // const string literals. 7022 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7023 bool isConstant = false; 7024 QualType T = DR->getType(); 7025 7026 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7027 isConstant = AT->getElementType().isConstant(S.Context); 7028 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7029 isConstant = T.isConstant(S.Context) && 7030 PT->getPointeeType().isConstant(S.Context); 7031 } else if (T->isObjCObjectPointerType()) { 7032 // In ObjC, there is usually no "const ObjectPointer" type, 7033 // so don't check if the pointee type is constant. 7034 isConstant = T.isConstant(S.Context); 7035 } 7036 7037 if (isConstant) { 7038 if (const Expr *Init = VD->getAnyInitializer()) { 7039 // Look through initializers like const char c[] = { "foo" } 7040 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7041 if (InitList->isStringLiteralInit()) 7042 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7043 } 7044 return checkFormatStringExpr(S, Init, Args, 7045 HasVAListArg, format_idx, 7046 firstDataArg, Type, CallType, 7047 /*InFunctionCall*/ false, CheckedVarArgs, 7048 UncoveredArg, Offset); 7049 } 7050 } 7051 7052 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7053 // special check to see if the format string is a function parameter 7054 // of the function calling the printf function. If the function 7055 // has an attribute indicating it is a printf-like function, then we 7056 // should suppress warnings concerning non-literals being used in a call 7057 // to a vprintf function. For example: 7058 // 7059 // void 7060 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7061 // va_list ap; 7062 // va_start(ap, fmt); 7063 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7064 // ... 7065 // } 7066 if (HasVAListArg) { 7067 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7068 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7069 int PVIndex = PV->getFunctionScopeIndex() + 1; 7070 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7071 // adjust for implicit parameter 7072 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7073 if (MD->isInstance()) 7074 ++PVIndex; 7075 // We also check if the formats are compatible. 7076 // We can't pass a 'scanf' string to a 'printf' function. 7077 if (PVIndex == PVFormat->getFormatIdx() && 7078 Type == S.GetFormatStringType(PVFormat)) 7079 return SLCT_UncheckedLiteral; 7080 } 7081 } 7082 } 7083 } 7084 } 7085 7086 return SLCT_NotALiteral; 7087 } 7088 7089 case Stmt::CallExprClass: 7090 case Stmt::CXXMemberCallExprClass: { 7091 const CallExpr *CE = cast<CallExpr>(E); 7092 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7093 bool IsFirst = true; 7094 StringLiteralCheckType CommonResult; 7095 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7096 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7097 StringLiteralCheckType Result = checkFormatStringExpr( 7098 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7099 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7100 IgnoreStringsWithoutSpecifiers); 7101 if (IsFirst) { 7102 CommonResult = Result; 7103 IsFirst = false; 7104 } 7105 } 7106 if (!IsFirst) 7107 return CommonResult; 7108 7109 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7110 unsigned BuiltinID = FD->getBuiltinID(); 7111 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7112 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7113 const Expr *Arg = CE->getArg(0); 7114 return checkFormatStringExpr(S, Arg, Args, 7115 HasVAListArg, format_idx, 7116 firstDataArg, Type, CallType, 7117 InFunctionCall, CheckedVarArgs, 7118 UncoveredArg, Offset, 7119 IgnoreStringsWithoutSpecifiers); 7120 } 7121 } 7122 } 7123 7124 return SLCT_NotALiteral; 7125 } 7126 case Stmt::ObjCMessageExprClass: { 7127 const auto *ME = cast<ObjCMessageExpr>(E); 7128 if (const auto *MD = ME->getMethodDecl()) { 7129 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7130 // As a special case heuristic, if we're using the method -[NSBundle 7131 // localizedStringForKey:value:table:], ignore any key strings that lack 7132 // format specifiers. The idea is that if the key doesn't have any 7133 // format specifiers then its probably just a key to map to the 7134 // localized strings. If it does have format specifiers though, then its 7135 // likely that the text of the key is the format string in the 7136 // programmer's language, and should be checked. 7137 const ObjCInterfaceDecl *IFace; 7138 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7139 IFace->getIdentifier()->isStr("NSBundle") && 7140 MD->getSelector().isKeywordSelector( 7141 {"localizedStringForKey", "value", "table"})) { 7142 IgnoreStringsWithoutSpecifiers = true; 7143 } 7144 7145 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7146 return checkFormatStringExpr( 7147 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7148 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7149 IgnoreStringsWithoutSpecifiers); 7150 } 7151 } 7152 7153 return SLCT_NotALiteral; 7154 } 7155 case Stmt::ObjCStringLiteralClass: 7156 case Stmt::StringLiteralClass: { 7157 const StringLiteral *StrE = nullptr; 7158 7159 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7160 StrE = ObjCFExpr->getString(); 7161 else 7162 StrE = cast<StringLiteral>(E); 7163 7164 if (StrE) { 7165 if (Offset.isNegative() || Offset > StrE->getLength()) { 7166 // TODO: It would be better to have an explicit warning for out of 7167 // bounds literals. 7168 return SLCT_NotALiteral; 7169 } 7170 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7171 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7172 firstDataArg, Type, InFunctionCall, CallType, 7173 CheckedVarArgs, UncoveredArg, 7174 IgnoreStringsWithoutSpecifiers); 7175 return SLCT_CheckedLiteral; 7176 } 7177 7178 return SLCT_NotALiteral; 7179 } 7180 case Stmt::BinaryOperatorClass: { 7181 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7182 7183 // A string literal + an int offset is still a string literal. 7184 if (BinOp->isAdditiveOp()) { 7185 Expr::EvalResult LResult, RResult; 7186 7187 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7188 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7189 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7190 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7191 7192 if (LIsInt != RIsInt) { 7193 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7194 7195 if (LIsInt) { 7196 if (BinOpKind == BO_Add) { 7197 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7198 E = BinOp->getRHS(); 7199 goto tryAgain; 7200 } 7201 } else { 7202 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7203 E = BinOp->getLHS(); 7204 goto tryAgain; 7205 } 7206 } 7207 } 7208 7209 return SLCT_NotALiteral; 7210 } 7211 case Stmt::UnaryOperatorClass: { 7212 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7213 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7214 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7215 Expr::EvalResult IndexResult; 7216 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7217 Expr::SE_NoSideEffects, 7218 S.isConstantEvaluated())) { 7219 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7220 /*RHS is int*/ true); 7221 E = ASE->getBase(); 7222 goto tryAgain; 7223 } 7224 } 7225 7226 return SLCT_NotALiteral; 7227 } 7228 7229 default: 7230 return SLCT_NotALiteral; 7231 } 7232 } 7233 7234 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7235 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7236 .Case("scanf", FST_Scanf) 7237 .Cases("printf", "printf0", FST_Printf) 7238 .Cases("NSString", "CFString", FST_NSString) 7239 .Case("strftime", FST_Strftime) 7240 .Case("strfmon", FST_Strfmon) 7241 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7242 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7243 .Case("os_trace", FST_OSLog) 7244 .Case("os_log", FST_OSLog) 7245 .Default(FST_Unknown); 7246 } 7247 7248 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7249 /// functions) for correct use of format strings. 7250 /// Returns true if a format string has been fully checked. 7251 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7252 ArrayRef<const Expr *> Args, 7253 bool IsCXXMember, 7254 VariadicCallType CallType, 7255 SourceLocation Loc, SourceRange Range, 7256 llvm::SmallBitVector &CheckedVarArgs) { 7257 FormatStringInfo FSI; 7258 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7259 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7260 FSI.FirstDataArg, GetFormatStringType(Format), 7261 CallType, Loc, Range, CheckedVarArgs); 7262 return false; 7263 } 7264 7265 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7266 bool HasVAListArg, unsigned format_idx, 7267 unsigned firstDataArg, FormatStringType Type, 7268 VariadicCallType CallType, 7269 SourceLocation Loc, SourceRange Range, 7270 llvm::SmallBitVector &CheckedVarArgs) { 7271 // CHECK: printf/scanf-like function is called with no format string. 7272 if (format_idx >= Args.size()) { 7273 Diag(Loc, diag::warn_missing_format_string) << Range; 7274 return false; 7275 } 7276 7277 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7278 7279 // CHECK: format string is not a string literal. 7280 // 7281 // Dynamically generated format strings are difficult to 7282 // automatically vet at compile time. Requiring that format strings 7283 // are string literals: (1) permits the checking of format strings by 7284 // the compiler and thereby (2) can practically remove the source of 7285 // many format string exploits. 7286 7287 // Format string can be either ObjC string (e.g. @"%d") or 7288 // C string (e.g. "%d") 7289 // ObjC string uses the same format specifiers as C string, so we can use 7290 // the same format string checking logic for both ObjC and C strings. 7291 UncoveredArgHandler UncoveredArg; 7292 StringLiteralCheckType CT = 7293 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7294 format_idx, firstDataArg, Type, CallType, 7295 /*IsFunctionCall*/ true, CheckedVarArgs, 7296 UncoveredArg, 7297 /*no string offset*/ llvm::APSInt(64, false) = 0); 7298 7299 // Generate a diagnostic where an uncovered argument is detected. 7300 if (UncoveredArg.hasUncoveredArg()) { 7301 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7302 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7303 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7304 } 7305 7306 if (CT != SLCT_NotALiteral) 7307 // Literal format string found, check done! 7308 return CT == SLCT_CheckedLiteral; 7309 7310 // Strftime is particular as it always uses a single 'time' argument, 7311 // so it is safe to pass a non-literal string. 7312 if (Type == FST_Strftime) 7313 return false; 7314 7315 // Do not emit diag when the string param is a macro expansion and the 7316 // format is either NSString or CFString. This is a hack to prevent 7317 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7318 // which are usually used in place of NS and CF string literals. 7319 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7320 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7321 return false; 7322 7323 // If there are no arguments specified, warn with -Wformat-security, otherwise 7324 // warn only with -Wformat-nonliteral. 7325 if (Args.size() == firstDataArg) { 7326 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7327 << OrigFormatExpr->getSourceRange(); 7328 switch (Type) { 7329 default: 7330 break; 7331 case FST_Kprintf: 7332 case FST_FreeBSDKPrintf: 7333 case FST_Printf: 7334 Diag(FormatLoc, diag::note_format_security_fixit) 7335 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7336 break; 7337 case FST_NSString: 7338 Diag(FormatLoc, diag::note_format_security_fixit) 7339 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7340 break; 7341 } 7342 } else { 7343 Diag(FormatLoc, diag::warn_format_nonliteral) 7344 << OrigFormatExpr->getSourceRange(); 7345 } 7346 return false; 7347 } 7348 7349 namespace { 7350 7351 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7352 protected: 7353 Sema &S; 7354 const FormatStringLiteral *FExpr; 7355 const Expr *OrigFormatExpr; 7356 const Sema::FormatStringType FSType; 7357 const unsigned FirstDataArg; 7358 const unsigned NumDataArgs; 7359 const char *Beg; // Start of format string. 7360 const bool HasVAListArg; 7361 ArrayRef<const Expr *> Args; 7362 unsigned FormatIdx; 7363 llvm::SmallBitVector CoveredArgs; 7364 bool usesPositionalArgs = false; 7365 bool atFirstArg = true; 7366 bool inFunctionCall; 7367 Sema::VariadicCallType CallType; 7368 llvm::SmallBitVector &CheckedVarArgs; 7369 UncoveredArgHandler &UncoveredArg; 7370 7371 public: 7372 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7373 const Expr *origFormatExpr, 7374 const Sema::FormatStringType type, unsigned firstDataArg, 7375 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7376 ArrayRef<const Expr *> Args, unsigned formatIdx, 7377 bool inFunctionCall, Sema::VariadicCallType callType, 7378 llvm::SmallBitVector &CheckedVarArgs, 7379 UncoveredArgHandler &UncoveredArg) 7380 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7381 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7382 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7383 inFunctionCall(inFunctionCall), CallType(callType), 7384 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7385 CoveredArgs.resize(numDataArgs); 7386 CoveredArgs.reset(); 7387 } 7388 7389 void DoneProcessing(); 7390 7391 void HandleIncompleteSpecifier(const char *startSpecifier, 7392 unsigned specifierLen) override; 7393 7394 void HandleInvalidLengthModifier( 7395 const analyze_format_string::FormatSpecifier &FS, 7396 const analyze_format_string::ConversionSpecifier &CS, 7397 const char *startSpecifier, unsigned specifierLen, 7398 unsigned DiagID); 7399 7400 void HandleNonStandardLengthModifier( 7401 const analyze_format_string::FormatSpecifier &FS, 7402 const char *startSpecifier, unsigned specifierLen); 7403 7404 void HandleNonStandardConversionSpecifier( 7405 const analyze_format_string::ConversionSpecifier &CS, 7406 const char *startSpecifier, unsigned specifierLen); 7407 7408 void HandlePosition(const char *startPos, unsigned posLen) override; 7409 7410 void HandleInvalidPosition(const char *startSpecifier, 7411 unsigned specifierLen, 7412 analyze_format_string::PositionContext p) override; 7413 7414 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7415 7416 void HandleNullChar(const char *nullCharacter) override; 7417 7418 template <typename Range> 7419 static void 7420 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7421 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7422 bool IsStringLocation, Range StringRange, 7423 ArrayRef<FixItHint> Fixit = None); 7424 7425 protected: 7426 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7427 const char *startSpec, 7428 unsigned specifierLen, 7429 const char *csStart, unsigned csLen); 7430 7431 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7432 const char *startSpec, 7433 unsigned specifierLen); 7434 7435 SourceRange getFormatStringRange(); 7436 CharSourceRange getSpecifierRange(const char *startSpecifier, 7437 unsigned specifierLen); 7438 SourceLocation getLocationOfByte(const char *x); 7439 7440 const Expr *getDataArg(unsigned i) const; 7441 7442 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7443 const analyze_format_string::ConversionSpecifier &CS, 7444 const char *startSpecifier, unsigned specifierLen, 7445 unsigned argIndex); 7446 7447 template <typename Range> 7448 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7449 bool IsStringLocation, Range StringRange, 7450 ArrayRef<FixItHint> Fixit = None); 7451 }; 7452 7453 } // namespace 7454 7455 SourceRange CheckFormatHandler::getFormatStringRange() { 7456 return OrigFormatExpr->getSourceRange(); 7457 } 7458 7459 CharSourceRange CheckFormatHandler:: 7460 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7461 SourceLocation Start = getLocationOfByte(startSpecifier); 7462 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7463 7464 // Advance the end SourceLocation by one due to half-open ranges. 7465 End = End.getLocWithOffset(1); 7466 7467 return CharSourceRange::getCharRange(Start, End); 7468 } 7469 7470 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7471 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7472 S.getLangOpts(), S.Context.getTargetInfo()); 7473 } 7474 7475 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7476 unsigned specifierLen){ 7477 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7478 getLocationOfByte(startSpecifier), 7479 /*IsStringLocation*/true, 7480 getSpecifierRange(startSpecifier, specifierLen)); 7481 } 7482 7483 void CheckFormatHandler::HandleInvalidLengthModifier( 7484 const analyze_format_string::FormatSpecifier &FS, 7485 const analyze_format_string::ConversionSpecifier &CS, 7486 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7487 using namespace analyze_format_string; 7488 7489 const LengthModifier &LM = FS.getLengthModifier(); 7490 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7491 7492 // See if we know how to fix this length modifier. 7493 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7494 if (FixedLM) { 7495 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7496 getLocationOfByte(LM.getStart()), 7497 /*IsStringLocation*/true, 7498 getSpecifierRange(startSpecifier, specifierLen)); 7499 7500 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7501 << FixedLM->toString() 7502 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7503 7504 } else { 7505 FixItHint Hint; 7506 if (DiagID == diag::warn_format_nonsensical_length) 7507 Hint = FixItHint::CreateRemoval(LMRange); 7508 7509 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7510 getLocationOfByte(LM.getStart()), 7511 /*IsStringLocation*/true, 7512 getSpecifierRange(startSpecifier, specifierLen), 7513 Hint); 7514 } 7515 } 7516 7517 void CheckFormatHandler::HandleNonStandardLengthModifier( 7518 const analyze_format_string::FormatSpecifier &FS, 7519 const char *startSpecifier, unsigned specifierLen) { 7520 using namespace analyze_format_string; 7521 7522 const LengthModifier &LM = FS.getLengthModifier(); 7523 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7524 7525 // See if we know how to fix this length modifier. 7526 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7527 if (FixedLM) { 7528 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7529 << LM.toString() << 0, 7530 getLocationOfByte(LM.getStart()), 7531 /*IsStringLocation*/true, 7532 getSpecifierRange(startSpecifier, specifierLen)); 7533 7534 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7535 << FixedLM->toString() 7536 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7537 7538 } else { 7539 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7540 << LM.toString() << 0, 7541 getLocationOfByte(LM.getStart()), 7542 /*IsStringLocation*/true, 7543 getSpecifierRange(startSpecifier, specifierLen)); 7544 } 7545 } 7546 7547 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7548 const analyze_format_string::ConversionSpecifier &CS, 7549 const char *startSpecifier, unsigned specifierLen) { 7550 using namespace analyze_format_string; 7551 7552 // See if we know how to fix this conversion specifier. 7553 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7554 if (FixedCS) { 7555 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7556 << CS.toString() << /*conversion specifier*/1, 7557 getLocationOfByte(CS.getStart()), 7558 /*IsStringLocation*/true, 7559 getSpecifierRange(startSpecifier, specifierLen)); 7560 7561 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7562 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7563 << FixedCS->toString() 7564 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7565 } else { 7566 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7567 << CS.toString() << /*conversion specifier*/1, 7568 getLocationOfByte(CS.getStart()), 7569 /*IsStringLocation*/true, 7570 getSpecifierRange(startSpecifier, specifierLen)); 7571 } 7572 } 7573 7574 void CheckFormatHandler::HandlePosition(const char *startPos, 7575 unsigned posLen) { 7576 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7577 getLocationOfByte(startPos), 7578 /*IsStringLocation*/true, 7579 getSpecifierRange(startPos, posLen)); 7580 } 7581 7582 void 7583 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7584 analyze_format_string::PositionContext p) { 7585 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7586 << (unsigned) p, 7587 getLocationOfByte(startPos), /*IsStringLocation*/true, 7588 getSpecifierRange(startPos, posLen)); 7589 } 7590 7591 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7592 unsigned posLen) { 7593 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7594 getLocationOfByte(startPos), 7595 /*IsStringLocation*/true, 7596 getSpecifierRange(startPos, posLen)); 7597 } 7598 7599 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7600 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7601 // The presence of a null character is likely an error. 7602 EmitFormatDiagnostic( 7603 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7604 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7605 getFormatStringRange()); 7606 } 7607 } 7608 7609 // Note that this may return NULL if there was an error parsing or building 7610 // one of the argument expressions. 7611 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7612 return Args[FirstDataArg + i]; 7613 } 7614 7615 void CheckFormatHandler::DoneProcessing() { 7616 // Does the number of data arguments exceed the number of 7617 // format conversions in the format string? 7618 if (!HasVAListArg) { 7619 // Find any arguments that weren't covered. 7620 CoveredArgs.flip(); 7621 signed notCoveredArg = CoveredArgs.find_first(); 7622 if (notCoveredArg >= 0) { 7623 assert((unsigned)notCoveredArg < NumDataArgs); 7624 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7625 } else { 7626 UncoveredArg.setAllCovered(); 7627 } 7628 } 7629 } 7630 7631 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7632 const Expr *ArgExpr) { 7633 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7634 "Invalid state"); 7635 7636 if (!ArgExpr) 7637 return; 7638 7639 SourceLocation Loc = ArgExpr->getBeginLoc(); 7640 7641 if (S.getSourceManager().isInSystemMacro(Loc)) 7642 return; 7643 7644 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7645 for (auto E : DiagnosticExprs) 7646 PDiag << E->getSourceRange(); 7647 7648 CheckFormatHandler::EmitFormatDiagnostic( 7649 S, IsFunctionCall, DiagnosticExprs[0], 7650 PDiag, Loc, /*IsStringLocation*/false, 7651 DiagnosticExprs[0]->getSourceRange()); 7652 } 7653 7654 bool 7655 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7656 SourceLocation Loc, 7657 const char *startSpec, 7658 unsigned specifierLen, 7659 const char *csStart, 7660 unsigned csLen) { 7661 bool keepGoing = true; 7662 if (argIndex < NumDataArgs) { 7663 // Consider the argument coverered, even though the specifier doesn't 7664 // make sense. 7665 CoveredArgs.set(argIndex); 7666 } 7667 else { 7668 // If argIndex exceeds the number of data arguments we 7669 // don't issue a warning because that is just a cascade of warnings (and 7670 // they may have intended '%%' anyway). We don't want to continue processing 7671 // the format string after this point, however, as we will like just get 7672 // gibberish when trying to match arguments. 7673 keepGoing = false; 7674 } 7675 7676 StringRef Specifier(csStart, csLen); 7677 7678 // If the specifier in non-printable, it could be the first byte of a UTF-8 7679 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7680 // hex value. 7681 std::string CodePointStr; 7682 if (!llvm::sys::locale::isPrint(*csStart)) { 7683 llvm::UTF32 CodePoint; 7684 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7685 const llvm::UTF8 *E = 7686 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7687 llvm::ConversionResult Result = 7688 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7689 7690 if (Result != llvm::conversionOK) { 7691 unsigned char FirstChar = *csStart; 7692 CodePoint = (llvm::UTF32)FirstChar; 7693 } 7694 7695 llvm::raw_string_ostream OS(CodePointStr); 7696 if (CodePoint < 256) 7697 OS << "\\x" << llvm::format("%02x", CodePoint); 7698 else if (CodePoint <= 0xFFFF) 7699 OS << "\\u" << llvm::format("%04x", CodePoint); 7700 else 7701 OS << "\\U" << llvm::format("%08x", CodePoint); 7702 OS.flush(); 7703 Specifier = CodePointStr; 7704 } 7705 7706 EmitFormatDiagnostic( 7707 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7708 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7709 7710 return keepGoing; 7711 } 7712 7713 void 7714 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7715 const char *startSpec, 7716 unsigned specifierLen) { 7717 EmitFormatDiagnostic( 7718 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7719 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7720 } 7721 7722 bool 7723 CheckFormatHandler::CheckNumArgs( 7724 const analyze_format_string::FormatSpecifier &FS, 7725 const analyze_format_string::ConversionSpecifier &CS, 7726 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7727 7728 if (argIndex >= NumDataArgs) { 7729 PartialDiagnostic PDiag = FS.usesPositionalArg() 7730 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7731 << (argIndex+1) << NumDataArgs) 7732 : S.PDiag(diag::warn_printf_insufficient_data_args); 7733 EmitFormatDiagnostic( 7734 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7735 getSpecifierRange(startSpecifier, specifierLen)); 7736 7737 // Since more arguments than conversion tokens are given, by extension 7738 // all arguments are covered, so mark this as so. 7739 UncoveredArg.setAllCovered(); 7740 return false; 7741 } 7742 return true; 7743 } 7744 7745 template<typename Range> 7746 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7747 SourceLocation Loc, 7748 bool IsStringLocation, 7749 Range StringRange, 7750 ArrayRef<FixItHint> FixIt) { 7751 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7752 Loc, IsStringLocation, StringRange, FixIt); 7753 } 7754 7755 /// If the format string is not within the function call, emit a note 7756 /// so that the function call and string are in diagnostic messages. 7757 /// 7758 /// \param InFunctionCall if true, the format string is within the function 7759 /// call and only one diagnostic message will be produced. Otherwise, an 7760 /// extra note will be emitted pointing to location of the format string. 7761 /// 7762 /// \param ArgumentExpr the expression that is passed as the format string 7763 /// argument in the function call. Used for getting locations when two 7764 /// diagnostics are emitted. 7765 /// 7766 /// \param PDiag the callee should already have provided any strings for the 7767 /// diagnostic message. This function only adds locations and fixits 7768 /// to diagnostics. 7769 /// 7770 /// \param Loc primary location for diagnostic. If two diagnostics are 7771 /// required, one will be at Loc and a new SourceLocation will be created for 7772 /// the other one. 7773 /// 7774 /// \param IsStringLocation if true, Loc points to the format string should be 7775 /// used for the note. Otherwise, Loc points to the argument list and will 7776 /// be used with PDiag. 7777 /// 7778 /// \param StringRange some or all of the string to highlight. This is 7779 /// templated so it can accept either a CharSourceRange or a SourceRange. 7780 /// 7781 /// \param FixIt optional fix it hint for the format string. 7782 template <typename Range> 7783 void CheckFormatHandler::EmitFormatDiagnostic( 7784 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7785 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7786 Range StringRange, ArrayRef<FixItHint> FixIt) { 7787 if (InFunctionCall) { 7788 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7789 D << StringRange; 7790 D << FixIt; 7791 } else { 7792 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7793 << ArgumentExpr->getSourceRange(); 7794 7795 const Sema::SemaDiagnosticBuilder &Note = 7796 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7797 diag::note_format_string_defined); 7798 7799 Note << StringRange; 7800 Note << FixIt; 7801 } 7802 } 7803 7804 //===--- CHECK: Printf format string checking ------------------------------===// 7805 7806 namespace { 7807 7808 class CheckPrintfHandler : public CheckFormatHandler { 7809 public: 7810 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7811 const Expr *origFormatExpr, 7812 const Sema::FormatStringType type, unsigned firstDataArg, 7813 unsigned numDataArgs, bool isObjC, const char *beg, 7814 bool hasVAListArg, ArrayRef<const Expr *> Args, 7815 unsigned formatIdx, bool inFunctionCall, 7816 Sema::VariadicCallType CallType, 7817 llvm::SmallBitVector &CheckedVarArgs, 7818 UncoveredArgHandler &UncoveredArg) 7819 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7820 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7821 inFunctionCall, CallType, CheckedVarArgs, 7822 UncoveredArg) {} 7823 7824 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7825 7826 /// Returns true if '%@' specifiers are allowed in the format string. 7827 bool allowsObjCArg() const { 7828 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7829 FSType == Sema::FST_OSTrace; 7830 } 7831 7832 bool HandleInvalidPrintfConversionSpecifier( 7833 const analyze_printf::PrintfSpecifier &FS, 7834 const char *startSpecifier, 7835 unsigned specifierLen) override; 7836 7837 void handleInvalidMaskType(StringRef MaskType) override; 7838 7839 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7840 const char *startSpecifier, 7841 unsigned specifierLen) override; 7842 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7843 const char *StartSpecifier, 7844 unsigned SpecifierLen, 7845 const Expr *E); 7846 7847 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7848 const char *startSpecifier, unsigned specifierLen); 7849 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7850 const analyze_printf::OptionalAmount &Amt, 7851 unsigned type, 7852 const char *startSpecifier, unsigned specifierLen); 7853 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7854 const analyze_printf::OptionalFlag &flag, 7855 const char *startSpecifier, unsigned specifierLen); 7856 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7857 const analyze_printf::OptionalFlag &ignoredFlag, 7858 const analyze_printf::OptionalFlag &flag, 7859 const char *startSpecifier, unsigned specifierLen); 7860 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7861 const Expr *E); 7862 7863 void HandleEmptyObjCModifierFlag(const char *startFlag, 7864 unsigned flagLen) override; 7865 7866 void HandleInvalidObjCModifierFlag(const char *startFlag, 7867 unsigned flagLen) override; 7868 7869 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7870 const char *flagsEnd, 7871 const char *conversionPosition) 7872 override; 7873 }; 7874 7875 } // namespace 7876 7877 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7878 const analyze_printf::PrintfSpecifier &FS, 7879 const char *startSpecifier, 7880 unsigned specifierLen) { 7881 const analyze_printf::PrintfConversionSpecifier &CS = 7882 FS.getConversionSpecifier(); 7883 7884 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7885 getLocationOfByte(CS.getStart()), 7886 startSpecifier, specifierLen, 7887 CS.getStart(), CS.getLength()); 7888 } 7889 7890 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7891 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7892 } 7893 7894 bool CheckPrintfHandler::HandleAmount( 7895 const analyze_format_string::OptionalAmount &Amt, 7896 unsigned k, const char *startSpecifier, 7897 unsigned specifierLen) { 7898 if (Amt.hasDataArgument()) { 7899 if (!HasVAListArg) { 7900 unsigned argIndex = Amt.getArgIndex(); 7901 if (argIndex >= NumDataArgs) { 7902 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7903 << k, 7904 getLocationOfByte(Amt.getStart()), 7905 /*IsStringLocation*/true, 7906 getSpecifierRange(startSpecifier, specifierLen)); 7907 // Don't do any more checking. We will just emit 7908 // spurious errors. 7909 return false; 7910 } 7911 7912 // Type check the data argument. It should be an 'int'. 7913 // Although not in conformance with C99, we also allow the argument to be 7914 // an 'unsigned int' as that is a reasonably safe case. GCC also 7915 // doesn't emit a warning for that case. 7916 CoveredArgs.set(argIndex); 7917 const Expr *Arg = getDataArg(argIndex); 7918 if (!Arg) 7919 return false; 7920 7921 QualType T = Arg->getType(); 7922 7923 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7924 assert(AT.isValid()); 7925 7926 if (!AT.matchesType(S.Context, T)) { 7927 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7928 << k << AT.getRepresentativeTypeName(S.Context) 7929 << T << Arg->getSourceRange(), 7930 getLocationOfByte(Amt.getStart()), 7931 /*IsStringLocation*/true, 7932 getSpecifierRange(startSpecifier, specifierLen)); 7933 // Don't do any more checking. We will just emit 7934 // spurious errors. 7935 return false; 7936 } 7937 } 7938 } 7939 return true; 7940 } 7941 7942 void CheckPrintfHandler::HandleInvalidAmount( 7943 const analyze_printf::PrintfSpecifier &FS, 7944 const analyze_printf::OptionalAmount &Amt, 7945 unsigned type, 7946 const char *startSpecifier, 7947 unsigned specifierLen) { 7948 const analyze_printf::PrintfConversionSpecifier &CS = 7949 FS.getConversionSpecifier(); 7950 7951 FixItHint fixit = 7952 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7953 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7954 Amt.getConstantLength())) 7955 : FixItHint(); 7956 7957 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7958 << type << CS.toString(), 7959 getLocationOfByte(Amt.getStart()), 7960 /*IsStringLocation*/true, 7961 getSpecifierRange(startSpecifier, specifierLen), 7962 fixit); 7963 } 7964 7965 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7966 const analyze_printf::OptionalFlag &flag, 7967 const char *startSpecifier, 7968 unsigned specifierLen) { 7969 // Warn about pointless flag with a fixit removal. 7970 const analyze_printf::PrintfConversionSpecifier &CS = 7971 FS.getConversionSpecifier(); 7972 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7973 << flag.toString() << CS.toString(), 7974 getLocationOfByte(flag.getPosition()), 7975 /*IsStringLocation*/true, 7976 getSpecifierRange(startSpecifier, specifierLen), 7977 FixItHint::CreateRemoval( 7978 getSpecifierRange(flag.getPosition(), 1))); 7979 } 7980 7981 void CheckPrintfHandler::HandleIgnoredFlag( 7982 const analyze_printf::PrintfSpecifier &FS, 7983 const analyze_printf::OptionalFlag &ignoredFlag, 7984 const analyze_printf::OptionalFlag &flag, 7985 const char *startSpecifier, 7986 unsigned specifierLen) { 7987 // Warn about ignored flag with a fixit removal. 7988 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7989 << ignoredFlag.toString() << flag.toString(), 7990 getLocationOfByte(ignoredFlag.getPosition()), 7991 /*IsStringLocation*/true, 7992 getSpecifierRange(startSpecifier, specifierLen), 7993 FixItHint::CreateRemoval( 7994 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7995 } 7996 7997 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7998 unsigned flagLen) { 7999 // Warn about an empty flag. 8000 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8001 getLocationOfByte(startFlag), 8002 /*IsStringLocation*/true, 8003 getSpecifierRange(startFlag, flagLen)); 8004 } 8005 8006 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8007 unsigned flagLen) { 8008 // Warn about an invalid flag. 8009 auto Range = getSpecifierRange(startFlag, flagLen); 8010 StringRef flag(startFlag, flagLen); 8011 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8012 getLocationOfByte(startFlag), 8013 /*IsStringLocation*/true, 8014 Range, FixItHint::CreateRemoval(Range)); 8015 } 8016 8017 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8018 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8019 // Warn about using '[...]' without a '@' conversion. 8020 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8021 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8022 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8023 getLocationOfByte(conversionPosition), 8024 /*IsStringLocation*/true, 8025 Range, FixItHint::CreateRemoval(Range)); 8026 } 8027 8028 // Determines if the specified is a C++ class or struct containing 8029 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8030 // "c_str()"). 8031 template<typename MemberKind> 8032 static llvm::SmallPtrSet<MemberKind*, 1> 8033 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8034 const RecordType *RT = Ty->getAs<RecordType>(); 8035 llvm::SmallPtrSet<MemberKind*, 1> Results; 8036 8037 if (!RT) 8038 return Results; 8039 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8040 if (!RD || !RD->getDefinition()) 8041 return Results; 8042 8043 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8044 Sema::LookupMemberName); 8045 R.suppressDiagnostics(); 8046 8047 // We just need to include all members of the right kind turned up by the 8048 // filter, at this point. 8049 if (S.LookupQualifiedName(R, RT->getDecl())) 8050 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8051 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8052 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8053 Results.insert(FK); 8054 } 8055 return Results; 8056 } 8057 8058 /// Check if we could call '.c_str()' on an object. 8059 /// 8060 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8061 /// allow the call, or if it would be ambiguous). 8062 bool Sema::hasCStrMethod(const Expr *E) { 8063 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8064 8065 MethodSet Results = 8066 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8067 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8068 MI != ME; ++MI) 8069 if ((*MI)->getMinRequiredArguments() == 0) 8070 return true; 8071 return false; 8072 } 8073 8074 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8075 // better diagnostic if so. AT is assumed to be valid. 8076 // Returns true when a c_str() conversion method is found. 8077 bool CheckPrintfHandler::checkForCStrMembers( 8078 const analyze_printf::ArgType &AT, const Expr *E) { 8079 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8080 8081 MethodSet Results = 8082 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8083 8084 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8085 MI != ME; ++MI) { 8086 const CXXMethodDecl *Method = *MI; 8087 if (Method->getMinRequiredArguments() == 0 && 8088 AT.matchesType(S.Context, Method->getReturnType())) { 8089 // FIXME: Suggest parens if the expression needs them. 8090 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8091 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8092 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8093 return true; 8094 } 8095 } 8096 8097 return false; 8098 } 8099 8100 bool 8101 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8102 &FS, 8103 const char *startSpecifier, 8104 unsigned specifierLen) { 8105 using namespace analyze_format_string; 8106 using namespace analyze_printf; 8107 8108 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8109 8110 if (FS.consumesDataArgument()) { 8111 if (atFirstArg) { 8112 atFirstArg = false; 8113 usesPositionalArgs = FS.usesPositionalArg(); 8114 } 8115 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8116 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8117 startSpecifier, specifierLen); 8118 return false; 8119 } 8120 } 8121 8122 // First check if the field width, precision, and conversion specifier 8123 // have matching data arguments. 8124 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8125 startSpecifier, specifierLen)) { 8126 return false; 8127 } 8128 8129 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8130 startSpecifier, specifierLen)) { 8131 return false; 8132 } 8133 8134 if (!CS.consumesDataArgument()) { 8135 // FIXME: Technically specifying a precision or field width here 8136 // makes no sense. Worth issuing a warning at some point. 8137 return true; 8138 } 8139 8140 // Consume the argument. 8141 unsigned argIndex = FS.getArgIndex(); 8142 if (argIndex < NumDataArgs) { 8143 // The check to see if the argIndex is valid will come later. 8144 // We set the bit here because we may exit early from this 8145 // function if we encounter some other error. 8146 CoveredArgs.set(argIndex); 8147 } 8148 8149 // FreeBSD kernel extensions. 8150 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8151 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8152 // We need at least two arguments. 8153 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8154 return false; 8155 8156 // Claim the second argument. 8157 CoveredArgs.set(argIndex + 1); 8158 8159 // Type check the first argument (int for %b, pointer for %D) 8160 const Expr *Ex = getDataArg(argIndex); 8161 const analyze_printf::ArgType &AT = 8162 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8163 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8164 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8165 EmitFormatDiagnostic( 8166 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8167 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8168 << false << Ex->getSourceRange(), 8169 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8170 getSpecifierRange(startSpecifier, specifierLen)); 8171 8172 // Type check the second argument (char * for both %b and %D) 8173 Ex = getDataArg(argIndex + 1); 8174 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8175 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8176 EmitFormatDiagnostic( 8177 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8178 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8179 << false << Ex->getSourceRange(), 8180 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8181 getSpecifierRange(startSpecifier, specifierLen)); 8182 8183 return true; 8184 } 8185 8186 // Check for using an Objective-C specific conversion specifier 8187 // in a non-ObjC literal. 8188 if (!allowsObjCArg() && CS.isObjCArg()) { 8189 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8190 specifierLen); 8191 } 8192 8193 // %P can only be used with os_log. 8194 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8195 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8196 specifierLen); 8197 } 8198 8199 // %n is not allowed with os_log. 8200 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8201 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8202 getLocationOfByte(CS.getStart()), 8203 /*IsStringLocation*/ false, 8204 getSpecifierRange(startSpecifier, specifierLen)); 8205 8206 return true; 8207 } 8208 8209 // Only scalars are allowed for os_trace. 8210 if (FSType == Sema::FST_OSTrace && 8211 (CS.getKind() == ConversionSpecifier::PArg || 8212 CS.getKind() == ConversionSpecifier::sArg || 8213 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8214 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8215 specifierLen); 8216 } 8217 8218 // Check for use of public/private annotation outside of os_log(). 8219 if (FSType != Sema::FST_OSLog) { 8220 if (FS.isPublic().isSet()) { 8221 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8222 << "public", 8223 getLocationOfByte(FS.isPublic().getPosition()), 8224 /*IsStringLocation*/ false, 8225 getSpecifierRange(startSpecifier, specifierLen)); 8226 } 8227 if (FS.isPrivate().isSet()) { 8228 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8229 << "private", 8230 getLocationOfByte(FS.isPrivate().getPosition()), 8231 /*IsStringLocation*/ false, 8232 getSpecifierRange(startSpecifier, specifierLen)); 8233 } 8234 } 8235 8236 // Check for invalid use of field width 8237 if (!FS.hasValidFieldWidth()) { 8238 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8239 startSpecifier, specifierLen); 8240 } 8241 8242 // Check for invalid use of precision 8243 if (!FS.hasValidPrecision()) { 8244 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8245 startSpecifier, specifierLen); 8246 } 8247 8248 // Precision is mandatory for %P specifier. 8249 if (CS.getKind() == ConversionSpecifier::PArg && 8250 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8251 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8252 getLocationOfByte(startSpecifier), 8253 /*IsStringLocation*/ false, 8254 getSpecifierRange(startSpecifier, specifierLen)); 8255 } 8256 8257 // Check each flag does not conflict with any other component. 8258 if (!FS.hasValidThousandsGroupingPrefix()) 8259 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8260 if (!FS.hasValidLeadingZeros()) 8261 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8262 if (!FS.hasValidPlusPrefix()) 8263 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8264 if (!FS.hasValidSpacePrefix()) 8265 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8266 if (!FS.hasValidAlternativeForm()) 8267 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8268 if (!FS.hasValidLeftJustified()) 8269 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8270 8271 // Check that flags are not ignored by another flag 8272 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8273 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8274 startSpecifier, specifierLen); 8275 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8276 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8277 startSpecifier, specifierLen); 8278 8279 // Check the length modifier is valid with the given conversion specifier. 8280 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8281 S.getLangOpts())) 8282 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8283 diag::warn_format_nonsensical_length); 8284 else if (!FS.hasStandardLengthModifier()) 8285 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8286 else if (!FS.hasStandardLengthConversionCombination()) 8287 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8288 diag::warn_format_non_standard_conversion_spec); 8289 8290 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8291 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8292 8293 // The remaining checks depend on the data arguments. 8294 if (HasVAListArg) 8295 return true; 8296 8297 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8298 return false; 8299 8300 const Expr *Arg = getDataArg(argIndex); 8301 if (!Arg) 8302 return true; 8303 8304 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8305 } 8306 8307 static bool requiresParensToAddCast(const Expr *E) { 8308 // FIXME: We should have a general way to reason about operator 8309 // precedence and whether parens are actually needed here. 8310 // Take care of a few common cases where they aren't. 8311 const Expr *Inside = E->IgnoreImpCasts(); 8312 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8313 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8314 8315 switch (Inside->getStmtClass()) { 8316 case Stmt::ArraySubscriptExprClass: 8317 case Stmt::CallExprClass: 8318 case Stmt::CharacterLiteralClass: 8319 case Stmt::CXXBoolLiteralExprClass: 8320 case Stmt::DeclRefExprClass: 8321 case Stmt::FloatingLiteralClass: 8322 case Stmt::IntegerLiteralClass: 8323 case Stmt::MemberExprClass: 8324 case Stmt::ObjCArrayLiteralClass: 8325 case Stmt::ObjCBoolLiteralExprClass: 8326 case Stmt::ObjCBoxedExprClass: 8327 case Stmt::ObjCDictionaryLiteralClass: 8328 case Stmt::ObjCEncodeExprClass: 8329 case Stmt::ObjCIvarRefExprClass: 8330 case Stmt::ObjCMessageExprClass: 8331 case Stmt::ObjCPropertyRefExprClass: 8332 case Stmt::ObjCStringLiteralClass: 8333 case Stmt::ObjCSubscriptRefExprClass: 8334 case Stmt::ParenExprClass: 8335 case Stmt::StringLiteralClass: 8336 case Stmt::UnaryOperatorClass: 8337 return false; 8338 default: 8339 return true; 8340 } 8341 } 8342 8343 static std::pair<QualType, StringRef> 8344 shouldNotPrintDirectly(const ASTContext &Context, 8345 QualType IntendedTy, 8346 const Expr *E) { 8347 // Use a 'while' to peel off layers of typedefs. 8348 QualType TyTy = IntendedTy; 8349 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8350 StringRef Name = UserTy->getDecl()->getName(); 8351 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8352 .Case("CFIndex", Context.getNSIntegerType()) 8353 .Case("NSInteger", Context.getNSIntegerType()) 8354 .Case("NSUInteger", Context.getNSUIntegerType()) 8355 .Case("SInt32", Context.IntTy) 8356 .Case("UInt32", Context.UnsignedIntTy) 8357 .Default(QualType()); 8358 8359 if (!CastTy.isNull()) 8360 return std::make_pair(CastTy, Name); 8361 8362 TyTy = UserTy->desugar(); 8363 } 8364 8365 // Strip parens if necessary. 8366 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8367 return shouldNotPrintDirectly(Context, 8368 PE->getSubExpr()->getType(), 8369 PE->getSubExpr()); 8370 8371 // If this is a conditional expression, then its result type is constructed 8372 // via usual arithmetic conversions and thus there might be no necessary 8373 // typedef sugar there. Recurse to operands to check for NSInteger & 8374 // Co. usage condition. 8375 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8376 QualType TrueTy, FalseTy; 8377 StringRef TrueName, FalseName; 8378 8379 std::tie(TrueTy, TrueName) = 8380 shouldNotPrintDirectly(Context, 8381 CO->getTrueExpr()->getType(), 8382 CO->getTrueExpr()); 8383 std::tie(FalseTy, FalseName) = 8384 shouldNotPrintDirectly(Context, 8385 CO->getFalseExpr()->getType(), 8386 CO->getFalseExpr()); 8387 8388 if (TrueTy == FalseTy) 8389 return std::make_pair(TrueTy, TrueName); 8390 else if (TrueTy.isNull()) 8391 return std::make_pair(FalseTy, FalseName); 8392 else if (FalseTy.isNull()) 8393 return std::make_pair(TrueTy, TrueName); 8394 } 8395 8396 return std::make_pair(QualType(), StringRef()); 8397 } 8398 8399 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8400 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8401 /// type do not count. 8402 static bool 8403 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8404 QualType From = ICE->getSubExpr()->getType(); 8405 QualType To = ICE->getType(); 8406 // It's an integer promotion if the destination type is the promoted 8407 // source type. 8408 if (ICE->getCastKind() == CK_IntegralCast && 8409 From->isPromotableIntegerType() && 8410 S.Context.getPromotedIntegerType(From) == To) 8411 return true; 8412 // Look through vector types, since we do default argument promotion for 8413 // those in OpenCL. 8414 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8415 From = VecTy->getElementType(); 8416 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8417 To = VecTy->getElementType(); 8418 // It's a floating promotion if the source type is a lower rank. 8419 return ICE->getCastKind() == CK_FloatingCast && 8420 S.Context.getFloatingTypeOrder(From, To) < 0; 8421 } 8422 8423 bool 8424 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8425 const char *StartSpecifier, 8426 unsigned SpecifierLen, 8427 const Expr *E) { 8428 using namespace analyze_format_string; 8429 using namespace analyze_printf; 8430 8431 // Now type check the data expression that matches the 8432 // format specifier. 8433 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8434 if (!AT.isValid()) 8435 return true; 8436 8437 QualType ExprTy = E->getType(); 8438 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8439 ExprTy = TET->getUnderlyingExpr()->getType(); 8440 } 8441 8442 // Diagnose attempts to print a boolean value as a character. Unlike other 8443 // -Wformat diagnostics, this is fine from a type perspective, but it still 8444 // doesn't make sense. 8445 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8446 E->isKnownToHaveBooleanValue()) { 8447 const CharSourceRange &CSR = 8448 getSpecifierRange(StartSpecifier, SpecifierLen); 8449 SmallString<4> FSString; 8450 llvm::raw_svector_ostream os(FSString); 8451 FS.toString(os); 8452 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8453 << FSString, 8454 E->getExprLoc(), false, CSR); 8455 return true; 8456 } 8457 8458 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8459 if (Match == analyze_printf::ArgType::Match) 8460 return true; 8461 8462 // Look through argument promotions for our error message's reported type. 8463 // This includes the integral and floating promotions, but excludes array 8464 // and function pointer decay (seeing that an argument intended to be a 8465 // string has type 'char [6]' is probably more confusing than 'char *') and 8466 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8467 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8468 if (isArithmeticArgumentPromotion(S, ICE)) { 8469 E = ICE->getSubExpr(); 8470 ExprTy = E->getType(); 8471 8472 // Check if we didn't match because of an implicit cast from a 'char' 8473 // or 'short' to an 'int'. This is done because printf is a varargs 8474 // function. 8475 if (ICE->getType() == S.Context.IntTy || 8476 ICE->getType() == S.Context.UnsignedIntTy) { 8477 // All further checking is done on the subexpression 8478 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8479 AT.matchesType(S.Context, ExprTy); 8480 if (ImplicitMatch == analyze_printf::ArgType::Match) 8481 return true; 8482 if (ImplicitMatch == ArgType::NoMatchPedantic || 8483 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8484 Match = ImplicitMatch; 8485 } 8486 } 8487 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8488 // Special case for 'a', which has type 'int' in C. 8489 // Note, however, that we do /not/ want to treat multibyte constants like 8490 // 'MooV' as characters! This form is deprecated but still exists. 8491 if (ExprTy == S.Context.IntTy) 8492 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8493 ExprTy = S.Context.CharTy; 8494 } 8495 8496 // Look through enums to their underlying type. 8497 bool IsEnum = false; 8498 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8499 ExprTy = EnumTy->getDecl()->getIntegerType(); 8500 IsEnum = true; 8501 } 8502 8503 // %C in an Objective-C context prints a unichar, not a wchar_t. 8504 // If the argument is an integer of some kind, believe the %C and suggest 8505 // a cast instead of changing the conversion specifier. 8506 QualType IntendedTy = ExprTy; 8507 if (isObjCContext() && 8508 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8509 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8510 !ExprTy->isCharType()) { 8511 // 'unichar' is defined as a typedef of unsigned short, but we should 8512 // prefer using the typedef if it is visible. 8513 IntendedTy = S.Context.UnsignedShortTy; 8514 8515 // While we are here, check if the value is an IntegerLiteral that happens 8516 // to be within the valid range. 8517 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8518 const llvm::APInt &V = IL->getValue(); 8519 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8520 return true; 8521 } 8522 8523 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8524 Sema::LookupOrdinaryName); 8525 if (S.LookupName(Result, S.getCurScope())) { 8526 NamedDecl *ND = Result.getFoundDecl(); 8527 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8528 if (TD->getUnderlyingType() == IntendedTy) 8529 IntendedTy = S.Context.getTypedefType(TD); 8530 } 8531 } 8532 } 8533 8534 // Special-case some of Darwin's platform-independence types by suggesting 8535 // casts to primitive types that are known to be large enough. 8536 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8537 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8538 QualType CastTy; 8539 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8540 if (!CastTy.isNull()) { 8541 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8542 // (long in ASTContext). Only complain to pedants. 8543 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8544 (AT.isSizeT() || AT.isPtrdiffT()) && 8545 AT.matchesType(S.Context, CastTy)) 8546 Match = ArgType::NoMatchPedantic; 8547 IntendedTy = CastTy; 8548 ShouldNotPrintDirectly = true; 8549 } 8550 } 8551 8552 // We may be able to offer a FixItHint if it is a supported type. 8553 PrintfSpecifier fixedFS = FS; 8554 bool Success = 8555 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8556 8557 if (Success) { 8558 // Get the fix string from the fixed format specifier 8559 SmallString<16> buf; 8560 llvm::raw_svector_ostream os(buf); 8561 fixedFS.toString(os); 8562 8563 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8564 8565 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8566 unsigned Diag; 8567 switch (Match) { 8568 case ArgType::Match: llvm_unreachable("expected non-matching"); 8569 case ArgType::NoMatchPedantic: 8570 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8571 break; 8572 case ArgType::NoMatchTypeConfusion: 8573 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8574 break; 8575 case ArgType::NoMatch: 8576 Diag = diag::warn_format_conversion_argument_type_mismatch; 8577 break; 8578 } 8579 8580 // In this case, the specifier is wrong and should be changed to match 8581 // the argument. 8582 EmitFormatDiagnostic(S.PDiag(Diag) 8583 << AT.getRepresentativeTypeName(S.Context) 8584 << IntendedTy << IsEnum << E->getSourceRange(), 8585 E->getBeginLoc(), 8586 /*IsStringLocation*/ false, SpecRange, 8587 FixItHint::CreateReplacement(SpecRange, os.str())); 8588 } else { 8589 // The canonical type for formatting this value is different from the 8590 // actual type of the expression. (This occurs, for example, with Darwin's 8591 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8592 // should be printed as 'long' for 64-bit compatibility.) 8593 // Rather than emitting a normal format/argument mismatch, we want to 8594 // add a cast to the recommended type (and correct the format string 8595 // if necessary). 8596 SmallString<16> CastBuf; 8597 llvm::raw_svector_ostream CastFix(CastBuf); 8598 CastFix << "("; 8599 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8600 CastFix << ")"; 8601 8602 SmallVector<FixItHint,4> Hints; 8603 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8604 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8605 8606 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8607 // If there's already a cast present, just replace it. 8608 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8609 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8610 8611 } else if (!requiresParensToAddCast(E)) { 8612 // If the expression has high enough precedence, 8613 // just write the C-style cast. 8614 Hints.push_back( 8615 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8616 } else { 8617 // Otherwise, add parens around the expression as well as the cast. 8618 CastFix << "("; 8619 Hints.push_back( 8620 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8621 8622 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8623 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8624 } 8625 8626 if (ShouldNotPrintDirectly) { 8627 // The expression has a type that should not be printed directly. 8628 // We extract the name from the typedef because we don't want to show 8629 // the underlying type in the diagnostic. 8630 StringRef Name; 8631 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8632 Name = TypedefTy->getDecl()->getName(); 8633 else 8634 Name = CastTyName; 8635 unsigned Diag = Match == ArgType::NoMatchPedantic 8636 ? diag::warn_format_argument_needs_cast_pedantic 8637 : diag::warn_format_argument_needs_cast; 8638 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8639 << E->getSourceRange(), 8640 E->getBeginLoc(), /*IsStringLocation=*/false, 8641 SpecRange, Hints); 8642 } else { 8643 // In this case, the expression could be printed using a different 8644 // specifier, but we've decided that the specifier is probably correct 8645 // and we should cast instead. Just use the normal warning message. 8646 EmitFormatDiagnostic( 8647 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8648 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8649 << E->getSourceRange(), 8650 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8651 } 8652 } 8653 } else { 8654 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8655 SpecifierLen); 8656 // Since the warning for passing non-POD types to variadic functions 8657 // was deferred until now, we emit a warning for non-POD 8658 // arguments here. 8659 switch (S.isValidVarArgType(ExprTy)) { 8660 case Sema::VAK_Valid: 8661 case Sema::VAK_ValidInCXX11: { 8662 unsigned Diag; 8663 switch (Match) { 8664 case ArgType::Match: llvm_unreachable("expected non-matching"); 8665 case ArgType::NoMatchPedantic: 8666 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8667 break; 8668 case ArgType::NoMatchTypeConfusion: 8669 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8670 break; 8671 case ArgType::NoMatch: 8672 Diag = diag::warn_format_conversion_argument_type_mismatch; 8673 break; 8674 } 8675 8676 EmitFormatDiagnostic( 8677 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8678 << IsEnum << CSR << E->getSourceRange(), 8679 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8680 break; 8681 } 8682 case Sema::VAK_Undefined: 8683 case Sema::VAK_MSVCUndefined: 8684 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8685 << S.getLangOpts().CPlusPlus11 << ExprTy 8686 << CallType 8687 << AT.getRepresentativeTypeName(S.Context) << CSR 8688 << E->getSourceRange(), 8689 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8690 checkForCStrMembers(AT, E); 8691 break; 8692 8693 case Sema::VAK_Invalid: 8694 if (ExprTy->isObjCObjectType()) 8695 EmitFormatDiagnostic( 8696 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8697 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8698 << AT.getRepresentativeTypeName(S.Context) << CSR 8699 << E->getSourceRange(), 8700 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8701 else 8702 // FIXME: If this is an initializer list, suggest removing the braces 8703 // or inserting a cast to the target type. 8704 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8705 << isa<InitListExpr>(E) << ExprTy << CallType 8706 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8707 break; 8708 } 8709 8710 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8711 "format string specifier index out of range"); 8712 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8713 } 8714 8715 return true; 8716 } 8717 8718 //===--- CHECK: Scanf format string checking ------------------------------===// 8719 8720 namespace { 8721 8722 class CheckScanfHandler : public CheckFormatHandler { 8723 public: 8724 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8725 const Expr *origFormatExpr, Sema::FormatStringType type, 8726 unsigned firstDataArg, unsigned numDataArgs, 8727 const char *beg, bool hasVAListArg, 8728 ArrayRef<const Expr *> Args, unsigned formatIdx, 8729 bool inFunctionCall, Sema::VariadicCallType CallType, 8730 llvm::SmallBitVector &CheckedVarArgs, 8731 UncoveredArgHandler &UncoveredArg) 8732 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8733 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8734 inFunctionCall, CallType, CheckedVarArgs, 8735 UncoveredArg) {} 8736 8737 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8738 const char *startSpecifier, 8739 unsigned specifierLen) override; 8740 8741 bool HandleInvalidScanfConversionSpecifier( 8742 const analyze_scanf::ScanfSpecifier &FS, 8743 const char *startSpecifier, 8744 unsigned specifierLen) override; 8745 8746 void HandleIncompleteScanList(const char *start, const char *end) override; 8747 }; 8748 8749 } // namespace 8750 8751 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8752 const char *end) { 8753 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8754 getLocationOfByte(end), /*IsStringLocation*/true, 8755 getSpecifierRange(start, end - start)); 8756 } 8757 8758 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8759 const analyze_scanf::ScanfSpecifier &FS, 8760 const char *startSpecifier, 8761 unsigned specifierLen) { 8762 const analyze_scanf::ScanfConversionSpecifier &CS = 8763 FS.getConversionSpecifier(); 8764 8765 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8766 getLocationOfByte(CS.getStart()), 8767 startSpecifier, specifierLen, 8768 CS.getStart(), CS.getLength()); 8769 } 8770 8771 bool CheckScanfHandler::HandleScanfSpecifier( 8772 const analyze_scanf::ScanfSpecifier &FS, 8773 const char *startSpecifier, 8774 unsigned specifierLen) { 8775 using namespace analyze_scanf; 8776 using namespace analyze_format_string; 8777 8778 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8779 8780 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8781 // be used to decide if we are using positional arguments consistently. 8782 if (FS.consumesDataArgument()) { 8783 if (atFirstArg) { 8784 atFirstArg = false; 8785 usesPositionalArgs = FS.usesPositionalArg(); 8786 } 8787 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8788 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8789 startSpecifier, specifierLen); 8790 return false; 8791 } 8792 } 8793 8794 // Check if the field with is non-zero. 8795 const OptionalAmount &Amt = FS.getFieldWidth(); 8796 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8797 if (Amt.getConstantAmount() == 0) { 8798 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8799 Amt.getConstantLength()); 8800 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8801 getLocationOfByte(Amt.getStart()), 8802 /*IsStringLocation*/true, R, 8803 FixItHint::CreateRemoval(R)); 8804 } 8805 } 8806 8807 if (!FS.consumesDataArgument()) { 8808 // FIXME: Technically specifying a precision or field width here 8809 // makes no sense. Worth issuing a warning at some point. 8810 return true; 8811 } 8812 8813 // Consume the argument. 8814 unsigned argIndex = FS.getArgIndex(); 8815 if (argIndex < NumDataArgs) { 8816 // The check to see if the argIndex is valid will come later. 8817 // We set the bit here because we may exit early from this 8818 // function if we encounter some other error. 8819 CoveredArgs.set(argIndex); 8820 } 8821 8822 // Check the length modifier is valid with the given conversion specifier. 8823 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8824 S.getLangOpts())) 8825 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8826 diag::warn_format_nonsensical_length); 8827 else if (!FS.hasStandardLengthModifier()) 8828 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8829 else if (!FS.hasStandardLengthConversionCombination()) 8830 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8831 diag::warn_format_non_standard_conversion_spec); 8832 8833 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8834 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8835 8836 // The remaining checks depend on the data arguments. 8837 if (HasVAListArg) 8838 return true; 8839 8840 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8841 return false; 8842 8843 // Check that the argument type matches the format specifier. 8844 const Expr *Ex = getDataArg(argIndex); 8845 if (!Ex) 8846 return true; 8847 8848 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8849 8850 if (!AT.isValid()) { 8851 return true; 8852 } 8853 8854 analyze_format_string::ArgType::MatchKind Match = 8855 AT.matchesType(S.Context, Ex->getType()); 8856 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8857 if (Match == analyze_format_string::ArgType::Match) 8858 return true; 8859 8860 ScanfSpecifier fixedFS = FS; 8861 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8862 S.getLangOpts(), S.Context); 8863 8864 unsigned Diag = 8865 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8866 : diag::warn_format_conversion_argument_type_mismatch; 8867 8868 if (Success) { 8869 // Get the fix string from the fixed format specifier. 8870 SmallString<128> buf; 8871 llvm::raw_svector_ostream os(buf); 8872 fixedFS.toString(os); 8873 8874 EmitFormatDiagnostic( 8875 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8876 << Ex->getType() << false << Ex->getSourceRange(), 8877 Ex->getBeginLoc(), 8878 /*IsStringLocation*/ false, 8879 getSpecifierRange(startSpecifier, specifierLen), 8880 FixItHint::CreateReplacement( 8881 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8882 } else { 8883 EmitFormatDiagnostic(S.PDiag(Diag) 8884 << AT.getRepresentativeTypeName(S.Context) 8885 << Ex->getType() << false << Ex->getSourceRange(), 8886 Ex->getBeginLoc(), 8887 /*IsStringLocation*/ false, 8888 getSpecifierRange(startSpecifier, specifierLen)); 8889 } 8890 8891 return true; 8892 } 8893 8894 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8895 const Expr *OrigFormatExpr, 8896 ArrayRef<const Expr *> Args, 8897 bool HasVAListArg, unsigned format_idx, 8898 unsigned firstDataArg, 8899 Sema::FormatStringType Type, 8900 bool inFunctionCall, 8901 Sema::VariadicCallType CallType, 8902 llvm::SmallBitVector &CheckedVarArgs, 8903 UncoveredArgHandler &UncoveredArg, 8904 bool IgnoreStringsWithoutSpecifiers) { 8905 // CHECK: is the format string a wide literal? 8906 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8907 CheckFormatHandler::EmitFormatDiagnostic( 8908 S, inFunctionCall, Args[format_idx], 8909 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8910 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8911 return; 8912 } 8913 8914 // Str - The format string. NOTE: this is NOT null-terminated! 8915 StringRef StrRef = FExpr->getString(); 8916 const char *Str = StrRef.data(); 8917 // Account for cases where the string literal is truncated in a declaration. 8918 const ConstantArrayType *T = 8919 S.Context.getAsConstantArrayType(FExpr->getType()); 8920 assert(T && "String literal not of constant array type!"); 8921 size_t TypeSize = T->getSize().getZExtValue(); 8922 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8923 const unsigned numDataArgs = Args.size() - firstDataArg; 8924 8925 if (IgnoreStringsWithoutSpecifiers && 8926 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8927 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8928 return; 8929 8930 // Emit a warning if the string literal is truncated and does not contain an 8931 // embedded null character. 8932 if (TypeSize <= StrRef.size() && 8933 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8934 CheckFormatHandler::EmitFormatDiagnostic( 8935 S, inFunctionCall, Args[format_idx], 8936 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8937 FExpr->getBeginLoc(), 8938 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8939 return; 8940 } 8941 8942 // CHECK: empty format string? 8943 if (StrLen == 0 && numDataArgs > 0) { 8944 CheckFormatHandler::EmitFormatDiagnostic( 8945 S, inFunctionCall, Args[format_idx], 8946 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8947 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8948 return; 8949 } 8950 8951 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8952 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8953 Type == Sema::FST_OSTrace) { 8954 CheckPrintfHandler H( 8955 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8956 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8957 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8958 CheckedVarArgs, UncoveredArg); 8959 8960 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8961 S.getLangOpts(), 8962 S.Context.getTargetInfo(), 8963 Type == Sema::FST_FreeBSDKPrintf)) 8964 H.DoneProcessing(); 8965 } else if (Type == Sema::FST_Scanf) { 8966 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8967 numDataArgs, Str, HasVAListArg, Args, format_idx, 8968 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8969 8970 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8971 S.getLangOpts(), 8972 S.Context.getTargetInfo())) 8973 H.DoneProcessing(); 8974 } // TODO: handle other formats 8975 } 8976 8977 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8978 // Str - The format string. NOTE: this is NOT null-terminated! 8979 StringRef StrRef = FExpr->getString(); 8980 const char *Str = StrRef.data(); 8981 // Account for cases where the string literal is truncated in a declaration. 8982 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8983 assert(T && "String literal not of constant array type!"); 8984 size_t TypeSize = T->getSize().getZExtValue(); 8985 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8986 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8987 getLangOpts(), 8988 Context.getTargetInfo()); 8989 } 8990 8991 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8992 8993 // Returns the related absolute value function that is larger, of 0 if one 8994 // does not exist. 8995 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8996 switch (AbsFunction) { 8997 default: 8998 return 0; 8999 9000 case Builtin::BI__builtin_abs: 9001 return Builtin::BI__builtin_labs; 9002 case Builtin::BI__builtin_labs: 9003 return Builtin::BI__builtin_llabs; 9004 case Builtin::BI__builtin_llabs: 9005 return 0; 9006 9007 case Builtin::BI__builtin_fabsf: 9008 return Builtin::BI__builtin_fabs; 9009 case Builtin::BI__builtin_fabs: 9010 return Builtin::BI__builtin_fabsl; 9011 case Builtin::BI__builtin_fabsl: 9012 return 0; 9013 9014 case Builtin::BI__builtin_cabsf: 9015 return Builtin::BI__builtin_cabs; 9016 case Builtin::BI__builtin_cabs: 9017 return Builtin::BI__builtin_cabsl; 9018 case Builtin::BI__builtin_cabsl: 9019 return 0; 9020 9021 case Builtin::BIabs: 9022 return Builtin::BIlabs; 9023 case Builtin::BIlabs: 9024 return Builtin::BIllabs; 9025 case Builtin::BIllabs: 9026 return 0; 9027 9028 case Builtin::BIfabsf: 9029 return Builtin::BIfabs; 9030 case Builtin::BIfabs: 9031 return Builtin::BIfabsl; 9032 case Builtin::BIfabsl: 9033 return 0; 9034 9035 case Builtin::BIcabsf: 9036 return Builtin::BIcabs; 9037 case Builtin::BIcabs: 9038 return Builtin::BIcabsl; 9039 case Builtin::BIcabsl: 9040 return 0; 9041 } 9042 } 9043 9044 // Returns the argument type of the absolute value function. 9045 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9046 unsigned AbsType) { 9047 if (AbsType == 0) 9048 return QualType(); 9049 9050 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9051 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9052 if (Error != ASTContext::GE_None) 9053 return QualType(); 9054 9055 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9056 if (!FT) 9057 return QualType(); 9058 9059 if (FT->getNumParams() != 1) 9060 return QualType(); 9061 9062 return FT->getParamType(0); 9063 } 9064 9065 // Returns the best absolute value function, or zero, based on type and 9066 // current absolute value function. 9067 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9068 unsigned AbsFunctionKind) { 9069 unsigned BestKind = 0; 9070 uint64_t ArgSize = Context.getTypeSize(ArgType); 9071 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9072 Kind = getLargerAbsoluteValueFunction(Kind)) { 9073 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9074 if (Context.getTypeSize(ParamType) >= ArgSize) { 9075 if (BestKind == 0) 9076 BestKind = Kind; 9077 else if (Context.hasSameType(ParamType, ArgType)) { 9078 BestKind = Kind; 9079 break; 9080 } 9081 } 9082 } 9083 return BestKind; 9084 } 9085 9086 enum AbsoluteValueKind { 9087 AVK_Integer, 9088 AVK_Floating, 9089 AVK_Complex 9090 }; 9091 9092 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9093 if (T->isIntegralOrEnumerationType()) 9094 return AVK_Integer; 9095 if (T->isRealFloatingType()) 9096 return AVK_Floating; 9097 if (T->isAnyComplexType()) 9098 return AVK_Complex; 9099 9100 llvm_unreachable("Type not integer, floating, or complex"); 9101 } 9102 9103 // Changes the absolute value function to a different type. Preserves whether 9104 // the function is a builtin. 9105 static unsigned changeAbsFunction(unsigned AbsKind, 9106 AbsoluteValueKind ValueKind) { 9107 switch (ValueKind) { 9108 case AVK_Integer: 9109 switch (AbsKind) { 9110 default: 9111 return 0; 9112 case Builtin::BI__builtin_fabsf: 9113 case Builtin::BI__builtin_fabs: 9114 case Builtin::BI__builtin_fabsl: 9115 case Builtin::BI__builtin_cabsf: 9116 case Builtin::BI__builtin_cabs: 9117 case Builtin::BI__builtin_cabsl: 9118 return Builtin::BI__builtin_abs; 9119 case Builtin::BIfabsf: 9120 case Builtin::BIfabs: 9121 case Builtin::BIfabsl: 9122 case Builtin::BIcabsf: 9123 case Builtin::BIcabs: 9124 case Builtin::BIcabsl: 9125 return Builtin::BIabs; 9126 } 9127 case AVK_Floating: 9128 switch (AbsKind) { 9129 default: 9130 return 0; 9131 case Builtin::BI__builtin_abs: 9132 case Builtin::BI__builtin_labs: 9133 case Builtin::BI__builtin_llabs: 9134 case Builtin::BI__builtin_cabsf: 9135 case Builtin::BI__builtin_cabs: 9136 case Builtin::BI__builtin_cabsl: 9137 return Builtin::BI__builtin_fabsf; 9138 case Builtin::BIabs: 9139 case Builtin::BIlabs: 9140 case Builtin::BIllabs: 9141 case Builtin::BIcabsf: 9142 case Builtin::BIcabs: 9143 case Builtin::BIcabsl: 9144 return Builtin::BIfabsf; 9145 } 9146 case AVK_Complex: 9147 switch (AbsKind) { 9148 default: 9149 return 0; 9150 case Builtin::BI__builtin_abs: 9151 case Builtin::BI__builtin_labs: 9152 case Builtin::BI__builtin_llabs: 9153 case Builtin::BI__builtin_fabsf: 9154 case Builtin::BI__builtin_fabs: 9155 case Builtin::BI__builtin_fabsl: 9156 return Builtin::BI__builtin_cabsf; 9157 case Builtin::BIabs: 9158 case Builtin::BIlabs: 9159 case Builtin::BIllabs: 9160 case Builtin::BIfabsf: 9161 case Builtin::BIfabs: 9162 case Builtin::BIfabsl: 9163 return Builtin::BIcabsf; 9164 } 9165 } 9166 llvm_unreachable("Unable to convert function"); 9167 } 9168 9169 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9170 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9171 if (!FnInfo) 9172 return 0; 9173 9174 switch (FDecl->getBuiltinID()) { 9175 default: 9176 return 0; 9177 case Builtin::BI__builtin_abs: 9178 case Builtin::BI__builtin_fabs: 9179 case Builtin::BI__builtin_fabsf: 9180 case Builtin::BI__builtin_fabsl: 9181 case Builtin::BI__builtin_labs: 9182 case Builtin::BI__builtin_llabs: 9183 case Builtin::BI__builtin_cabs: 9184 case Builtin::BI__builtin_cabsf: 9185 case Builtin::BI__builtin_cabsl: 9186 case Builtin::BIabs: 9187 case Builtin::BIlabs: 9188 case Builtin::BIllabs: 9189 case Builtin::BIfabs: 9190 case Builtin::BIfabsf: 9191 case Builtin::BIfabsl: 9192 case Builtin::BIcabs: 9193 case Builtin::BIcabsf: 9194 case Builtin::BIcabsl: 9195 return FDecl->getBuiltinID(); 9196 } 9197 llvm_unreachable("Unknown Builtin type"); 9198 } 9199 9200 // If the replacement is valid, emit a note with replacement function. 9201 // Additionally, suggest including the proper header if not already included. 9202 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9203 unsigned AbsKind, QualType ArgType) { 9204 bool EmitHeaderHint = true; 9205 const char *HeaderName = nullptr; 9206 const char *FunctionName = nullptr; 9207 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9208 FunctionName = "std::abs"; 9209 if (ArgType->isIntegralOrEnumerationType()) { 9210 HeaderName = "cstdlib"; 9211 } else if (ArgType->isRealFloatingType()) { 9212 HeaderName = "cmath"; 9213 } else { 9214 llvm_unreachable("Invalid Type"); 9215 } 9216 9217 // Lookup all std::abs 9218 if (NamespaceDecl *Std = S.getStdNamespace()) { 9219 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9220 R.suppressDiagnostics(); 9221 S.LookupQualifiedName(R, Std); 9222 9223 for (const auto *I : R) { 9224 const FunctionDecl *FDecl = nullptr; 9225 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9226 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9227 } else { 9228 FDecl = dyn_cast<FunctionDecl>(I); 9229 } 9230 if (!FDecl) 9231 continue; 9232 9233 // Found std::abs(), check that they are the right ones. 9234 if (FDecl->getNumParams() != 1) 9235 continue; 9236 9237 // Check that the parameter type can handle the argument. 9238 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9239 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9240 S.Context.getTypeSize(ArgType) <= 9241 S.Context.getTypeSize(ParamType)) { 9242 // Found a function, don't need the header hint. 9243 EmitHeaderHint = false; 9244 break; 9245 } 9246 } 9247 } 9248 } else { 9249 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9250 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9251 9252 if (HeaderName) { 9253 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9254 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9255 R.suppressDiagnostics(); 9256 S.LookupName(R, S.getCurScope()); 9257 9258 if (R.isSingleResult()) { 9259 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9260 if (FD && FD->getBuiltinID() == AbsKind) { 9261 EmitHeaderHint = false; 9262 } else { 9263 return; 9264 } 9265 } else if (!R.empty()) { 9266 return; 9267 } 9268 } 9269 } 9270 9271 S.Diag(Loc, diag::note_replace_abs_function) 9272 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9273 9274 if (!HeaderName) 9275 return; 9276 9277 if (!EmitHeaderHint) 9278 return; 9279 9280 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9281 << FunctionName; 9282 } 9283 9284 template <std::size_t StrLen> 9285 static bool IsStdFunction(const FunctionDecl *FDecl, 9286 const char (&Str)[StrLen]) { 9287 if (!FDecl) 9288 return false; 9289 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9290 return false; 9291 if (!FDecl->isInStdNamespace()) 9292 return false; 9293 9294 return true; 9295 } 9296 9297 // Warn when using the wrong abs() function. 9298 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9299 const FunctionDecl *FDecl) { 9300 if (Call->getNumArgs() != 1) 9301 return; 9302 9303 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9304 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9305 if (AbsKind == 0 && !IsStdAbs) 9306 return; 9307 9308 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9309 QualType ParamType = Call->getArg(0)->getType(); 9310 9311 // Unsigned types cannot be negative. Suggest removing the absolute value 9312 // function call. 9313 if (ArgType->isUnsignedIntegerType()) { 9314 const char *FunctionName = 9315 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9316 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9317 Diag(Call->getExprLoc(), diag::note_remove_abs) 9318 << FunctionName 9319 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9320 return; 9321 } 9322 9323 // Taking the absolute value of a pointer is very suspicious, they probably 9324 // wanted to index into an array, dereference a pointer, call a function, etc. 9325 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9326 unsigned DiagType = 0; 9327 if (ArgType->isFunctionType()) 9328 DiagType = 1; 9329 else if (ArgType->isArrayType()) 9330 DiagType = 2; 9331 9332 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9333 return; 9334 } 9335 9336 // std::abs has overloads which prevent most of the absolute value problems 9337 // from occurring. 9338 if (IsStdAbs) 9339 return; 9340 9341 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9342 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9343 9344 // The argument and parameter are the same kind. Check if they are the right 9345 // size. 9346 if (ArgValueKind == ParamValueKind) { 9347 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9348 return; 9349 9350 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9351 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9352 << FDecl << ArgType << ParamType; 9353 9354 if (NewAbsKind == 0) 9355 return; 9356 9357 emitReplacement(*this, Call->getExprLoc(), 9358 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9359 return; 9360 } 9361 9362 // ArgValueKind != ParamValueKind 9363 // The wrong type of absolute value function was used. Attempt to find the 9364 // proper one. 9365 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9366 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9367 if (NewAbsKind == 0) 9368 return; 9369 9370 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9371 << FDecl << ParamValueKind << ArgValueKind; 9372 9373 emitReplacement(*this, Call->getExprLoc(), 9374 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9375 } 9376 9377 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9378 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9379 const FunctionDecl *FDecl) { 9380 if (!Call || !FDecl) return; 9381 9382 // Ignore template specializations and macros. 9383 if (inTemplateInstantiation()) return; 9384 if (Call->getExprLoc().isMacroID()) return; 9385 9386 // Only care about the one template argument, two function parameter std::max 9387 if (Call->getNumArgs() != 2) return; 9388 if (!IsStdFunction(FDecl, "max")) return; 9389 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9390 if (!ArgList) return; 9391 if (ArgList->size() != 1) return; 9392 9393 // Check that template type argument is unsigned integer. 9394 const auto& TA = ArgList->get(0); 9395 if (TA.getKind() != TemplateArgument::Type) return; 9396 QualType ArgType = TA.getAsType(); 9397 if (!ArgType->isUnsignedIntegerType()) return; 9398 9399 // See if either argument is a literal zero. 9400 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9401 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9402 if (!MTE) return false; 9403 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9404 if (!Num) return false; 9405 if (Num->getValue() != 0) return false; 9406 return true; 9407 }; 9408 9409 const Expr *FirstArg = Call->getArg(0); 9410 const Expr *SecondArg = Call->getArg(1); 9411 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9412 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9413 9414 // Only warn when exactly one argument is zero. 9415 if (IsFirstArgZero == IsSecondArgZero) return; 9416 9417 SourceRange FirstRange = FirstArg->getSourceRange(); 9418 SourceRange SecondRange = SecondArg->getSourceRange(); 9419 9420 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9421 9422 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9423 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9424 9425 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9426 SourceRange RemovalRange; 9427 if (IsFirstArgZero) { 9428 RemovalRange = SourceRange(FirstRange.getBegin(), 9429 SecondRange.getBegin().getLocWithOffset(-1)); 9430 } else { 9431 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9432 SecondRange.getEnd()); 9433 } 9434 9435 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9436 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9437 << FixItHint::CreateRemoval(RemovalRange); 9438 } 9439 9440 //===--- CHECK: Standard memory functions ---------------------------------===// 9441 9442 /// Takes the expression passed to the size_t parameter of functions 9443 /// such as memcmp, strncat, etc and warns if it's a comparison. 9444 /// 9445 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9446 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9447 IdentifierInfo *FnName, 9448 SourceLocation FnLoc, 9449 SourceLocation RParenLoc) { 9450 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9451 if (!Size) 9452 return false; 9453 9454 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9455 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9456 return false; 9457 9458 SourceRange SizeRange = Size->getSourceRange(); 9459 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9460 << SizeRange << FnName; 9461 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9462 << FnName 9463 << FixItHint::CreateInsertion( 9464 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9465 << FixItHint::CreateRemoval(RParenLoc); 9466 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9467 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9468 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9469 ")"); 9470 9471 return true; 9472 } 9473 9474 /// Determine whether the given type is or contains a dynamic class type 9475 /// (e.g., whether it has a vtable). 9476 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9477 bool &IsContained) { 9478 // Look through array types while ignoring qualifiers. 9479 const Type *Ty = T->getBaseElementTypeUnsafe(); 9480 IsContained = false; 9481 9482 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9483 RD = RD ? RD->getDefinition() : nullptr; 9484 if (!RD || RD->isInvalidDecl()) 9485 return nullptr; 9486 9487 if (RD->isDynamicClass()) 9488 return RD; 9489 9490 // Check all the fields. If any bases were dynamic, the class is dynamic. 9491 // It's impossible for a class to transitively contain itself by value, so 9492 // infinite recursion is impossible. 9493 for (auto *FD : RD->fields()) { 9494 bool SubContained; 9495 if (const CXXRecordDecl *ContainedRD = 9496 getContainedDynamicClass(FD->getType(), SubContained)) { 9497 IsContained = true; 9498 return ContainedRD; 9499 } 9500 } 9501 9502 return nullptr; 9503 } 9504 9505 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9506 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9507 if (Unary->getKind() == UETT_SizeOf) 9508 return Unary; 9509 return nullptr; 9510 } 9511 9512 /// If E is a sizeof expression, returns its argument expression, 9513 /// otherwise returns NULL. 9514 static const Expr *getSizeOfExprArg(const Expr *E) { 9515 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9516 if (!SizeOf->isArgumentType()) 9517 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9518 return nullptr; 9519 } 9520 9521 /// If E is a sizeof expression, returns its argument type. 9522 static QualType getSizeOfArgType(const Expr *E) { 9523 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9524 return SizeOf->getTypeOfArgument(); 9525 return QualType(); 9526 } 9527 9528 namespace { 9529 9530 struct SearchNonTrivialToInitializeField 9531 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9532 using Super = 9533 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9534 9535 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9536 9537 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9538 SourceLocation SL) { 9539 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9540 asDerived().visitArray(PDIK, AT, SL); 9541 return; 9542 } 9543 9544 Super::visitWithKind(PDIK, FT, SL); 9545 } 9546 9547 void visitARCStrong(QualType FT, SourceLocation SL) { 9548 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9549 } 9550 void visitARCWeak(QualType FT, SourceLocation SL) { 9551 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9552 } 9553 void visitStruct(QualType FT, SourceLocation SL) { 9554 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9555 visit(FD->getType(), FD->getLocation()); 9556 } 9557 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9558 const ArrayType *AT, SourceLocation SL) { 9559 visit(getContext().getBaseElementType(AT), SL); 9560 } 9561 void visitTrivial(QualType FT, SourceLocation SL) {} 9562 9563 static void diag(QualType RT, const Expr *E, Sema &S) { 9564 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9565 } 9566 9567 ASTContext &getContext() { return S.getASTContext(); } 9568 9569 const Expr *E; 9570 Sema &S; 9571 }; 9572 9573 struct SearchNonTrivialToCopyField 9574 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9575 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9576 9577 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9578 9579 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9580 SourceLocation SL) { 9581 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9582 asDerived().visitArray(PCK, AT, SL); 9583 return; 9584 } 9585 9586 Super::visitWithKind(PCK, FT, SL); 9587 } 9588 9589 void visitARCStrong(QualType FT, SourceLocation SL) { 9590 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9591 } 9592 void visitARCWeak(QualType FT, SourceLocation SL) { 9593 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9594 } 9595 void visitStruct(QualType FT, SourceLocation SL) { 9596 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9597 visit(FD->getType(), FD->getLocation()); 9598 } 9599 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9600 SourceLocation SL) { 9601 visit(getContext().getBaseElementType(AT), SL); 9602 } 9603 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9604 SourceLocation SL) {} 9605 void visitTrivial(QualType FT, SourceLocation SL) {} 9606 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9607 9608 static void diag(QualType RT, const Expr *E, Sema &S) { 9609 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9610 } 9611 9612 ASTContext &getContext() { return S.getASTContext(); } 9613 9614 const Expr *E; 9615 Sema &S; 9616 }; 9617 9618 } 9619 9620 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9621 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9622 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9623 9624 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9625 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9626 return false; 9627 9628 return doesExprLikelyComputeSize(BO->getLHS()) || 9629 doesExprLikelyComputeSize(BO->getRHS()); 9630 } 9631 9632 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9633 } 9634 9635 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9636 /// 9637 /// \code 9638 /// #define MACRO 0 9639 /// foo(MACRO); 9640 /// foo(0); 9641 /// \endcode 9642 /// 9643 /// This should return true for the first call to foo, but not for the second 9644 /// (regardless of whether foo is a macro or function). 9645 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9646 SourceLocation CallLoc, 9647 SourceLocation ArgLoc) { 9648 if (!CallLoc.isMacroID()) 9649 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9650 9651 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9652 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9653 } 9654 9655 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9656 /// last two arguments transposed. 9657 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9658 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9659 return; 9660 9661 const Expr *SizeArg = 9662 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9663 9664 auto isLiteralZero = [](const Expr *E) { 9665 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9666 }; 9667 9668 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9669 SourceLocation CallLoc = Call->getRParenLoc(); 9670 SourceManager &SM = S.getSourceManager(); 9671 if (isLiteralZero(SizeArg) && 9672 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9673 9674 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9675 9676 // Some platforms #define bzero to __builtin_memset. See if this is the 9677 // case, and if so, emit a better diagnostic. 9678 if (BId == Builtin::BIbzero || 9679 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9680 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9681 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9682 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9683 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9684 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9685 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9686 } 9687 return; 9688 } 9689 9690 // If the second argument to a memset is a sizeof expression and the third 9691 // isn't, this is also likely an error. This should catch 9692 // 'memset(buf, sizeof(buf), 0xff)'. 9693 if (BId == Builtin::BImemset && 9694 doesExprLikelyComputeSize(Call->getArg(1)) && 9695 !doesExprLikelyComputeSize(Call->getArg(2))) { 9696 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9697 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9698 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9699 return; 9700 } 9701 } 9702 9703 /// Check for dangerous or invalid arguments to memset(). 9704 /// 9705 /// This issues warnings on known problematic, dangerous or unspecified 9706 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9707 /// function calls. 9708 /// 9709 /// \param Call The call expression to diagnose. 9710 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9711 unsigned BId, 9712 IdentifierInfo *FnName) { 9713 assert(BId != 0); 9714 9715 // It is possible to have a non-standard definition of memset. Validate 9716 // we have enough arguments, and if not, abort further checking. 9717 unsigned ExpectedNumArgs = 9718 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9719 if (Call->getNumArgs() < ExpectedNumArgs) 9720 return; 9721 9722 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9723 BId == Builtin::BIstrndup ? 1 : 2); 9724 unsigned LenArg = 9725 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9726 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9727 9728 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9729 Call->getBeginLoc(), Call->getRParenLoc())) 9730 return; 9731 9732 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9733 CheckMemaccessSize(*this, BId, Call); 9734 9735 // We have special checking when the length is a sizeof expression. 9736 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9737 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9738 llvm::FoldingSetNodeID SizeOfArgID; 9739 9740 // Although widely used, 'bzero' is not a standard function. Be more strict 9741 // with the argument types before allowing diagnostics and only allow the 9742 // form bzero(ptr, sizeof(...)). 9743 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9744 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9745 return; 9746 9747 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9748 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9749 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9750 9751 QualType DestTy = Dest->getType(); 9752 QualType PointeeTy; 9753 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9754 PointeeTy = DestPtrTy->getPointeeType(); 9755 9756 // Never warn about void type pointers. This can be used to suppress 9757 // false positives. 9758 if (PointeeTy->isVoidType()) 9759 continue; 9760 9761 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9762 // actually comparing the expressions for equality. Because computing the 9763 // expression IDs can be expensive, we only do this if the diagnostic is 9764 // enabled. 9765 if (SizeOfArg && 9766 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9767 SizeOfArg->getExprLoc())) { 9768 // We only compute IDs for expressions if the warning is enabled, and 9769 // cache the sizeof arg's ID. 9770 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9771 SizeOfArg->Profile(SizeOfArgID, Context, true); 9772 llvm::FoldingSetNodeID DestID; 9773 Dest->Profile(DestID, Context, true); 9774 if (DestID == SizeOfArgID) { 9775 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9776 // over sizeof(src) as well. 9777 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9778 StringRef ReadableName = FnName->getName(); 9779 9780 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9781 if (UnaryOp->getOpcode() == UO_AddrOf) 9782 ActionIdx = 1; // If its an address-of operator, just remove it. 9783 if (!PointeeTy->isIncompleteType() && 9784 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9785 ActionIdx = 2; // If the pointee's size is sizeof(char), 9786 // suggest an explicit length. 9787 9788 // If the function is defined as a builtin macro, do not show macro 9789 // expansion. 9790 SourceLocation SL = SizeOfArg->getExprLoc(); 9791 SourceRange DSR = Dest->getSourceRange(); 9792 SourceRange SSR = SizeOfArg->getSourceRange(); 9793 SourceManager &SM = getSourceManager(); 9794 9795 if (SM.isMacroArgExpansion(SL)) { 9796 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9797 SL = SM.getSpellingLoc(SL); 9798 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9799 SM.getSpellingLoc(DSR.getEnd())); 9800 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9801 SM.getSpellingLoc(SSR.getEnd())); 9802 } 9803 9804 DiagRuntimeBehavior(SL, SizeOfArg, 9805 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9806 << ReadableName 9807 << PointeeTy 9808 << DestTy 9809 << DSR 9810 << SSR); 9811 DiagRuntimeBehavior(SL, SizeOfArg, 9812 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9813 << ActionIdx 9814 << SSR); 9815 9816 break; 9817 } 9818 } 9819 9820 // Also check for cases where the sizeof argument is the exact same 9821 // type as the memory argument, and where it points to a user-defined 9822 // record type. 9823 if (SizeOfArgTy != QualType()) { 9824 if (PointeeTy->isRecordType() && 9825 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9826 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9827 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9828 << FnName << SizeOfArgTy << ArgIdx 9829 << PointeeTy << Dest->getSourceRange() 9830 << LenExpr->getSourceRange()); 9831 break; 9832 } 9833 } 9834 } else if (DestTy->isArrayType()) { 9835 PointeeTy = DestTy; 9836 } 9837 9838 if (PointeeTy == QualType()) 9839 continue; 9840 9841 // Always complain about dynamic classes. 9842 bool IsContained; 9843 if (const CXXRecordDecl *ContainedRD = 9844 getContainedDynamicClass(PointeeTy, IsContained)) { 9845 9846 unsigned OperationType = 0; 9847 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9848 // "overwritten" if we're warning about the destination for any call 9849 // but memcmp; otherwise a verb appropriate to the call. 9850 if (ArgIdx != 0 || IsCmp) { 9851 if (BId == Builtin::BImemcpy) 9852 OperationType = 1; 9853 else if(BId == Builtin::BImemmove) 9854 OperationType = 2; 9855 else if (IsCmp) 9856 OperationType = 3; 9857 } 9858 9859 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9860 PDiag(diag::warn_dyn_class_memaccess) 9861 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9862 << IsContained << ContainedRD << OperationType 9863 << Call->getCallee()->getSourceRange()); 9864 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9865 BId != Builtin::BImemset) 9866 DiagRuntimeBehavior( 9867 Dest->getExprLoc(), Dest, 9868 PDiag(diag::warn_arc_object_memaccess) 9869 << ArgIdx << FnName << PointeeTy 9870 << Call->getCallee()->getSourceRange()); 9871 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9872 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9873 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9874 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9875 PDiag(diag::warn_cstruct_memaccess) 9876 << ArgIdx << FnName << PointeeTy << 0); 9877 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9878 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9879 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9880 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9881 PDiag(diag::warn_cstruct_memaccess) 9882 << ArgIdx << FnName << PointeeTy << 1); 9883 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9884 } else { 9885 continue; 9886 } 9887 } else 9888 continue; 9889 9890 DiagRuntimeBehavior( 9891 Dest->getExprLoc(), Dest, 9892 PDiag(diag::note_bad_memaccess_silence) 9893 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9894 break; 9895 } 9896 } 9897 9898 // A little helper routine: ignore addition and subtraction of integer literals. 9899 // This intentionally does not ignore all integer constant expressions because 9900 // we don't want to remove sizeof(). 9901 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9902 Ex = Ex->IgnoreParenCasts(); 9903 9904 while (true) { 9905 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9906 if (!BO || !BO->isAdditiveOp()) 9907 break; 9908 9909 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9910 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9911 9912 if (isa<IntegerLiteral>(RHS)) 9913 Ex = LHS; 9914 else if (isa<IntegerLiteral>(LHS)) 9915 Ex = RHS; 9916 else 9917 break; 9918 } 9919 9920 return Ex; 9921 } 9922 9923 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9924 ASTContext &Context) { 9925 // Only handle constant-sized or VLAs, but not flexible members. 9926 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9927 // Only issue the FIXIT for arrays of size > 1. 9928 if (CAT->getSize().getSExtValue() <= 1) 9929 return false; 9930 } else if (!Ty->isVariableArrayType()) { 9931 return false; 9932 } 9933 return true; 9934 } 9935 9936 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9937 // be the size of the source, instead of the destination. 9938 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9939 IdentifierInfo *FnName) { 9940 9941 // Don't crash if the user has the wrong number of arguments 9942 unsigned NumArgs = Call->getNumArgs(); 9943 if ((NumArgs != 3) && (NumArgs != 4)) 9944 return; 9945 9946 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9947 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9948 const Expr *CompareWithSrc = nullptr; 9949 9950 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9951 Call->getBeginLoc(), Call->getRParenLoc())) 9952 return; 9953 9954 // Look for 'strlcpy(dst, x, sizeof(x))' 9955 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9956 CompareWithSrc = Ex; 9957 else { 9958 // Look for 'strlcpy(dst, x, strlen(x))' 9959 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9960 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9961 SizeCall->getNumArgs() == 1) 9962 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9963 } 9964 } 9965 9966 if (!CompareWithSrc) 9967 return; 9968 9969 // Determine if the argument to sizeof/strlen is equal to the source 9970 // argument. In principle there's all kinds of things you could do 9971 // here, for instance creating an == expression and evaluating it with 9972 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9973 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9974 if (!SrcArgDRE) 9975 return; 9976 9977 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9978 if (!CompareWithSrcDRE || 9979 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9980 return; 9981 9982 const Expr *OriginalSizeArg = Call->getArg(2); 9983 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9984 << OriginalSizeArg->getSourceRange() << FnName; 9985 9986 // Output a FIXIT hint if the destination is an array (rather than a 9987 // pointer to an array). This could be enhanced to handle some 9988 // pointers if we know the actual size, like if DstArg is 'array+2' 9989 // we could say 'sizeof(array)-2'. 9990 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9991 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9992 return; 9993 9994 SmallString<128> sizeString; 9995 llvm::raw_svector_ostream OS(sizeString); 9996 OS << "sizeof("; 9997 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9998 OS << ")"; 9999 10000 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10001 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10002 OS.str()); 10003 } 10004 10005 /// Check if two expressions refer to the same declaration. 10006 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10007 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10008 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10009 return D1->getDecl() == D2->getDecl(); 10010 return false; 10011 } 10012 10013 static const Expr *getStrlenExprArg(const Expr *E) { 10014 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10015 const FunctionDecl *FD = CE->getDirectCallee(); 10016 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10017 return nullptr; 10018 return CE->getArg(0)->IgnoreParenCasts(); 10019 } 10020 return nullptr; 10021 } 10022 10023 // Warn on anti-patterns as the 'size' argument to strncat. 10024 // The correct size argument should look like following: 10025 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10026 void Sema::CheckStrncatArguments(const CallExpr *CE, 10027 IdentifierInfo *FnName) { 10028 // Don't crash if the user has the wrong number of arguments. 10029 if (CE->getNumArgs() < 3) 10030 return; 10031 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10032 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10033 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10034 10035 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10036 CE->getRParenLoc())) 10037 return; 10038 10039 // Identify common expressions, which are wrongly used as the size argument 10040 // to strncat and may lead to buffer overflows. 10041 unsigned PatternType = 0; 10042 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10043 // - sizeof(dst) 10044 if (referToTheSameDecl(SizeOfArg, DstArg)) 10045 PatternType = 1; 10046 // - sizeof(src) 10047 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10048 PatternType = 2; 10049 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10050 if (BE->getOpcode() == BO_Sub) { 10051 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10052 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10053 // - sizeof(dst) - strlen(dst) 10054 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10055 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10056 PatternType = 1; 10057 // - sizeof(src) - (anything) 10058 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10059 PatternType = 2; 10060 } 10061 } 10062 10063 if (PatternType == 0) 10064 return; 10065 10066 // Generate the diagnostic. 10067 SourceLocation SL = LenArg->getBeginLoc(); 10068 SourceRange SR = LenArg->getSourceRange(); 10069 SourceManager &SM = getSourceManager(); 10070 10071 // If the function is defined as a builtin macro, do not show macro expansion. 10072 if (SM.isMacroArgExpansion(SL)) { 10073 SL = SM.getSpellingLoc(SL); 10074 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10075 SM.getSpellingLoc(SR.getEnd())); 10076 } 10077 10078 // Check if the destination is an array (rather than a pointer to an array). 10079 QualType DstTy = DstArg->getType(); 10080 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10081 Context); 10082 if (!isKnownSizeArray) { 10083 if (PatternType == 1) 10084 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10085 else 10086 Diag(SL, diag::warn_strncat_src_size) << SR; 10087 return; 10088 } 10089 10090 if (PatternType == 1) 10091 Diag(SL, diag::warn_strncat_large_size) << SR; 10092 else 10093 Diag(SL, diag::warn_strncat_src_size) << SR; 10094 10095 SmallString<128> sizeString; 10096 llvm::raw_svector_ostream OS(sizeString); 10097 OS << "sizeof("; 10098 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10099 OS << ") - "; 10100 OS << "strlen("; 10101 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10102 OS << ") - 1"; 10103 10104 Diag(SL, diag::note_strncat_wrong_size) 10105 << FixItHint::CreateReplacement(SR, OS.str()); 10106 } 10107 10108 void 10109 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10110 SourceLocation ReturnLoc, 10111 bool isObjCMethod, 10112 const AttrVec *Attrs, 10113 const FunctionDecl *FD) { 10114 // Check if the return value is null but should not be. 10115 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10116 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10117 CheckNonNullExpr(*this, RetValExp)) 10118 Diag(ReturnLoc, diag::warn_null_ret) 10119 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10120 10121 // C++11 [basic.stc.dynamic.allocation]p4: 10122 // If an allocation function declared with a non-throwing 10123 // exception-specification fails to allocate storage, it shall return 10124 // a null pointer. Any other allocation function that fails to allocate 10125 // storage shall indicate failure only by throwing an exception [...] 10126 if (FD) { 10127 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10128 if (Op == OO_New || Op == OO_Array_New) { 10129 const FunctionProtoType *Proto 10130 = FD->getType()->castAs<FunctionProtoType>(); 10131 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10132 CheckNonNullExpr(*this, RetValExp)) 10133 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10134 << FD << getLangOpts().CPlusPlus11; 10135 } 10136 } 10137 } 10138 10139 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10140 10141 /// Check for comparisons of floating point operands using != and ==. 10142 /// Issue a warning if these are no self-comparisons, as they are not likely 10143 /// to do what the programmer intended. 10144 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10145 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10146 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10147 10148 // Special case: check for x == x (which is OK). 10149 // Do not emit warnings for such cases. 10150 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10151 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10152 if (DRL->getDecl() == DRR->getDecl()) 10153 return; 10154 10155 // Special case: check for comparisons against literals that can be exactly 10156 // represented by APFloat. In such cases, do not emit a warning. This 10157 // is a heuristic: often comparison against such literals are used to 10158 // detect if a value in a variable has not changed. This clearly can 10159 // lead to false negatives. 10160 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10161 if (FLL->isExact()) 10162 return; 10163 } else 10164 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10165 if (FLR->isExact()) 10166 return; 10167 10168 // Check for comparisons with builtin types. 10169 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10170 if (CL->getBuiltinCallee()) 10171 return; 10172 10173 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10174 if (CR->getBuiltinCallee()) 10175 return; 10176 10177 // Emit the diagnostic. 10178 Diag(Loc, diag::warn_floatingpoint_eq) 10179 << LHS->getSourceRange() << RHS->getSourceRange(); 10180 } 10181 10182 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10183 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10184 10185 namespace { 10186 10187 /// Structure recording the 'active' range of an integer-valued 10188 /// expression. 10189 struct IntRange { 10190 /// The number of bits active in the int. Note that this includes exactly one 10191 /// sign bit if !NonNegative. 10192 unsigned Width; 10193 10194 /// True if the int is known not to have negative values. If so, all leading 10195 /// bits before Width are known zero, otherwise they are known to be the 10196 /// same as the MSB within Width. 10197 bool NonNegative; 10198 10199 IntRange(unsigned Width, bool NonNegative) 10200 : Width(Width), NonNegative(NonNegative) {} 10201 10202 /// Number of bits excluding the sign bit. 10203 unsigned valueBits() const { 10204 return NonNegative ? Width : Width - 1; 10205 } 10206 10207 /// Returns the range of the bool type. 10208 static IntRange forBoolType() { 10209 return IntRange(1, true); 10210 } 10211 10212 /// Returns the range of an opaque value of the given integral type. 10213 static IntRange forValueOfType(ASTContext &C, QualType T) { 10214 return forValueOfCanonicalType(C, 10215 T->getCanonicalTypeInternal().getTypePtr()); 10216 } 10217 10218 /// Returns the range of an opaque value of a canonical integral type. 10219 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10220 assert(T->isCanonicalUnqualified()); 10221 10222 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10223 T = VT->getElementType().getTypePtr(); 10224 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10225 T = CT->getElementType().getTypePtr(); 10226 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10227 T = AT->getValueType().getTypePtr(); 10228 10229 if (!C.getLangOpts().CPlusPlus) { 10230 // For enum types in C code, use the underlying datatype. 10231 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10232 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10233 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10234 // For enum types in C++, use the known bit width of the enumerators. 10235 EnumDecl *Enum = ET->getDecl(); 10236 // In C++11, enums can have a fixed underlying type. Use this type to 10237 // compute the range. 10238 if (Enum->isFixed()) { 10239 return IntRange(C.getIntWidth(QualType(T, 0)), 10240 !ET->isSignedIntegerOrEnumerationType()); 10241 } 10242 10243 unsigned NumPositive = Enum->getNumPositiveBits(); 10244 unsigned NumNegative = Enum->getNumNegativeBits(); 10245 10246 if (NumNegative == 0) 10247 return IntRange(NumPositive, true/*NonNegative*/); 10248 else 10249 return IntRange(std::max(NumPositive + 1, NumNegative), 10250 false/*NonNegative*/); 10251 } 10252 10253 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10254 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10255 10256 const BuiltinType *BT = cast<BuiltinType>(T); 10257 assert(BT->isInteger()); 10258 10259 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10260 } 10261 10262 /// Returns the "target" range of a canonical integral type, i.e. 10263 /// the range of values expressible in the type. 10264 /// 10265 /// This matches forValueOfCanonicalType except that enums have the 10266 /// full range of their type, not the range of their enumerators. 10267 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10268 assert(T->isCanonicalUnqualified()); 10269 10270 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10271 T = VT->getElementType().getTypePtr(); 10272 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10273 T = CT->getElementType().getTypePtr(); 10274 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10275 T = AT->getValueType().getTypePtr(); 10276 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10277 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10278 10279 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10280 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10281 10282 const BuiltinType *BT = cast<BuiltinType>(T); 10283 assert(BT->isInteger()); 10284 10285 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10286 } 10287 10288 /// Returns the supremum of two ranges: i.e. their conservative merge. 10289 static IntRange join(IntRange L, IntRange R) { 10290 bool Unsigned = L.NonNegative && R.NonNegative; 10291 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10292 L.NonNegative && R.NonNegative); 10293 } 10294 10295 /// Return the range of a bitwise-AND of the two ranges. 10296 static IntRange bit_and(IntRange L, IntRange R) { 10297 unsigned Bits = std::max(L.Width, R.Width); 10298 bool NonNegative = false; 10299 if (L.NonNegative) { 10300 Bits = std::min(Bits, L.Width); 10301 NonNegative = true; 10302 } 10303 if (R.NonNegative) { 10304 Bits = std::min(Bits, R.Width); 10305 NonNegative = true; 10306 } 10307 return IntRange(Bits, NonNegative); 10308 } 10309 10310 /// Return the range of a sum of the two ranges. 10311 static IntRange sum(IntRange L, IntRange R) { 10312 bool Unsigned = L.NonNegative && R.NonNegative; 10313 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10314 Unsigned); 10315 } 10316 10317 /// Return the range of a difference of the two ranges. 10318 static IntRange difference(IntRange L, IntRange R) { 10319 // We need a 1-bit-wider range if: 10320 // 1) LHS can be negative: least value can be reduced. 10321 // 2) RHS can be negative: greatest value can be increased. 10322 bool CanWiden = !L.NonNegative || !R.NonNegative; 10323 bool Unsigned = L.NonNegative && R.Width == 0; 10324 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10325 !Unsigned, 10326 Unsigned); 10327 } 10328 10329 /// Return the range of a product of the two ranges. 10330 static IntRange product(IntRange L, IntRange R) { 10331 // If both LHS and RHS can be negative, we can form 10332 // -2^L * -2^R = 2^(L + R) 10333 // which requires L + R + 1 value bits to represent. 10334 bool CanWiden = !L.NonNegative && !R.NonNegative; 10335 bool Unsigned = L.NonNegative && R.NonNegative; 10336 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10337 Unsigned); 10338 } 10339 10340 /// Return the range of a remainder operation between the two ranges. 10341 static IntRange rem(IntRange L, IntRange R) { 10342 // The result of a remainder can't be larger than the result of 10343 // either side. The sign of the result is the sign of the LHS. 10344 bool Unsigned = L.NonNegative; 10345 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10346 Unsigned); 10347 } 10348 }; 10349 10350 } // namespace 10351 10352 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10353 unsigned MaxWidth) { 10354 if (value.isSigned() && value.isNegative()) 10355 return IntRange(value.getMinSignedBits(), false); 10356 10357 if (value.getBitWidth() > MaxWidth) 10358 value = value.trunc(MaxWidth); 10359 10360 // isNonNegative() just checks the sign bit without considering 10361 // signedness. 10362 return IntRange(value.getActiveBits(), true); 10363 } 10364 10365 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10366 unsigned MaxWidth) { 10367 if (result.isInt()) 10368 return GetValueRange(C, result.getInt(), MaxWidth); 10369 10370 if (result.isVector()) { 10371 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10372 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10373 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10374 R = IntRange::join(R, El); 10375 } 10376 return R; 10377 } 10378 10379 if (result.isComplexInt()) { 10380 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10381 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10382 return IntRange::join(R, I); 10383 } 10384 10385 // This can happen with lossless casts to intptr_t of "based" lvalues. 10386 // Assume it might use arbitrary bits. 10387 // FIXME: The only reason we need to pass the type in here is to get 10388 // the sign right on this one case. It would be nice if APValue 10389 // preserved this. 10390 assert(result.isLValue() || result.isAddrLabelDiff()); 10391 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10392 } 10393 10394 static QualType GetExprType(const Expr *E) { 10395 QualType Ty = E->getType(); 10396 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10397 Ty = AtomicRHS->getValueType(); 10398 return Ty; 10399 } 10400 10401 /// Pseudo-evaluate the given integer expression, estimating the 10402 /// range of values it might take. 10403 /// 10404 /// \param MaxWidth The width to which the value will be truncated. 10405 /// \param Approximate If \c true, return a likely range for the result: in 10406 /// particular, assume that aritmetic on narrower types doesn't leave 10407 /// those types. If \c false, return a range including all possible 10408 /// result values. 10409 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10410 bool InConstantContext, bool Approximate) { 10411 E = E->IgnoreParens(); 10412 10413 // Try a full evaluation first. 10414 Expr::EvalResult result; 10415 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10416 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10417 10418 // I think we only want to look through implicit casts here; if the 10419 // user has an explicit widening cast, we should treat the value as 10420 // being of the new, wider type. 10421 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10422 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10423 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10424 Approximate); 10425 10426 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10427 10428 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10429 CE->getCastKind() == CK_BooleanToSignedIntegral; 10430 10431 // Assume that non-integer casts can span the full range of the type. 10432 if (!isIntegerCast) 10433 return OutputTypeRange; 10434 10435 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10436 std::min(MaxWidth, OutputTypeRange.Width), 10437 InConstantContext, Approximate); 10438 10439 // Bail out if the subexpr's range is as wide as the cast type. 10440 if (SubRange.Width >= OutputTypeRange.Width) 10441 return OutputTypeRange; 10442 10443 // Otherwise, we take the smaller width, and we're non-negative if 10444 // either the output type or the subexpr is. 10445 return IntRange(SubRange.Width, 10446 SubRange.NonNegative || OutputTypeRange.NonNegative); 10447 } 10448 10449 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10450 // If we can fold the condition, just take that operand. 10451 bool CondResult; 10452 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10453 return GetExprRange(C, 10454 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10455 MaxWidth, InConstantContext, Approximate); 10456 10457 // Otherwise, conservatively merge. 10458 // GetExprRange requires an integer expression, but a throw expression 10459 // results in a void type. 10460 Expr *E = CO->getTrueExpr(); 10461 IntRange L = E->getType()->isVoidType() 10462 ? IntRange{0, true} 10463 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10464 E = CO->getFalseExpr(); 10465 IntRange R = E->getType()->isVoidType() 10466 ? IntRange{0, true} 10467 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10468 return IntRange::join(L, R); 10469 } 10470 10471 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10472 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10473 10474 switch (BO->getOpcode()) { 10475 case BO_Cmp: 10476 llvm_unreachable("builtin <=> should have class type"); 10477 10478 // Boolean-valued operations are single-bit and positive. 10479 case BO_LAnd: 10480 case BO_LOr: 10481 case BO_LT: 10482 case BO_GT: 10483 case BO_LE: 10484 case BO_GE: 10485 case BO_EQ: 10486 case BO_NE: 10487 return IntRange::forBoolType(); 10488 10489 // The type of the assignments is the type of the LHS, so the RHS 10490 // is not necessarily the same type. 10491 case BO_MulAssign: 10492 case BO_DivAssign: 10493 case BO_RemAssign: 10494 case BO_AddAssign: 10495 case BO_SubAssign: 10496 case BO_XorAssign: 10497 case BO_OrAssign: 10498 // TODO: bitfields? 10499 return IntRange::forValueOfType(C, GetExprType(E)); 10500 10501 // Simple assignments just pass through the RHS, which will have 10502 // been coerced to the LHS type. 10503 case BO_Assign: 10504 // TODO: bitfields? 10505 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10506 Approximate); 10507 10508 // Operations with opaque sources are black-listed. 10509 case BO_PtrMemD: 10510 case BO_PtrMemI: 10511 return IntRange::forValueOfType(C, GetExprType(E)); 10512 10513 // Bitwise-and uses the *infinum* of the two source ranges. 10514 case BO_And: 10515 case BO_AndAssign: 10516 Combine = IntRange::bit_and; 10517 break; 10518 10519 // Left shift gets black-listed based on a judgement call. 10520 case BO_Shl: 10521 // ...except that we want to treat '1 << (blah)' as logically 10522 // positive. It's an important idiom. 10523 if (IntegerLiteral *I 10524 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10525 if (I->getValue() == 1) { 10526 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10527 return IntRange(R.Width, /*NonNegative*/ true); 10528 } 10529 } 10530 LLVM_FALLTHROUGH; 10531 10532 case BO_ShlAssign: 10533 return IntRange::forValueOfType(C, GetExprType(E)); 10534 10535 // Right shift by a constant can narrow its left argument. 10536 case BO_Shr: 10537 case BO_ShrAssign: { 10538 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10539 Approximate); 10540 10541 // If the shift amount is a positive constant, drop the width by 10542 // that much. 10543 if (Optional<llvm::APSInt> shift = 10544 BO->getRHS()->getIntegerConstantExpr(C)) { 10545 if (shift->isNonNegative()) { 10546 unsigned zext = shift->getZExtValue(); 10547 if (zext >= L.Width) 10548 L.Width = (L.NonNegative ? 0 : 1); 10549 else 10550 L.Width -= zext; 10551 } 10552 } 10553 10554 return L; 10555 } 10556 10557 // Comma acts as its right operand. 10558 case BO_Comma: 10559 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10560 Approximate); 10561 10562 case BO_Add: 10563 if (!Approximate) 10564 Combine = IntRange::sum; 10565 break; 10566 10567 case BO_Sub: 10568 if (BO->getLHS()->getType()->isPointerType()) 10569 return IntRange::forValueOfType(C, GetExprType(E)); 10570 if (!Approximate) 10571 Combine = IntRange::difference; 10572 break; 10573 10574 case BO_Mul: 10575 if (!Approximate) 10576 Combine = IntRange::product; 10577 break; 10578 10579 // The width of a division result is mostly determined by the size 10580 // of the LHS. 10581 case BO_Div: { 10582 // Don't 'pre-truncate' the operands. 10583 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10584 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 10585 Approximate); 10586 10587 // If the divisor is constant, use that. 10588 if (Optional<llvm::APSInt> divisor = 10589 BO->getRHS()->getIntegerConstantExpr(C)) { 10590 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10591 if (log2 >= L.Width) 10592 L.Width = (L.NonNegative ? 0 : 1); 10593 else 10594 L.Width = std::min(L.Width - log2, MaxWidth); 10595 return L; 10596 } 10597 10598 // Otherwise, just use the LHS's width. 10599 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10600 // could be -1. 10601 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 10602 Approximate); 10603 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10604 } 10605 10606 case BO_Rem: 10607 Combine = IntRange::rem; 10608 break; 10609 10610 // The default behavior is okay for these. 10611 case BO_Xor: 10612 case BO_Or: 10613 break; 10614 } 10615 10616 // Combine the two ranges, but limit the result to the type in which we 10617 // performed the computation. 10618 QualType T = GetExprType(E); 10619 unsigned opWidth = C.getIntWidth(T); 10620 IntRange L = 10621 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10622 IntRange R = 10623 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10624 IntRange C = Combine(L, R); 10625 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10626 C.Width = std::min(C.Width, MaxWidth); 10627 return C; 10628 } 10629 10630 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10631 switch (UO->getOpcode()) { 10632 // Boolean-valued operations are white-listed. 10633 case UO_LNot: 10634 return IntRange::forBoolType(); 10635 10636 // Operations with opaque sources are black-listed. 10637 case UO_Deref: 10638 case UO_AddrOf: // should be impossible 10639 return IntRange::forValueOfType(C, GetExprType(E)); 10640 10641 default: 10642 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 10643 Approximate); 10644 } 10645 } 10646 10647 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10648 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 10649 Approximate); 10650 10651 if (const auto *BitField = E->getSourceBitField()) 10652 return IntRange(BitField->getBitWidthValue(C), 10653 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10654 10655 return IntRange::forValueOfType(C, GetExprType(E)); 10656 } 10657 10658 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10659 bool InConstantContext, bool Approximate) { 10660 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 10661 Approximate); 10662 } 10663 10664 /// Checks whether the given value, which currently has the given 10665 /// source semantics, has the same value when coerced through the 10666 /// target semantics. 10667 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10668 const llvm::fltSemantics &Src, 10669 const llvm::fltSemantics &Tgt) { 10670 llvm::APFloat truncated = value; 10671 10672 bool ignored; 10673 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10674 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10675 10676 return truncated.bitwiseIsEqual(value); 10677 } 10678 10679 /// Checks whether the given value, which currently has the given 10680 /// source semantics, has the same value when coerced through the 10681 /// target semantics. 10682 /// 10683 /// The value might be a vector of floats (or a complex number). 10684 static bool IsSameFloatAfterCast(const APValue &value, 10685 const llvm::fltSemantics &Src, 10686 const llvm::fltSemantics &Tgt) { 10687 if (value.isFloat()) 10688 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10689 10690 if (value.isVector()) { 10691 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10692 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10693 return false; 10694 return true; 10695 } 10696 10697 assert(value.isComplexFloat()); 10698 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10699 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10700 } 10701 10702 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10703 bool IsListInit = false); 10704 10705 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10706 // Suppress cases where we are comparing against an enum constant. 10707 if (const DeclRefExpr *DR = 10708 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10709 if (isa<EnumConstantDecl>(DR->getDecl())) 10710 return true; 10711 10712 // Suppress cases where the value is expanded from a macro, unless that macro 10713 // is how a language represents a boolean literal. This is the case in both C 10714 // and Objective-C. 10715 SourceLocation BeginLoc = E->getBeginLoc(); 10716 if (BeginLoc.isMacroID()) { 10717 StringRef MacroName = Lexer::getImmediateMacroName( 10718 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10719 return MacroName != "YES" && MacroName != "NO" && 10720 MacroName != "true" && MacroName != "false"; 10721 } 10722 10723 return false; 10724 } 10725 10726 static bool isKnownToHaveUnsignedValue(Expr *E) { 10727 return E->getType()->isIntegerType() && 10728 (!E->getType()->isSignedIntegerType() || 10729 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10730 } 10731 10732 namespace { 10733 /// The promoted range of values of a type. In general this has the 10734 /// following structure: 10735 /// 10736 /// |-----------| . . . |-----------| 10737 /// ^ ^ ^ ^ 10738 /// Min HoleMin HoleMax Max 10739 /// 10740 /// ... where there is only a hole if a signed type is promoted to unsigned 10741 /// (in which case Min and Max are the smallest and largest representable 10742 /// values). 10743 struct PromotedRange { 10744 // Min, or HoleMax if there is a hole. 10745 llvm::APSInt PromotedMin; 10746 // Max, or HoleMin if there is a hole. 10747 llvm::APSInt PromotedMax; 10748 10749 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10750 if (R.Width == 0) 10751 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10752 else if (R.Width >= BitWidth && !Unsigned) { 10753 // Promotion made the type *narrower*. This happens when promoting 10754 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10755 // Treat all values of 'signed int' as being in range for now. 10756 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10757 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10758 } else { 10759 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10760 .extOrTrunc(BitWidth); 10761 PromotedMin.setIsUnsigned(Unsigned); 10762 10763 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10764 .extOrTrunc(BitWidth); 10765 PromotedMax.setIsUnsigned(Unsigned); 10766 } 10767 } 10768 10769 // Determine whether this range is contiguous (has no hole). 10770 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10771 10772 // Where a constant value is within the range. 10773 enum ComparisonResult { 10774 LT = 0x1, 10775 LE = 0x2, 10776 GT = 0x4, 10777 GE = 0x8, 10778 EQ = 0x10, 10779 NE = 0x20, 10780 InRangeFlag = 0x40, 10781 10782 Less = LE | LT | NE, 10783 Min = LE | InRangeFlag, 10784 InRange = InRangeFlag, 10785 Max = GE | InRangeFlag, 10786 Greater = GE | GT | NE, 10787 10788 OnlyValue = LE | GE | EQ | InRangeFlag, 10789 InHole = NE 10790 }; 10791 10792 ComparisonResult compare(const llvm::APSInt &Value) const { 10793 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10794 Value.isUnsigned() == PromotedMin.isUnsigned()); 10795 if (!isContiguous()) { 10796 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10797 if (Value.isMinValue()) return Min; 10798 if (Value.isMaxValue()) return Max; 10799 if (Value >= PromotedMin) return InRange; 10800 if (Value <= PromotedMax) return InRange; 10801 return InHole; 10802 } 10803 10804 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10805 case -1: return Less; 10806 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10807 case 1: 10808 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10809 case -1: return InRange; 10810 case 0: return Max; 10811 case 1: return Greater; 10812 } 10813 } 10814 10815 llvm_unreachable("impossible compare result"); 10816 } 10817 10818 static llvm::Optional<StringRef> 10819 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10820 if (Op == BO_Cmp) { 10821 ComparisonResult LTFlag = LT, GTFlag = GT; 10822 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10823 10824 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10825 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10826 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10827 return llvm::None; 10828 } 10829 10830 ComparisonResult TrueFlag, FalseFlag; 10831 if (Op == BO_EQ) { 10832 TrueFlag = EQ; 10833 FalseFlag = NE; 10834 } else if (Op == BO_NE) { 10835 TrueFlag = NE; 10836 FalseFlag = EQ; 10837 } else { 10838 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10839 TrueFlag = LT; 10840 FalseFlag = GE; 10841 } else { 10842 TrueFlag = GT; 10843 FalseFlag = LE; 10844 } 10845 if (Op == BO_GE || Op == BO_LE) 10846 std::swap(TrueFlag, FalseFlag); 10847 } 10848 if (R & TrueFlag) 10849 return StringRef("true"); 10850 if (R & FalseFlag) 10851 return StringRef("false"); 10852 return llvm::None; 10853 } 10854 }; 10855 } 10856 10857 static bool HasEnumType(Expr *E) { 10858 // Strip off implicit integral promotions. 10859 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10860 if (ICE->getCastKind() != CK_IntegralCast && 10861 ICE->getCastKind() != CK_NoOp) 10862 break; 10863 E = ICE->getSubExpr(); 10864 } 10865 10866 return E->getType()->isEnumeralType(); 10867 } 10868 10869 static int classifyConstantValue(Expr *Constant) { 10870 // The values of this enumeration are used in the diagnostics 10871 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10872 enum ConstantValueKind { 10873 Miscellaneous = 0, 10874 LiteralTrue, 10875 LiteralFalse 10876 }; 10877 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10878 return BL->getValue() ? ConstantValueKind::LiteralTrue 10879 : ConstantValueKind::LiteralFalse; 10880 return ConstantValueKind::Miscellaneous; 10881 } 10882 10883 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10884 Expr *Constant, Expr *Other, 10885 const llvm::APSInt &Value, 10886 bool RhsConstant) { 10887 if (S.inTemplateInstantiation()) 10888 return false; 10889 10890 Expr *OriginalOther = Other; 10891 10892 Constant = Constant->IgnoreParenImpCasts(); 10893 Other = Other->IgnoreParenImpCasts(); 10894 10895 // Suppress warnings on tautological comparisons between values of the same 10896 // enumeration type. There are only two ways we could warn on this: 10897 // - If the constant is outside the range of representable values of 10898 // the enumeration. In such a case, we should warn about the cast 10899 // to enumeration type, not about the comparison. 10900 // - If the constant is the maximum / minimum in-range value. For an 10901 // enumeratin type, such comparisons can be meaningful and useful. 10902 if (Constant->getType()->isEnumeralType() && 10903 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10904 return false; 10905 10906 IntRange OtherValueRange = GetExprRange( 10907 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 10908 10909 QualType OtherT = Other->getType(); 10910 if (const auto *AT = OtherT->getAs<AtomicType>()) 10911 OtherT = AT->getValueType(); 10912 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 10913 10914 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10915 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 10916 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10917 S.NSAPIObj->isObjCBOOLType(OtherT) && 10918 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10919 10920 // Whether we're treating Other as being a bool because of the form of 10921 // expression despite it having another type (typically 'int' in C). 10922 bool OtherIsBooleanDespiteType = 10923 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10924 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10925 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 10926 10927 // Check if all values in the range of possible values of this expression 10928 // lead to the same comparison outcome. 10929 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 10930 Value.isUnsigned()); 10931 auto Cmp = OtherPromotedValueRange.compare(Value); 10932 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10933 if (!Result) 10934 return false; 10935 10936 // Also consider the range determined by the type alone. This allows us to 10937 // classify the warning under the proper diagnostic group. 10938 bool TautologicalTypeCompare = false; 10939 { 10940 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 10941 Value.isUnsigned()); 10942 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 10943 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 10944 RhsConstant)) { 10945 TautologicalTypeCompare = true; 10946 Cmp = TypeCmp; 10947 Result = TypeResult; 10948 } 10949 } 10950 10951 // Don't warn if the non-constant operand actually always evaluates to the 10952 // same value. 10953 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 10954 return false; 10955 10956 // Suppress the diagnostic for an in-range comparison if the constant comes 10957 // from a macro or enumerator. We don't want to diagnose 10958 // 10959 // some_long_value <= INT_MAX 10960 // 10961 // when sizeof(int) == sizeof(long). 10962 bool InRange = Cmp & PromotedRange::InRangeFlag; 10963 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10964 return false; 10965 10966 // A comparison of an unsigned bit-field against 0 is really a type problem, 10967 // even though at the type level the bit-field might promote to 'signed int'. 10968 if (Other->refersToBitField() && InRange && Value == 0 && 10969 Other->getType()->isUnsignedIntegerOrEnumerationType()) 10970 TautologicalTypeCompare = true; 10971 10972 // If this is a comparison to an enum constant, include that 10973 // constant in the diagnostic. 10974 const EnumConstantDecl *ED = nullptr; 10975 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10976 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10977 10978 // Should be enough for uint128 (39 decimal digits) 10979 SmallString<64> PrettySourceValue; 10980 llvm::raw_svector_ostream OS(PrettySourceValue); 10981 if (ED) { 10982 OS << '\'' << *ED << "' (" << Value << ")"; 10983 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10984 Constant->IgnoreParenImpCasts())) { 10985 OS << (BL->getValue() ? "YES" : "NO"); 10986 } else { 10987 OS << Value; 10988 } 10989 10990 if (!TautologicalTypeCompare) { 10991 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 10992 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 10993 << E->getOpcodeStr() << OS.str() << *Result 10994 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10995 return true; 10996 } 10997 10998 if (IsObjCSignedCharBool) { 10999 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11000 S.PDiag(diag::warn_tautological_compare_objc_bool) 11001 << OS.str() << *Result); 11002 return true; 11003 } 11004 11005 // FIXME: We use a somewhat different formatting for the in-range cases and 11006 // cases involving boolean values for historical reasons. We should pick a 11007 // consistent way of presenting these diagnostics. 11008 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11009 11010 S.DiagRuntimeBehavior( 11011 E->getOperatorLoc(), E, 11012 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11013 : diag::warn_tautological_bool_compare) 11014 << OS.str() << classifyConstantValue(Constant) << OtherT 11015 << OtherIsBooleanDespiteType << *Result 11016 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11017 } else { 11018 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11019 ? (HasEnumType(OriginalOther) 11020 ? diag::warn_unsigned_enum_always_true_comparison 11021 : diag::warn_unsigned_always_true_comparison) 11022 : diag::warn_tautological_constant_compare; 11023 11024 S.Diag(E->getOperatorLoc(), Diag) 11025 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11026 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11027 } 11028 11029 return true; 11030 } 11031 11032 /// Analyze the operands of the given comparison. Implements the 11033 /// fallback case from AnalyzeComparison. 11034 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11035 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11036 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11037 } 11038 11039 /// Implements -Wsign-compare. 11040 /// 11041 /// \param E the binary operator to check for warnings 11042 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11043 // The type the comparison is being performed in. 11044 QualType T = E->getLHS()->getType(); 11045 11046 // Only analyze comparison operators where both sides have been converted to 11047 // the same type. 11048 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11049 return AnalyzeImpConvsInComparison(S, E); 11050 11051 // Don't analyze value-dependent comparisons directly. 11052 if (E->isValueDependent()) 11053 return AnalyzeImpConvsInComparison(S, E); 11054 11055 Expr *LHS = E->getLHS(); 11056 Expr *RHS = E->getRHS(); 11057 11058 if (T->isIntegralType(S.Context)) { 11059 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11060 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11061 11062 // We don't care about expressions whose result is a constant. 11063 if (RHSValue && LHSValue) 11064 return AnalyzeImpConvsInComparison(S, E); 11065 11066 // We only care about expressions where just one side is literal 11067 if ((bool)RHSValue ^ (bool)LHSValue) { 11068 // Is the constant on the RHS or LHS? 11069 const bool RhsConstant = (bool)RHSValue; 11070 Expr *Const = RhsConstant ? RHS : LHS; 11071 Expr *Other = RhsConstant ? LHS : RHS; 11072 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11073 11074 // Check whether an integer constant comparison results in a value 11075 // of 'true' or 'false'. 11076 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11077 return AnalyzeImpConvsInComparison(S, E); 11078 } 11079 } 11080 11081 if (!T->hasUnsignedIntegerRepresentation()) { 11082 // We don't do anything special if this isn't an unsigned integral 11083 // comparison: we're only interested in integral comparisons, and 11084 // signed comparisons only happen in cases we don't care to warn about. 11085 return AnalyzeImpConvsInComparison(S, E); 11086 } 11087 11088 LHS = LHS->IgnoreParenImpCasts(); 11089 RHS = RHS->IgnoreParenImpCasts(); 11090 11091 if (!S.getLangOpts().CPlusPlus) { 11092 // Avoid warning about comparison of integers with different signs when 11093 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11094 // the type of `E`. 11095 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11096 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11097 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11098 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11099 } 11100 11101 // Check to see if one of the (unmodified) operands is of different 11102 // signedness. 11103 Expr *signedOperand, *unsignedOperand; 11104 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11105 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11106 "unsigned comparison between two signed integer expressions?"); 11107 signedOperand = LHS; 11108 unsignedOperand = RHS; 11109 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11110 signedOperand = RHS; 11111 unsignedOperand = LHS; 11112 } else { 11113 return AnalyzeImpConvsInComparison(S, E); 11114 } 11115 11116 // Otherwise, calculate the effective range of the signed operand. 11117 IntRange signedRange = GetExprRange( 11118 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11119 11120 // Go ahead and analyze implicit conversions in the operands. Note 11121 // that we skip the implicit conversions on both sides. 11122 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11123 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11124 11125 // If the signed range is non-negative, -Wsign-compare won't fire. 11126 if (signedRange.NonNegative) 11127 return; 11128 11129 // For (in)equality comparisons, if the unsigned operand is a 11130 // constant which cannot collide with a overflowed signed operand, 11131 // then reinterpreting the signed operand as unsigned will not 11132 // change the result of the comparison. 11133 if (E->isEqualityOp()) { 11134 unsigned comparisonWidth = S.Context.getIntWidth(T); 11135 IntRange unsignedRange = 11136 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11137 /*Approximate*/ true); 11138 11139 // We should never be unable to prove that the unsigned operand is 11140 // non-negative. 11141 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11142 11143 if (unsignedRange.Width < comparisonWidth) 11144 return; 11145 } 11146 11147 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11148 S.PDiag(diag::warn_mixed_sign_comparison) 11149 << LHS->getType() << RHS->getType() 11150 << LHS->getSourceRange() << RHS->getSourceRange()); 11151 } 11152 11153 /// Analyzes an attempt to assign the given value to a bitfield. 11154 /// 11155 /// Returns true if there was something fishy about the attempt. 11156 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11157 SourceLocation InitLoc) { 11158 assert(Bitfield->isBitField()); 11159 if (Bitfield->isInvalidDecl()) 11160 return false; 11161 11162 // White-list bool bitfields. 11163 QualType BitfieldType = Bitfield->getType(); 11164 if (BitfieldType->isBooleanType()) 11165 return false; 11166 11167 if (BitfieldType->isEnumeralType()) { 11168 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11169 // If the underlying enum type was not explicitly specified as an unsigned 11170 // type and the enum contain only positive values, MSVC++ will cause an 11171 // inconsistency by storing this as a signed type. 11172 if (S.getLangOpts().CPlusPlus11 && 11173 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11174 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11175 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11176 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11177 << BitfieldEnumDecl; 11178 } 11179 } 11180 11181 if (Bitfield->getType()->isBooleanType()) 11182 return false; 11183 11184 // Ignore value- or type-dependent expressions. 11185 if (Bitfield->getBitWidth()->isValueDependent() || 11186 Bitfield->getBitWidth()->isTypeDependent() || 11187 Init->isValueDependent() || 11188 Init->isTypeDependent()) 11189 return false; 11190 11191 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11192 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11193 11194 Expr::EvalResult Result; 11195 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11196 Expr::SE_AllowSideEffects)) { 11197 // The RHS is not constant. If the RHS has an enum type, make sure the 11198 // bitfield is wide enough to hold all the values of the enum without 11199 // truncation. 11200 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11201 EnumDecl *ED = EnumTy->getDecl(); 11202 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11203 11204 // Enum types are implicitly signed on Windows, so check if there are any 11205 // negative enumerators to see if the enum was intended to be signed or 11206 // not. 11207 bool SignedEnum = ED->getNumNegativeBits() > 0; 11208 11209 // Check for surprising sign changes when assigning enum values to a 11210 // bitfield of different signedness. If the bitfield is signed and we 11211 // have exactly the right number of bits to store this unsigned enum, 11212 // suggest changing the enum to an unsigned type. This typically happens 11213 // on Windows where unfixed enums always use an underlying type of 'int'. 11214 unsigned DiagID = 0; 11215 if (SignedEnum && !SignedBitfield) { 11216 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11217 } else if (SignedBitfield && !SignedEnum && 11218 ED->getNumPositiveBits() == FieldWidth) { 11219 DiagID = diag::warn_signed_bitfield_enum_conversion; 11220 } 11221 11222 if (DiagID) { 11223 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11224 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11225 SourceRange TypeRange = 11226 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11227 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11228 << SignedEnum << TypeRange; 11229 } 11230 11231 // Compute the required bitwidth. If the enum has negative values, we need 11232 // one more bit than the normal number of positive bits to represent the 11233 // sign bit. 11234 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11235 ED->getNumNegativeBits()) 11236 : ED->getNumPositiveBits(); 11237 11238 // Check the bitwidth. 11239 if (BitsNeeded > FieldWidth) { 11240 Expr *WidthExpr = Bitfield->getBitWidth(); 11241 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11242 << Bitfield << ED; 11243 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11244 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11245 } 11246 } 11247 11248 return false; 11249 } 11250 11251 llvm::APSInt Value = Result.Val.getInt(); 11252 11253 unsigned OriginalWidth = Value.getBitWidth(); 11254 11255 if (!Value.isSigned() || Value.isNegative()) 11256 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11257 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11258 OriginalWidth = Value.getMinSignedBits(); 11259 11260 if (OriginalWidth <= FieldWidth) 11261 return false; 11262 11263 // Compute the value which the bitfield will contain. 11264 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11265 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11266 11267 // Check whether the stored value is equal to the original value. 11268 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11269 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11270 return false; 11271 11272 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11273 // therefore don't strictly fit into a signed bitfield of width 1. 11274 if (FieldWidth == 1 && Value == 1) 11275 return false; 11276 11277 std::string PrettyValue = Value.toString(10); 11278 std::string PrettyTrunc = TruncatedValue.toString(10); 11279 11280 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11281 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11282 << Init->getSourceRange(); 11283 11284 return true; 11285 } 11286 11287 /// Analyze the given simple or compound assignment for warning-worthy 11288 /// operations. 11289 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11290 // Just recurse on the LHS. 11291 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11292 11293 // We want to recurse on the RHS as normal unless we're assigning to 11294 // a bitfield. 11295 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11296 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11297 E->getOperatorLoc())) { 11298 // Recurse, ignoring any implicit conversions on the RHS. 11299 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11300 E->getOperatorLoc()); 11301 } 11302 } 11303 11304 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11305 11306 // Diagnose implicitly sequentially-consistent atomic assignment. 11307 if (E->getLHS()->getType()->isAtomicType()) 11308 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11309 } 11310 11311 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11312 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11313 SourceLocation CContext, unsigned diag, 11314 bool pruneControlFlow = false) { 11315 if (pruneControlFlow) { 11316 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11317 S.PDiag(diag) 11318 << SourceType << T << E->getSourceRange() 11319 << SourceRange(CContext)); 11320 return; 11321 } 11322 S.Diag(E->getExprLoc(), diag) 11323 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11324 } 11325 11326 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11327 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11328 SourceLocation CContext, 11329 unsigned diag, bool pruneControlFlow = false) { 11330 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11331 } 11332 11333 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11334 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11335 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11336 } 11337 11338 static void adornObjCBoolConversionDiagWithTernaryFixit( 11339 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11340 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11341 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11342 Ignored = OVE->getSourceExpr(); 11343 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11344 isa<BinaryOperator>(Ignored) || 11345 isa<CXXOperatorCallExpr>(Ignored); 11346 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11347 if (NeedsParens) 11348 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11349 << FixItHint::CreateInsertion(EndLoc, ")"); 11350 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11351 } 11352 11353 /// Diagnose an implicit cast from a floating point value to an integer value. 11354 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11355 SourceLocation CContext) { 11356 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11357 const bool PruneWarnings = S.inTemplateInstantiation(); 11358 11359 Expr *InnerE = E->IgnoreParenImpCasts(); 11360 // We also want to warn on, e.g., "int i = -1.234" 11361 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11362 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11363 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11364 11365 const bool IsLiteral = 11366 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11367 11368 llvm::APFloat Value(0.0); 11369 bool IsConstant = 11370 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11371 if (!IsConstant) { 11372 if (isObjCSignedCharBool(S, T)) { 11373 return adornObjCBoolConversionDiagWithTernaryFixit( 11374 S, E, 11375 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11376 << E->getType()); 11377 } 11378 11379 return DiagnoseImpCast(S, E, T, CContext, 11380 diag::warn_impcast_float_integer, PruneWarnings); 11381 } 11382 11383 bool isExact = false; 11384 11385 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11386 T->hasUnsignedIntegerRepresentation()); 11387 llvm::APFloat::opStatus Result = Value.convertToInteger( 11388 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11389 11390 // FIXME: Force the precision of the source value down so we don't print 11391 // digits which are usually useless (we don't really care here if we 11392 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11393 // would automatically print the shortest representation, but it's a bit 11394 // tricky to implement. 11395 SmallString<16> PrettySourceValue; 11396 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11397 precision = (precision * 59 + 195) / 196; 11398 Value.toString(PrettySourceValue, precision); 11399 11400 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11401 return adornObjCBoolConversionDiagWithTernaryFixit( 11402 S, E, 11403 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11404 << PrettySourceValue); 11405 } 11406 11407 if (Result == llvm::APFloat::opOK && isExact) { 11408 if (IsLiteral) return; 11409 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11410 PruneWarnings); 11411 } 11412 11413 // Conversion of a floating-point value to a non-bool integer where the 11414 // integral part cannot be represented by the integer type is undefined. 11415 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11416 return DiagnoseImpCast( 11417 S, E, T, CContext, 11418 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11419 : diag::warn_impcast_float_to_integer_out_of_range, 11420 PruneWarnings); 11421 11422 unsigned DiagID = 0; 11423 if (IsLiteral) { 11424 // Warn on floating point literal to integer. 11425 DiagID = diag::warn_impcast_literal_float_to_integer; 11426 } else if (IntegerValue == 0) { 11427 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11428 return DiagnoseImpCast(S, E, T, CContext, 11429 diag::warn_impcast_float_integer, PruneWarnings); 11430 } 11431 // Warn on non-zero to zero conversion. 11432 DiagID = diag::warn_impcast_float_to_integer_zero; 11433 } else { 11434 if (IntegerValue.isUnsigned()) { 11435 if (!IntegerValue.isMaxValue()) { 11436 return DiagnoseImpCast(S, E, T, CContext, 11437 diag::warn_impcast_float_integer, PruneWarnings); 11438 } 11439 } else { // IntegerValue.isSigned() 11440 if (!IntegerValue.isMaxSignedValue() && 11441 !IntegerValue.isMinSignedValue()) { 11442 return DiagnoseImpCast(S, E, T, CContext, 11443 diag::warn_impcast_float_integer, PruneWarnings); 11444 } 11445 } 11446 // Warn on evaluatable floating point expression to integer conversion. 11447 DiagID = diag::warn_impcast_float_to_integer; 11448 } 11449 11450 SmallString<16> PrettyTargetValue; 11451 if (IsBool) 11452 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11453 else 11454 IntegerValue.toString(PrettyTargetValue); 11455 11456 if (PruneWarnings) { 11457 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11458 S.PDiag(DiagID) 11459 << E->getType() << T.getUnqualifiedType() 11460 << PrettySourceValue << PrettyTargetValue 11461 << E->getSourceRange() << SourceRange(CContext)); 11462 } else { 11463 S.Diag(E->getExprLoc(), DiagID) 11464 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11465 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11466 } 11467 } 11468 11469 /// Analyze the given compound assignment for the possible losing of 11470 /// floating-point precision. 11471 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11472 assert(isa<CompoundAssignOperator>(E) && 11473 "Must be compound assignment operation"); 11474 // Recurse on the LHS and RHS in here 11475 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11476 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11477 11478 if (E->getLHS()->getType()->isAtomicType()) 11479 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11480 11481 // Now check the outermost expression 11482 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11483 const auto *RBT = cast<CompoundAssignOperator>(E) 11484 ->getComputationResultType() 11485 ->getAs<BuiltinType>(); 11486 11487 // The below checks assume source is floating point. 11488 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11489 11490 // If source is floating point but target is an integer. 11491 if (ResultBT->isInteger()) 11492 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11493 E->getExprLoc(), diag::warn_impcast_float_integer); 11494 11495 if (!ResultBT->isFloatingPoint()) 11496 return; 11497 11498 // If both source and target are floating points, warn about losing precision. 11499 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11500 QualType(ResultBT, 0), QualType(RBT, 0)); 11501 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11502 // warn about dropping FP rank. 11503 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11504 diag::warn_impcast_float_result_precision); 11505 } 11506 11507 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11508 IntRange Range) { 11509 if (!Range.Width) return "0"; 11510 11511 llvm::APSInt ValueInRange = Value; 11512 ValueInRange.setIsSigned(!Range.NonNegative); 11513 ValueInRange = ValueInRange.trunc(Range.Width); 11514 return ValueInRange.toString(10); 11515 } 11516 11517 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11518 if (!isa<ImplicitCastExpr>(Ex)) 11519 return false; 11520 11521 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11522 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11523 const Type *Source = 11524 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11525 if (Target->isDependentType()) 11526 return false; 11527 11528 const BuiltinType *FloatCandidateBT = 11529 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11530 const Type *BoolCandidateType = ToBool ? Target : Source; 11531 11532 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11533 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11534 } 11535 11536 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11537 SourceLocation CC) { 11538 unsigned NumArgs = TheCall->getNumArgs(); 11539 for (unsigned i = 0; i < NumArgs; ++i) { 11540 Expr *CurrA = TheCall->getArg(i); 11541 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11542 continue; 11543 11544 bool IsSwapped = ((i > 0) && 11545 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11546 IsSwapped |= ((i < (NumArgs - 1)) && 11547 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11548 if (IsSwapped) { 11549 // Warn on this floating-point to bool conversion. 11550 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11551 CurrA->getType(), CC, 11552 diag::warn_impcast_floating_point_to_bool); 11553 } 11554 } 11555 } 11556 11557 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11558 SourceLocation CC) { 11559 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11560 E->getExprLoc())) 11561 return; 11562 11563 // Don't warn on functions which have return type nullptr_t. 11564 if (isa<CallExpr>(E)) 11565 return; 11566 11567 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11568 const Expr::NullPointerConstantKind NullKind = 11569 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11570 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11571 return; 11572 11573 // Return if target type is a safe conversion. 11574 if (T->isAnyPointerType() || T->isBlockPointerType() || 11575 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11576 return; 11577 11578 SourceLocation Loc = E->getSourceRange().getBegin(); 11579 11580 // Venture through the macro stacks to get to the source of macro arguments. 11581 // The new location is a better location than the complete location that was 11582 // passed in. 11583 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11584 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11585 11586 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11587 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11588 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11589 Loc, S.SourceMgr, S.getLangOpts()); 11590 if (MacroName == "NULL") 11591 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11592 } 11593 11594 // Only warn if the null and context location are in the same macro expansion. 11595 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11596 return; 11597 11598 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11599 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11600 << FixItHint::CreateReplacement(Loc, 11601 S.getFixItZeroLiteralForType(T, Loc)); 11602 } 11603 11604 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11605 ObjCArrayLiteral *ArrayLiteral); 11606 11607 static void 11608 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11609 ObjCDictionaryLiteral *DictionaryLiteral); 11610 11611 /// Check a single element within a collection literal against the 11612 /// target element type. 11613 static void checkObjCCollectionLiteralElement(Sema &S, 11614 QualType TargetElementType, 11615 Expr *Element, 11616 unsigned ElementKind) { 11617 // Skip a bitcast to 'id' or qualified 'id'. 11618 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11619 if (ICE->getCastKind() == CK_BitCast && 11620 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11621 Element = ICE->getSubExpr(); 11622 } 11623 11624 QualType ElementType = Element->getType(); 11625 ExprResult ElementResult(Element); 11626 if (ElementType->getAs<ObjCObjectPointerType>() && 11627 S.CheckSingleAssignmentConstraints(TargetElementType, 11628 ElementResult, 11629 false, false) 11630 != Sema::Compatible) { 11631 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11632 << ElementType << ElementKind << TargetElementType 11633 << Element->getSourceRange(); 11634 } 11635 11636 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11637 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11638 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11639 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11640 } 11641 11642 /// Check an Objective-C array literal being converted to the given 11643 /// target type. 11644 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11645 ObjCArrayLiteral *ArrayLiteral) { 11646 if (!S.NSArrayDecl) 11647 return; 11648 11649 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11650 if (!TargetObjCPtr) 11651 return; 11652 11653 if (TargetObjCPtr->isUnspecialized() || 11654 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11655 != S.NSArrayDecl->getCanonicalDecl()) 11656 return; 11657 11658 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11659 if (TypeArgs.size() != 1) 11660 return; 11661 11662 QualType TargetElementType = TypeArgs[0]; 11663 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11664 checkObjCCollectionLiteralElement(S, TargetElementType, 11665 ArrayLiteral->getElement(I), 11666 0); 11667 } 11668 } 11669 11670 /// Check an Objective-C dictionary literal being converted to the given 11671 /// target type. 11672 static void 11673 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11674 ObjCDictionaryLiteral *DictionaryLiteral) { 11675 if (!S.NSDictionaryDecl) 11676 return; 11677 11678 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11679 if (!TargetObjCPtr) 11680 return; 11681 11682 if (TargetObjCPtr->isUnspecialized() || 11683 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11684 != S.NSDictionaryDecl->getCanonicalDecl()) 11685 return; 11686 11687 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11688 if (TypeArgs.size() != 2) 11689 return; 11690 11691 QualType TargetKeyType = TypeArgs[0]; 11692 QualType TargetObjectType = TypeArgs[1]; 11693 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11694 auto Element = DictionaryLiteral->getKeyValueElement(I); 11695 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11696 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11697 } 11698 } 11699 11700 // Helper function to filter out cases for constant width constant conversion. 11701 // Don't warn on char array initialization or for non-decimal values. 11702 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11703 SourceLocation CC) { 11704 // If initializing from a constant, and the constant starts with '0', 11705 // then it is a binary, octal, or hexadecimal. Allow these constants 11706 // to fill all the bits, even if there is a sign change. 11707 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11708 const char FirstLiteralCharacter = 11709 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11710 if (FirstLiteralCharacter == '0') 11711 return false; 11712 } 11713 11714 // If the CC location points to a '{', and the type is char, then assume 11715 // assume it is an array initialization. 11716 if (CC.isValid() && T->isCharType()) { 11717 const char FirstContextCharacter = 11718 S.getSourceManager().getCharacterData(CC)[0]; 11719 if (FirstContextCharacter == '{') 11720 return false; 11721 } 11722 11723 return true; 11724 } 11725 11726 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11727 const auto *IL = dyn_cast<IntegerLiteral>(E); 11728 if (!IL) { 11729 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11730 if (UO->getOpcode() == UO_Minus) 11731 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11732 } 11733 } 11734 11735 return IL; 11736 } 11737 11738 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11739 E = E->IgnoreParenImpCasts(); 11740 SourceLocation ExprLoc = E->getExprLoc(); 11741 11742 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11743 BinaryOperator::Opcode Opc = BO->getOpcode(); 11744 Expr::EvalResult Result; 11745 // Do not diagnose unsigned shifts. 11746 if (Opc == BO_Shl) { 11747 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11748 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11749 if (LHS && LHS->getValue() == 0) 11750 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11751 else if (!E->isValueDependent() && LHS && RHS && 11752 RHS->getValue().isNonNegative() && 11753 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11754 S.Diag(ExprLoc, diag::warn_left_shift_always) 11755 << (Result.Val.getInt() != 0); 11756 else if (E->getType()->isSignedIntegerType()) 11757 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11758 } 11759 } 11760 11761 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11762 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11763 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11764 if (!LHS || !RHS) 11765 return; 11766 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11767 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11768 // Do not diagnose common idioms. 11769 return; 11770 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11771 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11772 } 11773 } 11774 11775 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11776 SourceLocation CC, 11777 bool *ICContext = nullptr, 11778 bool IsListInit = false) { 11779 if (E->isTypeDependent() || E->isValueDependent()) return; 11780 11781 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11782 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11783 if (Source == Target) return; 11784 if (Target->isDependentType()) return; 11785 11786 // If the conversion context location is invalid don't complain. We also 11787 // don't want to emit a warning if the issue occurs from the expansion of 11788 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11789 // delay this check as long as possible. Once we detect we are in that 11790 // scenario, we just return. 11791 if (CC.isInvalid()) 11792 return; 11793 11794 if (Source->isAtomicType()) 11795 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11796 11797 // Diagnose implicit casts to bool. 11798 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11799 if (isa<StringLiteral>(E)) 11800 // Warn on string literal to bool. Checks for string literals in logical 11801 // and expressions, for instance, assert(0 && "error here"), are 11802 // prevented by a check in AnalyzeImplicitConversions(). 11803 return DiagnoseImpCast(S, E, T, CC, 11804 diag::warn_impcast_string_literal_to_bool); 11805 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11806 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11807 // This covers the literal expressions that evaluate to Objective-C 11808 // objects. 11809 return DiagnoseImpCast(S, E, T, CC, 11810 diag::warn_impcast_objective_c_literal_to_bool); 11811 } 11812 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11813 // Warn on pointer to bool conversion that is always true. 11814 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11815 SourceRange(CC)); 11816 } 11817 } 11818 11819 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11820 // is a typedef for signed char (macOS), then that constant value has to be 1 11821 // or 0. 11822 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11823 Expr::EvalResult Result; 11824 if (E->EvaluateAsInt(Result, S.getASTContext(), 11825 Expr::SE_AllowSideEffects)) { 11826 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11827 adornObjCBoolConversionDiagWithTernaryFixit( 11828 S, E, 11829 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11830 << Result.Val.getInt().toString(10)); 11831 } 11832 return; 11833 } 11834 } 11835 11836 // Check implicit casts from Objective-C collection literals to specialized 11837 // collection types, e.g., NSArray<NSString *> *. 11838 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11839 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11840 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11841 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11842 11843 // Strip vector types. 11844 if (isa<VectorType>(Source)) { 11845 if (!isa<VectorType>(Target)) { 11846 if (S.SourceMgr.isInSystemMacro(CC)) 11847 return; 11848 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11849 } 11850 11851 // If the vector cast is cast between two vectors of the same size, it is 11852 // a bitcast, not a conversion. 11853 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11854 return; 11855 11856 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11857 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11858 } 11859 if (auto VecTy = dyn_cast<VectorType>(Target)) 11860 Target = VecTy->getElementType().getTypePtr(); 11861 11862 // Strip complex types. 11863 if (isa<ComplexType>(Source)) { 11864 if (!isa<ComplexType>(Target)) { 11865 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11866 return; 11867 11868 return DiagnoseImpCast(S, E, T, CC, 11869 S.getLangOpts().CPlusPlus 11870 ? diag::err_impcast_complex_scalar 11871 : diag::warn_impcast_complex_scalar); 11872 } 11873 11874 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11875 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11876 } 11877 11878 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11879 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11880 11881 // If the source is floating point... 11882 if (SourceBT && SourceBT->isFloatingPoint()) { 11883 // ...and the target is floating point... 11884 if (TargetBT && TargetBT->isFloatingPoint()) { 11885 // ...then warn if we're dropping FP rank. 11886 11887 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11888 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11889 if (Order > 0) { 11890 // Don't warn about float constants that are precisely 11891 // representable in the target type. 11892 Expr::EvalResult result; 11893 if (E->EvaluateAsRValue(result, S.Context)) { 11894 // Value might be a float, a float vector, or a float complex. 11895 if (IsSameFloatAfterCast(result.Val, 11896 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11897 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11898 return; 11899 } 11900 11901 if (S.SourceMgr.isInSystemMacro(CC)) 11902 return; 11903 11904 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11905 } 11906 // ... or possibly if we're increasing rank, too 11907 else if (Order < 0) { 11908 if (S.SourceMgr.isInSystemMacro(CC)) 11909 return; 11910 11911 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11912 } 11913 return; 11914 } 11915 11916 // If the target is integral, always warn. 11917 if (TargetBT && TargetBT->isInteger()) { 11918 if (S.SourceMgr.isInSystemMacro(CC)) 11919 return; 11920 11921 DiagnoseFloatingImpCast(S, E, T, CC); 11922 } 11923 11924 // Detect the case where a call result is converted from floating-point to 11925 // to bool, and the final argument to the call is converted from bool, to 11926 // discover this typo: 11927 // 11928 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11929 // 11930 // FIXME: This is an incredibly special case; is there some more general 11931 // way to detect this class of misplaced-parentheses bug? 11932 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11933 // Check last argument of function call to see if it is an 11934 // implicit cast from a type matching the type the result 11935 // is being cast to. 11936 CallExpr *CEx = cast<CallExpr>(E); 11937 if (unsigned NumArgs = CEx->getNumArgs()) { 11938 Expr *LastA = CEx->getArg(NumArgs - 1); 11939 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11940 if (isa<ImplicitCastExpr>(LastA) && 11941 InnerE->getType()->isBooleanType()) { 11942 // Warn on this floating-point to bool conversion 11943 DiagnoseImpCast(S, E, T, CC, 11944 diag::warn_impcast_floating_point_to_bool); 11945 } 11946 } 11947 } 11948 return; 11949 } 11950 11951 // Valid casts involving fixed point types should be accounted for here. 11952 if (Source->isFixedPointType()) { 11953 if (Target->isUnsaturatedFixedPointType()) { 11954 Expr::EvalResult Result; 11955 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11956 S.isConstantEvaluated())) { 11957 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 11958 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11959 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11960 if (Value > MaxVal || Value < MinVal) { 11961 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11962 S.PDiag(diag::warn_impcast_fixed_point_range) 11963 << Value.toString() << T 11964 << E->getSourceRange() 11965 << clang::SourceRange(CC)); 11966 return; 11967 } 11968 } 11969 } else if (Target->isIntegerType()) { 11970 Expr::EvalResult Result; 11971 if (!S.isConstantEvaluated() && 11972 E->EvaluateAsFixedPoint(Result, S.Context, 11973 Expr::SE_AllowSideEffects)) { 11974 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 11975 11976 bool Overflowed; 11977 llvm::APSInt IntResult = FXResult.convertToInt( 11978 S.Context.getIntWidth(T), 11979 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11980 11981 if (Overflowed) { 11982 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11983 S.PDiag(diag::warn_impcast_fixed_point_range) 11984 << FXResult.toString() << T 11985 << E->getSourceRange() 11986 << clang::SourceRange(CC)); 11987 return; 11988 } 11989 } 11990 } 11991 } else if (Target->isUnsaturatedFixedPointType()) { 11992 if (Source->isIntegerType()) { 11993 Expr::EvalResult Result; 11994 if (!S.isConstantEvaluated() && 11995 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11996 llvm::APSInt Value = Result.Val.getInt(); 11997 11998 bool Overflowed; 11999 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12000 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12001 12002 if (Overflowed) { 12003 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12004 S.PDiag(diag::warn_impcast_fixed_point_range) 12005 << Value.toString(/*Radix=*/10) << T 12006 << E->getSourceRange() 12007 << clang::SourceRange(CC)); 12008 return; 12009 } 12010 } 12011 } 12012 } 12013 12014 // If we are casting an integer type to a floating point type without 12015 // initialization-list syntax, we might lose accuracy if the floating 12016 // point type has a narrower significand than the integer type. 12017 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12018 TargetBT->isFloatingType() && !IsListInit) { 12019 // Determine the number of precision bits in the source integer type. 12020 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12021 /*Approximate*/ true); 12022 unsigned int SourcePrecision = SourceRange.Width; 12023 12024 // Determine the number of precision bits in the 12025 // target floating point type. 12026 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12027 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12028 12029 if (SourcePrecision > 0 && TargetPrecision > 0 && 12030 SourcePrecision > TargetPrecision) { 12031 12032 if (Optional<llvm::APSInt> SourceInt = 12033 E->getIntegerConstantExpr(S.Context)) { 12034 // If the source integer is a constant, convert it to the target 12035 // floating point type. Issue a warning if the value changes 12036 // during the whole conversion. 12037 llvm::APFloat TargetFloatValue( 12038 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12039 llvm::APFloat::opStatus ConversionStatus = 12040 TargetFloatValue.convertFromAPInt( 12041 *SourceInt, SourceBT->isSignedInteger(), 12042 llvm::APFloat::rmNearestTiesToEven); 12043 12044 if (ConversionStatus != llvm::APFloat::opOK) { 12045 std::string PrettySourceValue = SourceInt->toString(10); 12046 SmallString<32> PrettyTargetValue; 12047 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12048 12049 S.DiagRuntimeBehavior( 12050 E->getExprLoc(), E, 12051 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12052 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12053 << E->getSourceRange() << clang::SourceRange(CC)); 12054 } 12055 } else { 12056 // Otherwise, the implicit conversion may lose precision. 12057 DiagnoseImpCast(S, E, T, CC, 12058 diag::warn_impcast_integer_float_precision); 12059 } 12060 } 12061 } 12062 12063 DiagnoseNullConversion(S, E, T, CC); 12064 12065 S.DiscardMisalignedMemberAddress(Target, E); 12066 12067 if (Target->isBooleanType()) 12068 DiagnoseIntInBoolContext(S, E); 12069 12070 if (!Source->isIntegerType() || !Target->isIntegerType()) 12071 return; 12072 12073 // TODO: remove this early return once the false positives for constant->bool 12074 // in templates, macros, etc, are reduced or removed. 12075 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12076 return; 12077 12078 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12079 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12080 return adornObjCBoolConversionDiagWithTernaryFixit( 12081 S, E, 12082 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12083 << E->getType()); 12084 } 12085 12086 IntRange SourceTypeRange = 12087 IntRange::forTargetOfCanonicalType(S.Context, Source); 12088 IntRange LikelySourceRange = 12089 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12090 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12091 12092 if (LikelySourceRange.Width > TargetRange.Width) { 12093 // If the source is a constant, use a default-on diagnostic. 12094 // TODO: this should happen for bitfield stores, too. 12095 Expr::EvalResult Result; 12096 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12097 S.isConstantEvaluated())) { 12098 llvm::APSInt Value(32); 12099 Value = Result.Val.getInt(); 12100 12101 if (S.SourceMgr.isInSystemMacro(CC)) 12102 return; 12103 12104 std::string PrettySourceValue = Value.toString(10); 12105 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12106 12107 S.DiagRuntimeBehavior( 12108 E->getExprLoc(), E, 12109 S.PDiag(diag::warn_impcast_integer_precision_constant) 12110 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12111 << E->getSourceRange() << SourceRange(CC)); 12112 return; 12113 } 12114 12115 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12116 if (S.SourceMgr.isInSystemMacro(CC)) 12117 return; 12118 12119 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12120 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12121 /* pruneControlFlow */ true); 12122 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12123 } 12124 12125 if (TargetRange.Width > SourceTypeRange.Width) { 12126 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12127 if (UO->getOpcode() == UO_Minus) 12128 if (Source->isUnsignedIntegerType()) { 12129 if (Target->isUnsignedIntegerType()) 12130 return DiagnoseImpCast(S, E, T, CC, 12131 diag::warn_impcast_high_order_zero_bits); 12132 if (Target->isSignedIntegerType()) 12133 return DiagnoseImpCast(S, E, T, CC, 12134 diag::warn_impcast_nonnegative_result); 12135 } 12136 } 12137 12138 if (TargetRange.Width == LikelySourceRange.Width && 12139 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12140 Source->isSignedIntegerType()) { 12141 // Warn when doing a signed to signed conversion, warn if the positive 12142 // source value is exactly the width of the target type, which will 12143 // cause a negative value to be stored. 12144 12145 Expr::EvalResult Result; 12146 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12147 !S.SourceMgr.isInSystemMacro(CC)) { 12148 llvm::APSInt Value = Result.Val.getInt(); 12149 if (isSameWidthConstantConversion(S, E, T, CC)) { 12150 std::string PrettySourceValue = Value.toString(10); 12151 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12152 12153 S.DiagRuntimeBehavior( 12154 E->getExprLoc(), E, 12155 S.PDiag(diag::warn_impcast_integer_precision_constant) 12156 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12157 << E->getSourceRange() << SourceRange(CC)); 12158 return; 12159 } 12160 } 12161 12162 // Fall through for non-constants to give a sign conversion warning. 12163 } 12164 12165 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12166 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12167 LikelySourceRange.Width == TargetRange.Width)) { 12168 if (S.SourceMgr.isInSystemMacro(CC)) 12169 return; 12170 12171 unsigned DiagID = diag::warn_impcast_integer_sign; 12172 12173 // Traditionally, gcc has warned about this under -Wsign-compare. 12174 // We also want to warn about it in -Wconversion. 12175 // So if -Wconversion is off, use a completely identical diagnostic 12176 // in the sign-compare group. 12177 // The conditional-checking code will 12178 if (ICContext) { 12179 DiagID = diag::warn_impcast_integer_sign_conditional; 12180 *ICContext = true; 12181 } 12182 12183 return DiagnoseImpCast(S, E, T, CC, DiagID); 12184 } 12185 12186 // Diagnose conversions between different enumeration types. 12187 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12188 // type, to give us better diagnostics. 12189 QualType SourceType = E->getType(); 12190 if (!S.getLangOpts().CPlusPlus) { 12191 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12192 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12193 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12194 SourceType = S.Context.getTypeDeclType(Enum); 12195 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12196 } 12197 } 12198 12199 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12200 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12201 if (SourceEnum->getDecl()->hasNameForLinkage() && 12202 TargetEnum->getDecl()->hasNameForLinkage() && 12203 SourceEnum != TargetEnum) { 12204 if (S.SourceMgr.isInSystemMacro(CC)) 12205 return; 12206 12207 return DiagnoseImpCast(S, E, SourceType, T, CC, 12208 diag::warn_impcast_different_enum_types); 12209 } 12210 } 12211 12212 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12213 SourceLocation CC, QualType T); 12214 12215 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12216 SourceLocation CC, bool &ICContext) { 12217 E = E->IgnoreParenImpCasts(); 12218 12219 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12220 return CheckConditionalOperator(S, CO, CC, T); 12221 12222 AnalyzeImplicitConversions(S, E, CC); 12223 if (E->getType() != T) 12224 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12225 } 12226 12227 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12228 SourceLocation CC, QualType T) { 12229 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12230 12231 Expr *TrueExpr = E->getTrueExpr(); 12232 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12233 TrueExpr = BCO->getCommon(); 12234 12235 bool Suspicious = false; 12236 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12237 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12238 12239 if (T->isBooleanType()) 12240 DiagnoseIntInBoolContext(S, E); 12241 12242 // If -Wconversion would have warned about either of the candidates 12243 // for a signedness conversion to the context type... 12244 if (!Suspicious) return; 12245 12246 // ...but it's currently ignored... 12247 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12248 return; 12249 12250 // ...then check whether it would have warned about either of the 12251 // candidates for a signedness conversion to the condition type. 12252 if (E->getType() == T) return; 12253 12254 Suspicious = false; 12255 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12256 E->getType(), CC, &Suspicious); 12257 if (!Suspicious) 12258 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12259 E->getType(), CC, &Suspicious); 12260 } 12261 12262 /// Check conversion of given expression to boolean. 12263 /// Input argument E is a logical expression. 12264 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12265 if (S.getLangOpts().Bool) 12266 return; 12267 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12268 return; 12269 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12270 } 12271 12272 namespace { 12273 struct AnalyzeImplicitConversionsWorkItem { 12274 Expr *E; 12275 SourceLocation CC; 12276 bool IsListInit; 12277 }; 12278 } 12279 12280 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12281 /// that should be visited are added to WorkList. 12282 static void AnalyzeImplicitConversions( 12283 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12284 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12285 Expr *OrigE = Item.E; 12286 SourceLocation CC = Item.CC; 12287 12288 QualType T = OrigE->getType(); 12289 Expr *E = OrigE->IgnoreParenImpCasts(); 12290 12291 // Propagate whether we are in a C++ list initialization expression. 12292 // If so, we do not issue warnings for implicit int-float conversion 12293 // precision loss, because C++11 narrowing already handles it. 12294 bool IsListInit = Item.IsListInit || 12295 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12296 12297 if (E->isTypeDependent() || E->isValueDependent()) 12298 return; 12299 12300 Expr *SourceExpr = E; 12301 // Examine, but don't traverse into the source expression of an 12302 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12303 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12304 // evaluate it in the context of checking the specific conversion to T though. 12305 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12306 if (auto *Src = OVE->getSourceExpr()) 12307 SourceExpr = Src; 12308 12309 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12310 if (UO->getOpcode() == UO_Not && 12311 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12312 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12313 << OrigE->getSourceRange() << T->isBooleanType() 12314 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12315 12316 // For conditional operators, we analyze the arguments as if they 12317 // were being fed directly into the output. 12318 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12319 CheckConditionalOperator(S, CO, CC, T); 12320 return; 12321 } 12322 12323 // Check implicit argument conversions for function calls. 12324 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12325 CheckImplicitArgumentConversions(S, Call, CC); 12326 12327 // Go ahead and check any implicit conversions we might have skipped. 12328 // The non-canonical typecheck is just an optimization; 12329 // CheckImplicitConversion will filter out dead implicit conversions. 12330 if (SourceExpr->getType() != T) 12331 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12332 12333 // Now continue drilling into this expression. 12334 12335 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12336 // The bound subexpressions in a PseudoObjectExpr are not reachable 12337 // as transitive children. 12338 // FIXME: Use a more uniform representation for this. 12339 for (auto *SE : POE->semantics()) 12340 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12341 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12342 } 12343 12344 // Skip past explicit casts. 12345 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12346 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12347 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12348 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12349 WorkList.push_back({E, CC, IsListInit}); 12350 return; 12351 } 12352 12353 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12354 // Do a somewhat different check with comparison operators. 12355 if (BO->isComparisonOp()) 12356 return AnalyzeComparison(S, BO); 12357 12358 // And with simple assignments. 12359 if (BO->getOpcode() == BO_Assign) 12360 return AnalyzeAssignment(S, BO); 12361 // And with compound assignments. 12362 if (BO->isAssignmentOp()) 12363 return AnalyzeCompoundAssignment(S, BO); 12364 } 12365 12366 // These break the otherwise-useful invariant below. Fortunately, 12367 // we don't really need to recurse into them, because any internal 12368 // expressions should have been analyzed already when they were 12369 // built into statements. 12370 if (isa<StmtExpr>(E)) return; 12371 12372 // Don't descend into unevaluated contexts. 12373 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12374 12375 // Now just recurse over the expression's children. 12376 CC = E->getExprLoc(); 12377 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12378 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12379 for (Stmt *SubStmt : E->children()) { 12380 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12381 if (!ChildExpr) 12382 continue; 12383 12384 if (IsLogicalAndOperator && 12385 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12386 // Ignore checking string literals that are in logical and operators. 12387 // This is a common pattern for asserts. 12388 continue; 12389 WorkList.push_back({ChildExpr, CC, IsListInit}); 12390 } 12391 12392 if (BO && BO->isLogicalOp()) { 12393 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12394 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12395 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12396 12397 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12398 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12399 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12400 } 12401 12402 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12403 if (U->getOpcode() == UO_LNot) { 12404 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12405 } else if (U->getOpcode() != UO_AddrOf) { 12406 if (U->getSubExpr()->getType()->isAtomicType()) 12407 S.Diag(U->getSubExpr()->getBeginLoc(), 12408 diag::warn_atomic_implicit_seq_cst); 12409 } 12410 } 12411 } 12412 12413 /// AnalyzeImplicitConversions - Find and report any interesting 12414 /// implicit conversions in the given expression. There are a couple 12415 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12416 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12417 bool IsListInit/*= false*/) { 12418 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12419 WorkList.push_back({OrigE, CC, IsListInit}); 12420 while (!WorkList.empty()) 12421 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12422 } 12423 12424 /// Diagnose integer type and any valid implicit conversion to it. 12425 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12426 // Taking into account implicit conversions, 12427 // allow any integer. 12428 if (!E->getType()->isIntegerType()) { 12429 S.Diag(E->getBeginLoc(), 12430 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12431 return true; 12432 } 12433 // Potentially emit standard warnings for implicit conversions if enabled 12434 // using -Wconversion. 12435 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12436 return false; 12437 } 12438 12439 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12440 // Returns true when emitting a warning about taking the address of a reference. 12441 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12442 const PartialDiagnostic &PD) { 12443 E = E->IgnoreParenImpCasts(); 12444 12445 const FunctionDecl *FD = nullptr; 12446 12447 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12448 if (!DRE->getDecl()->getType()->isReferenceType()) 12449 return false; 12450 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12451 if (!M->getMemberDecl()->getType()->isReferenceType()) 12452 return false; 12453 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12454 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12455 return false; 12456 FD = Call->getDirectCallee(); 12457 } else { 12458 return false; 12459 } 12460 12461 SemaRef.Diag(E->getExprLoc(), PD); 12462 12463 // If possible, point to location of function. 12464 if (FD) { 12465 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12466 } 12467 12468 return true; 12469 } 12470 12471 // Returns true if the SourceLocation is expanded from any macro body. 12472 // Returns false if the SourceLocation is invalid, is from not in a macro 12473 // expansion, or is from expanded from a top-level macro argument. 12474 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12475 if (Loc.isInvalid()) 12476 return false; 12477 12478 while (Loc.isMacroID()) { 12479 if (SM.isMacroBodyExpansion(Loc)) 12480 return true; 12481 Loc = SM.getImmediateMacroCallerLoc(Loc); 12482 } 12483 12484 return false; 12485 } 12486 12487 /// Diagnose pointers that are always non-null. 12488 /// \param E the expression containing the pointer 12489 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12490 /// compared to a null pointer 12491 /// \param IsEqual True when the comparison is equal to a null pointer 12492 /// \param Range Extra SourceRange to highlight in the diagnostic 12493 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12494 Expr::NullPointerConstantKind NullKind, 12495 bool IsEqual, SourceRange Range) { 12496 if (!E) 12497 return; 12498 12499 // Don't warn inside macros. 12500 if (E->getExprLoc().isMacroID()) { 12501 const SourceManager &SM = getSourceManager(); 12502 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12503 IsInAnyMacroBody(SM, Range.getBegin())) 12504 return; 12505 } 12506 E = E->IgnoreImpCasts(); 12507 12508 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12509 12510 if (isa<CXXThisExpr>(E)) { 12511 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12512 : diag::warn_this_bool_conversion; 12513 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12514 return; 12515 } 12516 12517 bool IsAddressOf = false; 12518 12519 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12520 if (UO->getOpcode() != UO_AddrOf) 12521 return; 12522 IsAddressOf = true; 12523 E = UO->getSubExpr(); 12524 } 12525 12526 if (IsAddressOf) { 12527 unsigned DiagID = IsCompare 12528 ? diag::warn_address_of_reference_null_compare 12529 : diag::warn_address_of_reference_bool_conversion; 12530 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12531 << IsEqual; 12532 if (CheckForReference(*this, E, PD)) { 12533 return; 12534 } 12535 } 12536 12537 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12538 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12539 std::string Str; 12540 llvm::raw_string_ostream S(Str); 12541 E->printPretty(S, nullptr, getPrintingPolicy()); 12542 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12543 : diag::warn_cast_nonnull_to_bool; 12544 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12545 << E->getSourceRange() << Range << IsEqual; 12546 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12547 }; 12548 12549 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12550 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12551 if (auto *Callee = Call->getDirectCallee()) { 12552 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12553 ComplainAboutNonnullParamOrCall(A); 12554 return; 12555 } 12556 } 12557 } 12558 12559 // Expect to find a single Decl. Skip anything more complicated. 12560 ValueDecl *D = nullptr; 12561 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12562 D = R->getDecl(); 12563 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12564 D = M->getMemberDecl(); 12565 } 12566 12567 // Weak Decls can be null. 12568 if (!D || D->isWeak()) 12569 return; 12570 12571 // Check for parameter decl with nonnull attribute 12572 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12573 if (getCurFunction() && 12574 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12575 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12576 ComplainAboutNonnullParamOrCall(A); 12577 return; 12578 } 12579 12580 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12581 // Skip function template not specialized yet. 12582 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12583 return; 12584 auto ParamIter = llvm::find(FD->parameters(), PV); 12585 assert(ParamIter != FD->param_end()); 12586 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12587 12588 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12589 if (!NonNull->args_size()) { 12590 ComplainAboutNonnullParamOrCall(NonNull); 12591 return; 12592 } 12593 12594 for (const ParamIdx &ArgNo : NonNull->args()) { 12595 if (ArgNo.getASTIndex() == ParamNo) { 12596 ComplainAboutNonnullParamOrCall(NonNull); 12597 return; 12598 } 12599 } 12600 } 12601 } 12602 } 12603 } 12604 12605 QualType T = D->getType(); 12606 const bool IsArray = T->isArrayType(); 12607 const bool IsFunction = T->isFunctionType(); 12608 12609 // Address of function is used to silence the function warning. 12610 if (IsAddressOf && IsFunction) { 12611 return; 12612 } 12613 12614 // Found nothing. 12615 if (!IsAddressOf && !IsFunction && !IsArray) 12616 return; 12617 12618 // Pretty print the expression for the diagnostic. 12619 std::string Str; 12620 llvm::raw_string_ostream S(Str); 12621 E->printPretty(S, nullptr, getPrintingPolicy()); 12622 12623 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12624 : diag::warn_impcast_pointer_to_bool; 12625 enum { 12626 AddressOf, 12627 FunctionPointer, 12628 ArrayPointer 12629 } DiagType; 12630 if (IsAddressOf) 12631 DiagType = AddressOf; 12632 else if (IsFunction) 12633 DiagType = FunctionPointer; 12634 else if (IsArray) 12635 DiagType = ArrayPointer; 12636 else 12637 llvm_unreachable("Could not determine diagnostic."); 12638 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12639 << Range << IsEqual; 12640 12641 if (!IsFunction) 12642 return; 12643 12644 // Suggest '&' to silence the function warning. 12645 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12646 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12647 12648 // Check to see if '()' fixit should be emitted. 12649 QualType ReturnType; 12650 UnresolvedSet<4> NonTemplateOverloads; 12651 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12652 if (ReturnType.isNull()) 12653 return; 12654 12655 if (IsCompare) { 12656 // There are two cases here. If there is null constant, the only suggest 12657 // for a pointer return type. If the null is 0, then suggest if the return 12658 // type is a pointer or an integer type. 12659 if (!ReturnType->isPointerType()) { 12660 if (NullKind == Expr::NPCK_ZeroExpression || 12661 NullKind == Expr::NPCK_ZeroLiteral) { 12662 if (!ReturnType->isIntegerType()) 12663 return; 12664 } else { 12665 return; 12666 } 12667 } 12668 } else { // !IsCompare 12669 // For function to bool, only suggest if the function pointer has bool 12670 // return type. 12671 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12672 return; 12673 } 12674 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12675 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12676 } 12677 12678 /// Diagnoses "dangerous" implicit conversions within the given 12679 /// expression (which is a full expression). Implements -Wconversion 12680 /// and -Wsign-compare. 12681 /// 12682 /// \param CC the "context" location of the implicit conversion, i.e. 12683 /// the most location of the syntactic entity requiring the implicit 12684 /// conversion 12685 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12686 // Don't diagnose in unevaluated contexts. 12687 if (isUnevaluatedContext()) 12688 return; 12689 12690 // Don't diagnose for value- or type-dependent expressions. 12691 if (E->isTypeDependent() || E->isValueDependent()) 12692 return; 12693 12694 // Check for array bounds violations in cases where the check isn't triggered 12695 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12696 // ArraySubscriptExpr is on the RHS of a variable initialization. 12697 CheckArrayAccess(E); 12698 12699 // This is not the right CC for (e.g.) a variable initialization. 12700 AnalyzeImplicitConversions(*this, E, CC); 12701 } 12702 12703 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12704 /// Input argument E is a logical expression. 12705 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12706 ::CheckBoolLikeConversion(*this, E, CC); 12707 } 12708 12709 /// Diagnose when expression is an integer constant expression and its evaluation 12710 /// results in integer overflow 12711 void Sema::CheckForIntOverflow (Expr *E) { 12712 // Use a work list to deal with nested struct initializers. 12713 SmallVector<Expr *, 2> Exprs(1, E); 12714 12715 do { 12716 Expr *OriginalE = Exprs.pop_back_val(); 12717 Expr *E = OriginalE->IgnoreParenCasts(); 12718 12719 if (isa<BinaryOperator>(E)) { 12720 E->EvaluateForOverflow(Context); 12721 continue; 12722 } 12723 12724 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12725 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12726 else if (isa<ObjCBoxedExpr>(OriginalE)) 12727 E->EvaluateForOverflow(Context); 12728 else if (auto Call = dyn_cast<CallExpr>(E)) 12729 Exprs.append(Call->arg_begin(), Call->arg_end()); 12730 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12731 Exprs.append(Message->arg_begin(), Message->arg_end()); 12732 } while (!Exprs.empty()); 12733 } 12734 12735 namespace { 12736 12737 /// Visitor for expressions which looks for unsequenced operations on the 12738 /// same object. 12739 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12740 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12741 12742 /// A tree of sequenced regions within an expression. Two regions are 12743 /// unsequenced if one is an ancestor or a descendent of the other. When we 12744 /// finish processing an expression with sequencing, such as a comma 12745 /// expression, we fold its tree nodes into its parent, since they are 12746 /// unsequenced with respect to nodes we will visit later. 12747 class SequenceTree { 12748 struct Value { 12749 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12750 unsigned Parent : 31; 12751 unsigned Merged : 1; 12752 }; 12753 SmallVector<Value, 8> Values; 12754 12755 public: 12756 /// A region within an expression which may be sequenced with respect 12757 /// to some other region. 12758 class Seq { 12759 friend class SequenceTree; 12760 12761 unsigned Index; 12762 12763 explicit Seq(unsigned N) : Index(N) {} 12764 12765 public: 12766 Seq() : Index(0) {} 12767 }; 12768 12769 SequenceTree() { Values.push_back(Value(0)); } 12770 Seq root() const { return Seq(0); } 12771 12772 /// Create a new sequence of operations, which is an unsequenced 12773 /// subset of \p Parent. This sequence of operations is sequenced with 12774 /// respect to other children of \p Parent. 12775 Seq allocate(Seq Parent) { 12776 Values.push_back(Value(Parent.Index)); 12777 return Seq(Values.size() - 1); 12778 } 12779 12780 /// Merge a sequence of operations into its parent. 12781 void merge(Seq S) { 12782 Values[S.Index].Merged = true; 12783 } 12784 12785 /// Determine whether two operations are unsequenced. This operation 12786 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12787 /// should have been merged into its parent as appropriate. 12788 bool isUnsequenced(Seq Cur, Seq Old) { 12789 unsigned C = representative(Cur.Index); 12790 unsigned Target = representative(Old.Index); 12791 while (C >= Target) { 12792 if (C == Target) 12793 return true; 12794 C = Values[C].Parent; 12795 } 12796 return false; 12797 } 12798 12799 private: 12800 /// Pick a representative for a sequence. 12801 unsigned representative(unsigned K) { 12802 if (Values[K].Merged) 12803 // Perform path compression as we go. 12804 return Values[K].Parent = representative(Values[K].Parent); 12805 return K; 12806 } 12807 }; 12808 12809 /// An object for which we can track unsequenced uses. 12810 using Object = const NamedDecl *; 12811 12812 /// Different flavors of object usage which we track. We only track the 12813 /// least-sequenced usage of each kind. 12814 enum UsageKind { 12815 /// A read of an object. Multiple unsequenced reads are OK. 12816 UK_Use, 12817 12818 /// A modification of an object which is sequenced before the value 12819 /// computation of the expression, such as ++n in C++. 12820 UK_ModAsValue, 12821 12822 /// A modification of an object which is not sequenced before the value 12823 /// computation of the expression, such as n++. 12824 UK_ModAsSideEffect, 12825 12826 UK_Count = UK_ModAsSideEffect + 1 12827 }; 12828 12829 /// Bundle together a sequencing region and the expression corresponding 12830 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12831 struct Usage { 12832 const Expr *UsageExpr; 12833 SequenceTree::Seq Seq; 12834 12835 Usage() : UsageExpr(nullptr), Seq() {} 12836 }; 12837 12838 struct UsageInfo { 12839 Usage Uses[UK_Count]; 12840 12841 /// Have we issued a diagnostic for this object already? 12842 bool Diagnosed; 12843 12844 UsageInfo() : Uses(), Diagnosed(false) {} 12845 }; 12846 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12847 12848 Sema &SemaRef; 12849 12850 /// Sequenced regions within the expression. 12851 SequenceTree Tree; 12852 12853 /// Declaration modifications and references which we have seen. 12854 UsageInfoMap UsageMap; 12855 12856 /// The region we are currently within. 12857 SequenceTree::Seq Region; 12858 12859 /// Filled in with declarations which were modified as a side-effect 12860 /// (that is, post-increment operations). 12861 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12862 12863 /// Expressions to check later. We defer checking these to reduce 12864 /// stack usage. 12865 SmallVectorImpl<const Expr *> &WorkList; 12866 12867 /// RAII object wrapping the visitation of a sequenced subexpression of an 12868 /// expression. At the end of this process, the side-effects of the evaluation 12869 /// become sequenced with respect to the value computation of the result, so 12870 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12871 /// UK_ModAsValue. 12872 struct SequencedSubexpression { 12873 SequencedSubexpression(SequenceChecker &Self) 12874 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12875 Self.ModAsSideEffect = &ModAsSideEffect; 12876 } 12877 12878 ~SequencedSubexpression() { 12879 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12880 // Add a new usage with usage kind UK_ModAsValue, and then restore 12881 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12882 // the previous one was empty). 12883 UsageInfo &UI = Self.UsageMap[M.first]; 12884 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12885 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12886 SideEffectUsage = M.second; 12887 } 12888 Self.ModAsSideEffect = OldModAsSideEffect; 12889 } 12890 12891 SequenceChecker &Self; 12892 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12893 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12894 }; 12895 12896 /// RAII object wrapping the visitation of a subexpression which we might 12897 /// choose to evaluate as a constant. If any subexpression is evaluated and 12898 /// found to be non-constant, this allows us to suppress the evaluation of 12899 /// the outer expression. 12900 class EvaluationTracker { 12901 public: 12902 EvaluationTracker(SequenceChecker &Self) 12903 : Self(Self), Prev(Self.EvalTracker) { 12904 Self.EvalTracker = this; 12905 } 12906 12907 ~EvaluationTracker() { 12908 Self.EvalTracker = Prev; 12909 if (Prev) 12910 Prev->EvalOK &= EvalOK; 12911 } 12912 12913 bool evaluate(const Expr *E, bool &Result) { 12914 if (!EvalOK || E->isValueDependent()) 12915 return false; 12916 EvalOK = E->EvaluateAsBooleanCondition( 12917 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12918 return EvalOK; 12919 } 12920 12921 private: 12922 SequenceChecker &Self; 12923 EvaluationTracker *Prev; 12924 bool EvalOK = true; 12925 } *EvalTracker = nullptr; 12926 12927 /// Find the object which is produced by the specified expression, 12928 /// if any. 12929 Object getObject(const Expr *E, bool Mod) const { 12930 E = E->IgnoreParenCasts(); 12931 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12932 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12933 return getObject(UO->getSubExpr(), Mod); 12934 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12935 if (BO->getOpcode() == BO_Comma) 12936 return getObject(BO->getRHS(), Mod); 12937 if (Mod && BO->isAssignmentOp()) 12938 return getObject(BO->getLHS(), Mod); 12939 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12940 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12941 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12942 return ME->getMemberDecl(); 12943 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12944 // FIXME: If this is a reference, map through to its value. 12945 return DRE->getDecl(); 12946 return nullptr; 12947 } 12948 12949 /// Note that an object \p O was modified or used by an expression 12950 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12951 /// the object \p O as obtained via the \p UsageMap. 12952 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12953 // Get the old usage for the given object and usage kind. 12954 Usage &U = UI.Uses[UK]; 12955 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12956 // If we have a modification as side effect and are in a sequenced 12957 // subexpression, save the old Usage so that we can restore it later 12958 // in SequencedSubexpression::~SequencedSubexpression. 12959 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12960 ModAsSideEffect->push_back(std::make_pair(O, U)); 12961 // Then record the new usage with the current sequencing region. 12962 U.UsageExpr = UsageExpr; 12963 U.Seq = Region; 12964 } 12965 } 12966 12967 /// Check whether a modification or use of an object \p O in an expression 12968 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12969 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12970 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12971 /// usage and false we are checking for a mod-use unsequenced usage. 12972 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12973 UsageKind OtherKind, bool IsModMod) { 12974 if (UI.Diagnosed) 12975 return; 12976 12977 const Usage &U = UI.Uses[OtherKind]; 12978 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12979 return; 12980 12981 const Expr *Mod = U.UsageExpr; 12982 const Expr *ModOrUse = UsageExpr; 12983 if (OtherKind == UK_Use) 12984 std::swap(Mod, ModOrUse); 12985 12986 SemaRef.DiagRuntimeBehavior( 12987 Mod->getExprLoc(), {Mod, ModOrUse}, 12988 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12989 : diag::warn_unsequenced_mod_use) 12990 << O << SourceRange(ModOrUse->getExprLoc())); 12991 UI.Diagnosed = true; 12992 } 12993 12994 // A note on note{Pre, Post}{Use, Mod}: 12995 // 12996 // (It helps to follow the algorithm with an expression such as 12997 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12998 // operations before C++17 and both are well-defined in C++17). 12999 // 13000 // When visiting a node which uses/modify an object we first call notePreUse 13001 // or notePreMod before visiting its sub-expression(s). At this point the 13002 // children of the current node have not yet been visited and so the eventual 13003 // uses/modifications resulting from the children of the current node have not 13004 // been recorded yet. 13005 // 13006 // We then visit the children of the current node. After that notePostUse or 13007 // notePostMod is called. These will 1) detect an unsequenced modification 13008 // as side effect (as in "k++ + k") and 2) add a new usage with the 13009 // appropriate usage kind. 13010 // 13011 // We also have to be careful that some operation sequences modification as 13012 // side effect as well (for example: || or ,). To account for this we wrap 13013 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13014 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13015 // which record usages which are modifications as side effect, and then 13016 // downgrade them (or more accurately restore the previous usage which was a 13017 // modification as side effect) when exiting the scope of the sequenced 13018 // subexpression. 13019 13020 void notePreUse(Object O, const Expr *UseExpr) { 13021 UsageInfo &UI = UsageMap[O]; 13022 // Uses conflict with other modifications. 13023 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13024 } 13025 13026 void notePostUse(Object O, const Expr *UseExpr) { 13027 UsageInfo &UI = UsageMap[O]; 13028 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13029 /*IsModMod=*/false); 13030 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13031 } 13032 13033 void notePreMod(Object O, const Expr *ModExpr) { 13034 UsageInfo &UI = UsageMap[O]; 13035 // Modifications conflict with other modifications and with uses. 13036 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13037 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13038 } 13039 13040 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13041 UsageInfo &UI = UsageMap[O]; 13042 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13043 /*IsModMod=*/true); 13044 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13045 } 13046 13047 public: 13048 SequenceChecker(Sema &S, const Expr *E, 13049 SmallVectorImpl<const Expr *> &WorkList) 13050 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13051 Visit(E); 13052 // Silence a -Wunused-private-field since WorkList is now unused. 13053 // TODO: Evaluate if it can be used, and if not remove it. 13054 (void)this->WorkList; 13055 } 13056 13057 void VisitStmt(const Stmt *S) { 13058 // Skip all statements which aren't expressions for now. 13059 } 13060 13061 void VisitExpr(const Expr *E) { 13062 // By default, just recurse to evaluated subexpressions. 13063 Base::VisitStmt(E); 13064 } 13065 13066 void VisitCastExpr(const CastExpr *E) { 13067 Object O = Object(); 13068 if (E->getCastKind() == CK_LValueToRValue) 13069 O = getObject(E->getSubExpr(), false); 13070 13071 if (O) 13072 notePreUse(O, E); 13073 VisitExpr(E); 13074 if (O) 13075 notePostUse(O, E); 13076 } 13077 13078 void VisitSequencedExpressions(const Expr *SequencedBefore, 13079 const Expr *SequencedAfter) { 13080 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13081 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13082 SequenceTree::Seq OldRegion = Region; 13083 13084 { 13085 SequencedSubexpression SeqBefore(*this); 13086 Region = BeforeRegion; 13087 Visit(SequencedBefore); 13088 } 13089 13090 Region = AfterRegion; 13091 Visit(SequencedAfter); 13092 13093 Region = OldRegion; 13094 13095 Tree.merge(BeforeRegion); 13096 Tree.merge(AfterRegion); 13097 } 13098 13099 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13100 // C++17 [expr.sub]p1: 13101 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13102 // expression E1 is sequenced before the expression E2. 13103 if (SemaRef.getLangOpts().CPlusPlus17) 13104 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13105 else { 13106 Visit(ASE->getLHS()); 13107 Visit(ASE->getRHS()); 13108 } 13109 } 13110 13111 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13112 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13113 void VisitBinPtrMem(const BinaryOperator *BO) { 13114 // C++17 [expr.mptr.oper]p4: 13115 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13116 // the expression E1 is sequenced before the expression E2. 13117 if (SemaRef.getLangOpts().CPlusPlus17) 13118 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13119 else { 13120 Visit(BO->getLHS()); 13121 Visit(BO->getRHS()); 13122 } 13123 } 13124 13125 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13126 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13127 void VisitBinShlShr(const BinaryOperator *BO) { 13128 // C++17 [expr.shift]p4: 13129 // The expression E1 is sequenced before the expression E2. 13130 if (SemaRef.getLangOpts().CPlusPlus17) 13131 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13132 else { 13133 Visit(BO->getLHS()); 13134 Visit(BO->getRHS()); 13135 } 13136 } 13137 13138 void VisitBinComma(const BinaryOperator *BO) { 13139 // C++11 [expr.comma]p1: 13140 // Every value computation and side effect associated with the left 13141 // expression is sequenced before every value computation and side 13142 // effect associated with the right expression. 13143 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13144 } 13145 13146 void VisitBinAssign(const BinaryOperator *BO) { 13147 SequenceTree::Seq RHSRegion; 13148 SequenceTree::Seq LHSRegion; 13149 if (SemaRef.getLangOpts().CPlusPlus17) { 13150 RHSRegion = Tree.allocate(Region); 13151 LHSRegion = Tree.allocate(Region); 13152 } else { 13153 RHSRegion = Region; 13154 LHSRegion = Region; 13155 } 13156 SequenceTree::Seq OldRegion = Region; 13157 13158 // C++11 [expr.ass]p1: 13159 // [...] the assignment is sequenced after the value computation 13160 // of the right and left operands, [...] 13161 // 13162 // so check it before inspecting the operands and update the 13163 // map afterwards. 13164 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13165 if (O) 13166 notePreMod(O, BO); 13167 13168 if (SemaRef.getLangOpts().CPlusPlus17) { 13169 // C++17 [expr.ass]p1: 13170 // [...] The right operand is sequenced before the left operand. [...] 13171 { 13172 SequencedSubexpression SeqBefore(*this); 13173 Region = RHSRegion; 13174 Visit(BO->getRHS()); 13175 } 13176 13177 Region = LHSRegion; 13178 Visit(BO->getLHS()); 13179 13180 if (O && isa<CompoundAssignOperator>(BO)) 13181 notePostUse(O, BO); 13182 13183 } else { 13184 // C++11 does not specify any sequencing between the LHS and RHS. 13185 Region = LHSRegion; 13186 Visit(BO->getLHS()); 13187 13188 if (O && isa<CompoundAssignOperator>(BO)) 13189 notePostUse(O, BO); 13190 13191 Region = RHSRegion; 13192 Visit(BO->getRHS()); 13193 } 13194 13195 // C++11 [expr.ass]p1: 13196 // the assignment is sequenced [...] before the value computation of the 13197 // assignment expression. 13198 // C11 6.5.16/3 has no such rule. 13199 Region = OldRegion; 13200 if (O) 13201 notePostMod(O, BO, 13202 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13203 : UK_ModAsSideEffect); 13204 if (SemaRef.getLangOpts().CPlusPlus17) { 13205 Tree.merge(RHSRegion); 13206 Tree.merge(LHSRegion); 13207 } 13208 } 13209 13210 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13211 VisitBinAssign(CAO); 13212 } 13213 13214 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13215 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13216 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13217 Object O = getObject(UO->getSubExpr(), true); 13218 if (!O) 13219 return VisitExpr(UO); 13220 13221 notePreMod(O, UO); 13222 Visit(UO->getSubExpr()); 13223 // C++11 [expr.pre.incr]p1: 13224 // the expression ++x is equivalent to x+=1 13225 notePostMod(O, UO, 13226 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13227 : UK_ModAsSideEffect); 13228 } 13229 13230 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13231 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13232 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13233 Object O = getObject(UO->getSubExpr(), true); 13234 if (!O) 13235 return VisitExpr(UO); 13236 13237 notePreMod(O, UO); 13238 Visit(UO->getSubExpr()); 13239 notePostMod(O, UO, UK_ModAsSideEffect); 13240 } 13241 13242 void VisitBinLOr(const BinaryOperator *BO) { 13243 // C++11 [expr.log.or]p2: 13244 // If the second expression is evaluated, every value computation and 13245 // side effect associated with the first expression is sequenced before 13246 // every value computation and side effect associated with the 13247 // second expression. 13248 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13249 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13250 SequenceTree::Seq OldRegion = Region; 13251 13252 EvaluationTracker Eval(*this); 13253 { 13254 SequencedSubexpression Sequenced(*this); 13255 Region = LHSRegion; 13256 Visit(BO->getLHS()); 13257 } 13258 13259 // C++11 [expr.log.or]p1: 13260 // [...] the second operand is not evaluated if the first operand 13261 // evaluates to true. 13262 bool EvalResult = false; 13263 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13264 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13265 if (ShouldVisitRHS) { 13266 Region = RHSRegion; 13267 Visit(BO->getRHS()); 13268 } 13269 13270 Region = OldRegion; 13271 Tree.merge(LHSRegion); 13272 Tree.merge(RHSRegion); 13273 } 13274 13275 void VisitBinLAnd(const BinaryOperator *BO) { 13276 // C++11 [expr.log.and]p2: 13277 // If the second expression is evaluated, every value computation and 13278 // side effect associated with the first expression is sequenced before 13279 // every value computation and side effect associated with the 13280 // second expression. 13281 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13282 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13283 SequenceTree::Seq OldRegion = Region; 13284 13285 EvaluationTracker Eval(*this); 13286 { 13287 SequencedSubexpression Sequenced(*this); 13288 Region = LHSRegion; 13289 Visit(BO->getLHS()); 13290 } 13291 13292 // C++11 [expr.log.and]p1: 13293 // [...] the second operand is not evaluated if the first operand is false. 13294 bool EvalResult = false; 13295 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13296 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13297 if (ShouldVisitRHS) { 13298 Region = RHSRegion; 13299 Visit(BO->getRHS()); 13300 } 13301 13302 Region = OldRegion; 13303 Tree.merge(LHSRegion); 13304 Tree.merge(RHSRegion); 13305 } 13306 13307 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13308 // C++11 [expr.cond]p1: 13309 // [...] Every value computation and side effect associated with the first 13310 // expression is sequenced before every value computation and side effect 13311 // associated with the second or third expression. 13312 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13313 13314 // No sequencing is specified between the true and false expression. 13315 // However since exactly one of both is going to be evaluated we can 13316 // consider them to be sequenced. This is needed to avoid warning on 13317 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13318 // both the true and false expressions because we can't evaluate x. 13319 // This will still allow us to detect an expression like (pre C++17) 13320 // "(x ? y += 1 : y += 2) = y". 13321 // 13322 // We don't wrap the visitation of the true and false expression with 13323 // SequencedSubexpression because we don't want to downgrade modifications 13324 // as side effect in the true and false expressions after the visition 13325 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13326 // not warn between the two "y++", but we should warn between the "y++" 13327 // and the "y". 13328 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13329 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13330 SequenceTree::Seq OldRegion = Region; 13331 13332 EvaluationTracker Eval(*this); 13333 { 13334 SequencedSubexpression Sequenced(*this); 13335 Region = ConditionRegion; 13336 Visit(CO->getCond()); 13337 } 13338 13339 // C++11 [expr.cond]p1: 13340 // [...] The first expression is contextually converted to bool (Clause 4). 13341 // It is evaluated and if it is true, the result of the conditional 13342 // expression is the value of the second expression, otherwise that of the 13343 // third expression. Only one of the second and third expressions is 13344 // evaluated. [...] 13345 bool EvalResult = false; 13346 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13347 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13348 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13349 if (ShouldVisitTrueExpr) { 13350 Region = TrueRegion; 13351 Visit(CO->getTrueExpr()); 13352 } 13353 if (ShouldVisitFalseExpr) { 13354 Region = FalseRegion; 13355 Visit(CO->getFalseExpr()); 13356 } 13357 13358 Region = OldRegion; 13359 Tree.merge(ConditionRegion); 13360 Tree.merge(TrueRegion); 13361 Tree.merge(FalseRegion); 13362 } 13363 13364 void VisitCallExpr(const CallExpr *CE) { 13365 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13366 13367 if (CE->isUnevaluatedBuiltinCall(Context)) 13368 return; 13369 13370 // C++11 [intro.execution]p15: 13371 // When calling a function [...], every value computation and side effect 13372 // associated with any argument expression, or with the postfix expression 13373 // designating the called function, is sequenced before execution of every 13374 // expression or statement in the body of the function [and thus before 13375 // the value computation of its result]. 13376 SequencedSubexpression Sequenced(*this); 13377 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13378 // C++17 [expr.call]p5 13379 // The postfix-expression is sequenced before each expression in the 13380 // expression-list and any default argument. [...] 13381 SequenceTree::Seq CalleeRegion; 13382 SequenceTree::Seq OtherRegion; 13383 if (SemaRef.getLangOpts().CPlusPlus17) { 13384 CalleeRegion = Tree.allocate(Region); 13385 OtherRegion = Tree.allocate(Region); 13386 } else { 13387 CalleeRegion = Region; 13388 OtherRegion = Region; 13389 } 13390 SequenceTree::Seq OldRegion = Region; 13391 13392 // Visit the callee expression first. 13393 Region = CalleeRegion; 13394 if (SemaRef.getLangOpts().CPlusPlus17) { 13395 SequencedSubexpression Sequenced(*this); 13396 Visit(CE->getCallee()); 13397 } else { 13398 Visit(CE->getCallee()); 13399 } 13400 13401 // Then visit the argument expressions. 13402 Region = OtherRegion; 13403 for (const Expr *Argument : CE->arguments()) 13404 Visit(Argument); 13405 13406 Region = OldRegion; 13407 if (SemaRef.getLangOpts().CPlusPlus17) { 13408 Tree.merge(CalleeRegion); 13409 Tree.merge(OtherRegion); 13410 } 13411 }); 13412 } 13413 13414 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13415 // C++17 [over.match.oper]p2: 13416 // [...] the operator notation is first transformed to the equivalent 13417 // function-call notation as summarized in Table 12 (where @ denotes one 13418 // of the operators covered in the specified subclause). However, the 13419 // operands are sequenced in the order prescribed for the built-in 13420 // operator (Clause 8). 13421 // 13422 // From the above only overloaded binary operators and overloaded call 13423 // operators have sequencing rules in C++17 that we need to handle 13424 // separately. 13425 if (!SemaRef.getLangOpts().CPlusPlus17 || 13426 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13427 return VisitCallExpr(CXXOCE); 13428 13429 enum { 13430 NoSequencing, 13431 LHSBeforeRHS, 13432 RHSBeforeLHS, 13433 LHSBeforeRest 13434 } SequencingKind; 13435 switch (CXXOCE->getOperator()) { 13436 case OO_Equal: 13437 case OO_PlusEqual: 13438 case OO_MinusEqual: 13439 case OO_StarEqual: 13440 case OO_SlashEqual: 13441 case OO_PercentEqual: 13442 case OO_CaretEqual: 13443 case OO_AmpEqual: 13444 case OO_PipeEqual: 13445 case OO_LessLessEqual: 13446 case OO_GreaterGreaterEqual: 13447 SequencingKind = RHSBeforeLHS; 13448 break; 13449 13450 case OO_LessLess: 13451 case OO_GreaterGreater: 13452 case OO_AmpAmp: 13453 case OO_PipePipe: 13454 case OO_Comma: 13455 case OO_ArrowStar: 13456 case OO_Subscript: 13457 SequencingKind = LHSBeforeRHS; 13458 break; 13459 13460 case OO_Call: 13461 SequencingKind = LHSBeforeRest; 13462 break; 13463 13464 default: 13465 SequencingKind = NoSequencing; 13466 break; 13467 } 13468 13469 if (SequencingKind == NoSequencing) 13470 return VisitCallExpr(CXXOCE); 13471 13472 // This is a call, so all subexpressions are sequenced before the result. 13473 SequencedSubexpression Sequenced(*this); 13474 13475 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13476 assert(SemaRef.getLangOpts().CPlusPlus17 && 13477 "Should only get there with C++17 and above!"); 13478 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13479 "Should only get there with an overloaded binary operator" 13480 " or an overloaded call operator!"); 13481 13482 if (SequencingKind == LHSBeforeRest) { 13483 assert(CXXOCE->getOperator() == OO_Call && 13484 "We should only have an overloaded call operator here!"); 13485 13486 // This is very similar to VisitCallExpr, except that we only have the 13487 // C++17 case. The postfix-expression is the first argument of the 13488 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13489 // are in the following arguments. 13490 // 13491 // Note that we intentionally do not visit the callee expression since 13492 // it is just a decayed reference to a function. 13493 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13494 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13495 SequenceTree::Seq OldRegion = Region; 13496 13497 assert(CXXOCE->getNumArgs() >= 1 && 13498 "An overloaded call operator must have at least one argument" 13499 " for the postfix-expression!"); 13500 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13501 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13502 CXXOCE->getNumArgs() - 1); 13503 13504 // Visit the postfix-expression first. 13505 { 13506 Region = PostfixExprRegion; 13507 SequencedSubexpression Sequenced(*this); 13508 Visit(PostfixExpr); 13509 } 13510 13511 // Then visit the argument expressions. 13512 Region = ArgsRegion; 13513 for (const Expr *Arg : Args) 13514 Visit(Arg); 13515 13516 Region = OldRegion; 13517 Tree.merge(PostfixExprRegion); 13518 Tree.merge(ArgsRegion); 13519 } else { 13520 assert(CXXOCE->getNumArgs() == 2 && 13521 "Should only have two arguments here!"); 13522 assert((SequencingKind == LHSBeforeRHS || 13523 SequencingKind == RHSBeforeLHS) && 13524 "Unexpected sequencing kind!"); 13525 13526 // We do not visit the callee expression since it is just a decayed 13527 // reference to a function. 13528 const Expr *E1 = CXXOCE->getArg(0); 13529 const Expr *E2 = CXXOCE->getArg(1); 13530 if (SequencingKind == RHSBeforeLHS) 13531 std::swap(E1, E2); 13532 13533 return VisitSequencedExpressions(E1, E2); 13534 } 13535 }); 13536 } 13537 13538 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13539 // This is a call, so all subexpressions are sequenced before the result. 13540 SequencedSubexpression Sequenced(*this); 13541 13542 if (!CCE->isListInitialization()) 13543 return VisitExpr(CCE); 13544 13545 // In C++11, list initializations are sequenced. 13546 SmallVector<SequenceTree::Seq, 32> Elts; 13547 SequenceTree::Seq Parent = Region; 13548 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13549 E = CCE->arg_end(); 13550 I != E; ++I) { 13551 Region = Tree.allocate(Parent); 13552 Elts.push_back(Region); 13553 Visit(*I); 13554 } 13555 13556 // Forget that the initializers are sequenced. 13557 Region = Parent; 13558 for (unsigned I = 0; I < Elts.size(); ++I) 13559 Tree.merge(Elts[I]); 13560 } 13561 13562 void VisitInitListExpr(const InitListExpr *ILE) { 13563 if (!SemaRef.getLangOpts().CPlusPlus11) 13564 return VisitExpr(ILE); 13565 13566 // In C++11, list initializations are sequenced. 13567 SmallVector<SequenceTree::Seq, 32> Elts; 13568 SequenceTree::Seq Parent = Region; 13569 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13570 const Expr *E = ILE->getInit(I); 13571 if (!E) 13572 continue; 13573 Region = Tree.allocate(Parent); 13574 Elts.push_back(Region); 13575 Visit(E); 13576 } 13577 13578 // Forget that the initializers are sequenced. 13579 Region = Parent; 13580 for (unsigned I = 0; I < Elts.size(); ++I) 13581 Tree.merge(Elts[I]); 13582 } 13583 }; 13584 13585 } // namespace 13586 13587 void Sema::CheckUnsequencedOperations(const Expr *E) { 13588 SmallVector<const Expr *, 8> WorkList; 13589 WorkList.push_back(E); 13590 while (!WorkList.empty()) { 13591 const Expr *Item = WorkList.pop_back_val(); 13592 SequenceChecker(*this, Item, WorkList); 13593 } 13594 } 13595 13596 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13597 bool IsConstexpr) { 13598 llvm::SaveAndRestore<bool> ConstantContext( 13599 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13600 CheckImplicitConversions(E, CheckLoc); 13601 if (!E->isInstantiationDependent()) 13602 CheckUnsequencedOperations(E); 13603 if (!IsConstexpr && !E->isValueDependent()) 13604 CheckForIntOverflow(E); 13605 DiagnoseMisalignedMembers(); 13606 } 13607 13608 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13609 FieldDecl *BitField, 13610 Expr *Init) { 13611 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13612 } 13613 13614 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13615 SourceLocation Loc) { 13616 if (!PType->isVariablyModifiedType()) 13617 return; 13618 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13619 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13620 return; 13621 } 13622 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13623 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13624 return; 13625 } 13626 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13627 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13628 return; 13629 } 13630 13631 const ArrayType *AT = S.Context.getAsArrayType(PType); 13632 if (!AT) 13633 return; 13634 13635 if (AT->getSizeModifier() != ArrayType::Star) { 13636 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13637 return; 13638 } 13639 13640 S.Diag(Loc, diag::err_array_star_in_function_definition); 13641 } 13642 13643 /// CheckParmsForFunctionDef - Check that the parameters of the given 13644 /// function are appropriate for the definition of a function. This 13645 /// takes care of any checks that cannot be performed on the 13646 /// declaration itself, e.g., that the types of each of the function 13647 /// parameters are complete. 13648 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13649 bool CheckParameterNames) { 13650 bool HasInvalidParm = false; 13651 for (ParmVarDecl *Param : Parameters) { 13652 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13653 // function declarator that is part of a function definition of 13654 // that function shall not have incomplete type. 13655 // 13656 // This is also C++ [dcl.fct]p6. 13657 if (!Param->isInvalidDecl() && 13658 RequireCompleteType(Param->getLocation(), Param->getType(), 13659 diag::err_typecheck_decl_incomplete_type)) { 13660 Param->setInvalidDecl(); 13661 HasInvalidParm = true; 13662 } 13663 13664 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13665 // declaration of each parameter shall include an identifier. 13666 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13667 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13668 // Diagnose this as an extension in C17 and earlier. 13669 if (!getLangOpts().C2x) 13670 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13671 } 13672 13673 // C99 6.7.5.3p12: 13674 // If the function declarator is not part of a definition of that 13675 // function, parameters may have incomplete type and may use the [*] 13676 // notation in their sequences of declarator specifiers to specify 13677 // variable length array types. 13678 QualType PType = Param->getOriginalType(); 13679 // FIXME: This diagnostic should point the '[*]' if source-location 13680 // information is added for it. 13681 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13682 13683 // If the parameter is a c++ class type and it has to be destructed in the 13684 // callee function, declare the destructor so that it can be called by the 13685 // callee function. Do not perform any direct access check on the dtor here. 13686 if (!Param->isInvalidDecl()) { 13687 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13688 if (!ClassDecl->isInvalidDecl() && 13689 !ClassDecl->hasIrrelevantDestructor() && 13690 !ClassDecl->isDependentContext() && 13691 ClassDecl->isParamDestroyedInCallee()) { 13692 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13693 MarkFunctionReferenced(Param->getLocation(), Destructor); 13694 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13695 } 13696 } 13697 } 13698 13699 // Parameters with the pass_object_size attribute only need to be marked 13700 // constant at function definitions. Because we lack information about 13701 // whether we're on a declaration or definition when we're instantiating the 13702 // attribute, we need to check for constness here. 13703 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13704 if (!Param->getType().isConstQualified()) 13705 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13706 << Attr->getSpelling() << 1; 13707 13708 // Check for parameter names shadowing fields from the class. 13709 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13710 // The owning context for the parameter should be the function, but we 13711 // want to see if this function's declaration context is a record. 13712 DeclContext *DC = Param->getDeclContext(); 13713 if (DC && DC->isFunctionOrMethod()) { 13714 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13715 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13716 RD, /*DeclIsField*/ false); 13717 } 13718 } 13719 } 13720 13721 return HasInvalidParm; 13722 } 13723 13724 Optional<std::pair<CharUnits, CharUnits>> 13725 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13726 13727 /// Compute the alignment and offset of the base class object given the 13728 /// derived-to-base cast expression and the alignment and offset of the derived 13729 /// class object. 13730 static std::pair<CharUnits, CharUnits> 13731 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13732 CharUnits BaseAlignment, CharUnits Offset, 13733 ASTContext &Ctx) { 13734 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13735 ++PathI) { 13736 const CXXBaseSpecifier *Base = *PathI; 13737 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13738 if (Base->isVirtual()) { 13739 // The complete object may have a lower alignment than the non-virtual 13740 // alignment of the base, in which case the base may be misaligned. Choose 13741 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13742 // conservative lower bound of the complete object alignment. 13743 CharUnits NonVirtualAlignment = 13744 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13745 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13746 Offset = CharUnits::Zero(); 13747 } else { 13748 const ASTRecordLayout &RL = 13749 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13750 Offset += RL.getBaseClassOffset(BaseDecl); 13751 } 13752 DerivedType = Base->getType(); 13753 } 13754 13755 return std::make_pair(BaseAlignment, Offset); 13756 } 13757 13758 /// Compute the alignment and offset of a binary additive operator. 13759 static Optional<std::pair<CharUnits, CharUnits>> 13760 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13761 bool IsSub, ASTContext &Ctx) { 13762 QualType PointeeType = PtrE->getType()->getPointeeType(); 13763 13764 if (!PointeeType->isConstantSizeType()) 13765 return llvm::None; 13766 13767 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13768 13769 if (!P) 13770 return llvm::None; 13771 13772 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13773 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13774 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13775 if (IsSub) 13776 Offset = -Offset; 13777 return std::make_pair(P->first, P->second + Offset); 13778 } 13779 13780 // If the integer expression isn't a constant expression, compute the lower 13781 // bound of the alignment using the alignment and offset of the pointer 13782 // expression and the element size. 13783 return std::make_pair( 13784 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13785 CharUnits::Zero()); 13786 } 13787 13788 /// This helper function takes an lvalue expression and returns the alignment of 13789 /// a VarDecl and a constant offset from the VarDecl. 13790 Optional<std::pair<CharUnits, CharUnits>> 13791 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13792 E = E->IgnoreParens(); 13793 switch (E->getStmtClass()) { 13794 default: 13795 break; 13796 case Stmt::CStyleCastExprClass: 13797 case Stmt::CXXStaticCastExprClass: 13798 case Stmt::ImplicitCastExprClass: { 13799 auto *CE = cast<CastExpr>(E); 13800 const Expr *From = CE->getSubExpr(); 13801 switch (CE->getCastKind()) { 13802 default: 13803 break; 13804 case CK_NoOp: 13805 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13806 case CK_UncheckedDerivedToBase: 13807 case CK_DerivedToBase: { 13808 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13809 if (!P) 13810 break; 13811 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13812 P->second, Ctx); 13813 } 13814 } 13815 break; 13816 } 13817 case Stmt::ArraySubscriptExprClass: { 13818 auto *ASE = cast<ArraySubscriptExpr>(E); 13819 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13820 false, Ctx); 13821 } 13822 case Stmt::DeclRefExprClass: { 13823 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13824 // FIXME: If VD is captured by copy or is an escaping __block variable, 13825 // use the alignment of VD's type. 13826 if (!VD->getType()->isReferenceType()) 13827 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13828 if (VD->hasInit()) 13829 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13830 } 13831 break; 13832 } 13833 case Stmt::MemberExprClass: { 13834 auto *ME = cast<MemberExpr>(E); 13835 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13836 if (!FD || FD->getType()->isReferenceType()) 13837 break; 13838 Optional<std::pair<CharUnits, CharUnits>> P; 13839 if (ME->isArrow()) 13840 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 13841 else 13842 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13843 if (!P) 13844 break; 13845 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13846 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13847 return std::make_pair(P->first, 13848 P->second + CharUnits::fromQuantity(Offset)); 13849 } 13850 case Stmt::UnaryOperatorClass: { 13851 auto *UO = cast<UnaryOperator>(E); 13852 switch (UO->getOpcode()) { 13853 default: 13854 break; 13855 case UO_Deref: 13856 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13857 } 13858 break; 13859 } 13860 case Stmt::BinaryOperatorClass: { 13861 auto *BO = cast<BinaryOperator>(E); 13862 auto Opcode = BO->getOpcode(); 13863 switch (Opcode) { 13864 default: 13865 break; 13866 case BO_Comma: 13867 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13868 } 13869 break; 13870 } 13871 } 13872 return llvm::None; 13873 } 13874 13875 /// This helper function takes a pointer expression and returns the alignment of 13876 /// a VarDecl and a constant offset from the VarDecl. 13877 Optional<std::pair<CharUnits, CharUnits>> 13878 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13879 E = E->IgnoreParens(); 13880 switch (E->getStmtClass()) { 13881 default: 13882 break; 13883 case Stmt::CStyleCastExprClass: 13884 case Stmt::CXXStaticCastExprClass: 13885 case Stmt::ImplicitCastExprClass: { 13886 auto *CE = cast<CastExpr>(E); 13887 const Expr *From = CE->getSubExpr(); 13888 switch (CE->getCastKind()) { 13889 default: 13890 break; 13891 case CK_NoOp: 13892 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13893 case CK_ArrayToPointerDecay: 13894 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13895 case CK_UncheckedDerivedToBase: 13896 case CK_DerivedToBase: { 13897 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13898 if (!P) 13899 break; 13900 return getDerivedToBaseAlignmentAndOffset( 13901 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13902 } 13903 } 13904 break; 13905 } 13906 case Stmt::CXXThisExprClass: { 13907 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 13908 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 13909 return std::make_pair(Alignment, CharUnits::Zero()); 13910 } 13911 case Stmt::UnaryOperatorClass: { 13912 auto *UO = cast<UnaryOperator>(E); 13913 if (UO->getOpcode() == UO_AddrOf) 13914 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13915 break; 13916 } 13917 case Stmt::BinaryOperatorClass: { 13918 auto *BO = cast<BinaryOperator>(E); 13919 auto Opcode = BO->getOpcode(); 13920 switch (Opcode) { 13921 default: 13922 break; 13923 case BO_Add: 13924 case BO_Sub: { 13925 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13926 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13927 std::swap(LHS, RHS); 13928 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13929 Ctx); 13930 } 13931 case BO_Comma: 13932 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13933 } 13934 break; 13935 } 13936 } 13937 return llvm::None; 13938 } 13939 13940 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13941 // See if we can compute the alignment of a VarDecl and an offset from it. 13942 Optional<std::pair<CharUnits, CharUnits>> P = 13943 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13944 13945 if (P) 13946 return P->first.alignmentAtOffset(P->second); 13947 13948 // If that failed, return the type's alignment. 13949 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13950 } 13951 13952 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13953 /// pointer cast increases the alignment requirements. 13954 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13955 // This is actually a lot of work to potentially be doing on every 13956 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13957 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13958 return; 13959 13960 // Ignore dependent types. 13961 if (T->isDependentType() || Op->getType()->isDependentType()) 13962 return; 13963 13964 // Require that the destination be a pointer type. 13965 const PointerType *DestPtr = T->getAs<PointerType>(); 13966 if (!DestPtr) return; 13967 13968 // If the destination has alignment 1, we're done. 13969 QualType DestPointee = DestPtr->getPointeeType(); 13970 if (DestPointee->isIncompleteType()) return; 13971 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13972 if (DestAlign.isOne()) return; 13973 13974 // Require that the source be a pointer type. 13975 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13976 if (!SrcPtr) return; 13977 QualType SrcPointee = SrcPtr->getPointeeType(); 13978 13979 // Explicitly allow casts from cv void*. We already implicitly 13980 // allowed casts to cv void*, since they have alignment 1. 13981 // Also allow casts involving incomplete types, which implicitly 13982 // includes 'void'. 13983 if (SrcPointee->isIncompleteType()) return; 13984 13985 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13986 13987 if (SrcAlign >= DestAlign) return; 13988 13989 Diag(TRange.getBegin(), diag::warn_cast_align) 13990 << Op->getType() << T 13991 << static_cast<unsigned>(SrcAlign.getQuantity()) 13992 << static_cast<unsigned>(DestAlign.getQuantity()) 13993 << TRange << Op->getSourceRange(); 13994 } 13995 13996 /// Check whether this array fits the idiom of a size-one tail padded 13997 /// array member of a struct. 13998 /// 13999 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14000 /// commonly used to emulate flexible arrays in C89 code. 14001 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14002 const NamedDecl *ND) { 14003 if (Size != 1 || !ND) return false; 14004 14005 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14006 if (!FD) return false; 14007 14008 // Don't consider sizes resulting from macro expansions or template argument 14009 // substitution to form C89 tail-padded arrays. 14010 14011 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14012 while (TInfo) { 14013 TypeLoc TL = TInfo->getTypeLoc(); 14014 // Look through typedefs. 14015 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14016 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14017 TInfo = TDL->getTypeSourceInfo(); 14018 continue; 14019 } 14020 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14021 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14022 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14023 return false; 14024 } 14025 break; 14026 } 14027 14028 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14029 if (!RD) return false; 14030 if (RD->isUnion()) return false; 14031 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14032 if (!CRD->isStandardLayout()) return false; 14033 } 14034 14035 // See if this is the last field decl in the record. 14036 const Decl *D = FD; 14037 while ((D = D->getNextDeclInContext())) 14038 if (isa<FieldDecl>(D)) 14039 return false; 14040 return true; 14041 } 14042 14043 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14044 const ArraySubscriptExpr *ASE, 14045 bool AllowOnePastEnd, bool IndexNegated) { 14046 // Already diagnosed by the constant evaluator. 14047 if (isConstantEvaluated()) 14048 return; 14049 14050 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14051 if (IndexExpr->isValueDependent()) 14052 return; 14053 14054 const Type *EffectiveType = 14055 BaseExpr->getType()->getPointeeOrArrayElementType(); 14056 BaseExpr = BaseExpr->IgnoreParenCasts(); 14057 const ConstantArrayType *ArrayTy = 14058 Context.getAsConstantArrayType(BaseExpr->getType()); 14059 14060 if (!ArrayTy) 14061 return; 14062 14063 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14064 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14065 return; 14066 14067 Expr::EvalResult Result; 14068 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14069 return; 14070 14071 llvm::APSInt index = Result.Val.getInt(); 14072 if (IndexNegated) 14073 index = -index; 14074 14075 const NamedDecl *ND = nullptr; 14076 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14077 ND = DRE->getDecl(); 14078 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14079 ND = ME->getMemberDecl(); 14080 14081 if (index.isUnsigned() || !index.isNegative()) { 14082 // It is possible that the type of the base expression after 14083 // IgnoreParenCasts is incomplete, even though the type of the base 14084 // expression before IgnoreParenCasts is complete (see PR39746 for an 14085 // example). In this case we have no information about whether the array 14086 // access exceeds the array bounds. However we can still diagnose an array 14087 // access which precedes the array bounds. 14088 if (BaseType->isIncompleteType()) 14089 return; 14090 14091 llvm::APInt size = ArrayTy->getSize(); 14092 if (!size.isStrictlyPositive()) 14093 return; 14094 14095 if (BaseType != EffectiveType) { 14096 // Make sure we're comparing apples to apples when comparing index to size 14097 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14098 uint64_t array_typesize = Context.getTypeSize(BaseType); 14099 // Handle ptrarith_typesize being zero, such as when casting to void* 14100 if (!ptrarith_typesize) ptrarith_typesize = 1; 14101 if (ptrarith_typesize != array_typesize) { 14102 // There's a cast to a different size type involved 14103 uint64_t ratio = array_typesize / ptrarith_typesize; 14104 // TODO: Be smarter about handling cases where array_typesize is not a 14105 // multiple of ptrarith_typesize 14106 if (ptrarith_typesize * ratio == array_typesize) 14107 size *= llvm::APInt(size.getBitWidth(), ratio); 14108 } 14109 } 14110 14111 if (size.getBitWidth() > index.getBitWidth()) 14112 index = index.zext(size.getBitWidth()); 14113 else if (size.getBitWidth() < index.getBitWidth()) 14114 size = size.zext(index.getBitWidth()); 14115 14116 // For array subscripting the index must be less than size, but for pointer 14117 // arithmetic also allow the index (offset) to be equal to size since 14118 // computing the next address after the end of the array is legal and 14119 // commonly done e.g. in C++ iterators and range-based for loops. 14120 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14121 return; 14122 14123 // Also don't warn for arrays of size 1 which are members of some 14124 // structure. These are often used to approximate flexible arrays in C89 14125 // code. 14126 if (IsTailPaddedMemberArray(*this, size, ND)) 14127 return; 14128 14129 // Suppress the warning if the subscript expression (as identified by the 14130 // ']' location) and the index expression are both from macro expansions 14131 // within a system header. 14132 if (ASE) { 14133 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14134 ASE->getRBracketLoc()); 14135 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14136 SourceLocation IndexLoc = 14137 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14138 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14139 return; 14140 } 14141 } 14142 14143 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14144 if (ASE) 14145 DiagID = diag::warn_array_index_exceeds_bounds; 14146 14147 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14148 PDiag(DiagID) << index.toString(10, true) 14149 << size.toString(10, true) 14150 << (unsigned)size.getLimitedValue(~0U) 14151 << IndexExpr->getSourceRange()); 14152 } else { 14153 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14154 if (!ASE) { 14155 DiagID = diag::warn_ptr_arith_precedes_bounds; 14156 if (index.isNegative()) index = -index; 14157 } 14158 14159 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14160 PDiag(DiagID) << index.toString(10, true) 14161 << IndexExpr->getSourceRange()); 14162 } 14163 14164 if (!ND) { 14165 // Try harder to find a NamedDecl to point at in the note. 14166 while (const ArraySubscriptExpr *ASE = 14167 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14168 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14169 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14170 ND = DRE->getDecl(); 14171 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14172 ND = ME->getMemberDecl(); 14173 } 14174 14175 if (ND) 14176 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14177 PDiag(diag::note_array_declared_here) << ND); 14178 } 14179 14180 void Sema::CheckArrayAccess(const Expr *expr) { 14181 int AllowOnePastEnd = 0; 14182 while (expr) { 14183 expr = expr->IgnoreParenImpCasts(); 14184 switch (expr->getStmtClass()) { 14185 case Stmt::ArraySubscriptExprClass: { 14186 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14187 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14188 AllowOnePastEnd > 0); 14189 expr = ASE->getBase(); 14190 break; 14191 } 14192 case Stmt::MemberExprClass: { 14193 expr = cast<MemberExpr>(expr)->getBase(); 14194 break; 14195 } 14196 case Stmt::OMPArraySectionExprClass: { 14197 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14198 if (ASE->getLowerBound()) 14199 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14200 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14201 return; 14202 } 14203 case Stmt::UnaryOperatorClass: { 14204 // Only unwrap the * and & unary operators 14205 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14206 expr = UO->getSubExpr(); 14207 switch (UO->getOpcode()) { 14208 case UO_AddrOf: 14209 AllowOnePastEnd++; 14210 break; 14211 case UO_Deref: 14212 AllowOnePastEnd--; 14213 break; 14214 default: 14215 return; 14216 } 14217 break; 14218 } 14219 case Stmt::ConditionalOperatorClass: { 14220 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14221 if (const Expr *lhs = cond->getLHS()) 14222 CheckArrayAccess(lhs); 14223 if (const Expr *rhs = cond->getRHS()) 14224 CheckArrayAccess(rhs); 14225 return; 14226 } 14227 case Stmt::CXXOperatorCallExprClass: { 14228 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14229 for (const auto *Arg : OCE->arguments()) 14230 CheckArrayAccess(Arg); 14231 return; 14232 } 14233 default: 14234 return; 14235 } 14236 } 14237 } 14238 14239 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14240 14241 namespace { 14242 14243 struct RetainCycleOwner { 14244 VarDecl *Variable = nullptr; 14245 SourceRange Range; 14246 SourceLocation Loc; 14247 bool Indirect = false; 14248 14249 RetainCycleOwner() = default; 14250 14251 void setLocsFrom(Expr *e) { 14252 Loc = e->getExprLoc(); 14253 Range = e->getSourceRange(); 14254 } 14255 }; 14256 14257 } // namespace 14258 14259 /// Consider whether capturing the given variable can possibly lead to 14260 /// a retain cycle. 14261 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14262 // In ARC, it's captured strongly iff the variable has __strong 14263 // lifetime. In MRR, it's captured strongly if the variable is 14264 // __block and has an appropriate type. 14265 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14266 return false; 14267 14268 owner.Variable = var; 14269 if (ref) 14270 owner.setLocsFrom(ref); 14271 return true; 14272 } 14273 14274 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14275 while (true) { 14276 e = e->IgnoreParens(); 14277 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14278 switch (cast->getCastKind()) { 14279 case CK_BitCast: 14280 case CK_LValueBitCast: 14281 case CK_LValueToRValue: 14282 case CK_ARCReclaimReturnedObject: 14283 e = cast->getSubExpr(); 14284 continue; 14285 14286 default: 14287 return false; 14288 } 14289 } 14290 14291 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14292 ObjCIvarDecl *ivar = ref->getDecl(); 14293 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14294 return false; 14295 14296 // Try to find a retain cycle in the base. 14297 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14298 return false; 14299 14300 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14301 owner.Indirect = true; 14302 return true; 14303 } 14304 14305 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14306 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14307 if (!var) return false; 14308 return considerVariable(var, ref, owner); 14309 } 14310 14311 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14312 if (member->isArrow()) return false; 14313 14314 // Don't count this as an indirect ownership. 14315 e = member->getBase(); 14316 continue; 14317 } 14318 14319 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14320 // Only pay attention to pseudo-objects on property references. 14321 ObjCPropertyRefExpr *pre 14322 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14323 ->IgnoreParens()); 14324 if (!pre) return false; 14325 if (pre->isImplicitProperty()) return false; 14326 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14327 if (!property->isRetaining() && 14328 !(property->getPropertyIvarDecl() && 14329 property->getPropertyIvarDecl()->getType() 14330 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14331 return false; 14332 14333 owner.Indirect = true; 14334 if (pre->isSuperReceiver()) { 14335 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14336 if (!owner.Variable) 14337 return false; 14338 owner.Loc = pre->getLocation(); 14339 owner.Range = pre->getSourceRange(); 14340 return true; 14341 } 14342 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14343 ->getSourceExpr()); 14344 continue; 14345 } 14346 14347 // Array ivars? 14348 14349 return false; 14350 } 14351 } 14352 14353 namespace { 14354 14355 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14356 ASTContext &Context; 14357 VarDecl *Variable; 14358 Expr *Capturer = nullptr; 14359 bool VarWillBeReased = false; 14360 14361 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14362 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14363 Context(Context), Variable(variable) {} 14364 14365 void VisitDeclRefExpr(DeclRefExpr *ref) { 14366 if (ref->getDecl() == Variable && !Capturer) 14367 Capturer = ref; 14368 } 14369 14370 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14371 if (Capturer) return; 14372 Visit(ref->getBase()); 14373 if (Capturer && ref->isFreeIvar()) 14374 Capturer = ref; 14375 } 14376 14377 void VisitBlockExpr(BlockExpr *block) { 14378 // Look inside nested blocks 14379 if (block->getBlockDecl()->capturesVariable(Variable)) 14380 Visit(block->getBlockDecl()->getBody()); 14381 } 14382 14383 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14384 if (Capturer) return; 14385 if (OVE->getSourceExpr()) 14386 Visit(OVE->getSourceExpr()); 14387 } 14388 14389 void VisitBinaryOperator(BinaryOperator *BinOp) { 14390 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14391 return; 14392 Expr *LHS = BinOp->getLHS(); 14393 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14394 if (DRE->getDecl() != Variable) 14395 return; 14396 if (Expr *RHS = BinOp->getRHS()) { 14397 RHS = RHS->IgnoreParenCasts(); 14398 Optional<llvm::APSInt> Value; 14399 VarWillBeReased = 14400 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14401 *Value == 0); 14402 } 14403 } 14404 } 14405 }; 14406 14407 } // namespace 14408 14409 /// Check whether the given argument is a block which captures a 14410 /// variable. 14411 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14412 assert(owner.Variable && owner.Loc.isValid()); 14413 14414 e = e->IgnoreParenCasts(); 14415 14416 // Look through [^{...} copy] and Block_copy(^{...}). 14417 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14418 Selector Cmd = ME->getSelector(); 14419 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14420 e = ME->getInstanceReceiver(); 14421 if (!e) 14422 return nullptr; 14423 e = e->IgnoreParenCasts(); 14424 } 14425 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14426 if (CE->getNumArgs() == 1) { 14427 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14428 if (Fn) { 14429 const IdentifierInfo *FnI = Fn->getIdentifier(); 14430 if (FnI && FnI->isStr("_Block_copy")) { 14431 e = CE->getArg(0)->IgnoreParenCasts(); 14432 } 14433 } 14434 } 14435 } 14436 14437 BlockExpr *block = dyn_cast<BlockExpr>(e); 14438 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14439 return nullptr; 14440 14441 FindCaptureVisitor visitor(S.Context, owner.Variable); 14442 visitor.Visit(block->getBlockDecl()->getBody()); 14443 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14444 } 14445 14446 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14447 RetainCycleOwner &owner) { 14448 assert(capturer); 14449 assert(owner.Variable && owner.Loc.isValid()); 14450 14451 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14452 << owner.Variable << capturer->getSourceRange(); 14453 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14454 << owner.Indirect << owner.Range; 14455 } 14456 14457 /// Check for a keyword selector that starts with the word 'add' or 14458 /// 'set'. 14459 static bool isSetterLikeSelector(Selector sel) { 14460 if (sel.isUnarySelector()) return false; 14461 14462 StringRef str = sel.getNameForSlot(0); 14463 while (!str.empty() && str.front() == '_') str = str.substr(1); 14464 if (str.startswith("set")) 14465 str = str.substr(3); 14466 else if (str.startswith("add")) { 14467 // Specially allow 'addOperationWithBlock:'. 14468 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14469 return false; 14470 str = str.substr(3); 14471 } 14472 else 14473 return false; 14474 14475 if (str.empty()) return true; 14476 return !isLowercase(str.front()); 14477 } 14478 14479 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14480 ObjCMessageExpr *Message) { 14481 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14482 Message->getReceiverInterface(), 14483 NSAPI::ClassId_NSMutableArray); 14484 if (!IsMutableArray) { 14485 return None; 14486 } 14487 14488 Selector Sel = Message->getSelector(); 14489 14490 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14491 S.NSAPIObj->getNSArrayMethodKind(Sel); 14492 if (!MKOpt) { 14493 return None; 14494 } 14495 14496 NSAPI::NSArrayMethodKind MK = *MKOpt; 14497 14498 switch (MK) { 14499 case NSAPI::NSMutableArr_addObject: 14500 case NSAPI::NSMutableArr_insertObjectAtIndex: 14501 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14502 return 0; 14503 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14504 return 1; 14505 14506 default: 14507 return None; 14508 } 14509 14510 return None; 14511 } 14512 14513 static 14514 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14515 ObjCMessageExpr *Message) { 14516 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14517 Message->getReceiverInterface(), 14518 NSAPI::ClassId_NSMutableDictionary); 14519 if (!IsMutableDictionary) { 14520 return None; 14521 } 14522 14523 Selector Sel = Message->getSelector(); 14524 14525 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14526 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14527 if (!MKOpt) { 14528 return None; 14529 } 14530 14531 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14532 14533 switch (MK) { 14534 case NSAPI::NSMutableDict_setObjectForKey: 14535 case NSAPI::NSMutableDict_setValueForKey: 14536 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14537 return 0; 14538 14539 default: 14540 return None; 14541 } 14542 14543 return None; 14544 } 14545 14546 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14547 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14548 Message->getReceiverInterface(), 14549 NSAPI::ClassId_NSMutableSet); 14550 14551 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14552 Message->getReceiverInterface(), 14553 NSAPI::ClassId_NSMutableOrderedSet); 14554 if (!IsMutableSet && !IsMutableOrderedSet) { 14555 return None; 14556 } 14557 14558 Selector Sel = Message->getSelector(); 14559 14560 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14561 if (!MKOpt) { 14562 return None; 14563 } 14564 14565 NSAPI::NSSetMethodKind MK = *MKOpt; 14566 14567 switch (MK) { 14568 case NSAPI::NSMutableSet_addObject: 14569 case NSAPI::NSOrderedSet_setObjectAtIndex: 14570 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14571 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14572 return 0; 14573 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14574 return 1; 14575 } 14576 14577 return None; 14578 } 14579 14580 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14581 if (!Message->isInstanceMessage()) { 14582 return; 14583 } 14584 14585 Optional<int> ArgOpt; 14586 14587 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14588 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14589 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14590 return; 14591 } 14592 14593 int ArgIndex = *ArgOpt; 14594 14595 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14596 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14597 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14598 } 14599 14600 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14601 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14602 if (ArgRE->isObjCSelfExpr()) { 14603 Diag(Message->getSourceRange().getBegin(), 14604 diag::warn_objc_circular_container) 14605 << ArgRE->getDecl() << StringRef("'super'"); 14606 } 14607 } 14608 } else { 14609 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14610 14611 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14612 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14613 } 14614 14615 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14616 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14617 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14618 ValueDecl *Decl = ReceiverRE->getDecl(); 14619 Diag(Message->getSourceRange().getBegin(), 14620 diag::warn_objc_circular_container) 14621 << Decl << Decl; 14622 if (!ArgRE->isObjCSelfExpr()) { 14623 Diag(Decl->getLocation(), 14624 diag::note_objc_circular_container_declared_here) 14625 << Decl; 14626 } 14627 } 14628 } 14629 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14630 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14631 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14632 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14633 Diag(Message->getSourceRange().getBegin(), 14634 diag::warn_objc_circular_container) 14635 << Decl << Decl; 14636 Diag(Decl->getLocation(), 14637 diag::note_objc_circular_container_declared_here) 14638 << Decl; 14639 } 14640 } 14641 } 14642 } 14643 } 14644 14645 /// Check a message send to see if it's likely to cause a retain cycle. 14646 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14647 // Only check instance methods whose selector looks like a setter. 14648 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14649 return; 14650 14651 // Try to find a variable that the receiver is strongly owned by. 14652 RetainCycleOwner owner; 14653 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14654 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14655 return; 14656 } else { 14657 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14658 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14659 owner.Loc = msg->getSuperLoc(); 14660 owner.Range = msg->getSuperLoc(); 14661 } 14662 14663 // Check whether the receiver is captured by any of the arguments. 14664 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14665 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14666 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14667 // noescape blocks should not be retained by the method. 14668 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14669 continue; 14670 return diagnoseRetainCycle(*this, capturer, owner); 14671 } 14672 } 14673 } 14674 14675 /// Check a property assign to see if it's likely to cause a retain cycle. 14676 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14677 RetainCycleOwner owner; 14678 if (!findRetainCycleOwner(*this, receiver, owner)) 14679 return; 14680 14681 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14682 diagnoseRetainCycle(*this, capturer, owner); 14683 } 14684 14685 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14686 RetainCycleOwner Owner; 14687 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14688 return; 14689 14690 // Because we don't have an expression for the variable, we have to set the 14691 // location explicitly here. 14692 Owner.Loc = Var->getLocation(); 14693 Owner.Range = Var->getSourceRange(); 14694 14695 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14696 diagnoseRetainCycle(*this, Capturer, Owner); 14697 } 14698 14699 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14700 Expr *RHS, bool isProperty) { 14701 // Check if RHS is an Objective-C object literal, which also can get 14702 // immediately zapped in a weak reference. Note that we explicitly 14703 // allow ObjCStringLiterals, since those are designed to never really die. 14704 RHS = RHS->IgnoreParenImpCasts(); 14705 14706 // This enum needs to match with the 'select' in 14707 // warn_objc_arc_literal_assign (off-by-1). 14708 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14709 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14710 return false; 14711 14712 S.Diag(Loc, diag::warn_arc_literal_assign) 14713 << (unsigned) Kind 14714 << (isProperty ? 0 : 1) 14715 << RHS->getSourceRange(); 14716 14717 return true; 14718 } 14719 14720 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14721 Qualifiers::ObjCLifetime LT, 14722 Expr *RHS, bool isProperty) { 14723 // Strip off any implicit cast added to get to the one ARC-specific. 14724 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14725 if (cast->getCastKind() == CK_ARCConsumeObject) { 14726 S.Diag(Loc, diag::warn_arc_retained_assign) 14727 << (LT == Qualifiers::OCL_ExplicitNone) 14728 << (isProperty ? 0 : 1) 14729 << RHS->getSourceRange(); 14730 return true; 14731 } 14732 RHS = cast->getSubExpr(); 14733 } 14734 14735 if (LT == Qualifiers::OCL_Weak && 14736 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14737 return true; 14738 14739 return false; 14740 } 14741 14742 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14743 QualType LHS, Expr *RHS) { 14744 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14745 14746 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14747 return false; 14748 14749 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14750 return true; 14751 14752 return false; 14753 } 14754 14755 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14756 Expr *LHS, Expr *RHS) { 14757 QualType LHSType; 14758 // PropertyRef on LHS type need be directly obtained from 14759 // its declaration as it has a PseudoType. 14760 ObjCPropertyRefExpr *PRE 14761 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14762 if (PRE && !PRE->isImplicitProperty()) { 14763 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14764 if (PD) 14765 LHSType = PD->getType(); 14766 } 14767 14768 if (LHSType.isNull()) 14769 LHSType = LHS->getType(); 14770 14771 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14772 14773 if (LT == Qualifiers::OCL_Weak) { 14774 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14775 getCurFunction()->markSafeWeakUse(LHS); 14776 } 14777 14778 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14779 return; 14780 14781 // FIXME. Check for other life times. 14782 if (LT != Qualifiers::OCL_None) 14783 return; 14784 14785 if (PRE) { 14786 if (PRE->isImplicitProperty()) 14787 return; 14788 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14789 if (!PD) 14790 return; 14791 14792 unsigned Attributes = PD->getPropertyAttributes(); 14793 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14794 // when 'assign' attribute was not explicitly specified 14795 // by user, ignore it and rely on property type itself 14796 // for lifetime info. 14797 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14798 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14799 LHSType->isObjCRetainableType()) 14800 return; 14801 14802 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14803 if (cast->getCastKind() == CK_ARCConsumeObject) { 14804 Diag(Loc, diag::warn_arc_retained_property_assign) 14805 << RHS->getSourceRange(); 14806 return; 14807 } 14808 RHS = cast->getSubExpr(); 14809 } 14810 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14811 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14812 return; 14813 } 14814 } 14815 } 14816 14817 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14818 14819 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14820 SourceLocation StmtLoc, 14821 const NullStmt *Body) { 14822 // Do not warn if the body is a macro that expands to nothing, e.g: 14823 // 14824 // #define CALL(x) 14825 // if (condition) 14826 // CALL(0); 14827 if (Body->hasLeadingEmptyMacro()) 14828 return false; 14829 14830 // Get line numbers of statement and body. 14831 bool StmtLineInvalid; 14832 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14833 &StmtLineInvalid); 14834 if (StmtLineInvalid) 14835 return false; 14836 14837 bool BodyLineInvalid; 14838 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14839 &BodyLineInvalid); 14840 if (BodyLineInvalid) 14841 return false; 14842 14843 // Warn if null statement and body are on the same line. 14844 if (StmtLine != BodyLine) 14845 return false; 14846 14847 return true; 14848 } 14849 14850 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14851 const Stmt *Body, 14852 unsigned DiagID) { 14853 // Since this is a syntactic check, don't emit diagnostic for template 14854 // instantiations, this just adds noise. 14855 if (CurrentInstantiationScope) 14856 return; 14857 14858 // The body should be a null statement. 14859 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14860 if (!NBody) 14861 return; 14862 14863 // Do the usual checks. 14864 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14865 return; 14866 14867 Diag(NBody->getSemiLoc(), DiagID); 14868 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14869 } 14870 14871 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14872 const Stmt *PossibleBody) { 14873 assert(!CurrentInstantiationScope); // Ensured by caller 14874 14875 SourceLocation StmtLoc; 14876 const Stmt *Body; 14877 unsigned DiagID; 14878 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14879 StmtLoc = FS->getRParenLoc(); 14880 Body = FS->getBody(); 14881 DiagID = diag::warn_empty_for_body; 14882 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14883 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14884 Body = WS->getBody(); 14885 DiagID = diag::warn_empty_while_body; 14886 } else 14887 return; // Neither `for' nor `while'. 14888 14889 // The body should be a null statement. 14890 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14891 if (!NBody) 14892 return; 14893 14894 // Skip expensive checks if diagnostic is disabled. 14895 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14896 return; 14897 14898 // Do the usual checks. 14899 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14900 return; 14901 14902 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14903 // noise level low, emit diagnostics only if for/while is followed by a 14904 // CompoundStmt, e.g.: 14905 // for (int i = 0; i < n; i++); 14906 // { 14907 // a(i); 14908 // } 14909 // or if for/while is followed by a statement with more indentation 14910 // than for/while itself: 14911 // for (int i = 0; i < n; i++); 14912 // a(i); 14913 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14914 if (!ProbableTypo) { 14915 bool BodyColInvalid; 14916 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14917 PossibleBody->getBeginLoc(), &BodyColInvalid); 14918 if (BodyColInvalid) 14919 return; 14920 14921 bool StmtColInvalid; 14922 unsigned StmtCol = 14923 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14924 if (StmtColInvalid) 14925 return; 14926 14927 if (BodyCol > StmtCol) 14928 ProbableTypo = true; 14929 } 14930 14931 if (ProbableTypo) { 14932 Diag(NBody->getSemiLoc(), DiagID); 14933 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14934 } 14935 } 14936 14937 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14938 14939 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14940 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14941 SourceLocation OpLoc) { 14942 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14943 return; 14944 14945 if (inTemplateInstantiation()) 14946 return; 14947 14948 // Strip parens and casts away. 14949 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14950 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14951 14952 // Check for a call expression 14953 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14954 if (!CE || CE->getNumArgs() != 1) 14955 return; 14956 14957 // Check for a call to std::move 14958 if (!CE->isCallToStdMove()) 14959 return; 14960 14961 // Get argument from std::move 14962 RHSExpr = CE->getArg(0); 14963 14964 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14965 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14966 14967 // Two DeclRefExpr's, check that the decls are the same. 14968 if (LHSDeclRef && RHSDeclRef) { 14969 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14970 return; 14971 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14972 RHSDeclRef->getDecl()->getCanonicalDecl()) 14973 return; 14974 14975 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14976 << LHSExpr->getSourceRange() 14977 << RHSExpr->getSourceRange(); 14978 return; 14979 } 14980 14981 // Member variables require a different approach to check for self moves. 14982 // MemberExpr's are the same if every nested MemberExpr refers to the same 14983 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14984 // the base Expr's are CXXThisExpr's. 14985 const Expr *LHSBase = LHSExpr; 14986 const Expr *RHSBase = RHSExpr; 14987 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14988 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14989 if (!LHSME || !RHSME) 14990 return; 14991 14992 while (LHSME && RHSME) { 14993 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14994 RHSME->getMemberDecl()->getCanonicalDecl()) 14995 return; 14996 14997 LHSBase = LHSME->getBase(); 14998 RHSBase = RHSME->getBase(); 14999 LHSME = dyn_cast<MemberExpr>(LHSBase); 15000 RHSME = dyn_cast<MemberExpr>(RHSBase); 15001 } 15002 15003 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15004 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15005 if (LHSDeclRef && RHSDeclRef) { 15006 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15007 return; 15008 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15009 RHSDeclRef->getDecl()->getCanonicalDecl()) 15010 return; 15011 15012 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15013 << LHSExpr->getSourceRange() 15014 << RHSExpr->getSourceRange(); 15015 return; 15016 } 15017 15018 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15019 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15020 << LHSExpr->getSourceRange() 15021 << RHSExpr->getSourceRange(); 15022 } 15023 15024 //===--- Layout compatibility ----------------------------------------------// 15025 15026 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15027 15028 /// Check if two enumeration types are layout-compatible. 15029 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15030 // C++11 [dcl.enum] p8: 15031 // Two enumeration types are layout-compatible if they have the same 15032 // underlying type. 15033 return ED1->isComplete() && ED2->isComplete() && 15034 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15035 } 15036 15037 /// Check if two fields are layout-compatible. 15038 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15039 FieldDecl *Field2) { 15040 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15041 return false; 15042 15043 if (Field1->isBitField() != Field2->isBitField()) 15044 return false; 15045 15046 if (Field1->isBitField()) { 15047 // Make sure that the bit-fields are the same length. 15048 unsigned Bits1 = Field1->getBitWidthValue(C); 15049 unsigned Bits2 = Field2->getBitWidthValue(C); 15050 15051 if (Bits1 != Bits2) 15052 return false; 15053 } 15054 15055 return true; 15056 } 15057 15058 /// Check if two standard-layout structs are layout-compatible. 15059 /// (C++11 [class.mem] p17) 15060 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15061 RecordDecl *RD2) { 15062 // If both records are C++ classes, check that base classes match. 15063 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15064 // If one of records is a CXXRecordDecl we are in C++ mode, 15065 // thus the other one is a CXXRecordDecl, too. 15066 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15067 // Check number of base classes. 15068 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15069 return false; 15070 15071 // Check the base classes. 15072 for (CXXRecordDecl::base_class_const_iterator 15073 Base1 = D1CXX->bases_begin(), 15074 BaseEnd1 = D1CXX->bases_end(), 15075 Base2 = D2CXX->bases_begin(); 15076 Base1 != BaseEnd1; 15077 ++Base1, ++Base2) { 15078 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15079 return false; 15080 } 15081 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15082 // If only RD2 is a C++ class, it should have zero base classes. 15083 if (D2CXX->getNumBases() > 0) 15084 return false; 15085 } 15086 15087 // Check the fields. 15088 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15089 Field2End = RD2->field_end(), 15090 Field1 = RD1->field_begin(), 15091 Field1End = RD1->field_end(); 15092 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15093 if (!isLayoutCompatible(C, *Field1, *Field2)) 15094 return false; 15095 } 15096 if (Field1 != Field1End || Field2 != Field2End) 15097 return false; 15098 15099 return true; 15100 } 15101 15102 /// Check if two standard-layout unions are layout-compatible. 15103 /// (C++11 [class.mem] p18) 15104 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15105 RecordDecl *RD2) { 15106 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15107 for (auto *Field2 : RD2->fields()) 15108 UnmatchedFields.insert(Field2); 15109 15110 for (auto *Field1 : RD1->fields()) { 15111 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15112 I = UnmatchedFields.begin(), 15113 E = UnmatchedFields.end(); 15114 15115 for ( ; I != E; ++I) { 15116 if (isLayoutCompatible(C, Field1, *I)) { 15117 bool Result = UnmatchedFields.erase(*I); 15118 (void) Result; 15119 assert(Result); 15120 break; 15121 } 15122 } 15123 if (I == E) 15124 return false; 15125 } 15126 15127 return UnmatchedFields.empty(); 15128 } 15129 15130 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15131 RecordDecl *RD2) { 15132 if (RD1->isUnion() != RD2->isUnion()) 15133 return false; 15134 15135 if (RD1->isUnion()) 15136 return isLayoutCompatibleUnion(C, RD1, RD2); 15137 else 15138 return isLayoutCompatibleStruct(C, RD1, RD2); 15139 } 15140 15141 /// Check if two types are layout-compatible in C++11 sense. 15142 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15143 if (T1.isNull() || T2.isNull()) 15144 return false; 15145 15146 // C++11 [basic.types] p11: 15147 // If two types T1 and T2 are the same type, then T1 and T2 are 15148 // layout-compatible types. 15149 if (C.hasSameType(T1, T2)) 15150 return true; 15151 15152 T1 = T1.getCanonicalType().getUnqualifiedType(); 15153 T2 = T2.getCanonicalType().getUnqualifiedType(); 15154 15155 const Type::TypeClass TC1 = T1->getTypeClass(); 15156 const Type::TypeClass TC2 = T2->getTypeClass(); 15157 15158 if (TC1 != TC2) 15159 return false; 15160 15161 if (TC1 == Type::Enum) { 15162 return isLayoutCompatible(C, 15163 cast<EnumType>(T1)->getDecl(), 15164 cast<EnumType>(T2)->getDecl()); 15165 } else if (TC1 == Type::Record) { 15166 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15167 return false; 15168 15169 return isLayoutCompatible(C, 15170 cast<RecordType>(T1)->getDecl(), 15171 cast<RecordType>(T2)->getDecl()); 15172 } 15173 15174 return false; 15175 } 15176 15177 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15178 15179 /// Given a type tag expression find the type tag itself. 15180 /// 15181 /// \param TypeExpr Type tag expression, as it appears in user's code. 15182 /// 15183 /// \param VD Declaration of an identifier that appears in a type tag. 15184 /// 15185 /// \param MagicValue Type tag magic value. 15186 /// 15187 /// \param isConstantEvaluated wether the evalaution should be performed in 15188 15189 /// constant context. 15190 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15191 const ValueDecl **VD, uint64_t *MagicValue, 15192 bool isConstantEvaluated) { 15193 while(true) { 15194 if (!TypeExpr) 15195 return false; 15196 15197 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15198 15199 switch (TypeExpr->getStmtClass()) { 15200 case Stmt::UnaryOperatorClass: { 15201 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15202 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15203 TypeExpr = UO->getSubExpr(); 15204 continue; 15205 } 15206 return false; 15207 } 15208 15209 case Stmt::DeclRefExprClass: { 15210 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15211 *VD = DRE->getDecl(); 15212 return true; 15213 } 15214 15215 case Stmt::IntegerLiteralClass: { 15216 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15217 llvm::APInt MagicValueAPInt = IL->getValue(); 15218 if (MagicValueAPInt.getActiveBits() <= 64) { 15219 *MagicValue = MagicValueAPInt.getZExtValue(); 15220 return true; 15221 } else 15222 return false; 15223 } 15224 15225 case Stmt::BinaryConditionalOperatorClass: 15226 case Stmt::ConditionalOperatorClass: { 15227 const AbstractConditionalOperator *ACO = 15228 cast<AbstractConditionalOperator>(TypeExpr); 15229 bool Result; 15230 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15231 isConstantEvaluated)) { 15232 if (Result) 15233 TypeExpr = ACO->getTrueExpr(); 15234 else 15235 TypeExpr = ACO->getFalseExpr(); 15236 continue; 15237 } 15238 return false; 15239 } 15240 15241 case Stmt::BinaryOperatorClass: { 15242 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15243 if (BO->getOpcode() == BO_Comma) { 15244 TypeExpr = BO->getRHS(); 15245 continue; 15246 } 15247 return false; 15248 } 15249 15250 default: 15251 return false; 15252 } 15253 } 15254 } 15255 15256 /// Retrieve the C type corresponding to type tag TypeExpr. 15257 /// 15258 /// \param TypeExpr Expression that specifies a type tag. 15259 /// 15260 /// \param MagicValues Registered magic values. 15261 /// 15262 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15263 /// kind. 15264 /// 15265 /// \param TypeInfo Information about the corresponding C type. 15266 /// 15267 /// \param isConstantEvaluated wether the evalaution should be performed in 15268 /// constant context. 15269 /// 15270 /// \returns true if the corresponding C type was found. 15271 static bool GetMatchingCType( 15272 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15273 const ASTContext &Ctx, 15274 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15275 *MagicValues, 15276 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15277 bool isConstantEvaluated) { 15278 FoundWrongKind = false; 15279 15280 // Variable declaration that has type_tag_for_datatype attribute. 15281 const ValueDecl *VD = nullptr; 15282 15283 uint64_t MagicValue; 15284 15285 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15286 return false; 15287 15288 if (VD) { 15289 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15290 if (I->getArgumentKind() != ArgumentKind) { 15291 FoundWrongKind = true; 15292 return false; 15293 } 15294 TypeInfo.Type = I->getMatchingCType(); 15295 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15296 TypeInfo.MustBeNull = I->getMustBeNull(); 15297 return true; 15298 } 15299 return false; 15300 } 15301 15302 if (!MagicValues) 15303 return false; 15304 15305 llvm::DenseMap<Sema::TypeTagMagicValue, 15306 Sema::TypeTagData>::const_iterator I = 15307 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15308 if (I == MagicValues->end()) 15309 return false; 15310 15311 TypeInfo = I->second; 15312 return true; 15313 } 15314 15315 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15316 uint64_t MagicValue, QualType Type, 15317 bool LayoutCompatible, 15318 bool MustBeNull) { 15319 if (!TypeTagForDatatypeMagicValues) 15320 TypeTagForDatatypeMagicValues.reset( 15321 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15322 15323 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15324 (*TypeTagForDatatypeMagicValues)[Magic] = 15325 TypeTagData(Type, LayoutCompatible, MustBeNull); 15326 } 15327 15328 static bool IsSameCharType(QualType T1, QualType T2) { 15329 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15330 if (!BT1) 15331 return false; 15332 15333 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15334 if (!BT2) 15335 return false; 15336 15337 BuiltinType::Kind T1Kind = BT1->getKind(); 15338 BuiltinType::Kind T2Kind = BT2->getKind(); 15339 15340 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15341 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15342 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15343 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15344 } 15345 15346 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15347 const ArrayRef<const Expr *> ExprArgs, 15348 SourceLocation CallSiteLoc) { 15349 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15350 bool IsPointerAttr = Attr->getIsPointer(); 15351 15352 // Retrieve the argument representing the 'type_tag'. 15353 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15354 if (TypeTagIdxAST >= ExprArgs.size()) { 15355 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15356 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15357 return; 15358 } 15359 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15360 bool FoundWrongKind; 15361 TypeTagData TypeInfo; 15362 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15363 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15364 TypeInfo, isConstantEvaluated())) { 15365 if (FoundWrongKind) 15366 Diag(TypeTagExpr->getExprLoc(), 15367 diag::warn_type_tag_for_datatype_wrong_kind) 15368 << TypeTagExpr->getSourceRange(); 15369 return; 15370 } 15371 15372 // Retrieve the argument representing the 'arg_idx'. 15373 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15374 if (ArgumentIdxAST >= ExprArgs.size()) { 15375 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15376 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15377 return; 15378 } 15379 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15380 if (IsPointerAttr) { 15381 // Skip implicit cast of pointer to `void *' (as a function argument). 15382 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15383 if (ICE->getType()->isVoidPointerType() && 15384 ICE->getCastKind() == CK_BitCast) 15385 ArgumentExpr = ICE->getSubExpr(); 15386 } 15387 QualType ArgumentType = ArgumentExpr->getType(); 15388 15389 // Passing a `void*' pointer shouldn't trigger a warning. 15390 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15391 return; 15392 15393 if (TypeInfo.MustBeNull) { 15394 // Type tag with matching void type requires a null pointer. 15395 if (!ArgumentExpr->isNullPointerConstant(Context, 15396 Expr::NPC_ValueDependentIsNotNull)) { 15397 Diag(ArgumentExpr->getExprLoc(), 15398 diag::warn_type_safety_null_pointer_required) 15399 << ArgumentKind->getName() 15400 << ArgumentExpr->getSourceRange() 15401 << TypeTagExpr->getSourceRange(); 15402 } 15403 return; 15404 } 15405 15406 QualType RequiredType = TypeInfo.Type; 15407 if (IsPointerAttr) 15408 RequiredType = Context.getPointerType(RequiredType); 15409 15410 bool mismatch = false; 15411 if (!TypeInfo.LayoutCompatible) { 15412 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15413 15414 // C++11 [basic.fundamental] p1: 15415 // Plain char, signed char, and unsigned char are three distinct types. 15416 // 15417 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15418 // char' depending on the current char signedness mode. 15419 if (mismatch) 15420 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15421 RequiredType->getPointeeType())) || 15422 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15423 mismatch = false; 15424 } else 15425 if (IsPointerAttr) 15426 mismatch = !isLayoutCompatible(Context, 15427 ArgumentType->getPointeeType(), 15428 RequiredType->getPointeeType()); 15429 else 15430 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15431 15432 if (mismatch) 15433 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15434 << ArgumentType << ArgumentKind 15435 << TypeInfo.LayoutCompatible << RequiredType 15436 << ArgumentExpr->getSourceRange() 15437 << TypeTagExpr->getSourceRange(); 15438 } 15439 15440 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15441 CharUnits Alignment) { 15442 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15443 } 15444 15445 void Sema::DiagnoseMisalignedMembers() { 15446 for (MisalignedMember &m : MisalignedMembers) { 15447 const NamedDecl *ND = m.RD; 15448 if (ND->getName().empty()) { 15449 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15450 ND = TD; 15451 } 15452 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15453 << m.MD << ND << m.E->getSourceRange(); 15454 } 15455 MisalignedMembers.clear(); 15456 } 15457 15458 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15459 E = E->IgnoreParens(); 15460 if (!T->isPointerType() && !T->isIntegerType()) 15461 return; 15462 if (isa<UnaryOperator>(E) && 15463 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15464 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15465 if (isa<MemberExpr>(Op)) { 15466 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15467 if (MA != MisalignedMembers.end() && 15468 (T->isIntegerType() || 15469 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15470 Context.getTypeAlignInChars( 15471 T->getPointeeType()) <= MA->Alignment)))) 15472 MisalignedMembers.erase(MA); 15473 } 15474 } 15475 } 15476 15477 void Sema::RefersToMemberWithReducedAlignment( 15478 Expr *E, 15479 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15480 Action) { 15481 const auto *ME = dyn_cast<MemberExpr>(E); 15482 if (!ME) 15483 return; 15484 15485 // No need to check expressions with an __unaligned-qualified type. 15486 if (E->getType().getQualifiers().hasUnaligned()) 15487 return; 15488 15489 // For a chain of MemberExpr like "a.b.c.d" this list 15490 // will keep FieldDecl's like [d, c, b]. 15491 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15492 const MemberExpr *TopME = nullptr; 15493 bool AnyIsPacked = false; 15494 do { 15495 QualType BaseType = ME->getBase()->getType(); 15496 if (BaseType->isDependentType()) 15497 return; 15498 if (ME->isArrow()) 15499 BaseType = BaseType->getPointeeType(); 15500 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15501 if (RD->isInvalidDecl()) 15502 return; 15503 15504 ValueDecl *MD = ME->getMemberDecl(); 15505 auto *FD = dyn_cast<FieldDecl>(MD); 15506 // We do not care about non-data members. 15507 if (!FD || FD->isInvalidDecl()) 15508 return; 15509 15510 AnyIsPacked = 15511 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15512 ReverseMemberChain.push_back(FD); 15513 15514 TopME = ME; 15515 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15516 } while (ME); 15517 assert(TopME && "We did not compute a topmost MemberExpr!"); 15518 15519 // Not the scope of this diagnostic. 15520 if (!AnyIsPacked) 15521 return; 15522 15523 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15524 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15525 // TODO: The innermost base of the member expression may be too complicated. 15526 // For now, just disregard these cases. This is left for future 15527 // improvement. 15528 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15529 return; 15530 15531 // Alignment expected by the whole expression. 15532 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15533 15534 // No need to do anything else with this case. 15535 if (ExpectedAlignment.isOne()) 15536 return; 15537 15538 // Synthesize offset of the whole access. 15539 CharUnits Offset; 15540 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15541 I++) { 15542 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15543 } 15544 15545 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15546 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15547 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15548 15549 // The base expression of the innermost MemberExpr may give 15550 // stronger guarantees than the class containing the member. 15551 if (DRE && !TopME->isArrow()) { 15552 const ValueDecl *VD = DRE->getDecl(); 15553 if (!VD->getType()->isReferenceType()) 15554 CompleteObjectAlignment = 15555 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15556 } 15557 15558 // Check if the synthesized offset fulfills the alignment. 15559 if (Offset % ExpectedAlignment != 0 || 15560 // It may fulfill the offset it but the effective alignment may still be 15561 // lower than the expected expression alignment. 15562 CompleteObjectAlignment < ExpectedAlignment) { 15563 // If this happens, we want to determine a sensible culprit of this. 15564 // Intuitively, watching the chain of member expressions from right to 15565 // left, we start with the required alignment (as required by the field 15566 // type) but some packed attribute in that chain has reduced the alignment. 15567 // It may happen that another packed structure increases it again. But if 15568 // we are here such increase has not been enough. So pointing the first 15569 // FieldDecl that either is packed or else its RecordDecl is, 15570 // seems reasonable. 15571 FieldDecl *FD = nullptr; 15572 CharUnits Alignment; 15573 for (FieldDecl *FDI : ReverseMemberChain) { 15574 if (FDI->hasAttr<PackedAttr>() || 15575 FDI->getParent()->hasAttr<PackedAttr>()) { 15576 FD = FDI; 15577 Alignment = std::min( 15578 Context.getTypeAlignInChars(FD->getType()), 15579 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15580 break; 15581 } 15582 } 15583 assert(FD && "We did not find a packed FieldDecl!"); 15584 Action(E, FD->getParent(), FD, Alignment); 15585 } 15586 } 15587 15588 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15589 using namespace std::placeholders; 15590 15591 RefersToMemberWithReducedAlignment( 15592 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15593 _2, _3, _4)); 15594 } 15595 15596 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15597 ExprResult CallResult) { 15598 if (checkArgCount(*this, TheCall, 1)) 15599 return ExprError(); 15600 15601 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15602 if (MatrixArg.isInvalid()) 15603 return MatrixArg; 15604 Expr *Matrix = MatrixArg.get(); 15605 15606 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15607 if (!MType) { 15608 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15609 return ExprError(); 15610 } 15611 15612 // Create returned matrix type by swapping rows and columns of the argument 15613 // matrix type. 15614 QualType ResultType = Context.getConstantMatrixType( 15615 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15616 15617 // Change the return type to the type of the returned matrix. 15618 TheCall->setType(ResultType); 15619 15620 // Update call argument to use the possibly converted matrix argument. 15621 TheCall->setArg(0, Matrix); 15622 return CallResult; 15623 } 15624 15625 // Get and verify the matrix dimensions. 15626 static llvm::Optional<unsigned> 15627 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15628 SourceLocation ErrorPos; 15629 Optional<llvm::APSInt> Value = 15630 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15631 if (!Value) { 15632 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15633 << Name; 15634 return {}; 15635 } 15636 uint64_t Dim = Value->getZExtValue(); 15637 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15638 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15639 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15640 return {}; 15641 } 15642 return Dim; 15643 } 15644 15645 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15646 ExprResult CallResult) { 15647 if (!getLangOpts().MatrixTypes) { 15648 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15649 return ExprError(); 15650 } 15651 15652 if (checkArgCount(*this, TheCall, 4)) 15653 return ExprError(); 15654 15655 unsigned PtrArgIdx = 0; 15656 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15657 Expr *RowsExpr = TheCall->getArg(1); 15658 Expr *ColumnsExpr = TheCall->getArg(2); 15659 Expr *StrideExpr = TheCall->getArg(3); 15660 15661 bool ArgError = false; 15662 15663 // Check pointer argument. 15664 { 15665 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15666 if (PtrConv.isInvalid()) 15667 return PtrConv; 15668 PtrExpr = PtrConv.get(); 15669 TheCall->setArg(0, PtrExpr); 15670 if (PtrExpr->isTypeDependent()) { 15671 TheCall->setType(Context.DependentTy); 15672 return TheCall; 15673 } 15674 } 15675 15676 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15677 QualType ElementTy; 15678 if (!PtrTy) { 15679 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15680 << PtrArgIdx + 1; 15681 ArgError = true; 15682 } else { 15683 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15684 15685 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15686 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15687 << PtrArgIdx + 1; 15688 ArgError = true; 15689 } 15690 } 15691 15692 // Apply default Lvalue conversions and convert the expression to size_t. 15693 auto ApplyArgumentConversions = [this](Expr *E) { 15694 ExprResult Conv = DefaultLvalueConversion(E); 15695 if (Conv.isInvalid()) 15696 return Conv; 15697 15698 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15699 }; 15700 15701 // Apply conversion to row and column expressions. 15702 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15703 if (!RowsConv.isInvalid()) { 15704 RowsExpr = RowsConv.get(); 15705 TheCall->setArg(1, RowsExpr); 15706 } else 15707 RowsExpr = nullptr; 15708 15709 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15710 if (!ColumnsConv.isInvalid()) { 15711 ColumnsExpr = ColumnsConv.get(); 15712 TheCall->setArg(2, ColumnsExpr); 15713 } else 15714 ColumnsExpr = nullptr; 15715 15716 // If any any part of the result matrix type is still pending, just use 15717 // Context.DependentTy, until all parts are resolved. 15718 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15719 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15720 TheCall->setType(Context.DependentTy); 15721 return CallResult; 15722 } 15723 15724 // Check row and column dimenions. 15725 llvm::Optional<unsigned> MaybeRows; 15726 if (RowsExpr) 15727 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15728 15729 llvm::Optional<unsigned> MaybeColumns; 15730 if (ColumnsExpr) 15731 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15732 15733 // Check stride argument. 15734 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15735 if (StrideConv.isInvalid()) 15736 return ExprError(); 15737 StrideExpr = StrideConv.get(); 15738 TheCall->setArg(3, StrideExpr); 15739 15740 if (MaybeRows) { 15741 if (Optional<llvm::APSInt> Value = 15742 StrideExpr->getIntegerConstantExpr(Context)) { 15743 uint64_t Stride = Value->getZExtValue(); 15744 if (Stride < *MaybeRows) { 15745 Diag(StrideExpr->getBeginLoc(), 15746 diag::err_builtin_matrix_stride_too_small); 15747 ArgError = true; 15748 } 15749 } 15750 } 15751 15752 if (ArgError || !MaybeRows || !MaybeColumns) 15753 return ExprError(); 15754 15755 TheCall->setType( 15756 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15757 return CallResult; 15758 } 15759 15760 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15761 ExprResult CallResult) { 15762 if (checkArgCount(*this, TheCall, 3)) 15763 return ExprError(); 15764 15765 unsigned PtrArgIdx = 1; 15766 Expr *MatrixExpr = TheCall->getArg(0); 15767 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15768 Expr *StrideExpr = TheCall->getArg(2); 15769 15770 bool ArgError = false; 15771 15772 { 15773 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15774 if (MatrixConv.isInvalid()) 15775 return MatrixConv; 15776 MatrixExpr = MatrixConv.get(); 15777 TheCall->setArg(0, MatrixExpr); 15778 } 15779 if (MatrixExpr->isTypeDependent()) { 15780 TheCall->setType(Context.DependentTy); 15781 return TheCall; 15782 } 15783 15784 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15785 if (!MatrixTy) { 15786 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15787 ArgError = true; 15788 } 15789 15790 { 15791 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15792 if (PtrConv.isInvalid()) 15793 return PtrConv; 15794 PtrExpr = PtrConv.get(); 15795 TheCall->setArg(1, PtrExpr); 15796 if (PtrExpr->isTypeDependent()) { 15797 TheCall->setType(Context.DependentTy); 15798 return TheCall; 15799 } 15800 } 15801 15802 // Check pointer argument. 15803 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15804 if (!PtrTy) { 15805 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15806 << PtrArgIdx + 1; 15807 ArgError = true; 15808 } else { 15809 QualType ElementTy = PtrTy->getPointeeType(); 15810 if (ElementTy.isConstQualified()) { 15811 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15812 ArgError = true; 15813 } 15814 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15815 if (MatrixTy && 15816 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15817 Diag(PtrExpr->getBeginLoc(), 15818 diag::err_builtin_matrix_pointer_arg_mismatch) 15819 << ElementTy << MatrixTy->getElementType(); 15820 ArgError = true; 15821 } 15822 } 15823 15824 // Apply default Lvalue conversions and convert the stride expression to 15825 // size_t. 15826 { 15827 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15828 if (StrideConv.isInvalid()) 15829 return StrideConv; 15830 15831 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15832 if (StrideConv.isInvalid()) 15833 return StrideConv; 15834 StrideExpr = StrideConv.get(); 15835 TheCall->setArg(2, StrideExpr); 15836 } 15837 15838 // Check stride argument. 15839 if (MatrixTy) { 15840 if (Optional<llvm::APSInt> Value = 15841 StrideExpr->getIntegerConstantExpr(Context)) { 15842 uint64_t Stride = Value->getZExtValue(); 15843 if (Stride < MatrixTy->getNumRows()) { 15844 Diag(StrideExpr->getBeginLoc(), 15845 diag::err_builtin_matrix_stride_too_small); 15846 ArgError = true; 15847 } 15848 } 15849 } 15850 15851 if (ArgError) 15852 return ExprError(); 15853 15854 return CallResult; 15855 } 15856