1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 594 isConstantEvaluated()) 595 return; 596 597 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 598 if (!BuiltinID) 599 return; 600 601 const TargetInfo &TI = getASTContext().getTargetInfo(); 602 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 603 604 auto ComputeExplicitObjectSizeArgument = 605 [&](unsigned Index) -> Optional<llvm::APSInt> { 606 Expr::EvalResult Result; 607 Expr *SizeArg = TheCall->getArg(Index); 608 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 609 return llvm::None; 610 return Result.Val.getInt(); 611 }; 612 613 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 614 // If the parameter has a pass_object_size attribute, then we should use its 615 // (potentially) more strict checking mode. Otherwise, conservatively assume 616 // type 0. 617 int BOSType = 0; 618 if (const auto *POS = 619 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 620 BOSType = POS->getType(); 621 622 const Expr *ObjArg = TheCall->getArg(Index); 623 uint64_t Result; 624 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 625 return llvm::None; 626 627 // Get the object size in the target's size_t width. 628 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 629 }; 630 631 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 632 Expr *ObjArg = TheCall->getArg(Index); 633 uint64_t Result; 634 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 635 return llvm::None; 636 // Add 1 for null byte. 637 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 638 }; 639 640 Optional<llvm::APSInt> SourceSize; 641 Optional<llvm::APSInt> DestinationSize; 642 unsigned DiagID = 0; 643 bool IsChkVariant = false; 644 645 switch (BuiltinID) { 646 default: 647 return; 648 case Builtin::BI__builtin_strcpy: 649 case Builtin::BIstrcpy: { 650 DiagID = diag::warn_fortify_strlen_overflow; 651 SourceSize = ComputeStrLenArgument(1); 652 DestinationSize = ComputeSizeArgument(0); 653 break; 654 } 655 656 case Builtin::BI__builtin___strcpy_chk: { 657 DiagID = diag::warn_fortify_strlen_overflow; 658 SourceSize = ComputeStrLenArgument(1); 659 DestinationSize = ComputeExplicitObjectSizeArgument(2); 660 IsChkVariant = true; 661 break; 662 } 663 664 case Builtin::BIsprintf: 665 case Builtin::BI__builtin___sprintf_chk: { 666 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 667 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 668 669 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 670 671 if (!Format->isAscii() && !Format->isUTF8()) 672 return; 673 674 StringRef FormatStrRef = Format->getString(); 675 EstimateSizeFormatHandler H(FormatStrRef); 676 const char *FormatBytes = FormatStrRef.data(); 677 const ConstantArrayType *T = 678 Context.getAsConstantArrayType(Format->getType()); 679 assert(T && "String literal not of constant array type!"); 680 size_t TypeSize = T->getSize().getZExtValue(); 681 682 // In case there's a null byte somewhere. 683 size_t StrLen = 684 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 685 if (!analyze_format_string::ParsePrintfString( 686 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 687 Context.getTargetInfo(), false)) { 688 DiagID = diag::warn_fortify_source_format_overflow; 689 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 690 .extOrTrunc(SizeTypeWidth); 691 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 692 DestinationSize = ComputeExplicitObjectSizeArgument(2); 693 IsChkVariant = true; 694 } else { 695 DestinationSize = ComputeSizeArgument(0); 696 } 697 break; 698 } 699 } 700 return; 701 } 702 case Builtin::BI__builtin___memcpy_chk: 703 case Builtin::BI__builtin___memmove_chk: 704 case Builtin::BI__builtin___memset_chk: 705 case Builtin::BI__builtin___strlcat_chk: 706 case Builtin::BI__builtin___strlcpy_chk: 707 case Builtin::BI__builtin___strncat_chk: 708 case Builtin::BI__builtin___strncpy_chk: 709 case Builtin::BI__builtin___stpncpy_chk: 710 case Builtin::BI__builtin___memccpy_chk: 711 case Builtin::BI__builtin___mempcpy_chk: { 712 DiagID = diag::warn_builtin_chk_overflow; 713 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 714 DestinationSize = 715 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 716 IsChkVariant = true; 717 break; 718 } 719 720 case Builtin::BI__builtin___snprintf_chk: 721 case Builtin::BI__builtin___vsnprintf_chk: { 722 DiagID = diag::warn_builtin_chk_overflow; 723 SourceSize = ComputeExplicitObjectSizeArgument(1); 724 DestinationSize = ComputeExplicitObjectSizeArgument(3); 725 IsChkVariant = true; 726 break; 727 } 728 729 case Builtin::BIstrncat: 730 case Builtin::BI__builtin_strncat: 731 case Builtin::BIstrncpy: 732 case Builtin::BI__builtin_strncpy: 733 case Builtin::BIstpncpy: 734 case Builtin::BI__builtin_stpncpy: { 735 // Whether these functions overflow depends on the runtime strlen of the 736 // string, not just the buffer size, so emitting the "always overflow" 737 // diagnostic isn't quite right. We should still diagnose passing a buffer 738 // size larger than the destination buffer though; this is a runtime abort 739 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 740 DiagID = diag::warn_fortify_source_size_mismatch; 741 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 742 DestinationSize = ComputeSizeArgument(0); 743 break; 744 } 745 746 case Builtin::BImemcpy: 747 case Builtin::BI__builtin_memcpy: 748 case Builtin::BImemmove: 749 case Builtin::BI__builtin_memmove: 750 case Builtin::BImemset: 751 case Builtin::BI__builtin_memset: 752 case Builtin::BImempcpy: 753 case Builtin::BI__builtin_mempcpy: { 754 DiagID = diag::warn_fortify_source_overflow; 755 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 756 DestinationSize = ComputeSizeArgument(0); 757 break; 758 } 759 case Builtin::BIsnprintf: 760 case Builtin::BI__builtin_snprintf: 761 case Builtin::BIvsnprintf: 762 case Builtin::BI__builtin_vsnprintf: { 763 DiagID = diag::warn_fortify_source_size_mismatch; 764 SourceSize = ComputeExplicitObjectSizeArgument(1); 765 DestinationSize = ComputeSizeArgument(0); 766 break; 767 } 768 } 769 770 if (!SourceSize || !DestinationSize || 771 SourceSize.getValue().ule(DestinationSize.getValue())) 772 return; 773 774 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 775 // Skim off the details of whichever builtin was called to produce a better 776 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 777 if (IsChkVariant) { 778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 779 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 780 } else if (FunctionName.startswith("__builtin_")) { 781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 782 } 783 784 SmallString<16> DestinationStr; 785 SmallString<16> SourceStr; 786 DestinationSize->toString(DestinationStr, /*Radix=*/10); 787 SourceSize->toString(SourceStr, /*Radix=*/10); 788 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 789 PDiag(DiagID) 790 << FunctionName << DestinationStr << SourceStr); 791 } 792 793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 794 Scope::ScopeFlags NeededScopeFlags, 795 unsigned DiagID) { 796 // Scopes aren't available during instantiation. Fortunately, builtin 797 // functions cannot be template args so they cannot be formed through template 798 // instantiation. Therefore checking once during the parse is sufficient. 799 if (SemaRef.inTemplateInstantiation()) 800 return false; 801 802 Scope *S = SemaRef.getCurScope(); 803 while (S && !S->isSEHExceptScope()) 804 S = S->getParent(); 805 if (!S || !(S->getFlags() & NeededScopeFlags)) { 806 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 807 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 808 << DRE->getDecl()->getIdentifier(); 809 return true; 810 } 811 812 return false; 813 } 814 815 static inline bool isBlockPointer(Expr *Arg) { 816 return Arg->getType()->isBlockPointerType(); 817 } 818 819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 820 /// void*, which is a requirement of device side enqueue. 821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 822 const BlockPointerType *BPT = 823 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 824 ArrayRef<QualType> Params = 825 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 826 unsigned ArgCounter = 0; 827 bool IllegalParams = false; 828 // Iterate through the block parameters until either one is found that is not 829 // a local void*, or the block is valid. 830 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 831 I != E; ++I, ++ArgCounter) { 832 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 833 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 834 LangAS::opencl_local) { 835 // Get the location of the error. If a block literal has been passed 836 // (BlockExpr) then we can point straight to the offending argument, 837 // else we just point to the variable reference. 838 SourceLocation ErrorLoc; 839 if (isa<BlockExpr>(BlockArg)) { 840 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 841 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 842 } else if (isa<DeclRefExpr>(BlockArg)) { 843 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 844 } 845 S.Diag(ErrorLoc, 846 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 847 IllegalParams = true; 848 } 849 } 850 851 return IllegalParams; 852 } 853 854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 855 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 857 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 858 return true; 859 } 860 return false; 861 } 862 863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 864 if (checkArgCount(S, TheCall, 2)) 865 return true; 866 867 if (checkOpenCLSubgroupExt(S, TheCall)) 868 return true; 869 870 // First argument is an ndrange_t type. 871 Expr *NDRangeArg = TheCall->getArg(0); 872 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 873 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 874 << TheCall->getDirectCallee() << "'ndrange_t'"; 875 return true; 876 } 877 878 Expr *BlockArg = TheCall->getArg(1); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 888 /// get_kernel_work_group_size 889 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 891 if (checkArgCount(S, TheCall, 1)) 892 return true; 893 894 Expr *BlockArg = TheCall->getArg(0); 895 if (!isBlockPointer(BlockArg)) { 896 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 897 << TheCall->getDirectCallee() << "block"; 898 return true; 899 } 900 return checkOpenCLBlockArgs(S, BlockArg); 901 } 902 903 /// Diagnose integer type and any valid implicit conversion to it. 904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 905 const QualType &IntType); 906 907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 908 unsigned Start, unsigned End) { 909 bool IllegalParams = false; 910 for (unsigned I = Start; I <= End; ++I) 911 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 912 S.Context.getSizeType()); 913 return IllegalParams; 914 } 915 916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 917 /// 'local void*' parameter of passed block. 918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 919 Expr *BlockArg, 920 unsigned NumNonVarArgs) { 921 const BlockPointerType *BPT = 922 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 923 unsigned NumBlockParams = 924 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 925 unsigned TotalNumArgs = TheCall->getNumArgs(); 926 927 // For each argument passed to the block, a corresponding uint needs to 928 // be passed to describe the size of the local memory. 929 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 930 S.Diag(TheCall->getBeginLoc(), 931 diag::err_opencl_enqueue_kernel_local_size_args); 932 return true; 933 } 934 935 // Check that the sizes of the local memory are specified by integers. 936 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 937 TotalNumArgs - 1); 938 } 939 940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 941 /// overload formats specified in Table 6.13.17.1. 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// void (^block)(void)) 946 /// int enqueue_kernel(queue_t queue, 947 /// kernel_enqueue_flags_t flags, 948 /// const ndrange_t ndrange, 949 /// uint num_events_in_wait_list, 950 /// clk_event_t *event_wait_list, 951 /// clk_event_t *event_ret, 952 /// void (^block)(void)) 953 /// int enqueue_kernel(queue_t queue, 954 /// kernel_enqueue_flags_t flags, 955 /// const ndrange_t ndrange, 956 /// void (^block)(local void*, ...), 957 /// uint size0, ...) 958 /// int enqueue_kernel(queue_t queue, 959 /// kernel_enqueue_flags_t flags, 960 /// const ndrange_t ndrange, 961 /// uint num_events_in_wait_list, 962 /// clk_event_t *event_wait_list, 963 /// clk_event_t *event_ret, 964 /// void (^block)(local void*, ...), 965 /// uint size0, ...) 966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 967 unsigned NumArgs = TheCall->getNumArgs(); 968 969 if (NumArgs < 4) { 970 S.Diag(TheCall->getBeginLoc(), 971 diag::err_typecheck_call_too_few_args_at_least) 972 << 0 << 4 << NumArgs; 973 return true; 974 } 975 976 Expr *Arg0 = TheCall->getArg(0); 977 Expr *Arg1 = TheCall->getArg(1); 978 Expr *Arg2 = TheCall->getArg(2); 979 Expr *Arg3 = TheCall->getArg(3); 980 981 // First argument always needs to be a queue_t type. 982 if (!Arg0->getType()->isQueueT()) { 983 S.Diag(TheCall->getArg(0)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 986 return true; 987 } 988 989 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 990 if (!Arg1->getType()->isIntegerType()) { 991 S.Diag(TheCall->getArg(1)->getBeginLoc(), 992 diag::err_opencl_builtin_expected_type) 993 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 994 return true; 995 } 996 997 // Third argument is always an ndrange_t type. 998 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 999 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1000 diag::err_opencl_builtin_expected_type) 1001 << TheCall->getDirectCallee() << "'ndrange_t'"; 1002 return true; 1003 } 1004 1005 // With four arguments, there is only one form that the function could be 1006 // called in: no events and no variable arguments. 1007 if (NumArgs == 4) { 1008 // check that the last argument is the right block type. 1009 if (!isBlockPointer(Arg3)) { 1010 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1011 << TheCall->getDirectCallee() << "block"; 1012 return true; 1013 } 1014 // we have a block type, check the prototype 1015 const BlockPointerType *BPT = 1016 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1017 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1018 S.Diag(Arg3->getBeginLoc(), 1019 diag::err_opencl_enqueue_kernel_blocks_no_args); 1020 return true; 1021 } 1022 return false; 1023 } 1024 // we can have block + varargs. 1025 if (isBlockPointer(Arg3)) 1026 return (checkOpenCLBlockArgs(S, Arg3) || 1027 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1028 // last two cases with either exactly 7 args or 7 args and varargs. 1029 if (NumArgs >= 7) { 1030 // check common block argument. 1031 Expr *Arg6 = TheCall->getArg(6); 1032 if (!isBlockPointer(Arg6)) { 1033 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1034 << TheCall->getDirectCallee() << "block"; 1035 return true; 1036 } 1037 if (checkOpenCLBlockArgs(S, Arg6)) 1038 return true; 1039 1040 // Forth argument has to be any integer type. 1041 if (!Arg3->getType()->isIntegerType()) { 1042 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1043 diag::err_opencl_builtin_expected_type) 1044 << TheCall->getDirectCallee() << "integer"; 1045 return true; 1046 } 1047 // check remaining common arguments. 1048 Expr *Arg4 = TheCall->getArg(4); 1049 Expr *Arg5 = TheCall->getArg(5); 1050 1051 // Fifth argument is always passed as a pointer to clk_event_t. 1052 if (!Arg4->isNullPointerConstant(S.Context, 1053 Expr::NPC_ValueDependentIsNotNull) && 1054 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1055 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1056 diag::err_opencl_builtin_expected_type) 1057 << TheCall->getDirectCallee() 1058 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1059 return true; 1060 } 1061 1062 // Sixth argument is always passed as a pointer to clk_event_t. 1063 if (!Arg5->isNullPointerConstant(S.Context, 1064 Expr::NPC_ValueDependentIsNotNull) && 1065 !(Arg5->getType()->isPointerType() && 1066 Arg5->getType()->getPointeeType()->isClkEventT())) { 1067 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1068 diag::err_opencl_builtin_expected_type) 1069 << TheCall->getDirectCallee() 1070 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1071 return true; 1072 } 1073 1074 if (NumArgs == 7) 1075 return false; 1076 1077 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1078 } 1079 1080 // None of the specific case has been detected, give generic error 1081 S.Diag(TheCall->getBeginLoc(), 1082 diag::err_opencl_enqueue_kernel_incorrect_args); 1083 return true; 1084 } 1085 1086 /// Returns OpenCL access qual. 1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1088 return D->getAttr<OpenCLAccessAttr>(); 1089 } 1090 1091 /// Returns true if pipe element type is different from the pointer. 1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1093 const Expr *Arg0 = Call->getArg(0); 1094 // First argument type should always be pipe. 1095 if (!Arg0->getType()->isPipeType()) { 1096 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1097 << Call->getDirectCallee() << Arg0->getSourceRange(); 1098 return true; 1099 } 1100 OpenCLAccessAttr *AccessQual = 1101 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1102 // Validates the access qualifier is compatible with the call. 1103 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1104 // read_only and write_only, and assumed to be read_only if no qualifier is 1105 // specified. 1106 switch (Call->getDirectCallee()->getBuiltinID()) { 1107 case Builtin::BIread_pipe: 1108 case Builtin::BIreserve_read_pipe: 1109 case Builtin::BIcommit_read_pipe: 1110 case Builtin::BIwork_group_reserve_read_pipe: 1111 case Builtin::BIsub_group_reserve_read_pipe: 1112 case Builtin::BIwork_group_commit_read_pipe: 1113 case Builtin::BIsub_group_commit_read_pipe: 1114 if (!(!AccessQual || AccessQual->isReadOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "read_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 case Builtin::BIwrite_pipe: 1122 case Builtin::BIreserve_write_pipe: 1123 case Builtin::BIcommit_write_pipe: 1124 case Builtin::BIwork_group_reserve_write_pipe: 1125 case Builtin::BIsub_group_reserve_write_pipe: 1126 case Builtin::BIwork_group_commit_write_pipe: 1127 case Builtin::BIsub_group_commit_write_pipe: 1128 if (!(AccessQual && AccessQual->isWriteOnly())) { 1129 S.Diag(Arg0->getBeginLoc(), 1130 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1131 << "write_only" << Arg0->getSourceRange(); 1132 return true; 1133 } 1134 break; 1135 default: 1136 break; 1137 } 1138 return false; 1139 } 1140 1141 /// Returns true if pipe element type is different from the pointer. 1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1143 const Expr *Arg0 = Call->getArg(0); 1144 const Expr *ArgIdx = Call->getArg(Idx); 1145 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1146 const QualType EltTy = PipeTy->getElementType(); 1147 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1148 // The Idx argument should be a pointer and the type of the pointer and 1149 // the type of pipe element should also be the same. 1150 if (!ArgTy || 1151 !S.Context.hasSameType( 1152 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1153 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1154 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1155 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 // Performs semantic analysis for the read/write_pipe call. 1162 // \param S Reference to the semantic analyzer. 1163 // \param Call A pointer to the builtin call. 1164 // \return True if a semantic error has been found, false otherwise. 1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1166 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1167 // functions have two forms. 1168 switch (Call->getNumArgs()) { 1169 case 2: 1170 if (checkOpenCLPipeArg(S, Call)) 1171 return true; 1172 // The call with 2 arguments should be 1173 // read/write_pipe(pipe T, T*). 1174 // Check packet type T. 1175 if (checkOpenCLPipePacketType(S, Call, 1)) 1176 return true; 1177 break; 1178 1179 case 4: { 1180 if (checkOpenCLPipeArg(S, Call)) 1181 return true; 1182 // The call with 4 arguments should be 1183 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1184 // Check reserve_id_t. 1185 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1186 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1187 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1188 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1189 return true; 1190 } 1191 1192 // Check the index. 1193 const Expr *Arg2 = Call->getArg(2); 1194 if (!Arg2->getType()->isIntegerType() && 1195 !Arg2->getType()->isUnsignedIntegerType()) { 1196 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1197 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1198 << Arg2->getType() << Arg2->getSourceRange(); 1199 return true; 1200 } 1201 1202 // Check packet type T. 1203 if (checkOpenCLPipePacketType(S, Call, 3)) 1204 return true; 1205 } break; 1206 default: 1207 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1208 << Call->getDirectCallee() << Call->getSourceRange(); 1209 return true; 1210 } 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on the {work_group_/sub_group_ 1216 // /_}reserve_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check the reserve size. 1228 if (!Call->getArg(1)->getType()->isIntegerType() && 1229 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1230 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1231 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1232 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1233 return true; 1234 } 1235 1236 // Since return type of reserve_read/write_pipe built-in function is 1237 // reserve_id_t, which is not defined in the builtin def file , we used int 1238 // as return type and need to override the return type of these functions. 1239 Call->setType(S.Context.OCLReserveIDTy); 1240 1241 return false; 1242 } 1243 1244 // Performs a semantic analysis on {work_group_/sub_group_ 1245 // /_}commit_{read/write}_pipe 1246 // \param S Reference to the semantic analyzer. 1247 // \param Call The call to the builtin function to be analyzed. 1248 // \return True if a semantic error was found, false otherwise. 1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1250 if (checkArgCount(S, Call, 2)) 1251 return true; 1252 1253 if (checkOpenCLPipeArg(S, Call)) 1254 return true; 1255 1256 // Check reserve_id_t. 1257 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1258 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1259 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1260 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1261 return true; 1262 } 1263 1264 return false; 1265 } 1266 1267 // Performs a semantic analysis on the call to built-in Pipe 1268 // Query Functions. 1269 // \param S Reference to the semantic analyzer. 1270 // \param Call The call to the builtin function to be analyzed. 1271 // \return True if a semantic error was found, false otherwise. 1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1273 if (checkArgCount(S, Call, 1)) 1274 return true; 1275 1276 if (!Call->getArg(0)->getType()->isPipeType()) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1278 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1279 return true; 1280 } 1281 1282 return false; 1283 } 1284 1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1286 // Performs semantic analysis for the to_global/local/private call. 1287 // \param S Reference to the semantic analyzer. 1288 // \param BuiltinID ID of the builtin function. 1289 // \param Call A pointer to the builtin call. 1290 // \return True if a semantic error has been found, false otherwise. 1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1292 CallExpr *Call) { 1293 if (checkArgCount(S, Call, 1)) 1294 return true; 1295 1296 auto RT = Call->getArg(0)->getType(); 1297 if (!RT->isPointerType() || RT->getPointeeType() 1298 .getAddressSpace() == LangAS::opencl_constant) { 1299 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1300 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1301 return true; 1302 } 1303 1304 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1305 S.Diag(Call->getArg(0)->getBeginLoc(), 1306 diag::warn_opencl_generic_address_space_arg) 1307 << Call->getDirectCallee()->getNameInfo().getAsString() 1308 << Call->getArg(0)->getSourceRange(); 1309 } 1310 1311 RT = RT->getPointeeType(); 1312 auto Qual = RT.getQualifiers(); 1313 switch (BuiltinID) { 1314 case Builtin::BIto_global: 1315 Qual.setAddressSpace(LangAS::opencl_global); 1316 break; 1317 case Builtin::BIto_local: 1318 Qual.setAddressSpace(LangAS::opencl_local); 1319 break; 1320 case Builtin::BIto_private: 1321 Qual.setAddressSpace(LangAS::opencl_private); 1322 break; 1323 default: 1324 llvm_unreachable("Invalid builtin function"); 1325 } 1326 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1327 RT.getUnqualifiedType(), Qual))); 1328 1329 return false; 1330 } 1331 1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1333 if (checkArgCount(S, TheCall, 1)) 1334 return ExprError(); 1335 1336 // Compute __builtin_launder's parameter type from the argument. 1337 // The parameter type is: 1338 // * The type of the argument if it's not an array or function type, 1339 // Otherwise, 1340 // * The decayed argument type. 1341 QualType ParamTy = [&]() { 1342 QualType ArgTy = TheCall->getArg(0)->getType(); 1343 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1344 return S.Context.getPointerType(Ty->getElementType()); 1345 if (ArgTy->isFunctionType()) { 1346 return S.Context.getPointerType(ArgTy); 1347 } 1348 return ArgTy; 1349 }(); 1350 1351 TheCall->setType(ParamTy); 1352 1353 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1354 if (!ParamTy->isPointerType()) 1355 return 0; 1356 if (ParamTy->isFunctionPointerType()) 1357 return 1; 1358 if (ParamTy->isVoidPointerType()) 1359 return 2; 1360 return llvm::Optional<unsigned>{}; 1361 }(); 1362 if (DiagSelect.hasValue()) { 1363 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1364 << DiagSelect.getValue() << TheCall->getSourceRange(); 1365 return ExprError(); 1366 } 1367 1368 // We either have an incomplete class type, or we have a class template 1369 // whose instantiation has not been forced. Example: 1370 // 1371 // template <class T> struct Foo { T value; }; 1372 // Foo<int> *p = nullptr; 1373 // auto *d = __builtin_launder(p); 1374 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1375 diag::err_incomplete_type)) 1376 return ExprError(); 1377 1378 assert(ParamTy->getPointeeType()->isObjectType() && 1379 "Unhandled non-object pointer case"); 1380 1381 InitializedEntity Entity = 1382 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1383 ExprResult Arg = 1384 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1385 if (Arg.isInvalid()) 1386 return ExprError(); 1387 TheCall->setArg(0, Arg.get()); 1388 1389 return TheCall; 1390 } 1391 1392 // Emit an error and return true if the current architecture is not in the list 1393 // of supported architectures. 1394 static bool 1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1396 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1397 llvm::Triple::ArchType CurArch = 1398 S.getASTContext().getTargetInfo().getTriple().getArch(); 1399 if (llvm::is_contained(SupportedArchs, CurArch)) 1400 return false; 1401 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1402 << TheCall->getSourceRange(); 1403 return true; 1404 } 1405 1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1407 SourceLocation CallSiteLoc); 1408 1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1410 CallExpr *TheCall) { 1411 switch (TI.getTriple().getArch()) { 1412 default: 1413 // Some builtins don't require additional checking, so just consider these 1414 // acceptable. 1415 return false; 1416 case llvm::Triple::arm: 1417 case llvm::Triple::armeb: 1418 case llvm::Triple::thumb: 1419 case llvm::Triple::thumbeb: 1420 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::aarch64: 1422 case llvm::Triple::aarch64_32: 1423 case llvm::Triple::aarch64_be: 1424 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::bpfeb: 1426 case llvm::Triple::bpfel: 1427 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1428 case llvm::Triple::hexagon: 1429 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1430 case llvm::Triple::mips: 1431 case llvm::Triple::mipsel: 1432 case llvm::Triple::mips64: 1433 case llvm::Triple::mips64el: 1434 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 case llvm::Triple::systemz: 1436 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1437 case llvm::Triple::x86: 1438 case llvm::Triple::x86_64: 1439 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1440 case llvm::Triple::ppc: 1441 case llvm::Triple::ppcle: 1442 case llvm::Triple::ppc64: 1443 case llvm::Triple::ppc64le: 1444 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1445 case llvm::Triple::amdgcn: 1446 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1447 case llvm::Triple::riscv32: 1448 case llvm::Triple::riscv64: 1449 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1450 } 1451 } 1452 1453 ExprResult 1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1455 CallExpr *TheCall) { 1456 ExprResult TheCallResult(TheCall); 1457 1458 // Find out if any arguments are required to be integer constant expressions. 1459 unsigned ICEArguments = 0; 1460 ASTContext::GetBuiltinTypeError Error; 1461 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1462 if (Error != ASTContext::GE_None) 1463 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1464 1465 // If any arguments are required to be ICE's, check and diagnose. 1466 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1467 // Skip arguments not required to be ICE's. 1468 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1469 1470 llvm::APSInt Result; 1471 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1472 return true; 1473 ICEArguments &= ~(1 << ArgNo); 1474 } 1475 1476 switch (BuiltinID) { 1477 case Builtin::BI__builtin___CFStringMakeConstantString: 1478 assert(TheCall->getNumArgs() == 1 && 1479 "Wrong # arguments to builtin CFStringMakeConstantString"); 1480 if (CheckObjCString(TheCall->getArg(0))) 1481 return ExprError(); 1482 break; 1483 case Builtin::BI__builtin_ms_va_start: 1484 case Builtin::BI__builtin_stdarg_start: 1485 case Builtin::BI__builtin_va_start: 1486 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1487 return ExprError(); 1488 break; 1489 case Builtin::BI__va_start: { 1490 switch (Context.getTargetInfo().getTriple().getArch()) { 1491 case llvm::Triple::aarch64: 1492 case llvm::Triple::arm: 1493 case llvm::Triple::thumb: 1494 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1495 return ExprError(); 1496 break; 1497 default: 1498 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1499 return ExprError(); 1500 break; 1501 } 1502 break; 1503 } 1504 1505 // The acquire, release, and no fence variants are ARM and AArch64 only. 1506 case Builtin::BI_interlockedbittestandset_acq: 1507 case Builtin::BI_interlockedbittestandset_rel: 1508 case Builtin::BI_interlockedbittestandset_nf: 1509 case Builtin::BI_interlockedbittestandreset_acq: 1510 case Builtin::BI_interlockedbittestandreset_rel: 1511 case Builtin::BI_interlockedbittestandreset_nf: 1512 if (CheckBuiltinTargetSupport( 1513 *this, BuiltinID, TheCall, 1514 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1515 return ExprError(); 1516 break; 1517 1518 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1519 case Builtin::BI_bittest64: 1520 case Builtin::BI_bittestandcomplement64: 1521 case Builtin::BI_bittestandreset64: 1522 case Builtin::BI_bittestandset64: 1523 case Builtin::BI_interlockedbittestandreset64: 1524 case Builtin::BI_interlockedbittestandset64: 1525 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1526 {llvm::Triple::x86_64, llvm::Triple::arm, 1527 llvm::Triple::thumb, llvm::Triple::aarch64})) 1528 return ExprError(); 1529 break; 1530 1531 case Builtin::BI__builtin_isgreater: 1532 case Builtin::BI__builtin_isgreaterequal: 1533 case Builtin::BI__builtin_isless: 1534 case Builtin::BI__builtin_islessequal: 1535 case Builtin::BI__builtin_islessgreater: 1536 case Builtin::BI__builtin_isunordered: 1537 if (SemaBuiltinUnorderedCompare(TheCall)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_fpclassify: 1541 if (SemaBuiltinFPClassification(TheCall, 6)) 1542 return ExprError(); 1543 break; 1544 case Builtin::BI__builtin_isfinite: 1545 case Builtin::BI__builtin_isinf: 1546 case Builtin::BI__builtin_isinf_sign: 1547 case Builtin::BI__builtin_isnan: 1548 case Builtin::BI__builtin_isnormal: 1549 case Builtin::BI__builtin_signbit: 1550 case Builtin::BI__builtin_signbitf: 1551 case Builtin::BI__builtin_signbitl: 1552 if (SemaBuiltinFPClassification(TheCall, 1)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_shufflevector: 1556 return SemaBuiltinShuffleVector(TheCall); 1557 // TheCall will be freed by the smart pointer here, but that's fine, since 1558 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1559 case Builtin::BI__builtin_prefetch: 1560 if (SemaBuiltinPrefetch(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_alloca_with_align: 1564 if (SemaBuiltinAllocaWithAlign(TheCall)) 1565 return ExprError(); 1566 LLVM_FALLTHROUGH; 1567 case Builtin::BI__builtin_alloca: 1568 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1569 << TheCall->getDirectCallee(); 1570 break; 1571 case Builtin::BI__arithmetic_fence: 1572 if (SemaBuiltinArithmeticFence(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__assume: 1576 case Builtin::BI__builtin_assume: 1577 if (SemaBuiltinAssume(TheCall)) 1578 return ExprError(); 1579 break; 1580 case Builtin::BI__builtin_assume_aligned: 1581 if (SemaBuiltinAssumeAligned(TheCall)) 1582 return ExprError(); 1583 break; 1584 case Builtin::BI__builtin_dynamic_object_size: 1585 case Builtin::BI__builtin_object_size: 1586 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BI__builtin_longjmp: 1590 if (SemaBuiltinLongjmp(TheCall)) 1591 return ExprError(); 1592 break; 1593 case Builtin::BI__builtin_setjmp: 1594 if (SemaBuiltinSetjmp(TheCall)) 1595 return ExprError(); 1596 break; 1597 case Builtin::BI__builtin_classify_type: 1598 if (checkArgCount(*this, TheCall, 1)) return true; 1599 TheCall->setType(Context.IntTy); 1600 break; 1601 case Builtin::BI__builtin_complex: 1602 if (SemaBuiltinComplex(TheCall)) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_constant_p: { 1606 if (checkArgCount(*this, TheCall, 1)) return true; 1607 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1608 if (Arg.isInvalid()) return true; 1609 TheCall->setArg(0, Arg.get()); 1610 TheCall->setType(Context.IntTy); 1611 break; 1612 } 1613 case Builtin::BI__builtin_launder: 1614 return SemaBuiltinLaunder(*this, TheCall); 1615 case Builtin::BI__sync_fetch_and_add: 1616 case Builtin::BI__sync_fetch_and_add_1: 1617 case Builtin::BI__sync_fetch_and_add_2: 1618 case Builtin::BI__sync_fetch_and_add_4: 1619 case Builtin::BI__sync_fetch_and_add_8: 1620 case Builtin::BI__sync_fetch_and_add_16: 1621 case Builtin::BI__sync_fetch_and_sub: 1622 case Builtin::BI__sync_fetch_and_sub_1: 1623 case Builtin::BI__sync_fetch_and_sub_2: 1624 case Builtin::BI__sync_fetch_and_sub_4: 1625 case Builtin::BI__sync_fetch_and_sub_8: 1626 case Builtin::BI__sync_fetch_and_sub_16: 1627 case Builtin::BI__sync_fetch_and_or: 1628 case Builtin::BI__sync_fetch_and_or_1: 1629 case Builtin::BI__sync_fetch_and_or_2: 1630 case Builtin::BI__sync_fetch_and_or_4: 1631 case Builtin::BI__sync_fetch_and_or_8: 1632 case Builtin::BI__sync_fetch_and_or_16: 1633 case Builtin::BI__sync_fetch_and_and: 1634 case Builtin::BI__sync_fetch_and_and_1: 1635 case Builtin::BI__sync_fetch_and_and_2: 1636 case Builtin::BI__sync_fetch_and_and_4: 1637 case Builtin::BI__sync_fetch_and_and_8: 1638 case Builtin::BI__sync_fetch_and_and_16: 1639 case Builtin::BI__sync_fetch_and_xor: 1640 case Builtin::BI__sync_fetch_and_xor_1: 1641 case Builtin::BI__sync_fetch_and_xor_2: 1642 case Builtin::BI__sync_fetch_and_xor_4: 1643 case Builtin::BI__sync_fetch_and_xor_8: 1644 case Builtin::BI__sync_fetch_and_xor_16: 1645 case Builtin::BI__sync_fetch_and_nand: 1646 case Builtin::BI__sync_fetch_and_nand_1: 1647 case Builtin::BI__sync_fetch_and_nand_2: 1648 case Builtin::BI__sync_fetch_and_nand_4: 1649 case Builtin::BI__sync_fetch_and_nand_8: 1650 case Builtin::BI__sync_fetch_and_nand_16: 1651 case Builtin::BI__sync_add_and_fetch: 1652 case Builtin::BI__sync_add_and_fetch_1: 1653 case Builtin::BI__sync_add_and_fetch_2: 1654 case Builtin::BI__sync_add_and_fetch_4: 1655 case Builtin::BI__sync_add_and_fetch_8: 1656 case Builtin::BI__sync_add_and_fetch_16: 1657 case Builtin::BI__sync_sub_and_fetch: 1658 case Builtin::BI__sync_sub_and_fetch_1: 1659 case Builtin::BI__sync_sub_and_fetch_2: 1660 case Builtin::BI__sync_sub_and_fetch_4: 1661 case Builtin::BI__sync_sub_and_fetch_8: 1662 case Builtin::BI__sync_sub_and_fetch_16: 1663 case Builtin::BI__sync_and_and_fetch: 1664 case Builtin::BI__sync_and_and_fetch_1: 1665 case Builtin::BI__sync_and_and_fetch_2: 1666 case Builtin::BI__sync_and_and_fetch_4: 1667 case Builtin::BI__sync_and_and_fetch_8: 1668 case Builtin::BI__sync_and_and_fetch_16: 1669 case Builtin::BI__sync_or_and_fetch: 1670 case Builtin::BI__sync_or_and_fetch_1: 1671 case Builtin::BI__sync_or_and_fetch_2: 1672 case Builtin::BI__sync_or_and_fetch_4: 1673 case Builtin::BI__sync_or_and_fetch_8: 1674 case Builtin::BI__sync_or_and_fetch_16: 1675 case Builtin::BI__sync_xor_and_fetch: 1676 case Builtin::BI__sync_xor_and_fetch_1: 1677 case Builtin::BI__sync_xor_and_fetch_2: 1678 case Builtin::BI__sync_xor_and_fetch_4: 1679 case Builtin::BI__sync_xor_and_fetch_8: 1680 case Builtin::BI__sync_xor_and_fetch_16: 1681 case Builtin::BI__sync_nand_and_fetch: 1682 case Builtin::BI__sync_nand_and_fetch_1: 1683 case Builtin::BI__sync_nand_and_fetch_2: 1684 case Builtin::BI__sync_nand_and_fetch_4: 1685 case Builtin::BI__sync_nand_and_fetch_8: 1686 case Builtin::BI__sync_nand_and_fetch_16: 1687 case Builtin::BI__sync_val_compare_and_swap: 1688 case Builtin::BI__sync_val_compare_and_swap_1: 1689 case Builtin::BI__sync_val_compare_and_swap_2: 1690 case Builtin::BI__sync_val_compare_and_swap_4: 1691 case Builtin::BI__sync_val_compare_and_swap_8: 1692 case Builtin::BI__sync_val_compare_and_swap_16: 1693 case Builtin::BI__sync_bool_compare_and_swap: 1694 case Builtin::BI__sync_bool_compare_and_swap_1: 1695 case Builtin::BI__sync_bool_compare_and_swap_2: 1696 case Builtin::BI__sync_bool_compare_and_swap_4: 1697 case Builtin::BI__sync_bool_compare_and_swap_8: 1698 case Builtin::BI__sync_bool_compare_and_swap_16: 1699 case Builtin::BI__sync_lock_test_and_set: 1700 case Builtin::BI__sync_lock_test_and_set_1: 1701 case Builtin::BI__sync_lock_test_and_set_2: 1702 case Builtin::BI__sync_lock_test_and_set_4: 1703 case Builtin::BI__sync_lock_test_and_set_8: 1704 case Builtin::BI__sync_lock_test_and_set_16: 1705 case Builtin::BI__sync_lock_release: 1706 case Builtin::BI__sync_lock_release_1: 1707 case Builtin::BI__sync_lock_release_2: 1708 case Builtin::BI__sync_lock_release_4: 1709 case Builtin::BI__sync_lock_release_8: 1710 case Builtin::BI__sync_lock_release_16: 1711 case Builtin::BI__sync_swap: 1712 case Builtin::BI__sync_swap_1: 1713 case Builtin::BI__sync_swap_2: 1714 case Builtin::BI__sync_swap_4: 1715 case Builtin::BI__sync_swap_8: 1716 case Builtin::BI__sync_swap_16: 1717 return SemaBuiltinAtomicOverloaded(TheCallResult); 1718 case Builtin::BI__sync_synchronize: 1719 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1720 << TheCall->getCallee()->getSourceRange(); 1721 break; 1722 case Builtin::BI__builtin_nontemporal_load: 1723 case Builtin::BI__builtin_nontemporal_store: 1724 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1725 case Builtin::BI__builtin_memcpy_inline: { 1726 clang::Expr *SizeOp = TheCall->getArg(2); 1727 // We warn about copying to or from `nullptr` pointers when `size` is 1728 // greater than 0. When `size` is value dependent we cannot evaluate its 1729 // value so we bail out. 1730 if (SizeOp->isValueDependent()) 1731 break; 1732 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1733 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1734 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1735 } 1736 break; 1737 } 1738 #define BUILTIN(ID, TYPE, ATTRS) 1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1740 case Builtin::BI##ID: \ 1741 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1742 #include "clang/Basic/Builtins.def" 1743 case Builtin::BI__annotation: 1744 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_annotation: 1748 if (SemaBuiltinAnnotation(*this, TheCall)) 1749 return ExprError(); 1750 break; 1751 case Builtin::BI__builtin_addressof: 1752 if (SemaBuiltinAddressof(*this, TheCall)) 1753 return ExprError(); 1754 break; 1755 case Builtin::BI__builtin_is_aligned: 1756 case Builtin::BI__builtin_align_up: 1757 case Builtin::BI__builtin_align_down: 1758 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_add_overflow: 1762 case Builtin::BI__builtin_sub_overflow: 1763 case Builtin::BI__builtin_mul_overflow: 1764 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__builtin_operator_new: 1768 case Builtin::BI__builtin_operator_delete: { 1769 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1770 ExprResult Res = 1771 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1772 if (Res.isInvalid()) 1773 CorrectDelayedTyposInExpr(TheCallResult.get()); 1774 return Res; 1775 } 1776 case Builtin::BI__builtin_dump_struct: { 1777 // We first want to ensure we are called with 2 arguments 1778 if (checkArgCount(*this, TheCall, 2)) 1779 return ExprError(); 1780 // Ensure that the first argument is of type 'struct XX *' 1781 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1782 const QualType PtrArgType = PtrArg->getType(); 1783 if (!PtrArgType->isPointerType() || 1784 !PtrArgType->getPointeeType()->isRecordType()) { 1785 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1786 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1787 << "structure pointer"; 1788 return ExprError(); 1789 } 1790 1791 // Ensure that the second argument is of type 'FunctionType' 1792 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1793 const QualType FnPtrArgType = FnPtrArg->getType(); 1794 if (!FnPtrArgType->isPointerType()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1797 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 1801 const auto *FuncType = 1802 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1803 1804 if (!FuncType) { 1805 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1806 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1807 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1808 return ExprError(); 1809 } 1810 1811 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1812 if (!FT->getNumParams()) { 1813 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1814 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1815 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1816 return ExprError(); 1817 } 1818 QualType PT = FT->getParamType(0); 1819 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1820 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1821 !PT->getPointeeType().isConstQualified()) { 1822 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1823 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1824 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1825 return ExprError(); 1826 } 1827 } 1828 1829 TheCall->setType(Context.IntTy); 1830 break; 1831 } 1832 case Builtin::BI__builtin_expect_with_probability: { 1833 // We first want to ensure we are called with 3 arguments 1834 if (checkArgCount(*this, TheCall, 3)) 1835 return ExprError(); 1836 // then check probability is constant float in range [0.0, 1.0] 1837 const Expr *ProbArg = TheCall->getArg(2); 1838 SmallVector<PartialDiagnosticAt, 8> Notes; 1839 Expr::EvalResult Eval; 1840 Eval.Diag = &Notes; 1841 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1842 !Eval.Val.isFloat()) { 1843 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1844 << ProbArg->getSourceRange(); 1845 for (const PartialDiagnosticAt &PDiag : Notes) 1846 Diag(PDiag.first, PDiag.second); 1847 return ExprError(); 1848 } 1849 llvm::APFloat Probability = Eval.Val.getFloat(); 1850 bool LoseInfo = false; 1851 Probability.convert(llvm::APFloat::IEEEdouble(), 1852 llvm::RoundingMode::Dynamic, &LoseInfo); 1853 if (!(Probability >= llvm::APFloat(0.0) && 1854 Probability <= llvm::APFloat(1.0))) { 1855 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1856 << ProbArg->getSourceRange(); 1857 return ExprError(); 1858 } 1859 break; 1860 } 1861 case Builtin::BI__builtin_preserve_access_index: 1862 if (SemaBuiltinPreserveAI(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BI__builtin_call_with_static_chain: 1866 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__exception_code: 1870 case Builtin::BI_exception_code: 1871 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1872 diag::err_seh___except_block)) 1873 return ExprError(); 1874 break; 1875 case Builtin::BI__exception_info: 1876 case Builtin::BI_exception_info: 1877 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1878 diag::err_seh___except_filter)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BI__GetExceptionInfo: 1882 if (checkArgCount(*this, TheCall, 1)) 1883 return ExprError(); 1884 1885 if (CheckCXXThrowOperand( 1886 TheCall->getBeginLoc(), 1887 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1888 TheCall)) 1889 return ExprError(); 1890 1891 TheCall->setType(Context.VoidPtrTy); 1892 break; 1893 // OpenCL v2.0, s6.13.16 - Pipe functions 1894 case Builtin::BIread_pipe: 1895 case Builtin::BIwrite_pipe: 1896 // Since those two functions are declared with var args, we need a semantic 1897 // check for the argument. 1898 if (SemaBuiltinRWPipe(*this, TheCall)) 1899 return ExprError(); 1900 break; 1901 case Builtin::BIreserve_read_pipe: 1902 case Builtin::BIreserve_write_pipe: 1903 case Builtin::BIwork_group_reserve_read_pipe: 1904 case Builtin::BIwork_group_reserve_write_pipe: 1905 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIsub_group_reserve_read_pipe: 1909 case Builtin::BIsub_group_reserve_write_pipe: 1910 if (checkOpenCLSubgroupExt(*this, TheCall) || 1911 SemaBuiltinReserveRWPipe(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIcommit_read_pipe: 1915 case Builtin::BIcommit_write_pipe: 1916 case Builtin::BIwork_group_commit_read_pipe: 1917 case Builtin::BIwork_group_commit_write_pipe: 1918 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1919 return ExprError(); 1920 break; 1921 case Builtin::BIsub_group_commit_read_pipe: 1922 case Builtin::BIsub_group_commit_write_pipe: 1923 if (checkOpenCLSubgroupExt(*this, TheCall) || 1924 SemaBuiltinCommitRWPipe(*this, TheCall)) 1925 return ExprError(); 1926 break; 1927 case Builtin::BIget_pipe_num_packets: 1928 case Builtin::BIget_pipe_max_packets: 1929 if (SemaBuiltinPipePackets(*this, TheCall)) 1930 return ExprError(); 1931 break; 1932 case Builtin::BIto_global: 1933 case Builtin::BIto_local: 1934 case Builtin::BIto_private: 1935 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1936 return ExprError(); 1937 break; 1938 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1939 case Builtin::BIenqueue_kernel: 1940 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1941 return ExprError(); 1942 break; 1943 case Builtin::BIget_kernel_work_group_size: 1944 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1945 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1946 return ExprError(); 1947 break; 1948 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1949 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1950 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1951 return ExprError(); 1952 break; 1953 case Builtin::BI__builtin_os_log_format: 1954 Cleanup.setExprNeedsCleanups(true); 1955 LLVM_FALLTHROUGH; 1956 case Builtin::BI__builtin_os_log_format_buffer_size: 1957 if (SemaBuiltinOSLogFormat(TheCall)) 1958 return ExprError(); 1959 break; 1960 case Builtin::BI__builtin_frame_address: 1961 case Builtin::BI__builtin_return_address: { 1962 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1963 return ExprError(); 1964 1965 // -Wframe-address warning if non-zero passed to builtin 1966 // return/frame address. 1967 Expr::EvalResult Result; 1968 if (!TheCall->getArg(0)->isValueDependent() && 1969 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1970 Result.Val.getInt() != 0) 1971 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1972 << ((BuiltinID == Builtin::BI__builtin_return_address) 1973 ? "__builtin_return_address" 1974 : "__builtin_frame_address") 1975 << TheCall->getSourceRange(); 1976 break; 1977 } 1978 1979 case Builtin::BI__builtin_matrix_transpose: 1980 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1981 1982 case Builtin::BI__builtin_matrix_column_major_load: 1983 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1984 1985 case Builtin::BI__builtin_matrix_column_major_store: 1986 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1987 1988 case Builtin::BI__builtin_get_device_side_mangled_name: { 1989 auto Check = [](CallExpr *TheCall) { 1990 if (TheCall->getNumArgs() != 1) 1991 return false; 1992 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1993 if (!DRE) 1994 return false; 1995 auto *D = DRE->getDecl(); 1996 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1997 return false; 1998 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1999 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2000 }; 2001 if (!Check(TheCall)) { 2002 Diag(TheCall->getBeginLoc(), 2003 diag::err_hip_invalid_args_builtin_mangled_name); 2004 return ExprError(); 2005 } 2006 } 2007 } 2008 2009 // Since the target specific builtins for each arch overlap, only check those 2010 // of the arch we are compiling for. 2011 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2012 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2013 assert(Context.getAuxTargetInfo() && 2014 "Aux Target Builtin, but not an aux target?"); 2015 2016 if (CheckTSBuiltinFunctionCall( 2017 *Context.getAuxTargetInfo(), 2018 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2019 return ExprError(); 2020 } else { 2021 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2022 TheCall)) 2023 return ExprError(); 2024 } 2025 } 2026 2027 return TheCallResult; 2028 } 2029 2030 // Get the valid immediate range for the specified NEON type code. 2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2032 NeonTypeFlags Type(t); 2033 int IsQuad = ForceQuad ? true : Type.isQuad(); 2034 switch (Type.getEltType()) { 2035 case NeonTypeFlags::Int8: 2036 case NeonTypeFlags::Poly8: 2037 return shift ? 7 : (8 << IsQuad) - 1; 2038 case NeonTypeFlags::Int16: 2039 case NeonTypeFlags::Poly16: 2040 return shift ? 15 : (4 << IsQuad) - 1; 2041 case NeonTypeFlags::Int32: 2042 return shift ? 31 : (2 << IsQuad) - 1; 2043 case NeonTypeFlags::Int64: 2044 case NeonTypeFlags::Poly64: 2045 return shift ? 63 : (1 << IsQuad) - 1; 2046 case NeonTypeFlags::Poly128: 2047 return shift ? 127 : (1 << IsQuad) - 1; 2048 case NeonTypeFlags::Float16: 2049 assert(!shift && "cannot shift float types!"); 2050 return (4 << IsQuad) - 1; 2051 case NeonTypeFlags::Float32: 2052 assert(!shift && "cannot shift float types!"); 2053 return (2 << IsQuad) - 1; 2054 case NeonTypeFlags::Float64: 2055 assert(!shift && "cannot shift float types!"); 2056 return (1 << IsQuad) - 1; 2057 case NeonTypeFlags::BFloat16: 2058 assert(!shift && "cannot shift float types!"); 2059 return (4 << IsQuad) - 1; 2060 } 2061 llvm_unreachable("Invalid NeonTypeFlag!"); 2062 } 2063 2064 /// getNeonEltType - Return the QualType corresponding to the elements of 2065 /// the vector type specified by the NeonTypeFlags. This is used to check 2066 /// the pointer arguments for Neon load/store intrinsics. 2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2068 bool IsPolyUnsigned, bool IsInt64Long) { 2069 switch (Flags.getEltType()) { 2070 case NeonTypeFlags::Int8: 2071 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2072 case NeonTypeFlags::Int16: 2073 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2074 case NeonTypeFlags::Int32: 2075 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2076 case NeonTypeFlags::Int64: 2077 if (IsInt64Long) 2078 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2079 else 2080 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2081 : Context.LongLongTy; 2082 case NeonTypeFlags::Poly8: 2083 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2084 case NeonTypeFlags::Poly16: 2085 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2086 case NeonTypeFlags::Poly64: 2087 if (IsInt64Long) 2088 return Context.UnsignedLongTy; 2089 else 2090 return Context.UnsignedLongLongTy; 2091 case NeonTypeFlags::Poly128: 2092 break; 2093 case NeonTypeFlags::Float16: 2094 return Context.HalfTy; 2095 case NeonTypeFlags::Float32: 2096 return Context.FloatTy; 2097 case NeonTypeFlags::Float64: 2098 return Context.DoubleTy; 2099 case NeonTypeFlags::BFloat16: 2100 return Context.BFloat16Ty; 2101 } 2102 llvm_unreachable("Invalid NeonTypeFlag!"); 2103 } 2104 2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2106 // Range check SVE intrinsics that take immediate values. 2107 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2108 2109 switch (BuiltinID) { 2110 default: 2111 return false; 2112 #define GET_SVE_IMMEDIATE_CHECK 2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2114 #undef GET_SVE_IMMEDIATE_CHECK 2115 } 2116 2117 // Perform all the immediate checks for this builtin call. 2118 bool HasError = false; 2119 for (auto &I : ImmChecks) { 2120 int ArgNum, CheckTy, ElementSizeInBits; 2121 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2122 2123 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2124 2125 // Function that checks whether the operand (ArgNum) is an immediate 2126 // that is one of the predefined values. 2127 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2128 int ErrDiag) -> bool { 2129 // We can't check the value of a dependent argument. 2130 Expr *Arg = TheCall->getArg(ArgNum); 2131 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2132 return false; 2133 2134 // Check constant-ness first. 2135 llvm::APSInt Imm; 2136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2137 return true; 2138 2139 if (!CheckImm(Imm.getSExtValue())) 2140 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2141 return false; 2142 }; 2143 2144 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2145 case SVETypeFlags::ImmCheck0_31: 2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheck0_13: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2151 HasError = true; 2152 break; 2153 case SVETypeFlags::ImmCheck1_16: 2154 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheck0_7: 2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckExtract: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 (2048 / ElementSizeInBits) - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckShiftRight: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2168 HasError = true; 2169 break; 2170 case SVETypeFlags::ImmCheckShiftRightNarrow: 2171 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2172 ElementSizeInBits / 2)) 2173 HasError = true; 2174 break; 2175 case SVETypeFlags::ImmCheckShiftLeft: 2176 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2177 ElementSizeInBits - 1)) 2178 HasError = true; 2179 break; 2180 case SVETypeFlags::ImmCheckLaneIndex: 2181 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2182 (128 / (1 * ElementSizeInBits)) - 1)) 2183 HasError = true; 2184 break; 2185 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2186 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2187 (128 / (2 * ElementSizeInBits)) - 1)) 2188 HasError = true; 2189 break; 2190 case SVETypeFlags::ImmCheckLaneIndexDot: 2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2192 (128 / (4 * ElementSizeInBits)) - 1)) 2193 HasError = true; 2194 break; 2195 case SVETypeFlags::ImmCheckComplexRot90_270: 2196 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2197 diag::err_rotation_argument_to_cadd)) 2198 HasError = true; 2199 break; 2200 case SVETypeFlags::ImmCheckComplexRotAll90: 2201 if (CheckImmediateInSet( 2202 [](int64_t V) { 2203 return V == 0 || V == 90 || V == 180 || V == 270; 2204 }, 2205 diag::err_rotation_argument_to_cmla)) 2206 HasError = true; 2207 break; 2208 case SVETypeFlags::ImmCheck0_1: 2209 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2210 HasError = true; 2211 break; 2212 case SVETypeFlags::ImmCheck0_2: 2213 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2214 HasError = true; 2215 break; 2216 case SVETypeFlags::ImmCheck0_3: 2217 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2218 HasError = true; 2219 break; 2220 } 2221 } 2222 2223 return HasError; 2224 } 2225 2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2227 unsigned BuiltinID, CallExpr *TheCall) { 2228 llvm::APSInt Result; 2229 uint64_t mask = 0; 2230 unsigned TV = 0; 2231 int PtrArgNum = -1; 2232 bool HasConstPtr = false; 2233 switch (BuiltinID) { 2234 #define GET_NEON_OVERLOAD_CHECK 2235 #include "clang/Basic/arm_neon.inc" 2236 #include "clang/Basic/arm_fp16.inc" 2237 #undef GET_NEON_OVERLOAD_CHECK 2238 } 2239 2240 // For NEON intrinsics which are overloaded on vector element type, validate 2241 // the immediate which specifies which variant to emit. 2242 unsigned ImmArg = TheCall->getNumArgs()-1; 2243 if (mask) { 2244 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2245 return true; 2246 2247 TV = Result.getLimitedValue(64); 2248 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2249 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2250 << TheCall->getArg(ImmArg)->getSourceRange(); 2251 } 2252 2253 if (PtrArgNum >= 0) { 2254 // Check that pointer arguments have the specified type. 2255 Expr *Arg = TheCall->getArg(PtrArgNum); 2256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2257 Arg = ICE->getSubExpr(); 2258 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2259 QualType RHSTy = RHS.get()->getType(); 2260 2261 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2262 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2263 Arch == llvm::Triple::aarch64_32 || 2264 Arch == llvm::Triple::aarch64_be; 2265 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2266 QualType EltTy = 2267 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2268 if (HasConstPtr) 2269 EltTy = EltTy.withConst(); 2270 QualType LHSTy = Context.getPointerType(EltTy); 2271 AssignConvertType ConvTy; 2272 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2273 if (RHS.isInvalid()) 2274 return true; 2275 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2276 RHS.get(), AA_Assigning)) 2277 return true; 2278 } 2279 2280 // For NEON intrinsics which take an immediate value as part of the 2281 // instruction, range check them here. 2282 unsigned i = 0, l = 0, u = 0; 2283 switch (BuiltinID) { 2284 default: 2285 return false; 2286 #define GET_NEON_IMMEDIATE_CHECK 2287 #include "clang/Basic/arm_neon.inc" 2288 #include "clang/Basic/arm_fp16.inc" 2289 #undef GET_NEON_IMMEDIATE_CHECK 2290 } 2291 2292 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2293 } 2294 2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2296 switch (BuiltinID) { 2297 default: 2298 return false; 2299 #include "clang/Basic/arm_mve_builtin_sema.inc" 2300 } 2301 } 2302 2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2304 CallExpr *TheCall) { 2305 bool Err = false; 2306 switch (BuiltinID) { 2307 default: 2308 return false; 2309 #include "clang/Basic/arm_cde_builtin_sema.inc" 2310 } 2311 2312 if (Err) 2313 return true; 2314 2315 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2316 } 2317 2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2319 const Expr *CoprocArg, bool WantCDE) { 2320 if (isConstantEvaluated()) 2321 return false; 2322 2323 // We can't check the value of a dependent argument. 2324 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2325 return false; 2326 2327 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2328 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2329 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2330 2331 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2332 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2333 2334 if (IsCDECoproc != WantCDE) 2335 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2336 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2337 2338 return false; 2339 } 2340 2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2342 unsigned MaxWidth) { 2343 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2344 BuiltinID == ARM::BI__builtin_arm_ldaex || 2345 BuiltinID == ARM::BI__builtin_arm_strex || 2346 BuiltinID == ARM::BI__builtin_arm_stlex || 2347 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2348 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2349 BuiltinID == AArch64::BI__builtin_arm_strex || 2350 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2351 "unexpected ARM builtin"); 2352 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2353 BuiltinID == ARM::BI__builtin_arm_ldaex || 2354 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2355 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2356 2357 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2358 2359 // Ensure that we have the proper number of arguments. 2360 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2361 return true; 2362 2363 // Inspect the pointer argument of the atomic builtin. This should always be 2364 // a pointer type, whose element is an integral scalar or pointer type. 2365 // Because it is a pointer type, we don't have to worry about any implicit 2366 // casts here. 2367 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2368 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2369 if (PointerArgRes.isInvalid()) 2370 return true; 2371 PointerArg = PointerArgRes.get(); 2372 2373 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2374 if (!pointerType) { 2375 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2376 << PointerArg->getType() << PointerArg->getSourceRange(); 2377 return true; 2378 } 2379 2380 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2381 // task is to insert the appropriate casts into the AST. First work out just 2382 // what the appropriate type is. 2383 QualType ValType = pointerType->getPointeeType(); 2384 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2385 if (IsLdrex) 2386 AddrType.addConst(); 2387 2388 // Issue a warning if the cast is dodgy. 2389 CastKind CastNeeded = CK_NoOp; 2390 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2391 CastNeeded = CK_BitCast; 2392 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2393 << PointerArg->getType() << Context.getPointerType(AddrType) 2394 << AA_Passing << PointerArg->getSourceRange(); 2395 } 2396 2397 // Finally, do the cast and replace the argument with the corrected version. 2398 AddrType = Context.getPointerType(AddrType); 2399 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2400 if (PointerArgRes.isInvalid()) 2401 return true; 2402 PointerArg = PointerArgRes.get(); 2403 2404 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2405 2406 // In general, we allow ints, floats and pointers to be loaded and stored. 2407 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2408 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2409 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2410 << PointerArg->getType() << PointerArg->getSourceRange(); 2411 return true; 2412 } 2413 2414 // But ARM doesn't have instructions to deal with 128-bit versions. 2415 if (Context.getTypeSize(ValType) > MaxWidth) { 2416 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2417 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2418 << PointerArg->getType() << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 switch (ValType.getObjCLifetime()) { 2423 case Qualifiers::OCL_None: 2424 case Qualifiers::OCL_ExplicitNone: 2425 // okay 2426 break; 2427 2428 case Qualifiers::OCL_Weak: 2429 case Qualifiers::OCL_Strong: 2430 case Qualifiers::OCL_Autoreleasing: 2431 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2432 << ValType << PointerArg->getSourceRange(); 2433 return true; 2434 } 2435 2436 if (IsLdrex) { 2437 TheCall->setType(ValType); 2438 return false; 2439 } 2440 2441 // Initialize the argument to be stored. 2442 ExprResult ValArg = TheCall->getArg(0); 2443 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2444 Context, ValType, /*consume*/ false); 2445 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2446 if (ValArg.isInvalid()) 2447 return true; 2448 TheCall->setArg(0, ValArg.get()); 2449 2450 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2451 // but the custom checker bypasses all default analysis. 2452 TheCall->setType(Context.IntTy); 2453 return false; 2454 } 2455 2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2457 CallExpr *TheCall) { 2458 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2459 BuiltinID == ARM::BI__builtin_arm_ldaex || 2460 BuiltinID == ARM::BI__builtin_arm_strex || 2461 BuiltinID == ARM::BI__builtin_arm_stlex) { 2462 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2463 } 2464 2465 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2466 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2467 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2468 } 2469 2470 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2471 BuiltinID == ARM::BI__builtin_arm_wsr64) 2472 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2473 2474 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2475 BuiltinID == ARM::BI__builtin_arm_rsrp || 2476 BuiltinID == ARM::BI__builtin_arm_wsr || 2477 BuiltinID == ARM::BI__builtin_arm_wsrp) 2478 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2479 2480 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2481 return true; 2482 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2483 return true; 2484 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2485 return true; 2486 2487 // For intrinsics which take an immediate value as part of the instruction, 2488 // range check them here. 2489 // FIXME: VFP Intrinsics should error if VFP not present. 2490 switch (BuiltinID) { 2491 default: return false; 2492 case ARM::BI__builtin_arm_ssat: 2493 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2494 case ARM::BI__builtin_arm_usat: 2495 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2496 case ARM::BI__builtin_arm_ssat16: 2497 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2498 case ARM::BI__builtin_arm_usat16: 2499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2500 case ARM::BI__builtin_arm_vcvtr_f: 2501 case ARM::BI__builtin_arm_vcvtr_d: 2502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2503 case ARM::BI__builtin_arm_dmb: 2504 case ARM::BI__builtin_arm_dsb: 2505 case ARM::BI__builtin_arm_isb: 2506 case ARM::BI__builtin_arm_dbg: 2507 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2508 case ARM::BI__builtin_arm_cdp: 2509 case ARM::BI__builtin_arm_cdp2: 2510 case ARM::BI__builtin_arm_mcr: 2511 case ARM::BI__builtin_arm_mcr2: 2512 case ARM::BI__builtin_arm_mrc: 2513 case ARM::BI__builtin_arm_mrc2: 2514 case ARM::BI__builtin_arm_mcrr: 2515 case ARM::BI__builtin_arm_mcrr2: 2516 case ARM::BI__builtin_arm_mrrc: 2517 case ARM::BI__builtin_arm_mrrc2: 2518 case ARM::BI__builtin_arm_ldc: 2519 case ARM::BI__builtin_arm_ldcl: 2520 case ARM::BI__builtin_arm_ldc2: 2521 case ARM::BI__builtin_arm_ldc2l: 2522 case ARM::BI__builtin_arm_stc: 2523 case ARM::BI__builtin_arm_stcl: 2524 case ARM::BI__builtin_arm_stc2: 2525 case ARM::BI__builtin_arm_stc2l: 2526 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2527 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2528 /*WantCDE*/ false); 2529 } 2530 } 2531 2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2533 unsigned BuiltinID, 2534 CallExpr *TheCall) { 2535 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2536 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2537 BuiltinID == AArch64::BI__builtin_arm_strex || 2538 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2539 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2540 } 2541 2542 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2543 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2544 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2545 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2546 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2550 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2551 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2552 2553 // Memory Tagging Extensions (MTE) Intrinsics 2554 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2555 BuiltinID == AArch64::BI__builtin_arm_addg || 2556 BuiltinID == AArch64::BI__builtin_arm_gmi || 2557 BuiltinID == AArch64::BI__builtin_arm_ldg || 2558 BuiltinID == AArch64::BI__builtin_arm_stg || 2559 BuiltinID == AArch64::BI__builtin_arm_subp) { 2560 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2561 } 2562 2563 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2564 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2565 BuiltinID == AArch64::BI__builtin_arm_wsr || 2566 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2567 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2568 2569 // Only check the valid encoding range. Any constant in this range would be 2570 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2571 // an exception for incorrect registers. This matches MSVC behavior. 2572 if (BuiltinID == AArch64::BI_ReadStatusReg || 2573 BuiltinID == AArch64::BI_WriteStatusReg) 2574 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2575 2576 if (BuiltinID == AArch64::BI__getReg) 2577 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2578 2579 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2580 return true; 2581 2582 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2583 return true; 2584 2585 // For intrinsics which take an immediate value as part of the instruction, 2586 // range check them here. 2587 unsigned i = 0, l = 0, u = 0; 2588 switch (BuiltinID) { 2589 default: return false; 2590 case AArch64::BI__builtin_arm_dmb: 2591 case AArch64::BI__builtin_arm_dsb: 2592 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2593 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2594 } 2595 2596 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2597 } 2598 2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2600 if (Arg->getType()->getAsPlaceholderType()) 2601 return false; 2602 2603 // The first argument needs to be a record field access. 2604 // If it is an array element access, we delay decision 2605 // to BPF backend to check whether the access is a 2606 // field access or not. 2607 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2608 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2609 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2610 } 2611 2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2613 QualType VectorTy, QualType EltTy) { 2614 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2615 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2616 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2617 << Call->getSourceRange() << VectorEltTy << EltTy; 2618 return false; 2619 } 2620 return true; 2621 } 2622 2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2624 QualType ArgType = Arg->getType(); 2625 if (ArgType->getAsPlaceholderType()) 2626 return false; 2627 2628 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2629 // format: 2630 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2631 // 2. <type> var; 2632 // __builtin_preserve_type_info(var, flag); 2633 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2634 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2635 return false; 2636 2637 // Typedef type. 2638 if (ArgType->getAs<TypedefType>()) 2639 return true; 2640 2641 // Record type or Enum type. 2642 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2643 if (const auto *RT = Ty->getAs<RecordType>()) { 2644 if (!RT->getDecl()->getDeclName().isEmpty()) 2645 return true; 2646 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2647 if (!ET->getDecl()->getDeclName().isEmpty()) 2648 return true; 2649 } 2650 2651 return false; 2652 } 2653 2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2655 QualType ArgType = Arg->getType(); 2656 if (ArgType->getAsPlaceholderType()) 2657 return false; 2658 2659 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2660 // format: 2661 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2662 // flag); 2663 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2664 if (!UO) 2665 return false; 2666 2667 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2668 if (!CE) 2669 return false; 2670 if (CE->getCastKind() != CK_IntegralToPointer && 2671 CE->getCastKind() != CK_NullToPointer) 2672 return false; 2673 2674 // The integer must be from an EnumConstantDecl. 2675 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2676 if (!DR) 2677 return false; 2678 2679 const EnumConstantDecl *Enumerator = 2680 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2681 if (!Enumerator) 2682 return false; 2683 2684 // The type must be EnumType. 2685 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2686 const auto *ET = Ty->getAs<EnumType>(); 2687 if (!ET) 2688 return false; 2689 2690 // The enum value must be supported. 2691 for (auto *EDI : ET->getDecl()->enumerators()) { 2692 if (EDI == Enumerator) 2693 return true; 2694 } 2695 2696 return false; 2697 } 2698 2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2700 CallExpr *TheCall) { 2701 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2702 BuiltinID == BPF::BI__builtin_btf_type_id || 2703 BuiltinID == BPF::BI__builtin_preserve_type_info || 2704 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2705 "unexpected BPF builtin"); 2706 2707 if (checkArgCount(*this, TheCall, 2)) 2708 return true; 2709 2710 // The second argument needs to be a constant int 2711 Expr *Arg = TheCall->getArg(1); 2712 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2713 diag::kind kind; 2714 if (!Value) { 2715 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2716 kind = diag::err_preserve_field_info_not_const; 2717 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2718 kind = diag::err_btf_type_id_not_const; 2719 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2720 kind = diag::err_preserve_type_info_not_const; 2721 else 2722 kind = diag::err_preserve_enum_value_not_const; 2723 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2724 return true; 2725 } 2726 2727 // The first argument 2728 Arg = TheCall->getArg(0); 2729 bool InvalidArg = false; 2730 bool ReturnUnsignedInt = true; 2731 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2732 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2733 InvalidArg = true; 2734 kind = diag::err_preserve_field_info_not_field; 2735 } 2736 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2737 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2738 InvalidArg = true; 2739 kind = diag::err_preserve_type_info_invalid; 2740 } 2741 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2742 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2743 InvalidArg = true; 2744 kind = diag::err_preserve_enum_value_invalid; 2745 } 2746 ReturnUnsignedInt = false; 2747 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2748 ReturnUnsignedInt = false; 2749 } 2750 2751 if (InvalidArg) { 2752 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2753 return true; 2754 } 2755 2756 if (ReturnUnsignedInt) 2757 TheCall->setType(Context.UnsignedIntTy); 2758 else 2759 TheCall->setType(Context.UnsignedLongTy); 2760 return false; 2761 } 2762 2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2764 struct ArgInfo { 2765 uint8_t OpNum; 2766 bool IsSigned; 2767 uint8_t BitWidth; 2768 uint8_t Align; 2769 }; 2770 struct BuiltinInfo { 2771 unsigned BuiltinID; 2772 ArgInfo Infos[2]; 2773 }; 2774 2775 static BuiltinInfo Infos[] = { 2776 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2777 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2778 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2779 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2780 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2782 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2783 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2784 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2785 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2786 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2787 2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2799 2800 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2852 {{ 1, false, 6, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2860 {{ 1, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2867 { 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2869 { 2, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2871 { 3, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2873 { 3, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2890 {{ 2, false, 4, 0 }, 2891 { 3, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2893 {{ 2, false, 4, 0 }, 2894 { 3, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2896 {{ 2, false, 4, 0 }, 2897 { 3, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2899 {{ 2, false, 4, 0 }, 2900 { 3, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2912 { 2, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2914 { 2, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2924 {{ 1, false, 4, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2927 {{ 1, false, 4, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2948 {{ 3, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2953 {{ 3, false, 1, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2958 {{ 3, false, 1, 0 }} }, 2959 }; 2960 2961 // Use a dynamically initialized static to sort the table exactly once on 2962 // first run. 2963 static const bool SortOnce = 2964 (llvm::sort(Infos, 2965 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2966 return LHS.BuiltinID < RHS.BuiltinID; 2967 }), 2968 true); 2969 (void)SortOnce; 2970 2971 const BuiltinInfo *F = llvm::partition_point( 2972 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2973 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2974 return false; 2975 2976 bool Error = false; 2977 2978 for (const ArgInfo &A : F->Infos) { 2979 // Ignore empty ArgInfo elements. 2980 if (A.BitWidth == 0) 2981 continue; 2982 2983 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2984 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2985 if (!A.Align) { 2986 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2987 } else { 2988 unsigned M = 1 << A.Align; 2989 Min *= M; 2990 Max *= M; 2991 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2992 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2993 } 2994 } 2995 return Error; 2996 } 2997 2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2999 CallExpr *TheCall) { 3000 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3001 } 3002 3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3004 unsigned BuiltinID, CallExpr *TheCall) { 3005 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3006 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3007 } 3008 3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3010 CallExpr *TheCall) { 3011 3012 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3013 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3014 if (!TI.hasFeature("dsp")) 3015 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3016 } 3017 3018 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3019 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3020 if (!TI.hasFeature("dspr2")) 3021 return Diag(TheCall->getBeginLoc(), 3022 diag::err_mips_builtin_requires_dspr2); 3023 } 3024 3025 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3026 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3027 if (!TI.hasFeature("msa")) 3028 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3029 } 3030 3031 return false; 3032 } 3033 3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3036 // ordering for DSP is unspecified. MSA is ordered by the data format used 3037 // by the underlying instruction i.e., df/m, df/n and then by size. 3038 // 3039 // FIXME: The size tests here should instead be tablegen'd along with the 3040 // definitions from include/clang/Basic/BuiltinsMips.def. 3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3042 // be too. 3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3044 unsigned i = 0, l = 0, u = 0, m = 0; 3045 switch (BuiltinID) { 3046 default: return false; 3047 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3048 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3049 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3050 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3051 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3052 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3053 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3054 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3055 // df/m field. 3056 // These intrinsics take an unsigned 3 bit immediate. 3057 case Mips::BI__builtin_msa_bclri_b: 3058 case Mips::BI__builtin_msa_bnegi_b: 3059 case Mips::BI__builtin_msa_bseti_b: 3060 case Mips::BI__builtin_msa_sat_s_b: 3061 case Mips::BI__builtin_msa_sat_u_b: 3062 case Mips::BI__builtin_msa_slli_b: 3063 case Mips::BI__builtin_msa_srai_b: 3064 case Mips::BI__builtin_msa_srari_b: 3065 case Mips::BI__builtin_msa_srli_b: 3066 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3067 case Mips::BI__builtin_msa_binsli_b: 3068 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3069 // These intrinsics take an unsigned 4 bit immediate. 3070 case Mips::BI__builtin_msa_bclri_h: 3071 case Mips::BI__builtin_msa_bnegi_h: 3072 case Mips::BI__builtin_msa_bseti_h: 3073 case Mips::BI__builtin_msa_sat_s_h: 3074 case Mips::BI__builtin_msa_sat_u_h: 3075 case Mips::BI__builtin_msa_slli_h: 3076 case Mips::BI__builtin_msa_srai_h: 3077 case Mips::BI__builtin_msa_srari_h: 3078 case Mips::BI__builtin_msa_srli_h: 3079 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3080 case Mips::BI__builtin_msa_binsli_h: 3081 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3082 // These intrinsics take an unsigned 5 bit immediate. 3083 // The first block of intrinsics actually have an unsigned 5 bit field, 3084 // not a df/n field. 3085 case Mips::BI__builtin_msa_cfcmsa: 3086 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3087 case Mips::BI__builtin_msa_clei_u_b: 3088 case Mips::BI__builtin_msa_clei_u_h: 3089 case Mips::BI__builtin_msa_clei_u_w: 3090 case Mips::BI__builtin_msa_clei_u_d: 3091 case Mips::BI__builtin_msa_clti_u_b: 3092 case Mips::BI__builtin_msa_clti_u_h: 3093 case Mips::BI__builtin_msa_clti_u_w: 3094 case Mips::BI__builtin_msa_clti_u_d: 3095 case Mips::BI__builtin_msa_maxi_u_b: 3096 case Mips::BI__builtin_msa_maxi_u_h: 3097 case Mips::BI__builtin_msa_maxi_u_w: 3098 case Mips::BI__builtin_msa_maxi_u_d: 3099 case Mips::BI__builtin_msa_mini_u_b: 3100 case Mips::BI__builtin_msa_mini_u_h: 3101 case Mips::BI__builtin_msa_mini_u_w: 3102 case Mips::BI__builtin_msa_mini_u_d: 3103 case Mips::BI__builtin_msa_addvi_b: 3104 case Mips::BI__builtin_msa_addvi_h: 3105 case Mips::BI__builtin_msa_addvi_w: 3106 case Mips::BI__builtin_msa_addvi_d: 3107 case Mips::BI__builtin_msa_bclri_w: 3108 case Mips::BI__builtin_msa_bnegi_w: 3109 case Mips::BI__builtin_msa_bseti_w: 3110 case Mips::BI__builtin_msa_sat_s_w: 3111 case Mips::BI__builtin_msa_sat_u_w: 3112 case Mips::BI__builtin_msa_slli_w: 3113 case Mips::BI__builtin_msa_srai_w: 3114 case Mips::BI__builtin_msa_srari_w: 3115 case Mips::BI__builtin_msa_srli_w: 3116 case Mips::BI__builtin_msa_srlri_w: 3117 case Mips::BI__builtin_msa_subvi_b: 3118 case Mips::BI__builtin_msa_subvi_h: 3119 case Mips::BI__builtin_msa_subvi_w: 3120 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3121 case Mips::BI__builtin_msa_binsli_w: 3122 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3123 // These intrinsics take an unsigned 6 bit immediate. 3124 case Mips::BI__builtin_msa_bclri_d: 3125 case Mips::BI__builtin_msa_bnegi_d: 3126 case Mips::BI__builtin_msa_bseti_d: 3127 case Mips::BI__builtin_msa_sat_s_d: 3128 case Mips::BI__builtin_msa_sat_u_d: 3129 case Mips::BI__builtin_msa_slli_d: 3130 case Mips::BI__builtin_msa_srai_d: 3131 case Mips::BI__builtin_msa_srari_d: 3132 case Mips::BI__builtin_msa_srli_d: 3133 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3134 case Mips::BI__builtin_msa_binsli_d: 3135 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3136 // These intrinsics take a signed 5 bit immediate. 3137 case Mips::BI__builtin_msa_ceqi_b: 3138 case Mips::BI__builtin_msa_ceqi_h: 3139 case Mips::BI__builtin_msa_ceqi_w: 3140 case Mips::BI__builtin_msa_ceqi_d: 3141 case Mips::BI__builtin_msa_clti_s_b: 3142 case Mips::BI__builtin_msa_clti_s_h: 3143 case Mips::BI__builtin_msa_clti_s_w: 3144 case Mips::BI__builtin_msa_clti_s_d: 3145 case Mips::BI__builtin_msa_clei_s_b: 3146 case Mips::BI__builtin_msa_clei_s_h: 3147 case Mips::BI__builtin_msa_clei_s_w: 3148 case Mips::BI__builtin_msa_clei_s_d: 3149 case Mips::BI__builtin_msa_maxi_s_b: 3150 case Mips::BI__builtin_msa_maxi_s_h: 3151 case Mips::BI__builtin_msa_maxi_s_w: 3152 case Mips::BI__builtin_msa_maxi_s_d: 3153 case Mips::BI__builtin_msa_mini_s_b: 3154 case Mips::BI__builtin_msa_mini_s_h: 3155 case Mips::BI__builtin_msa_mini_s_w: 3156 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3157 // These intrinsics take an unsigned 8 bit immediate. 3158 case Mips::BI__builtin_msa_andi_b: 3159 case Mips::BI__builtin_msa_nori_b: 3160 case Mips::BI__builtin_msa_ori_b: 3161 case Mips::BI__builtin_msa_shf_b: 3162 case Mips::BI__builtin_msa_shf_h: 3163 case Mips::BI__builtin_msa_shf_w: 3164 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3165 case Mips::BI__builtin_msa_bseli_b: 3166 case Mips::BI__builtin_msa_bmnzi_b: 3167 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3168 // df/n format 3169 // These intrinsics take an unsigned 4 bit immediate. 3170 case Mips::BI__builtin_msa_copy_s_b: 3171 case Mips::BI__builtin_msa_copy_u_b: 3172 case Mips::BI__builtin_msa_insve_b: 3173 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3174 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3175 // These intrinsics take an unsigned 3 bit immediate. 3176 case Mips::BI__builtin_msa_copy_s_h: 3177 case Mips::BI__builtin_msa_copy_u_h: 3178 case Mips::BI__builtin_msa_insve_h: 3179 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3180 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3181 // These intrinsics take an unsigned 2 bit immediate. 3182 case Mips::BI__builtin_msa_copy_s_w: 3183 case Mips::BI__builtin_msa_copy_u_w: 3184 case Mips::BI__builtin_msa_insve_w: 3185 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3186 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3187 // These intrinsics take an unsigned 1 bit immediate. 3188 case Mips::BI__builtin_msa_copy_s_d: 3189 case Mips::BI__builtin_msa_copy_u_d: 3190 case Mips::BI__builtin_msa_insve_d: 3191 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3192 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3193 // Memory offsets and immediate loads. 3194 // These intrinsics take a signed 10 bit immediate. 3195 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3196 case Mips::BI__builtin_msa_ldi_h: 3197 case Mips::BI__builtin_msa_ldi_w: 3198 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3199 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3200 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3201 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3202 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3203 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3204 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3205 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3206 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3207 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3208 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3209 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3210 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3211 } 3212 3213 if (!m) 3214 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3215 3216 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3217 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3218 } 3219 3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3221 /// advancing the pointer over the consumed characters. The decoded type is 3222 /// returned. If the decoded type represents a constant integer with a 3223 /// constraint on its value then Mask is set to that value. The type descriptors 3224 /// used in Str are specific to PPC MMA builtins and are documented in the file 3225 /// defining the PPC builtins. 3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3227 unsigned &Mask) { 3228 bool RequireICE = false; 3229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3230 switch (*Str++) { 3231 case 'V': 3232 return Context.getVectorType(Context.UnsignedCharTy, 16, 3233 VectorType::VectorKind::AltiVecVector); 3234 case 'i': { 3235 char *End; 3236 unsigned size = strtoul(Str, &End, 10); 3237 assert(End != Str && "Missing constant parameter constraint"); 3238 Str = End; 3239 Mask = size; 3240 return Context.IntTy; 3241 } 3242 case 'W': { 3243 char *End; 3244 unsigned size = strtoul(Str, &End, 10); 3245 assert(End != Str && "Missing PowerPC MMA type size"); 3246 Str = End; 3247 QualType Type; 3248 switch (size) { 3249 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3250 case size: Type = Context.Id##Ty; break; 3251 #include "clang/Basic/PPCTypes.def" 3252 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3253 } 3254 bool CheckVectorArgs = false; 3255 while (!CheckVectorArgs) { 3256 switch (*Str++) { 3257 case '*': 3258 Type = Context.getPointerType(Type); 3259 break; 3260 case 'C': 3261 Type = Type.withConst(); 3262 break; 3263 default: 3264 CheckVectorArgs = true; 3265 --Str; 3266 break; 3267 } 3268 } 3269 return Type; 3270 } 3271 default: 3272 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3273 } 3274 } 3275 3276 static bool isPPC_64Builtin(unsigned BuiltinID) { 3277 // These builtins only work on PPC 64bit targets. 3278 switch (BuiltinID) { 3279 case PPC::BI__builtin_divde: 3280 case PPC::BI__builtin_divdeu: 3281 case PPC::BI__builtin_bpermd: 3282 case PPC::BI__builtin_ppc_ldarx: 3283 case PPC::BI__builtin_ppc_stdcx: 3284 case PPC::BI__builtin_ppc_tdw: 3285 case PPC::BI__builtin_ppc_trapd: 3286 case PPC::BI__builtin_ppc_cmpeqb: 3287 case PPC::BI__builtin_ppc_setb: 3288 case PPC::BI__builtin_ppc_mulhd: 3289 case PPC::BI__builtin_ppc_mulhdu: 3290 case PPC::BI__builtin_ppc_maddhd: 3291 case PPC::BI__builtin_ppc_maddhdu: 3292 case PPC::BI__builtin_ppc_maddld: 3293 case PPC::BI__builtin_ppc_load8r: 3294 case PPC::BI__builtin_ppc_store8r: 3295 case PPC::BI__builtin_ppc_insert_exp: 3296 case PPC::BI__builtin_ppc_extract_sig: 3297 case PPC::BI__builtin_ppc_addex: 3298 return true; 3299 } 3300 return false; 3301 } 3302 3303 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3304 StringRef FeatureToCheck, unsigned DiagID, 3305 StringRef DiagArg = "") { 3306 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3307 return false; 3308 3309 if (DiagArg.empty()) 3310 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3311 else 3312 S.Diag(TheCall->getBeginLoc(), DiagID) 3313 << DiagArg << TheCall->getSourceRange(); 3314 3315 return true; 3316 } 3317 3318 /// Returns true if the argument consists of one contiguous run of 1s with any 3319 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3320 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3321 /// since all 1s are not contiguous. 3322 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3323 llvm::APSInt Result; 3324 // We can't check the value of a dependent argument. 3325 Expr *Arg = TheCall->getArg(ArgNum); 3326 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3327 return false; 3328 3329 // Check constant-ness first. 3330 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3331 return true; 3332 3333 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3334 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3335 return false; 3336 3337 return Diag(TheCall->getBeginLoc(), 3338 diag::err_argument_not_contiguous_bit_field) 3339 << ArgNum << Arg->getSourceRange(); 3340 } 3341 3342 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3343 CallExpr *TheCall) { 3344 unsigned i = 0, l = 0, u = 0; 3345 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3346 llvm::APSInt Result; 3347 3348 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3349 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3350 << TheCall->getSourceRange(); 3351 3352 switch (BuiltinID) { 3353 default: return false; 3354 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3355 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3356 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3357 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3358 case PPC::BI__builtin_altivec_dss: 3359 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3360 case PPC::BI__builtin_tbegin: 3361 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3362 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3363 case PPC::BI__builtin_tabortwc: 3364 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3365 case PPC::BI__builtin_tabortwci: 3366 case PPC::BI__builtin_tabortdci: 3367 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3368 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3369 case PPC::BI__builtin_altivec_dst: 3370 case PPC::BI__builtin_altivec_dstt: 3371 case PPC::BI__builtin_altivec_dstst: 3372 case PPC::BI__builtin_altivec_dststt: 3373 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3374 case PPC::BI__builtin_vsx_xxpermdi: 3375 case PPC::BI__builtin_vsx_xxsldwi: 3376 return SemaBuiltinVSX(TheCall); 3377 case PPC::BI__builtin_divwe: 3378 case PPC::BI__builtin_divweu: 3379 case PPC::BI__builtin_divde: 3380 case PPC::BI__builtin_divdeu: 3381 return SemaFeatureCheck(*this, TheCall, "extdiv", 3382 diag::err_ppc_builtin_only_on_arch, "7"); 3383 case PPC::BI__builtin_bpermd: 3384 return SemaFeatureCheck(*this, TheCall, "bpermd", 3385 diag::err_ppc_builtin_only_on_arch, "7"); 3386 case PPC::BI__builtin_unpack_vector_int128: 3387 return SemaFeatureCheck(*this, TheCall, "vsx", 3388 diag::err_ppc_builtin_only_on_arch, "7") || 3389 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3390 case PPC::BI__builtin_pack_vector_int128: 3391 return SemaFeatureCheck(*this, TheCall, "vsx", 3392 diag::err_ppc_builtin_only_on_arch, "7"); 3393 case PPC::BI__builtin_altivec_vgnb: 3394 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3395 case PPC::BI__builtin_altivec_vec_replace_elt: 3396 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3397 QualType VecTy = TheCall->getArg(0)->getType(); 3398 QualType EltTy = TheCall->getArg(1)->getType(); 3399 unsigned Width = Context.getIntWidth(EltTy); 3400 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3401 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3402 } 3403 case PPC::BI__builtin_vsx_xxeval: 3404 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3405 case PPC::BI__builtin_altivec_vsldbi: 3406 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3407 case PPC::BI__builtin_altivec_vsrdbi: 3408 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3409 case PPC::BI__builtin_vsx_xxpermx: 3410 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3411 case PPC::BI__builtin_ppc_tw: 3412 case PPC::BI__builtin_ppc_tdw: 3413 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3414 case PPC::BI__builtin_ppc_cmpeqb: 3415 case PPC::BI__builtin_ppc_setb: 3416 case PPC::BI__builtin_ppc_maddhd: 3417 case PPC::BI__builtin_ppc_maddhdu: 3418 case PPC::BI__builtin_ppc_maddld: 3419 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3420 diag::err_ppc_builtin_only_on_arch, "9"); 3421 case PPC::BI__builtin_ppc_cmprb: 3422 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3423 diag::err_ppc_builtin_only_on_arch, "9") || 3424 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3425 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3426 // be a constant that represents a contiguous bit field. 3427 case PPC::BI__builtin_ppc_rlwnm: 3428 return SemaBuiltinConstantArg(TheCall, 1, Result) || 3429 SemaValueIsRunOfOnes(TheCall, 2); 3430 case PPC::BI__builtin_ppc_rlwimi: 3431 case PPC::BI__builtin_ppc_rldimi: 3432 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3433 SemaValueIsRunOfOnes(TheCall, 3); 3434 case PPC::BI__builtin_ppc_extract_exp: 3435 case PPC::BI__builtin_ppc_extract_sig: 3436 case PPC::BI__builtin_ppc_insert_exp: 3437 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3438 diag::err_ppc_builtin_only_on_arch, "9"); 3439 case PPC::BI__builtin_ppc_addex: { 3440 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3441 diag::err_ppc_builtin_only_on_arch, "9") || 3442 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3443 return true; 3444 // Output warning for reserved values 1 to 3. 3445 int ArgValue = 3446 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3447 if (ArgValue != 0) 3448 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3449 << ArgValue; 3450 return false; 3451 } 3452 case PPC::BI__builtin_ppc_mtfsb0: 3453 case PPC::BI__builtin_ppc_mtfsb1: 3454 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3455 case PPC::BI__builtin_ppc_mtfsf: 3456 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3457 case PPC::BI__builtin_ppc_mtfsfi: 3458 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3459 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3460 case PPC::BI__builtin_ppc_alignx: 3461 return SemaBuiltinConstantArgPower2(TheCall, 0); 3462 case PPC::BI__builtin_ppc_rdlam: 3463 return SemaValueIsRunOfOnes(TheCall, 2); 3464 case PPC::BI__builtin_ppc_icbt: 3465 case PPC::BI__builtin_ppc_sthcx: 3466 case PPC::BI__builtin_ppc_stbcx: 3467 case PPC::BI__builtin_ppc_lharx: 3468 case PPC::BI__builtin_ppc_lbarx: 3469 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3470 diag::err_ppc_builtin_only_on_arch, "8"); 3471 case PPC::BI__builtin_vsx_ldrmb: 3472 case PPC::BI__builtin_vsx_strmb: 3473 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3474 diag::err_ppc_builtin_only_on_arch, "8") || 3475 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3476 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3477 case PPC::BI__builtin_##Name: \ 3478 return SemaBuiltinPPCMMACall(TheCall, Types); 3479 #include "clang/Basic/BuiltinsPPC.def" 3480 } 3481 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3482 } 3483 3484 // Check if the given type is a non-pointer PPC MMA type. This function is used 3485 // in Sema to prevent invalid uses of restricted PPC MMA types. 3486 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3487 if (Type->isPointerType() || Type->isArrayType()) 3488 return false; 3489 3490 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3491 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3492 if (false 3493 #include "clang/Basic/PPCTypes.def" 3494 ) { 3495 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3496 return true; 3497 } 3498 return false; 3499 } 3500 3501 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3502 CallExpr *TheCall) { 3503 // position of memory order and scope arguments in the builtin 3504 unsigned OrderIndex, ScopeIndex; 3505 switch (BuiltinID) { 3506 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3507 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3508 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3509 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3510 OrderIndex = 2; 3511 ScopeIndex = 3; 3512 break; 3513 case AMDGPU::BI__builtin_amdgcn_fence: 3514 OrderIndex = 0; 3515 ScopeIndex = 1; 3516 break; 3517 default: 3518 return false; 3519 } 3520 3521 ExprResult Arg = TheCall->getArg(OrderIndex); 3522 auto ArgExpr = Arg.get(); 3523 Expr::EvalResult ArgResult; 3524 3525 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3526 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3527 << ArgExpr->getType(); 3528 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3529 3530 // Check valididty of memory ordering as per C11 / C++11's memody model. 3531 // Only fence needs check. Atomic dec/inc allow all memory orders. 3532 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3533 return Diag(ArgExpr->getBeginLoc(), 3534 diag::warn_atomic_op_has_invalid_memory_order) 3535 << ArgExpr->getSourceRange(); 3536 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3537 case llvm::AtomicOrderingCABI::relaxed: 3538 case llvm::AtomicOrderingCABI::consume: 3539 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3540 return Diag(ArgExpr->getBeginLoc(), 3541 diag::warn_atomic_op_has_invalid_memory_order) 3542 << ArgExpr->getSourceRange(); 3543 break; 3544 case llvm::AtomicOrderingCABI::acquire: 3545 case llvm::AtomicOrderingCABI::release: 3546 case llvm::AtomicOrderingCABI::acq_rel: 3547 case llvm::AtomicOrderingCABI::seq_cst: 3548 break; 3549 } 3550 3551 Arg = TheCall->getArg(ScopeIndex); 3552 ArgExpr = Arg.get(); 3553 Expr::EvalResult ArgResult1; 3554 // Check that sync scope is a constant literal 3555 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3556 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3557 << ArgExpr->getType(); 3558 3559 return false; 3560 } 3561 3562 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3563 llvm::APSInt Result; 3564 3565 // We can't check the value of a dependent argument. 3566 Expr *Arg = TheCall->getArg(ArgNum); 3567 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3568 return false; 3569 3570 // Check constant-ness first. 3571 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3572 return true; 3573 3574 int64_t Val = Result.getSExtValue(); 3575 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3576 return false; 3577 3578 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3579 << Arg->getSourceRange(); 3580 } 3581 3582 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3583 unsigned BuiltinID, 3584 CallExpr *TheCall) { 3585 // CodeGenFunction can also detect this, but this gives a better error 3586 // message. 3587 bool FeatureMissing = false; 3588 SmallVector<StringRef> ReqFeatures; 3589 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3590 Features.split(ReqFeatures, ','); 3591 3592 // Check if each required feature is included 3593 for (StringRef F : ReqFeatures) { 3594 if (TI.hasFeature(F)) 3595 continue; 3596 3597 // If the feature is 64bit, alter the string so it will print better in 3598 // the diagnostic. 3599 if (F == "64bit") 3600 F = "RV64"; 3601 3602 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3603 F.consume_front("experimental-"); 3604 std::string FeatureStr = F.str(); 3605 FeatureStr[0] = std::toupper(FeatureStr[0]); 3606 3607 // Error message 3608 FeatureMissing = true; 3609 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3610 << TheCall->getSourceRange() << StringRef(FeatureStr); 3611 } 3612 3613 if (FeatureMissing) 3614 return true; 3615 3616 switch (BuiltinID) { 3617 case RISCV::BI__builtin_rvv_vsetvli: 3618 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3619 CheckRISCVLMUL(TheCall, 2); 3620 case RISCV::BI__builtin_rvv_vsetvlimax: 3621 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3622 CheckRISCVLMUL(TheCall, 1); 3623 case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1: 3624 case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1: 3625 case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1: 3626 case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1: 3627 case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1: 3628 case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1: 3629 case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1: 3630 case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1: 3631 case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1: 3632 case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1: 3633 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2: 3634 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2: 3635 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2: 3636 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2: 3637 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2: 3638 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2: 3639 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2: 3640 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2: 3641 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2: 3642 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2: 3643 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4: 3644 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4: 3645 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4: 3646 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4: 3647 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4: 3648 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4: 3649 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4: 3650 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4: 3651 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4: 3652 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4: 3653 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3654 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1: 3655 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1: 3656 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1: 3657 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1: 3658 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1: 3659 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1: 3660 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1: 3661 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1: 3662 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1: 3663 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1: 3664 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2: 3665 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2: 3666 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2: 3667 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2: 3668 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2: 3669 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2: 3670 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2: 3671 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2: 3672 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2: 3673 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2: 3674 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3675 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1: 3676 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1: 3677 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1: 3678 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1: 3679 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1: 3680 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1: 3681 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1: 3682 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1: 3683 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1: 3684 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1: 3685 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3686 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2: 3687 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2: 3688 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2: 3689 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2: 3690 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2: 3691 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2: 3692 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2: 3693 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2: 3694 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2: 3695 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2: 3696 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4: 3697 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4: 3698 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4: 3699 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4: 3700 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4: 3701 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4: 3702 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4: 3703 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4: 3704 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4: 3705 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4: 3706 case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8: 3707 case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8: 3708 case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8: 3709 case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8: 3710 case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8: 3711 case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8: 3712 case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8: 3713 case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8: 3714 case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8: 3715 case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8: 3716 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3717 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4: 3718 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4: 3719 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4: 3720 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4: 3721 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4: 3722 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4: 3723 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4: 3724 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4: 3725 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4: 3726 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4: 3727 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8: 3728 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8: 3729 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8: 3730 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8: 3731 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8: 3732 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8: 3733 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8: 3734 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8: 3735 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8: 3736 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8: 3737 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3738 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8: 3739 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8: 3740 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8: 3741 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8: 3742 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8: 3743 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8: 3744 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8: 3745 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8: 3746 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8: 3747 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8: 3748 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3749 } 3750 3751 return false; 3752 } 3753 3754 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3755 CallExpr *TheCall) { 3756 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3757 Expr *Arg = TheCall->getArg(0); 3758 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3759 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3760 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3761 << Arg->getSourceRange(); 3762 } 3763 3764 // For intrinsics which take an immediate value as part of the instruction, 3765 // range check them here. 3766 unsigned i = 0, l = 0, u = 0; 3767 switch (BuiltinID) { 3768 default: return false; 3769 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3770 case SystemZ::BI__builtin_s390_verimb: 3771 case SystemZ::BI__builtin_s390_verimh: 3772 case SystemZ::BI__builtin_s390_verimf: 3773 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3774 case SystemZ::BI__builtin_s390_vfaeb: 3775 case SystemZ::BI__builtin_s390_vfaeh: 3776 case SystemZ::BI__builtin_s390_vfaef: 3777 case SystemZ::BI__builtin_s390_vfaebs: 3778 case SystemZ::BI__builtin_s390_vfaehs: 3779 case SystemZ::BI__builtin_s390_vfaefs: 3780 case SystemZ::BI__builtin_s390_vfaezb: 3781 case SystemZ::BI__builtin_s390_vfaezh: 3782 case SystemZ::BI__builtin_s390_vfaezf: 3783 case SystemZ::BI__builtin_s390_vfaezbs: 3784 case SystemZ::BI__builtin_s390_vfaezhs: 3785 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3786 case SystemZ::BI__builtin_s390_vfisb: 3787 case SystemZ::BI__builtin_s390_vfidb: 3788 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3789 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3790 case SystemZ::BI__builtin_s390_vftcisb: 3791 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3792 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3793 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3794 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3795 case SystemZ::BI__builtin_s390_vstrcb: 3796 case SystemZ::BI__builtin_s390_vstrch: 3797 case SystemZ::BI__builtin_s390_vstrcf: 3798 case SystemZ::BI__builtin_s390_vstrczb: 3799 case SystemZ::BI__builtin_s390_vstrczh: 3800 case SystemZ::BI__builtin_s390_vstrczf: 3801 case SystemZ::BI__builtin_s390_vstrcbs: 3802 case SystemZ::BI__builtin_s390_vstrchs: 3803 case SystemZ::BI__builtin_s390_vstrcfs: 3804 case SystemZ::BI__builtin_s390_vstrczbs: 3805 case SystemZ::BI__builtin_s390_vstrczhs: 3806 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3807 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3808 case SystemZ::BI__builtin_s390_vfminsb: 3809 case SystemZ::BI__builtin_s390_vfmaxsb: 3810 case SystemZ::BI__builtin_s390_vfmindb: 3811 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3812 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3813 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3814 case SystemZ::BI__builtin_s390_vclfnhs: 3815 case SystemZ::BI__builtin_s390_vclfnls: 3816 case SystemZ::BI__builtin_s390_vcfn: 3817 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3818 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3819 } 3820 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3821 } 3822 3823 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3824 /// This checks that the target supports __builtin_cpu_supports and 3825 /// that the string argument is constant and valid. 3826 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3827 CallExpr *TheCall) { 3828 Expr *Arg = TheCall->getArg(0); 3829 3830 // Check if the argument is a string literal. 3831 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3832 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3833 << Arg->getSourceRange(); 3834 3835 // Check the contents of the string. 3836 StringRef Feature = 3837 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3838 if (!TI.validateCpuSupports(Feature)) 3839 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3840 << Arg->getSourceRange(); 3841 return false; 3842 } 3843 3844 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3845 /// This checks that the target supports __builtin_cpu_is and 3846 /// that the string argument is constant and valid. 3847 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3848 Expr *Arg = TheCall->getArg(0); 3849 3850 // Check if the argument is a string literal. 3851 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3852 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3853 << Arg->getSourceRange(); 3854 3855 // Check the contents of the string. 3856 StringRef Feature = 3857 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3858 if (!TI.validateCpuIs(Feature)) 3859 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3860 << Arg->getSourceRange(); 3861 return false; 3862 } 3863 3864 // Check if the rounding mode is legal. 3865 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3866 // Indicates if this instruction has rounding control or just SAE. 3867 bool HasRC = false; 3868 3869 unsigned ArgNum = 0; 3870 switch (BuiltinID) { 3871 default: 3872 return false; 3873 case X86::BI__builtin_ia32_vcvttsd2si32: 3874 case X86::BI__builtin_ia32_vcvttsd2si64: 3875 case X86::BI__builtin_ia32_vcvttsd2usi32: 3876 case X86::BI__builtin_ia32_vcvttsd2usi64: 3877 case X86::BI__builtin_ia32_vcvttss2si32: 3878 case X86::BI__builtin_ia32_vcvttss2si64: 3879 case X86::BI__builtin_ia32_vcvttss2usi32: 3880 case X86::BI__builtin_ia32_vcvttss2usi64: 3881 case X86::BI__builtin_ia32_vcvttsh2si32: 3882 case X86::BI__builtin_ia32_vcvttsh2si64: 3883 case X86::BI__builtin_ia32_vcvttsh2usi32: 3884 case X86::BI__builtin_ia32_vcvttsh2usi64: 3885 ArgNum = 1; 3886 break; 3887 case X86::BI__builtin_ia32_maxpd512: 3888 case X86::BI__builtin_ia32_maxps512: 3889 case X86::BI__builtin_ia32_minpd512: 3890 case X86::BI__builtin_ia32_minps512: 3891 case X86::BI__builtin_ia32_maxph512: 3892 case X86::BI__builtin_ia32_minph512: 3893 ArgNum = 2; 3894 break; 3895 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3896 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3897 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3898 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3899 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3900 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3901 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3902 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3903 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3904 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3905 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3906 case X86::BI__builtin_ia32_vcvttph2w512_mask: 3907 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 3908 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 3909 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 3910 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 3911 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 3912 case X86::BI__builtin_ia32_exp2pd_mask: 3913 case X86::BI__builtin_ia32_exp2ps_mask: 3914 case X86::BI__builtin_ia32_getexppd512_mask: 3915 case X86::BI__builtin_ia32_getexpps512_mask: 3916 case X86::BI__builtin_ia32_getexpph512_mask: 3917 case X86::BI__builtin_ia32_rcp28pd_mask: 3918 case X86::BI__builtin_ia32_rcp28ps_mask: 3919 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3920 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3921 case X86::BI__builtin_ia32_vcomisd: 3922 case X86::BI__builtin_ia32_vcomiss: 3923 case X86::BI__builtin_ia32_vcomish: 3924 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3925 ArgNum = 3; 3926 break; 3927 case X86::BI__builtin_ia32_cmppd512_mask: 3928 case X86::BI__builtin_ia32_cmpps512_mask: 3929 case X86::BI__builtin_ia32_cmpsd_mask: 3930 case X86::BI__builtin_ia32_cmpss_mask: 3931 case X86::BI__builtin_ia32_cmpsh_mask: 3932 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 3933 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 3934 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3935 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3936 case X86::BI__builtin_ia32_getexpss128_round_mask: 3937 case X86::BI__builtin_ia32_getexpsh128_round_mask: 3938 case X86::BI__builtin_ia32_getmantpd512_mask: 3939 case X86::BI__builtin_ia32_getmantps512_mask: 3940 case X86::BI__builtin_ia32_getmantph512_mask: 3941 case X86::BI__builtin_ia32_maxsd_round_mask: 3942 case X86::BI__builtin_ia32_maxss_round_mask: 3943 case X86::BI__builtin_ia32_maxsh_round_mask: 3944 case X86::BI__builtin_ia32_minsd_round_mask: 3945 case X86::BI__builtin_ia32_minss_round_mask: 3946 case X86::BI__builtin_ia32_minsh_round_mask: 3947 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3948 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3949 case X86::BI__builtin_ia32_reducepd512_mask: 3950 case X86::BI__builtin_ia32_reduceps512_mask: 3951 case X86::BI__builtin_ia32_reduceph512_mask: 3952 case X86::BI__builtin_ia32_rndscalepd_mask: 3953 case X86::BI__builtin_ia32_rndscaleps_mask: 3954 case X86::BI__builtin_ia32_rndscaleph_mask: 3955 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3956 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3957 ArgNum = 4; 3958 break; 3959 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3960 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3961 case X86::BI__builtin_ia32_fixupimmps512_mask: 3962 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3963 case X86::BI__builtin_ia32_fixupimmsd_mask: 3964 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3965 case X86::BI__builtin_ia32_fixupimmss_mask: 3966 case X86::BI__builtin_ia32_fixupimmss_maskz: 3967 case X86::BI__builtin_ia32_getmantsd_round_mask: 3968 case X86::BI__builtin_ia32_getmantss_round_mask: 3969 case X86::BI__builtin_ia32_getmantsh_round_mask: 3970 case X86::BI__builtin_ia32_rangepd512_mask: 3971 case X86::BI__builtin_ia32_rangeps512_mask: 3972 case X86::BI__builtin_ia32_rangesd128_round_mask: 3973 case X86::BI__builtin_ia32_rangess128_round_mask: 3974 case X86::BI__builtin_ia32_reducesd_mask: 3975 case X86::BI__builtin_ia32_reducess_mask: 3976 case X86::BI__builtin_ia32_reducesh_mask: 3977 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3978 case X86::BI__builtin_ia32_rndscaless_round_mask: 3979 case X86::BI__builtin_ia32_rndscalesh_round_mask: 3980 ArgNum = 5; 3981 break; 3982 case X86::BI__builtin_ia32_vcvtsd2si64: 3983 case X86::BI__builtin_ia32_vcvtsd2si32: 3984 case X86::BI__builtin_ia32_vcvtsd2usi32: 3985 case X86::BI__builtin_ia32_vcvtsd2usi64: 3986 case X86::BI__builtin_ia32_vcvtss2si32: 3987 case X86::BI__builtin_ia32_vcvtss2si64: 3988 case X86::BI__builtin_ia32_vcvtss2usi32: 3989 case X86::BI__builtin_ia32_vcvtss2usi64: 3990 case X86::BI__builtin_ia32_vcvtsh2si32: 3991 case X86::BI__builtin_ia32_vcvtsh2si64: 3992 case X86::BI__builtin_ia32_vcvtsh2usi32: 3993 case X86::BI__builtin_ia32_vcvtsh2usi64: 3994 case X86::BI__builtin_ia32_sqrtpd512: 3995 case X86::BI__builtin_ia32_sqrtps512: 3996 case X86::BI__builtin_ia32_sqrtph512: 3997 ArgNum = 1; 3998 HasRC = true; 3999 break; 4000 case X86::BI__builtin_ia32_addph512: 4001 case X86::BI__builtin_ia32_divph512: 4002 case X86::BI__builtin_ia32_mulph512: 4003 case X86::BI__builtin_ia32_subph512: 4004 case X86::BI__builtin_ia32_addpd512: 4005 case X86::BI__builtin_ia32_addps512: 4006 case X86::BI__builtin_ia32_divpd512: 4007 case X86::BI__builtin_ia32_divps512: 4008 case X86::BI__builtin_ia32_mulpd512: 4009 case X86::BI__builtin_ia32_mulps512: 4010 case X86::BI__builtin_ia32_subpd512: 4011 case X86::BI__builtin_ia32_subps512: 4012 case X86::BI__builtin_ia32_cvtsi2sd64: 4013 case X86::BI__builtin_ia32_cvtsi2ss32: 4014 case X86::BI__builtin_ia32_cvtsi2ss64: 4015 case X86::BI__builtin_ia32_cvtusi2sd64: 4016 case X86::BI__builtin_ia32_cvtusi2ss32: 4017 case X86::BI__builtin_ia32_cvtusi2ss64: 4018 case X86::BI__builtin_ia32_vcvtusi2sh: 4019 case X86::BI__builtin_ia32_vcvtusi642sh: 4020 case X86::BI__builtin_ia32_vcvtsi2sh: 4021 case X86::BI__builtin_ia32_vcvtsi642sh: 4022 ArgNum = 2; 4023 HasRC = true; 4024 break; 4025 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4026 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4027 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4028 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4029 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4030 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4031 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4032 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4033 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4034 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4035 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4036 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4037 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4038 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4039 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4040 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4041 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4042 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4043 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4044 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4045 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4046 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4047 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4048 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4049 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4050 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4051 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4052 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4053 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4054 ArgNum = 3; 4055 HasRC = true; 4056 break; 4057 case X86::BI__builtin_ia32_addsh_round_mask: 4058 case X86::BI__builtin_ia32_addss_round_mask: 4059 case X86::BI__builtin_ia32_addsd_round_mask: 4060 case X86::BI__builtin_ia32_divsh_round_mask: 4061 case X86::BI__builtin_ia32_divss_round_mask: 4062 case X86::BI__builtin_ia32_divsd_round_mask: 4063 case X86::BI__builtin_ia32_mulsh_round_mask: 4064 case X86::BI__builtin_ia32_mulss_round_mask: 4065 case X86::BI__builtin_ia32_mulsd_round_mask: 4066 case X86::BI__builtin_ia32_subsh_round_mask: 4067 case X86::BI__builtin_ia32_subss_round_mask: 4068 case X86::BI__builtin_ia32_subsd_round_mask: 4069 case X86::BI__builtin_ia32_scalefph512_mask: 4070 case X86::BI__builtin_ia32_scalefpd512_mask: 4071 case X86::BI__builtin_ia32_scalefps512_mask: 4072 case X86::BI__builtin_ia32_scalefsd_round_mask: 4073 case X86::BI__builtin_ia32_scalefss_round_mask: 4074 case X86::BI__builtin_ia32_scalefsh_round_mask: 4075 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4076 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4077 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4078 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4079 case X86::BI__builtin_ia32_sqrtss_round_mask: 4080 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4081 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4082 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4083 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4084 case X86::BI__builtin_ia32_vfmaddss3_mask: 4085 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4086 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4087 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4088 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4089 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4090 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4091 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4092 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4093 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4094 case X86::BI__builtin_ia32_vfmaddps512_mask: 4095 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4096 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4097 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4098 case X86::BI__builtin_ia32_vfmaddph512_mask: 4099 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4100 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4101 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4102 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4103 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4104 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4105 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4106 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4107 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4108 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4109 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4110 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4111 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4112 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4113 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4114 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4115 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4116 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4117 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4118 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4119 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4120 case X86::BI__builtin_ia32_vfmulcsh_mask: 4121 case X86::BI__builtin_ia32_vfmulcph512_mask: 4122 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4123 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4124 ArgNum = 4; 4125 HasRC = true; 4126 break; 4127 } 4128 4129 llvm::APSInt Result; 4130 4131 // We can't check the value of a dependent argument. 4132 Expr *Arg = TheCall->getArg(ArgNum); 4133 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4134 return false; 4135 4136 // Check constant-ness first. 4137 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4138 return true; 4139 4140 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4141 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4142 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4143 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4144 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4145 Result == 8/*ROUND_NO_EXC*/ || 4146 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4147 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4148 return false; 4149 4150 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4151 << Arg->getSourceRange(); 4152 } 4153 4154 // Check if the gather/scatter scale is legal. 4155 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4156 CallExpr *TheCall) { 4157 unsigned ArgNum = 0; 4158 switch (BuiltinID) { 4159 default: 4160 return false; 4161 case X86::BI__builtin_ia32_gatherpfdpd: 4162 case X86::BI__builtin_ia32_gatherpfdps: 4163 case X86::BI__builtin_ia32_gatherpfqpd: 4164 case X86::BI__builtin_ia32_gatherpfqps: 4165 case X86::BI__builtin_ia32_scatterpfdpd: 4166 case X86::BI__builtin_ia32_scatterpfdps: 4167 case X86::BI__builtin_ia32_scatterpfqpd: 4168 case X86::BI__builtin_ia32_scatterpfqps: 4169 ArgNum = 3; 4170 break; 4171 case X86::BI__builtin_ia32_gatherd_pd: 4172 case X86::BI__builtin_ia32_gatherd_pd256: 4173 case X86::BI__builtin_ia32_gatherq_pd: 4174 case X86::BI__builtin_ia32_gatherq_pd256: 4175 case X86::BI__builtin_ia32_gatherd_ps: 4176 case X86::BI__builtin_ia32_gatherd_ps256: 4177 case X86::BI__builtin_ia32_gatherq_ps: 4178 case X86::BI__builtin_ia32_gatherq_ps256: 4179 case X86::BI__builtin_ia32_gatherd_q: 4180 case X86::BI__builtin_ia32_gatherd_q256: 4181 case X86::BI__builtin_ia32_gatherq_q: 4182 case X86::BI__builtin_ia32_gatherq_q256: 4183 case X86::BI__builtin_ia32_gatherd_d: 4184 case X86::BI__builtin_ia32_gatherd_d256: 4185 case X86::BI__builtin_ia32_gatherq_d: 4186 case X86::BI__builtin_ia32_gatherq_d256: 4187 case X86::BI__builtin_ia32_gather3div2df: 4188 case X86::BI__builtin_ia32_gather3div2di: 4189 case X86::BI__builtin_ia32_gather3div4df: 4190 case X86::BI__builtin_ia32_gather3div4di: 4191 case X86::BI__builtin_ia32_gather3div4sf: 4192 case X86::BI__builtin_ia32_gather3div4si: 4193 case X86::BI__builtin_ia32_gather3div8sf: 4194 case X86::BI__builtin_ia32_gather3div8si: 4195 case X86::BI__builtin_ia32_gather3siv2df: 4196 case X86::BI__builtin_ia32_gather3siv2di: 4197 case X86::BI__builtin_ia32_gather3siv4df: 4198 case X86::BI__builtin_ia32_gather3siv4di: 4199 case X86::BI__builtin_ia32_gather3siv4sf: 4200 case X86::BI__builtin_ia32_gather3siv4si: 4201 case X86::BI__builtin_ia32_gather3siv8sf: 4202 case X86::BI__builtin_ia32_gather3siv8si: 4203 case X86::BI__builtin_ia32_gathersiv8df: 4204 case X86::BI__builtin_ia32_gathersiv16sf: 4205 case X86::BI__builtin_ia32_gatherdiv8df: 4206 case X86::BI__builtin_ia32_gatherdiv16sf: 4207 case X86::BI__builtin_ia32_gathersiv8di: 4208 case X86::BI__builtin_ia32_gathersiv16si: 4209 case X86::BI__builtin_ia32_gatherdiv8di: 4210 case X86::BI__builtin_ia32_gatherdiv16si: 4211 case X86::BI__builtin_ia32_scatterdiv2df: 4212 case X86::BI__builtin_ia32_scatterdiv2di: 4213 case X86::BI__builtin_ia32_scatterdiv4df: 4214 case X86::BI__builtin_ia32_scatterdiv4di: 4215 case X86::BI__builtin_ia32_scatterdiv4sf: 4216 case X86::BI__builtin_ia32_scatterdiv4si: 4217 case X86::BI__builtin_ia32_scatterdiv8sf: 4218 case X86::BI__builtin_ia32_scatterdiv8si: 4219 case X86::BI__builtin_ia32_scattersiv2df: 4220 case X86::BI__builtin_ia32_scattersiv2di: 4221 case X86::BI__builtin_ia32_scattersiv4df: 4222 case X86::BI__builtin_ia32_scattersiv4di: 4223 case X86::BI__builtin_ia32_scattersiv4sf: 4224 case X86::BI__builtin_ia32_scattersiv4si: 4225 case X86::BI__builtin_ia32_scattersiv8sf: 4226 case X86::BI__builtin_ia32_scattersiv8si: 4227 case X86::BI__builtin_ia32_scattersiv8df: 4228 case X86::BI__builtin_ia32_scattersiv16sf: 4229 case X86::BI__builtin_ia32_scatterdiv8df: 4230 case X86::BI__builtin_ia32_scatterdiv16sf: 4231 case X86::BI__builtin_ia32_scattersiv8di: 4232 case X86::BI__builtin_ia32_scattersiv16si: 4233 case X86::BI__builtin_ia32_scatterdiv8di: 4234 case X86::BI__builtin_ia32_scatterdiv16si: 4235 ArgNum = 4; 4236 break; 4237 } 4238 4239 llvm::APSInt Result; 4240 4241 // We can't check the value of a dependent argument. 4242 Expr *Arg = TheCall->getArg(ArgNum); 4243 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4244 return false; 4245 4246 // Check constant-ness first. 4247 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4248 return true; 4249 4250 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4251 return false; 4252 4253 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4254 << Arg->getSourceRange(); 4255 } 4256 4257 enum { TileRegLow = 0, TileRegHigh = 7 }; 4258 4259 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4260 ArrayRef<int> ArgNums) { 4261 for (int ArgNum : ArgNums) { 4262 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4263 return true; 4264 } 4265 return false; 4266 } 4267 4268 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4269 ArrayRef<int> ArgNums) { 4270 // Because the max number of tile register is TileRegHigh + 1, so here we use 4271 // each bit to represent the usage of them in bitset. 4272 std::bitset<TileRegHigh + 1> ArgValues; 4273 for (int ArgNum : ArgNums) { 4274 Expr *Arg = TheCall->getArg(ArgNum); 4275 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4276 continue; 4277 4278 llvm::APSInt Result; 4279 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4280 return true; 4281 int ArgExtValue = Result.getExtValue(); 4282 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4283 "Incorrect tile register num."); 4284 if (ArgValues.test(ArgExtValue)) 4285 return Diag(TheCall->getBeginLoc(), 4286 diag::err_x86_builtin_tile_arg_duplicate) 4287 << TheCall->getArg(ArgNum)->getSourceRange(); 4288 ArgValues.set(ArgExtValue); 4289 } 4290 return false; 4291 } 4292 4293 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4294 ArrayRef<int> ArgNums) { 4295 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4296 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4297 } 4298 4299 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4300 switch (BuiltinID) { 4301 default: 4302 return false; 4303 case X86::BI__builtin_ia32_tileloadd64: 4304 case X86::BI__builtin_ia32_tileloaddt164: 4305 case X86::BI__builtin_ia32_tilestored64: 4306 case X86::BI__builtin_ia32_tilezero: 4307 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4308 case X86::BI__builtin_ia32_tdpbssd: 4309 case X86::BI__builtin_ia32_tdpbsud: 4310 case X86::BI__builtin_ia32_tdpbusd: 4311 case X86::BI__builtin_ia32_tdpbuud: 4312 case X86::BI__builtin_ia32_tdpbf16ps: 4313 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4314 } 4315 } 4316 static bool isX86_32Builtin(unsigned BuiltinID) { 4317 // These builtins only work on x86-32 targets. 4318 switch (BuiltinID) { 4319 case X86::BI__builtin_ia32_readeflags_u32: 4320 case X86::BI__builtin_ia32_writeeflags_u32: 4321 return true; 4322 } 4323 4324 return false; 4325 } 4326 4327 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4328 CallExpr *TheCall) { 4329 if (BuiltinID == X86::BI__builtin_cpu_supports) 4330 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4331 4332 if (BuiltinID == X86::BI__builtin_cpu_is) 4333 return SemaBuiltinCpuIs(*this, TI, TheCall); 4334 4335 // Check for 32-bit only builtins on a 64-bit target. 4336 const llvm::Triple &TT = TI.getTriple(); 4337 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4338 return Diag(TheCall->getCallee()->getBeginLoc(), 4339 diag::err_32_bit_builtin_64_bit_tgt); 4340 4341 // If the intrinsic has rounding or SAE make sure its valid. 4342 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4343 return true; 4344 4345 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4346 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4347 return true; 4348 4349 // If the intrinsic has a tile arguments, make sure they are valid. 4350 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4351 return true; 4352 4353 // For intrinsics which take an immediate value as part of the instruction, 4354 // range check them here. 4355 int i = 0, l = 0, u = 0; 4356 switch (BuiltinID) { 4357 default: 4358 return false; 4359 case X86::BI__builtin_ia32_vec_ext_v2si: 4360 case X86::BI__builtin_ia32_vec_ext_v2di: 4361 case X86::BI__builtin_ia32_vextractf128_pd256: 4362 case X86::BI__builtin_ia32_vextractf128_ps256: 4363 case X86::BI__builtin_ia32_vextractf128_si256: 4364 case X86::BI__builtin_ia32_extract128i256: 4365 case X86::BI__builtin_ia32_extractf64x4_mask: 4366 case X86::BI__builtin_ia32_extracti64x4_mask: 4367 case X86::BI__builtin_ia32_extractf32x8_mask: 4368 case X86::BI__builtin_ia32_extracti32x8_mask: 4369 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4370 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4371 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4372 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4373 i = 1; l = 0; u = 1; 4374 break; 4375 case X86::BI__builtin_ia32_vec_set_v2di: 4376 case X86::BI__builtin_ia32_vinsertf128_pd256: 4377 case X86::BI__builtin_ia32_vinsertf128_ps256: 4378 case X86::BI__builtin_ia32_vinsertf128_si256: 4379 case X86::BI__builtin_ia32_insert128i256: 4380 case X86::BI__builtin_ia32_insertf32x8: 4381 case X86::BI__builtin_ia32_inserti32x8: 4382 case X86::BI__builtin_ia32_insertf64x4: 4383 case X86::BI__builtin_ia32_inserti64x4: 4384 case X86::BI__builtin_ia32_insertf64x2_256: 4385 case X86::BI__builtin_ia32_inserti64x2_256: 4386 case X86::BI__builtin_ia32_insertf32x4_256: 4387 case X86::BI__builtin_ia32_inserti32x4_256: 4388 i = 2; l = 0; u = 1; 4389 break; 4390 case X86::BI__builtin_ia32_vpermilpd: 4391 case X86::BI__builtin_ia32_vec_ext_v4hi: 4392 case X86::BI__builtin_ia32_vec_ext_v4si: 4393 case X86::BI__builtin_ia32_vec_ext_v4sf: 4394 case X86::BI__builtin_ia32_vec_ext_v4di: 4395 case X86::BI__builtin_ia32_extractf32x4_mask: 4396 case X86::BI__builtin_ia32_extracti32x4_mask: 4397 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4398 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4399 i = 1; l = 0; u = 3; 4400 break; 4401 case X86::BI_mm_prefetch: 4402 case X86::BI__builtin_ia32_vec_ext_v8hi: 4403 case X86::BI__builtin_ia32_vec_ext_v8si: 4404 i = 1; l = 0; u = 7; 4405 break; 4406 case X86::BI__builtin_ia32_sha1rnds4: 4407 case X86::BI__builtin_ia32_blendpd: 4408 case X86::BI__builtin_ia32_shufpd: 4409 case X86::BI__builtin_ia32_vec_set_v4hi: 4410 case X86::BI__builtin_ia32_vec_set_v4si: 4411 case X86::BI__builtin_ia32_vec_set_v4di: 4412 case X86::BI__builtin_ia32_shuf_f32x4_256: 4413 case X86::BI__builtin_ia32_shuf_f64x2_256: 4414 case X86::BI__builtin_ia32_shuf_i32x4_256: 4415 case X86::BI__builtin_ia32_shuf_i64x2_256: 4416 case X86::BI__builtin_ia32_insertf64x2_512: 4417 case X86::BI__builtin_ia32_inserti64x2_512: 4418 case X86::BI__builtin_ia32_insertf32x4: 4419 case X86::BI__builtin_ia32_inserti32x4: 4420 i = 2; l = 0; u = 3; 4421 break; 4422 case X86::BI__builtin_ia32_vpermil2pd: 4423 case X86::BI__builtin_ia32_vpermil2pd256: 4424 case X86::BI__builtin_ia32_vpermil2ps: 4425 case X86::BI__builtin_ia32_vpermil2ps256: 4426 i = 3; l = 0; u = 3; 4427 break; 4428 case X86::BI__builtin_ia32_cmpb128_mask: 4429 case X86::BI__builtin_ia32_cmpw128_mask: 4430 case X86::BI__builtin_ia32_cmpd128_mask: 4431 case X86::BI__builtin_ia32_cmpq128_mask: 4432 case X86::BI__builtin_ia32_cmpb256_mask: 4433 case X86::BI__builtin_ia32_cmpw256_mask: 4434 case X86::BI__builtin_ia32_cmpd256_mask: 4435 case X86::BI__builtin_ia32_cmpq256_mask: 4436 case X86::BI__builtin_ia32_cmpb512_mask: 4437 case X86::BI__builtin_ia32_cmpw512_mask: 4438 case X86::BI__builtin_ia32_cmpd512_mask: 4439 case X86::BI__builtin_ia32_cmpq512_mask: 4440 case X86::BI__builtin_ia32_ucmpb128_mask: 4441 case X86::BI__builtin_ia32_ucmpw128_mask: 4442 case X86::BI__builtin_ia32_ucmpd128_mask: 4443 case X86::BI__builtin_ia32_ucmpq128_mask: 4444 case X86::BI__builtin_ia32_ucmpb256_mask: 4445 case X86::BI__builtin_ia32_ucmpw256_mask: 4446 case X86::BI__builtin_ia32_ucmpd256_mask: 4447 case X86::BI__builtin_ia32_ucmpq256_mask: 4448 case X86::BI__builtin_ia32_ucmpb512_mask: 4449 case X86::BI__builtin_ia32_ucmpw512_mask: 4450 case X86::BI__builtin_ia32_ucmpd512_mask: 4451 case X86::BI__builtin_ia32_ucmpq512_mask: 4452 case X86::BI__builtin_ia32_vpcomub: 4453 case X86::BI__builtin_ia32_vpcomuw: 4454 case X86::BI__builtin_ia32_vpcomud: 4455 case X86::BI__builtin_ia32_vpcomuq: 4456 case X86::BI__builtin_ia32_vpcomb: 4457 case X86::BI__builtin_ia32_vpcomw: 4458 case X86::BI__builtin_ia32_vpcomd: 4459 case X86::BI__builtin_ia32_vpcomq: 4460 case X86::BI__builtin_ia32_vec_set_v8hi: 4461 case X86::BI__builtin_ia32_vec_set_v8si: 4462 i = 2; l = 0; u = 7; 4463 break; 4464 case X86::BI__builtin_ia32_vpermilpd256: 4465 case X86::BI__builtin_ia32_roundps: 4466 case X86::BI__builtin_ia32_roundpd: 4467 case X86::BI__builtin_ia32_roundps256: 4468 case X86::BI__builtin_ia32_roundpd256: 4469 case X86::BI__builtin_ia32_getmantpd128_mask: 4470 case X86::BI__builtin_ia32_getmantpd256_mask: 4471 case X86::BI__builtin_ia32_getmantps128_mask: 4472 case X86::BI__builtin_ia32_getmantps256_mask: 4473 case X86::BI__builtin_ia32_getmantpd512_mask: 4474 case X86::BI__builtin_ia32_getmantps512_mask: 4475 case X86::BI__builtin_ia32_getmantph128_mask: 4476 case X86::BI__builtin_ia32_getmantph256_mask: 4477 case X86::BI__builtin_ia32_getmantph512_mask: 4478 case X86::BI__builtin_ia32_vec_ext_v16qi: 4479 case X86::BI__builtin_ia32_vec_ext_v16hi: 4480 i = 1; l = 0; u = 15; 4481 break; 4482 case X86::BI__builtin_ia32_pblendd128: 4483 case X86::BI__builtin_ia32_blendps: 4484 case X86::BI__builtin_ia32_blendpd256: 4485 case X86::BI__builtin_ia32_shufpd256: 4486 case X86::BI__builtin_ia32_roundss: 4487 case X86::BI__builtin_ia32_roundsd: 4488 case X86::BI__builtin_ia32_rangepd128_mask: 4489 case X86::BI__builtin_ia32_rangepd256_mask: 4490 case X86::BI__builtin_ia32_rangepd512_mask: 4491 case X86::BI__builtin_ia32_rangeps128_mask: 4492 case X86::BI__builtin_ia32_rangeps256_mask: 4493 case X86::BI__builtin_ia32_rangeps512_mask: 4494 case X86::BI__builtin_ia32_getmantsd_round_mask: 4495 case X86::BI__builtin_ia32_getmantss_round_mask: 4496 case X86::BI__builtin_ia32_getmantsh_round_mask: 4497 case X86::BI__builtin_ia32_vec_set_v16qi: 4498 case X86::BI__builtin_ia32_vec_set_v16hi: 4499 i = 2; l = 0; u = 15; 4500 break; 4501 case X86::BI__builtin_ia32_vec_ext_v32qi: 4502 i = 1; l = 0; u = 31; 4503 break; 4504 case X86::BI__builtin_ia32_cmpps: 4505 case X86::BI__builtin_ia32_cmpss: 4506 case X86::BI__builtin_ia32_cmppd: 4507 case X86::BI__builtin_ia32_cmpsd: 4508 case X86::BI__builtin_ia32_cmpps256: 4509 case X86::BI__builtin_ia32_cmppd256: 4510 case X86::BI__builtin_ia32_cmpps128_mask: 4511 case X86::BI__builtin_ia32_cmppd128_mask: 4512 case X86::BI__builtin_ia32_cmpps256_mask: 4513 case X86::BI__builtin_ia32_cmppd256_mask: 4514 case X86::BI__builtin_ia32_cmpps512_mask: 4515 case X86::BI__builtin_ia32_cmppd512_mask: 4516 case X86::BI__builtin_ia32_cmpsd_mask: 4517 case X86::BI__builtin_ia32_cmpss_mask: 4518 case X86::BI__builtin_ia32_vec_set_v32qi: 4519 i = 2; l = 0; u = 31; 4520 break; 4521 case X86::BI__builtin_ia32_permdf256: 4522 case X86::BI__builtin_ia32_permdi256: 4523 case X86::BI__builtin_ia32_permdf512: 4524 case X86::BI__builtin_ia32_permdi512: 4525 case X86::BI__builtin_ia32_vpermilps: 4526 case X86::BI__builtin_ia32_vpermilps256: 4527 case X86::BI__builtin_ia32_vpermilpd512: 4528 case X86::BI__builtin_ia32_vpermilps512: 4529 case X86::BI__builtin_ia32_pshufd: 4530 case X86::BI__builtin_ia32_pshufd256: 4531 case X86::BI__builtin_ia32_pshufd512: 4532 case X86::BI__builtin_ia32_pshufhw: 4533 case X86::BI__builtin_ia32_pshufhw256: 4534 case X86::BI__builtin_ia32_pshufhw512: 4535 case X86::BI__builtin_ia32_pshuflw: 4536 case X86::BI__builtin_ia32_pshuflw256: 4537 case X86::BI__builtin_ia32_pshuflw512: 4538 case X86::BI__builtin_ia32_vcvtps2ph: 4539 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4540 case X86::BI__builtin_ia32_vcvtps2ph256: 4541 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4542 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4543 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4544 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4545 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4546 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4547 case X86::BI__builtin_ia32_rndscaleps_mask: 4548 case X86::BI__builtin_ia32_rndscalepd_mask: 4549 case X86::BI__builtin_ia32_rndscaleph_mask: 4550 case X86::BI__builtin_ia32_reducepd128_mask: 4551 case X86::BI__builtin_ia32_reducepd256_mask: 4552 case X86::BI__builtin_ia32_reducepd512_mask: 4553 case X86::BI__builtin_ia32_reduceps128_mask: 4554 case X86::BI__builtin_ia32_reduceps256_mask: 4555 case X86::BI__builtin_ia32_reduceps512_mask: 4556 case X86::BI__builtin_ia32_reduceph128_mask: 4557 case X86::BI__builtin_ia32_reduceph256_mask: 4558 case X86::BI__builtin_ia32_reduceph512_mask: 4559 case X86::BI__builtin_ia32_prold512: 4560 case X86::BI__builtin_ia32_prolq512: 4561 case X86::BI__builtin_ia32_prold128: 4562 case X86::BI__builtin_ia32_prold256: 4563 case X86::BI__builtin_ia32_prolq128: 4564 case X86::BI__builtin_ia32_prolq256: 4565 case X86::BI__builtin_ia32_prord512: 4566 case X86::BI__builtin_ia32_prorq512: 4567 case X86::BI__builtin_ia32_prord128: 4568 case X86::BI__builtin_ia32_prord256: 4569 case X86::BI__builtin_ia32_prorq128: 4570 case X86::BI__builtin_ia32_prorq256: 4571 case X86::BI__builtin_ia32_fpclasspd128_mask: 4572 case X86::BI__builtin_ia32_fpclasspd256_mask: 4573 case X86::BI__builtin_ia32_fpclassps128_mask: 4574 case X86::BI__builtin_ia32_fpclassps256_mask: 4575 case X86::BI__builtin_ia32_fpclassps512_mask: 4576 case X86::BI__builtin_ia32_fpclasspd512_mask: 4577 case X86::BI__builtin_ia32_fpclassph128_mask: 4578 case X86::BI__builtin_ia32_fpclassph256_mask: 4579 case X86::BI__builtin_ia32_fpclassph512_mask: 4580 case X86::BI__builtin_ia32_fpclasssd_mask: 4581 case X86::BI__builtin_ia32_fpclassss_mask: 4582 case X86::BI__builtin_ia32_fpclasssh_mask: 4583 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4584 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4585 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4586 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4587 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4588 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4589 case X86::BI__builtin_ia32_kshiftliqi: 4590 case X86::BI__builtin_ia32_kshiftlihi: 4591 case X86::BI__builtin_ia32_kshiftlisi: 4592 case X86::BI__builtin_ia32_kshiftlidi: 4593 case X86::BI__builtin_ia32_kshiftriqi: 4594 case X86::BI__builtin_ia32_kshiftrihi: 4595 case X86::BI__builtin_ia32_kshiftrisi: 4596 case X86::BI__builtin_ia32_kshiftridi: 4597 i = 1; l = 0; u = 255; 4598 break; 4599 case X86::BI__builtin_ia32_vperm2f128_pd256: 4600 case X86::BI__builtin_ia32_vperm2f128_ps256: 4601 case X86::BI__builtin_ia32_vperm2f128_si256: 4602 case X86::BI__builtin_ia32_permti256: 4603 case X86::BI__builtin_ia32_pblendw128: 4604 case X86::BI__builtin_ia32_pblendw256: 4605 case X86::BI__builtin_ia32_blendps256: 4606 case X86::BI__builtin_ia32_pblendd256: 4607 case X86::BI__builtin_ia32_palignr128: 4608 case X86::BI__builtin_ia32_palignr256: 4609 case X86::BI__builtin_ia32_palignr512: 4610 case X86::BI__builtin_ia32_alignq512: 4611 case X86::BI__builtin_ia32_alignd512: 4612 case X86::BI__builtin_ia32_alignd128: 4613 case X86::BI__builtin_ia32_alignd256: 4614 case X86::BI__builtin_ia32_alignq128: 4615 case X86::BI__builtin_ia32_alignq256: 4616 case X86::BI__builtin_ia32_vcomisd: 4617 case X86::BI__builtin_ia32_vcomiss: 4618 case X86::BI__builtin_ia32_shuf_f32x4: 4619 case X86::BI__builtin_ia32_shuf_f64x2: 4620 case X86::BI__builtin_ia32_shuf_i32x4: 4621 case X86::BI__builtin_ia32_shuf_i64x2: 4622 case X86::BI__builtin_ia32_shufpd512: 4623 case X86::BI__builtin_ia32_shufps: 4624 case X86::BI__builtin_ia32_shufps256: 4625 case X86::BI__builtin_ia32_shufps512: 4626 case X86::BI__builtin_ia32_dbpsadbw128: 4627 case X86::BI__builtin_ia32_dbpsadbw256: 4628 case X86::BI__builtin_ia32_dbpsadbw512: 4629 case X86::BI__builtin_ia32_vpshldd128: 4630 case X86::BI__builtin_ia32_vpshldd256: 4631 case X86::BI__builtin_ia32_vpshldd512: 4632 case X86::BI__builtin_ia32_vpshldq128: 4633 case X86::BI__builtin_ia32_vpshldq256: 4634 case X86::BI__builtin_ia32_vpshldq512: 4635 case X86::BI__builtin_ia32_vpshldw128: 4636 case X86::BI__builtin_ia32_vpshldw256: 4637 case X86::BI__builtin_ia32_vpshldw512: 4638 case X86::BI__builtin_ia32_vpshrdd128: 4639 case X86::BI__builtin_ia32_vpshrdd256: 4640 case X86::BI__builtin_ia32_vpshrdd512: 4641 case X86::BI__builtin_ia32_vpshrdq128: 4642 case X86::BI__builtin_ia32_vpshrdq256: 4643 case X86::BI__builtin_ia32_vpshrdq512: 4644 case X86::BI__builtin_ia32_vpshrdw128: 4645 case X86::BI__builtin_ia32_vpshrdw256: 4646 case X86::BI__builtin_ia32_vpshrdw512: 4647 i = 2; l = 0; u = 255; 4648 break; 4649 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4650 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4651 case X86::BI__builtin_ia32_fixupimmps512_mask: 4652 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4653 case X86::BI__builtin_ia32_fixupimmsd_mask: 4654 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4655 case X86::BI__builtin_ia32_fixupimmss_mask: 4656 case X86::BI__builtin_ia32_fixupimmss_maskz: 4657 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4658 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4659 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4660 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4661 case X86::BI__builtin_ia32_fixupimmps128_mask: 4662 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4663 case X86::BI__builtin_ia32_fixupimmps256_mask: 4664 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4665 case X86::BI__builtin_ia32_pternlogd512_mask: 4666 case X86::BI__builtin_ia32_pternlogd512_maskz: 4667 case X86::BI__builtin_ia32_pternlogq512_mask: 4668 case X86::BI__builtin_ia32_pternlogq512_maskz: 4669 case X86::BI__builtin_ia32_pternlogd128_mask: 4670 case X86::BI__builtin_ia32_pternlogd128_maskz: 4671 case X86::BI__builtin_ia32_pternlogd256_mask: 4672 case X86::BI__builtin_ia32_pternlogd256_maskz: 4673 case X86::BI__builtin_ia32_pternlogq128_mask: 4674 case X86::BI__builtin_ia32_pternlogq128_maskz: 4675 case X86::BI__builtin_ia32_pternlogq256_mask: 4676 case X86::BI__builtin_ia32_pternlogq256_maskz: 4677 i = 3; l = 0; u = 255; 4678 break; 4679 case X86::BI__builtin_ia32_gatherpfdpd: 4680 case X86::BI__builtin_ia32_gatherpfdps: 4681 case X86::BI__builtin_ia32_gatherpfqpd: 4682 case X86::BI__builtin_ia32_gatherpfqps: 4683 case X86::BI__builtin_ia32_scatterpfdpd: 4684 case X86::BI__builtin_ia32_scatterpfdps: 4685 case X86::BI__builtin_ia32_scatterpfqpd: 4686 case X86::BI__builtin_ia32_scatterpfqps: 4687 i = 4; l = 2; u = 3; 4688 break; 4689 case X86::BI__builtin_ia32_reducesd_mask: 4690 case X86::BI__builtin_ia32_reducess_mask: 4691 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4692 case X86::BI__builtin_ia32_rndscaless_round_mask: 4693 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4694 case X86::BI__builtin_ia32_reducesh_mask: 4695 i = 4; l = 0; u = 255; 4696 break; 4697 } 4698 4699 // Note that we don't force a hard error on the range check here, allowing 4700 // template-generated or macro-generated dead code to potentially have out-of- 4701 // range values. These need to code generate, but don't need to necessarily 4702 // make any sense. We use a warning that defaults to an error. 4703 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4704 } 4705 4706 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4707 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4708 /// Returns true when the format fits the function and the FormatStringInfo has 4709 /// been populated. 4710 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4711 FormatStringInfo *FSI) { 4712 FSI->HasVAListArg = Format->getFirstArg() == 0; 4713 FSI->FormatIdx = Format->getFormatIdx() - 1; 4714 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4715 4716 // The way the format attribute works in GCC, the implicit this argument 4717 // of member functions is counted. However, it doesn't appear in our own 4718 // lists, so decrement format_idx in that case. 4719 if (IsCXXMember) { 4720 if(FSI->FormatIdx == 0) 4721 return false; 4722 --FSI->FormatIdx; 4723 if (FSI->FirstDataArg != 0) 4724 --FSI->FirstDataArg; 4725 } 4726 return true; 4727 } 4728 4729 /// Checks if a the given expression evaluates to null. 4730 /// 4731 /// Returns true if the value evaluates to null. 4732 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4733 // If the expression has non-null type, it doesn't evaluate to null. 4734 if (auto nullability 4735 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4736 if (*nullability == NullabilityKind::NonNull) 4737 return false; 4738 } 4739 4740 // As a special case, transparent unions initialized with zero are 4741 // considered null for the purposes of the nonnull attribute. 4742 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4743 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4744 if (const CompoundLiteralExpr *CLE = 4745 dyn_cast<CompoundLiteralExpr>(Expr)) 4746 if (const InitListExpr *ILE = 4747 dyn_cast<InitListExpr>(CLE->getInitializer())) 4748 Expr = ILE->getInit(0); 4749 } 4750 4751 bool Result; 4752 return (!Expr->isValueDependent() && 4753 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4754 !Result); 4755 } 4756 4757 static void CheckNonNullArgument(Sema &S, 4758 const Expr *ArgExpr, 4759 SourceLocation CallSiteLoc) { 4760 if (CheckNonNullExpr(S, ArgExpr)) 4761 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4762 S.PDiag(diag::warn_null_arg) 4763 << ArgExpr->getSourceRange()); 4764 } 4765 4766 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4767 FormatStringInfo FSI; 4768 if ((GetFormatStringType(Format) == FST_NSString) && 4769 getFormatStringInfo(Format, false, &FSI)) { 4770 Idx = FSI.FormatIdx; 4771 return true; 4772 } 4773 return false; 4774 } 4775 4776 /// Diagnose use of %s directive in an NSString which is being passed 4777 /// as formatting string to formatting method. 4778 static void 4779 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4780 const NamedDecl *FDecl, 4781 Expr **Args, 4782 unsigned NumArgs) { 4783 unsigned Idx = 0; 4784 bool Format = false; 4785 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4786 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4787 Idx = 2; 4788 Format = true; 4789 } 4790 else 4791 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4792 if (S.GetFormatNSStringIdx(I, Idx)) { 4793 Format = true; 4794 break; 4795 } 4796 } 4797 if (!Format || NumArgs <= Idx) 4798 return; 4799 const Expr *FormatExpr = Args[Idx]; 4800 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4801 FormatExpr = CSCE->getSubExpr(); 4802 const StringLiteral *FormatString; 4803 if (const ObjCStringLiteral *OSL = 4804 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4805 FormatString = OSL->getString(); 4806 else 4807 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4808 if (!FormatString) 4809 return; 4810 if (S.FormatStringHasSArg(FormatString)) { 4811 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4812 << "%s" << 1 << 1; 4813 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4814 << FDecl->getDeclName(); 4815 } 4816 } 4817 4818 /// Determine whether the given type has a non-null nullability annotation. 4819 static bool isNonNullType(ASTContext &ctx, QualType type) { 4820 if (auto nullability = type->getNullability(ctx)) 4821 return *nullability == NullabilityKind::NonNull; 4822 4823 return false; 4824 } 4825 4826 static void CheckNonNullArguments(Sema &S, 4827 const NamedDecl *FDecl, 4828 const FunctionProtoType *Proto, 4829 ArrayRef<const Expr *> Args, 4830 SourceLocation CallSiteLoc) { 4831 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4832 4833 // Already checked by by constant evaluator. 4834 if (S.isConstantEvaluated()) 4835 return; 4836 // Check the attributes attached to the method/function itself. 4837 llvm::SmallBitVector NonNullArgs; 4838 if (FDecl) { 4839 // Handle the nonnull attribute on the function/method declaration itself. 4840 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4841 if (!NonNull->args_size()) { 4842 // Easy case: all pointer arguments are nonnull. 4843 for (const auto *Arg : Args) 4844 if (S.isValidPointerAttrType(Arg->getType())) 4845 CheckNonNullArgument(S, Arg, CallSiteLoc); 4846 return; 4847 } 4848 4849 for (const ParamIdx &Idx : NonNull->args()) { 4850 unsigned IdxAST = Idx.getASTIndex(); 4851 if (IdxAST >= Args.size()) 4852 continue; 4853 if (NonNullArgs.empty()) 4854 NonNullArgs.resize(Args.size()); 4855 NonNullArgs.set(IdxAST); 4856 } 4857 } 4858 } 4859 4860 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4861 // Handle the nonnull attribute on the parameters of the 4862 // function/method. 4863 ArrayRef<ParmVarDecl*> parms; 4864 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4865 parms = FD->parameters(); 4866 else 4867 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4868 4869 unsigned ParamIndex = 0; 4870 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4871 I != E; ++I, ++ParamIndex) { 4872 const ParmVarDecl *PVD = *I; 4873 if (PVD->hasAttr<NonNullAttr>() || 4874 isNonNullType(S.Context, PVD->getType())) { 4875 if (NonNullArgs.empty()) 4876 NonNullArgs.resize(Args.size()); 4877 4878 NonNullArgs.set(ParamIndex); 4879 } 4880 } 4881 } else { 4882 // If we have a non-function, non-method declaration but no 4883 // function prototype, try to dig out the function prototype. 4884 if (!Proto) { 4885 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4886 QualType type = VD->getType().getNonReferenceType(); 4887 if (auto pointerType = type->getAs<PointerType>()) 4888 type = pointerType->getPointeeType(); 4889 else if (auto blockType = type->getAs<BlockPointerType>()) 4890 type = blockType->getPointeeType(); 4891 // FIXME: data member pointers? 4892 4893 // Dig out the function prototype, if there is one. 4894 Proto = type->getAs<FunctionProtoType>(); 4895 } 4896 } 4897 4898 // Fill in non-null argument information from the nullability 4899 // information on the parameter types (if we have them). 4900 if (Proto) { 4901 unsigned Index = 0; 4902 for (auto paramType : Proto->getParamTypes()) { 4903 if (isNonNullType(S.Context, paramType)) { 4904 if (NonNullArgs.empty()) 4905 NonNullArgs.resize(Args.size()); 4906 4907 NonNullArgs.set(Index); 4908 } 4909 4910 ++Index; 4911 } 4912 } 4913 } 4914 4915 // Check for non-null arguments. 4916 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4917 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4918 if (NonNullArgs[ArgIndex]) 4919 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4920 } 4921 } 4922 4923 /// Warn if a pointer or reference argument passed to a function points to an 4924 /// object that is less aligned than the parameter. This can happen when 4925 /// creating a typedef with a lower alignment than the original type and then 4926 /// calling functions defined in terms of the original type. 4927 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4928 StringRef ParamName, QualType ArgTy, 4929 QualType ParamTy) { 4930 4931 // If a function accepts a pointer or reference type 4932 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4933 return; 4934 4935 // If the parameter is a pointer type, get the pointee type for the 4936 // argument too. If the parameter is a reference type, don't try to get 4937 // the pointee type for the argument. 4938 if (ParamTy->isPointerType()) 4939 ArgTy = ArgTy->getPointeeType(); 4940 4941 // Remove reference or pointer 4942 ParamTy = ParamTy->getPointeeType(); 4943 4944 // Find expected alignment, and the actual alignment of the passed object. 4945 // getTypeAlignInChars requires complete types 4946 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4947 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4948 ArgTy->isUndeducedType()) 4949 return; 4950 4951 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4952 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4953 4954 // If the argument is less aligned than the parameter, there is a 4955 // potential alignment issue. 4956 if (ArgAlign < ParamAlign) 4957 Diag(Loc, diag::warn_param_mismatched_alignment) 4958 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4959 << ParamName << FDecl; 4960 } 4961 4962 /// Handles the checks for format strings, non-POD arguments to vararg 4963 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4964 /// attributes. 4965 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4966 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4967 bool IsMemberFunction, SourceLocation Loc, 4968 SourceRange Range, VariadicCallType CallType) { 4969 // FIXME: We should check as much as we can in the template definition. 4970 if (CurContext->isDependentContext()) 4971 return; 4972 4973 // Printf and scanf checking. 4974 llvm::SmallBitVector CheckedVarArgs; 4975 if (FDecl) { 4976 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4977 // Only create vector if there are format attributes. 4978 CheckedVarArgs.resize(Args.size()); 4979 4980 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4981 CheckedVarArgs); 4982 } 4983 } 4984 4985 // Refuse POD arguments that weren't caught by the format string 4986 // checks above. 4987 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4988 if (CallType != VariadicDoesNotApply && 4989 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4990 unsigned NumParams = Proto ? Proto->getNumParams() 4991 : FDecl && isa<FunctionDecl>(FDecl) 4992 ? cast<FunctionDecl>(FDecl)->getNumParams() 4993 : FDecl && isa<ObjCMethodDecl>(FDecl) 4994 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4995 : 0; 4996 4997 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4998 // Args[ArgIdx] can be null in malformed code. 4999 if (const Expr *Arg = Args[ArgIdx]) { 5000 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5001 checkVariadicArgument(Arg, CallType); 5002 } 5003 } 5004 } 5005 5006 if (FDecl || Proto) { 5007 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5008 5009 // Type safety checking. 5010 if (FDecl) { 5011 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5012 CheckArgumentWithTypeTag(I, Args, Loc); 5013 } 5014 } 5015 5016 // Check that passed arguments match the alignment of original arguments. 5017 // Try to get the missing prototype from the declaration. 5018 if (!Proto && FDecl) { 5019 const auto *FT = FDecl->getFunctionType(); 5020 if (isa_and_nonnull<FunctionProtoType>(FT)) 5021 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5022 } 5023 if (Proto) { 5024 // For variadic functions, we may have more args than parameters. 5025 // For some K&R functions, we may have less args than parameters. 5026 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5027 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5028 // Args[ArgIdx] can be null in malformed code. 5029 if (const Expr *Arg = Args[ArgIdx]) { 5030 if (Arg->containsErrors()) 5031 continue; 5032 5033 QualType ParamTy = Proto->getParamType(ArgIdx); 5034 QualType ArgTy = Arg->getType(); 5035 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5036 ArgTy, ParamTy); 5037 } 5038 } 5039 } 5040 5041 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5042 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5043 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5044 if (!Arg->isValueDependent()) { 5045 Expr::EvalResult Align; 5046 if (Arg->EvaluateAsInt(Align, Context)) { 5047 const llvm::APSInt &I = Align.Val.getInt(); 5048 if (!I.isPowerOf2()) 5049 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5050 << Arg->getSourceRange(); 5051 5052 if (I > Sema::MaximumAlignment) 5053 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5054 << Arg->getSourceRange() << Sema::MaximumAlignment; 5055 } 5056 } 5057 } 5058 5059 if (FD) 5060 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5061 } 5062 5063 /// CheckConstructorCall - Check a constructor call for correctness and safety 5064 /// properties not enforced by the C type system. 5065 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5066 ArrayRef<const Expr *> Args, 5067 const FunctionProtoType *Proto, 5068 SourceLocation Loc) { 5069 VariadicCallType CallType = 5070 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5071 5072 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5073 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5074 Context.getPointerType(Ctor->getThisObjectType())); 5075 5076 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5077 Loc, SourceRange(), CallType); 5078 } 5079 5080 /// CheckFunctionCall - Check a direct function call for various correctness 5081 /// and safety properties not strictly enforced by the C type system. 5082 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5083 const FunctionProtoType *Proto) { 5084 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5085 isa<CXXMethodDecl>(FDecl); 5086 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5087 IsMemberOperatorCall; 5088 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5089 TheCall->getCallee()); 5090 Expr** Args = TheCall->getArgs(); 5091 unsigned NumArgs = TheCall->getNumArgs(); 5092 5093 Expr *ImplicitThis = nullptr; 5094 if (IsMemberOperatorCall) { 5095 // If this is a call to a member operator, hide the first argument 5096 // from checkCall. 5097 // FIXME: Our choice of AST representation here is less than ideal. 5098 ImplicitThis = Args[0]; 5099 ++Args; 5100 --NumArgs; 5101 } else if (IsMemberFunction) 5102 ImplicitThis = 5103 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5104 5105 if (ImplicitThis) { 5106 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5107 // used. 5108 QualType ThisType = ImplicitThis->getType(); 5109 if (!ThisType->isPointerType()) { 5110 assert(!ThisType->isReferenceType()); 5111 ThisType = Context.getPointerType(ThisType); 5112 } 5113 5114 QualType ThisTypeFromDecl = 5115 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5116 5117 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5118 ThisTypeFromDecl); 5119 } 5120 5121 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5122 IsMemberFunction, TheCall->getRParenLoc(), 5123 TheCall->getCallee()->getSourceRange(), CallType); 5124 5125 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5126 // None of the checks below are needed for functions that don't have 5127 // simple names (e.g., C++ conversion functions). 5128 if (!FnInfo) 5129 return false; 5130 5131 CheckTCBEnforcement(TheCall, FDecl); 5132 5133 CheckAbsoluteValueFunction(TheCall, FDecl); 5134 CheckMaxUnsignedZero(TheCall, FDecl); 5135 5136 if (getLangOpts().ObjC) 5137 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5138 5139 unsigned CMId = FDecl->getMemoryFunctionKind(); 5140 5141 // Handle memory setting and copying functions. 5142 switch (CMId) { 5143 case 0: 5144 return false; 5145 case Builtin::BIstrlcpy: // fallthrough 5146 case Builtin::BIstrlcat: 5147 CheckStrlcpycatArguments(TheCall, FnInfo); 5148 break; 5149 case Builtin::BIstrncat: 5150 CheckStrncatArguments(TheCall, FnInfo); 5151 break; 5152 case Builtin::BIfree: 5153 CheckFreeArguments(TheCall); 5154 break; 5155 default: 5156 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5157 } 5158 5159 return false; 5160 } 5161 5162 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5163 ArrayRef<const Expr *> Args) { 5164 VariadicCallType CallType = 5165 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5166 5167 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5168 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5169 CallType); 5170 5171 return false; 5172 } 5173 5174 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5175 const FunctionProtoType *Proto) { 5176 QualType Ty; 5177 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5178 Ty = V->getType().getNonReferenceType(); 5179 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5180 Ty = F->getType().getNonReferenceType(); 5181 else 5182 return false; 5183 5184 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5185 !Ty->isFunctionProtoType()) 5186 return false; 5187 5188 VariadicCallType CallType; 5189 if (!Proto || !Proto->isVariadic()) { 5190 CallType = VariadicDoesNotApply; 5191 } else if (Ty->isBlockPointerType()) { 5192 CallType = VariadicBlock; 5193 } else { // Ty->isFunctionPointerType() 5194 CallType = VariadicFunction; 5195 } 5196 5197 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5198 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5199 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5200 TheCall->getCallee()->getSourceRange(), CallType); 5201 5202 return false; 5203 } 5204 5205 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5206 /// such as function pointers returned from functions. 5207 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5208 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5209 TheCall->getCallee()); 5210 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5211 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5212 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5213 TheCall->getCallee()->getSourceRange(), CallType); 5214 5215 return false; 5216 } 5217 5218 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5219 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5220 return false; 5221 5222 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5223 switch (Op) { 5224 case AtomicExpr::AO__c11_atomic_init: 5225 case AtomicExpr::AO__opencl_atomic_init: 5226 llvm_unreachable("There is no ordering argument for an init"); 5227 5228 case AtomicExpr::AO__c11_atomic_load: 5229 case AtomicExpr::AO__opencl_atomic_load: 5230 case AtomicExpr::AO__atomic_load_n: 5231 case AtomicExpr::AO__atomic_load: 5232 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5233 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5234 5235 case AtomicExpr::AO__c11_atomic_store: 5236 case AtomicExpr::AO__opencl_atomic_store: 5237 case AtomicExpr::AO__atomic_store: 5238 case AtomicExpr::AO__atomic_store_n: 5239 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5240 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5241 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5242 5243 default: 5244 return true; 5245 } 5246 } 5247 5248 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5249 AtomicExpr::AtomicOp Op) { 5250 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5251 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5252 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5253 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5254 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5255 Op); 5256 } 5257 5258 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5259 SourceLocation RParenLoc, MultiExprArg Args, 5260 AtomicExpr::AtomicOp Op, 5261 AtomicArgumentOrder ArgOrder) { 5262 // All the non-OpenCL operations take one of the following forms. 5263 // The OpenCL operations take the __c11 forms with one extra argument for 5264 // synchronization scope. 5265 enum { 5266 // C __c11_atomic_init(A *, C) 5267 Init, 5268 5269 // C __c11_atomic_load(A *, int) 5270 Load, 5271 5272 // void __atomic_load(A *, CP, int) 5273 LoadCopy, 5274 5275 // void __atomic_store(A *, CP, int) 5276 Copy, 5277 5278 // C __c11_atomic_add(A *, M, int) 5279 Arithmetic, 5280 5281 // C __atomic_exchange_n(A *, CP, int) 5282 Xchg, 5283 5284 // void __atomic_exchange(A *, C *, CP, int) 5285 GNUXchg, 5286 5287 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5288 C11CmpXchg, 5289 5290 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5291 GNUCmpXchg 5292 } Form = Init; 5293 5294 const unsigned NumForm = GNUCmpXchg + 1; 5295 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5296 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5297 // where: 5298 // C is an appropriate type, 5299 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5300 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5301 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5302 // the int parameters are for orderings. 5303 5304 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5305 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5306 "need to update code for modified forms"); 5307 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5308 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5309 AtomicExpr::AO__atomic_load, 5310 "need to update code for modified C11 atomics"); 5311 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5312 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5313 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5314 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5315 IsOpenCL; 5316 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5317 Op == AtomicExpr::AO__atomic_store_n || 5318 Op == AtomicExpr::AO__atomic_exchange_n || 5319 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5320 bool IsAddSub = false; 5321 5322 switch (Op) { 5323 case AtomicExpr::AO__c11_atomic_init: 5324 case AtomicExpr::AO__opencl_atomic_init: 5325 Form = Init; 5326 break; 5327 5328 case AtomicExpr::AO__c11_atomic_load: 5329 case AtomicExpr::AO__opencl_atomic_load: 5330 case AtomicExpr::AO__atomic_load_n: 5331 Form = Load; 5332 break; 5333 5334 case AtomicExpr::AO__atomic_load: 5335 Form = LoadCopy; 5336 break; 5337 5338 case AtomicExpr::AO__c11_atomic_store: 5339 case AtomicExpr::AO__opencl_atomic_store: 5340 case AtomicExpr::AO__atomic_store: 5341 case AtomicExpr::AO__atomic_store_n: 5342 Form = Copy; 5343 break; 5344 5345 case AtomicExpr::AO__c11_atomic_fetch_add: 5346 case AtomicExpr::AO__c11_atomic_fetch_sub: 5347 case AtomicExpr::AO__opencl_atomic_fetch_add: 5348 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5349 case AtomicExpr::AO__atomic_fetch_add: 5350 case AtomicExpr::AO__atomic_fetch_sub: 5351 case AtomicExpr::AO__atomic_add_fetch: 5352 case AtomicExpr::AO__atomic_sub_fetch: 5353 IsAddSub = true; 5354 Form = Arithmetic; 5355 break; 5356 case AtomicExpr::AO__c11_atomic_fetch_and: 5357 case AtomicExpr::AO__c11_atomic_fetch_or: 5358 case AtomicExpr::AO__c11_atomic_fetch_xor: 5359 case AtomicExpr::AO__opencl_atomic_fetch_and: 5360 case AtomicExpr::AO__opencl_atomic_fetch_or: 5361 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5362 case AtomicExpr::AO__atomic_fetch_and: 5363 case AtomicExpr::AO__atomic_fetch_or: 5364 case AtomicExpr::AO__atomic_fetch_xor: 5365 case AtomicExpr::AO__atomic_fetch_nand: 5366 case AtomicExpr::AO__atomic_and_fetch: 5367 case AtomicExpr::AO__atomic_or_fetch: 5368 case AtomicExpr::AO__atomic_xor_fetch: 5369 case AtomicExpr::AO__atomic_nand_fetch: 5370 Form = Arithmetic; 5371 break; 5372 case AtomicExpr::AO__c11_atomic_fetch_min: 5373 case AtomicExpr::AO__c11_atomic_fetch_max: 5374 case AtomicExpr::AO__opencl_atomic_fetch_min: 5375 case AtomicExpr::AO__opencl_atomic_fetch_max: 5376 case AtomicExpr::AO__atomic_min_fetch: 5377 case AtomicExpr::AO__atomic_max_fetch: 5378 case AtomicExpr::AO__atomic_fetch_min: 5379 case AtomicExpr::AO__atomic_fetch_max: 5380 Form = Arithmetic; 5381 break; 5382 5383 case AtomicExpr::AO__c11_atomic_exchange: 5384 case AtomicExpr::AO__opencl_atomic_exchange: 5385 case AtomicExpr::AO__atomic_exchange_n: 5386 Form = Xchg; 5387 break; 5388 5389 case AtomicExpr::AO__atomic_exchange: 5390 Form = GNUXchg; 5391 break; 5392 5393 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5394 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5395 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5396 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5397 Form = C11CmpXchg; 5398 break; 5399 5400 case AtomicExpr::AO__atomic_compare_exchange: 5401 case AtomicExpr::AO__atomic_compare_exchange_n: 5402 Form = GNUCmpXchg; 5403 break; 5404 } 5405 5406 unsigned AdjustedNumArgs = NumArgs[Form]; 5407 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5408 ++AdjustedNumArgs; 5409 // Check we have the right number of arguments. 5410 if (Args.size() < AdjustedNumArgs) { 5411 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5412 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5413 << ExprRange; 5414 return ExprError(); 5415 } else if (Args.size() > AdjustedNumArgs) { 5416 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5417 diag::err_typecheck_call_too_many_args) 5418 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5419 << ExprRange; 5420 return ExprError(); 5421 } 5422 5423 // Inspect the first argument of the atomic operation. 5424 Expr *Ptr = Args[0]; 5425 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5426 if (ConvertedPtr.isInvalid()) 5427 return ExprError(); 5428 5429 Ptr = ConvertedPtr.get(); 5430 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5431 if (!pointerType) { 5432 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5433 << Ptr->getType() << Ptr->getSourceRange(); 5434 return ExprError(); 5435 } 5436 5437 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5438 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5439 QualType ValType = AtomTy; // 'C' 5440 if (IsC11) { 5441 if (!AtomTy->isAtomicType()) { 5442 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5443 << Ptr->getType() << Ptr->getSourceRange(); 5444 return ExprError(); 5445 } 5446 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5447 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5448 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5449 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5450 << Ptr->getSourceRange(); 5451 return ExprError(); 5452 } 5453 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5454 } else if (Form != Load && Form != LoadCopy) { 5455 if (ValType.isConstQualified()) { 5456 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5457 << Ptr->getType() << Ptr->getSourceRange(); 5458 return ExprError(); 5459 } 5460 } 5461 5462 // For an arithmetic operation, the implied arithmetic must be well-formed. 5463 if (Form == Arithmetic) { 5464 // gcc does not enforce these rules for GNU atomics, but we do so for 5465 // sanity. 5466 auto IsAllowedValueType = [&](QualType ValType) { 5467 if (ValType->isIntegerType()) 5468 return true; 5469 if (ValType->isPointerType()) 5470 return true; 5471 if (!ValType->isFloatingType()) 5472 return false; 5473 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5474 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5475 &Context.getTargetInfo().getLongDoubleFormat() == 5476 &llvm::APFloat::x87DoubleExtended()) 5477 return false; 5478 return true; 5479 }; 5480 if (IsAddSub && !IsAllowedValueType(ValType)) { 5481 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5482 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5483 return ExprError(); 5484 } 5485 if (!IsAddSub && !ValType->isIntegerType()) { 5486 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5487 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5488 return ExprError(); 5489 } 5490 if (IsC11 && ValType->isPointerType() && 5491 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5492 diag::err_incomplete_type)) { 5493 return ExprError(); 5494 } 5495 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5496 // For __atomic_*_n operations, the value type must be a scalar integral or 5497 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5498 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5499 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5500 return ExprError(); 5501 } 5502 5503 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5504 !AtomTy->isScalarType()) { 5505 // For GNU atomics, require a trivially-copyable type. This is not part of 5506 // the GNU atomics specification, but we enforce it for sanity. 5507 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5508 << Ptr->getType() << Ptr->getSourceRange(); 5509 return ExprError(); 5510 } 5511 5512 switch (ValType.getObjCLifetime()) { 5513 case Qualifiers::OCL_None: 5514 case Qualifiers::OCL_ExplicitNone: 5515 // okay 5516 break; 5517 5518 case Qualifiers::OCL_Weak: 5519 case Qualifiers::OCL_Strong: 5520 case Qualifiers::OCL_Autoreleasing: 5521 // FIXME: Can this happen? By this point, ValType should be known 5522 // to be trivially copyable. 5523 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5524 << ValType << Ptr->getSourceRange(); 5525 return ExprError(); 5526 } 5527 5528 // All atomic operations have an overload which takes a pointer to a volatile 5529 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5530 // into the result or the other operands. Similarly atomic_load takes a 5531 // pointer to a const 'A'. 5532 ValType.removeLocalVolatile(); 5533 ValType.removeLocalConst(); 5534 QualType ResultType = ValType; 5535 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5536 Form == Init) 5537 ResultType = Context.VoidTy; 5538 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5539 ResultType = Context.BoolTy; 5540 5541 // The type of a parameter passed 'by value'. In the GNU atomics, such 5542 // arguments are actually passed as pointers. 5543 QualType ByValType = ValType; // 'CP' 5544 bool IsPassedByAddress = false; 5545 if (!IsC11 && !IsN) { 5546 ByValType = Ptr->getType(); 5547 IsPassedByAddress = true; 5548 } 5549 5550 SmallVector<Expr *, 5> APIOrderedArgs; 5551 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5552 APIOrderedArgs.push_back(Args[0]); 5553 switch (Form) { 5554 case Init: 5555 case Load: 5556 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5557 break; 5558 case LoadCopy: 5559 case Copy: 5560 case Arithmetic: 5561 case Xchg: 5562 APIOrderedArgs.push_back(Args[2]); // Val1 5563 APIOrderedArgs.push_back(Args[1]); // Order 5564 break; 5565 case GNUXchg: 5566 APIOrderedArgs.push_back(Args[2]); // Val1 5567 APIOrderedArgs.push_back(Args[3]); // Val2 5568 APIOrderedArgs.push_back(Args[1]); // Order 5569 break; 5570 case C11CmpXchg: 5571 APIOrderedArgs.push_back(Args[2]); // Val1 5572 APIOrderedArgs.push_back(Args[4]); // Val2 5573 APIOrderedArgs.push_back(Args[1]); // Order 5574 APIOrderedArgs.push_back(Args[3]); // OrderFail 5575 break; 5576 case GNUCmpXchg: 5577 APIOrderedArgs.push_back(Args[2]); // Val1 5578 APIOrderedArgs.push_back(Args[4]); // Val2 5579 APIOrderedArgs.push_back(Args[5]); // Weak 5580 APIOrderedArgs.push_back(Args[1]); // Order 5581 APIOrderedArgs.push_back(Args[3]); // OrderFail 5582 break; 5583 } 5584 } else 5585 APIOrderedArgs.append(Args.begin(), Args.end()); 5586 5587 // The first argument's non-CV pointer type is used to deduce the type of 5588 // subsequent arguments, except for: 5589 // - weak flag (always converted to bool) 5590 // - memory order (always converted to int) 5591 // - scope (always converted to int) 5592 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5593 QualType Ty; 5594 if (i < NumVals[Form] + 1) { 5595 switch (i) { 5596 case 0: 5597 // The first argument is always a pointer. It has a fixed type. 5598 // It is always dereferenced, a nullptr is undefined. 5599 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5600 // Nothing else to do: we already know all we want about this pointer. 5601 continue; 5602 case 1: 5603 // The second argument is the non-atomic operand. For arithmetic, this 5604 // is always passed by value, and for a compare_exchange it is always 5605 // passed by address. For the rest, GNU uses by-address and C11 uses 5606 // by-value. 5607 assert(Form != Load); 5608 if (Form == Arithmetic && ValType->isPointerType()) 5609 Ty = Context.getPointerDiffType(); 5610 else if (Form == Init || Form == Arithmetic) 5611 Ty = ValType; 5612 else if (Form == Copy || Form == Xchg) { 5613 if (IsPassedByAddress) { 5614 // The value pointer is always dereferenced, a nullptr is undefined. 5615 CheckNonNullArgument(*this, APIOrderedArgs[i], 5616 ExprRange.getBegin()); 5617 } 5618 Ty = ByValType; 5619 } else { 5620 Expr *ValArg = APIOrderedArgs[i]; 5621 // The value pointer is always dereferenced, a nullptr is undefined. 5622 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5623 LangAS AS = LangAS::Default; 5624 // Keep address space of non-atomic pointer type. 5625 if (const PointerType *PtrTy = 5626 ValArg->getType()->getAs<PointerType>()) { 5627 AS = PtrTy->getPointeeType().getAddressSpace(); 5628 } 5629 Ty = Context.getPointerType( 5630 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5631 } 5632 break; 5633 case 2: 5634 // The third argument to compare_exchange / GNU exchange is the desired 5635 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5636 if (IsPassedByAddress) 5637 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5638 Ty = ByValType; 5639 break; 5640 case 3: 5641 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5642 Ty = Context.BoolTy; 5643 break; 5644 } 5645 } else { 5646 // The order(s) and scope are always converted to int. 5647 Ty = Context.IntTy; 5648 } 5649 5650 InitializedEntity Entity = 5651 InitializedEntity::InitializeParameter(Context, Ty, false); 5652 ExprResult Arg = APIOrderedArgs[i]; 5653 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5654 if (Arg.isInvalid()) 5655 return true; 5656 APIOrderedArgs[i] = Arg.get(); 5657 } 5658 5659 // Permute the arguments into a 'consistent' order. 5660 SmallVector<Expr*, 5> SubExprs; 5661 SubExprs.push_back(Ptr); 5662 switch (Form) { 5663 case Init: 5664 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5665 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5666 break; 5667 case Load: 5668 SubExprs.push_back(APIOrderedArgs[1]); // Order 5669 break; 5670 case LoadCopy: 5671 case Copy: 5672 case Arithmetic: 5673 case Xchg: 5674 SubExprs.push_back(APIOrderedArgs[2]); // Order 5675 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5676 break; 5677 case GNUXchg: 5678 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5679 SubExprs.push_back(APIOrderedArgs[3]); // Order 5680 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5681 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5682 break; 5683 case C11CmpXchg: 5684 SubExprs.push_back(APIOrderedArgs[3]); // Order 5685 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5686 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5687 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5688 break; 5689 case GNUCmpXchg: 5690 SubExprs.push_back(APIOrderedArgs[4]); // Order 5691 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5692 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5693 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5694 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5695 break; 5696 } 5697 5698 if (SubExprs.size() >= 2 && Form != Init) { 5699 if (Optional<llvm::APSInt> Result = 5700 SubExprs[1]->getIntegerConstantExpr(Context)) 5701 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5702 Diag(SubExprs[1]->getBeginLoc(), 5703 diag::warn_atomic_op_has_invalid_memory_order) 5704 << SubExprs[1]->getSourceRange(); 5705 } 5706 5707 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5708 auto *Scope = Args[Args.size() - 1]; 5709 if (Optional<llvm::APSInt> Result = 5710 Scope->getIntegerConstantExpr(Context)) { 5711 if (!ScopeModel->isValid(Result->getZExtValue())) 5712 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5713 << Scope->getSourceRange(); 5714 } 5715 SubExprs.push_back(Scope); 5716 } 5717 5718 AtomicExpr *AE = new (Context) 5719 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5720 5721 if ((Op == AtomicExpr::AO__c11_atomic_load || 5722 Op == AtomicExpr::AO__c11_atomic_store || 5723 Op == AtomicExpr::AO__opencl_atomic_load || 5724 Op == AtomicExpr::AO__opencl_atomic_store ) && 5725 Context.AtomicUsesUnsupportedLibcall(AE)) 5726 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5727 << ((Op == AtomicExpr::AO__c11_atomic_load || 5728 Op == AtomicExpr::AO__opencl_atomic_load) 5729 ? 0 5730 : 1); 5731 5732 if (ValType->isExtIntType()) { 5733 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5734 return ExprError(); 5735 } 5736 5737 return AE; 5738 } 5739 5740 /// checkBuiltinArgument - Given a call to a builtin function, perform 5741 /// normal type-checking on the given argument, updating the call in 5742 /// place. This is useful when a builtin function requires custom 5743 /// type-checking for some of its arguments but not necessarily all of 5744 /// them. 5745 /// 5746 /// Returns true on error. 5747 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5748 FunctionDecl *Fn = E->getDirectCallee(); 5749 assert(Fn && "builtin call without direct callee!"); 5750 5751 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5752 InitializedEntity Entity = 5753 InitializedEntity::InitializeParameter(S.Context, Param); 5754 5755 ExprResult Arg = E->getArg(0); 5756 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5757 if (Arg.isInvalid()) 5758 return true; 5759 5760 E->setArg(ArgIndex, Arg.get()); 5761 return false; 5762 } 5763 5764 /// We have a call to a function like __sync_fetch_and_add, which is an 5765 /// overloaded function based on the pointer type of its first argument. 5766 /// The main BuildCallExpr routines have already promoted the types of 5767 /// arguments because all of these calls are prototyped as void(...). 5768 /// 5769 /// This function goes through and does final semantic checking for these 5770 /// builtins, as well as generating any warnings. 5771 ExprResult 5772 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5773 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5774 Expr *Callee = TheCall->getCallee(); 5775 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5776 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5777 5778 // Ensure that we have at least one argument to do type inference from. 5779 if (TheCall->getNumArgs() < 1) { 5780 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5781 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5782 return ExprError(); 5783 } 5784 5785 // Inspect the first argument of the atomic builtin. This should always be 5786 // a pointer type, whose element is an integral scalar or pointer type. 5787 // Because it is a pointer type, we don't have to worry about any implicit 5788 // casts here. 5789 // FIXME: We don't allow floating point scalars as input. 5790 Expr *FirstArg = TheCall->getArg(0); 5791 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5792 if (FirstArgResult.isInvalid()) 5793 return ExprError(); 5794 FirstArg = FirstArgResult.get(); 5795 TheCall->setArg(0, FirstArg); 5796 5797 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5798 if (!pointerType) { 5799 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5800 << FirstArg->getType() << FirstArg->getSourceRange(); 5801 return ExprError(); 5802 } 5803 5804 QualType ValType = pointerType->getPointeeType(); 5805 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5806 !ValType->isBlockPointerType()) { 5807 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5808 << FirstArg->getType() << FirstArg->getSourceRange(); 5809 return ExprError(); 5810 } 5811 5812 if (ValType.isConstQualified()) { 5813 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5814 << FirstArg->getType() << FirstArg->getSourceRange(); 5815 return ExprError(); 5816 } 5817 5818 switch (ValType.getObjCLifetime()) { 5819 case Qualifiers::OCL_None: 5820 case Qualifiers::OCL_ExplicitNone: 5821 // okay 5822 break; 5823 5824 case Qualifiers::OCL_Weak: 5825 case Qualifiers::OCL_Strong: 5826 case Qualifiers::OCL_Autoreleasing: 5827 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5828 << ValType << FirstArg->getSourceRange(); 5829 return ExprError(); 5830 } 5831 5832 // Strip any qualifiers off ValType. 5833 ValType = ValType.getUnqualifiedType(); 5834 5835 // The majority of builtins return a value, but a few have special return 5836 // types, so allow them to override appropriately below. 5837 QualType ResultType = ValType; 5838 5839 // We need to figure out which concrete builtin this maps onto. For example, 5840 // __sync_fetch_and_add with a 2 byte object turns into 5841 // __sync_fetch_and_add_2. 5842 #define BUILTIN_ROW(x) \ 5843 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5844 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5845 5846 static const unsigned BuiltinIndices[][5] = { 5847 BUILTIN_ROW(__sync_fetch_and_add), 5848 BUILTIN_ROW(__sync_fetch_and_sub), 5849 BUILTIN_ROW(__sync_fetch_and_or), 5850 BUILTIN_ROW(__sync_fetch_and_and), 5851 BUILTIN_ROW(__sync_fetch_and_xor), 5852 BUILTIN_ROW(__sync_fetch_and_nand), 5853 5854 BUILTIN_ROW(__sync_add_and_fetch), 5855 BUILTIN_ROW(__sync_sub_and_fetch), 5856 BUILTIN_ROW(__sync_and_and_fetch), 5857 BUILTIN_ROW(__sync_or_and_fetch), 5858 BUILTIN_ROW(__sync_xor_and_fetch), 5859 BUILTIN_ROW(__sync_nand_and_fetch), 5860 5861 BUILTIN_ROW(__sync_val_compare_and_swap), 5862 BUILTIN_ROW(__sync_bool_compare_and_swap), 5863 BUILTIN_ROW(__sync_lock_test_and_set), 5864 BUILTIN_ROW(__sync_lock_release), 5865 BUILTIN_ROW(__sync_swap) 5866 }; 5867 #undef BUILTIN_ROW 5868 5869 // Determine the index of the size. 5870 unsigned SizeIndex; 5871 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5872 case 1: SizeIndex = 0; break; 5873 case 2: SizeIndex = 1; break; 5874 case 4: SizeIndex = 2; break; 5875 case 8: SizeIndex = 3; break; 5876 case 16: SizeIndex = 4; break; 5877 default: 5878 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5879 << FirstArg->getType() << FirstArg->getSourceRange(); 5880 return ExprError(); 5881 } 5882 5883 // Each of these builtins has one pointer argument, followed by some number of 5884 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5885 // that we ignore. Find out which row of BuiltinIndices to read from as well 5886 // as the number of fixed args. 5887 unsigned BuiltinID = FDecl->getBuiltinID(); 5888 unsigned BuiltinIndex, NumFixed = 1; 5889 bool WarnAboutSemanticsChange = false; 5890 switch (BuiltinID) { 5891 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5892 case Builtin::BI__sync_fetch_and_add: 5893 case Builtin::BI__sync_fetch_and_add_1: 5894 case Builtin::BI__sync_fetch_and_add_2: 5895 case Builtin::BI__sync_fetch_and_add_4: 5896 case Builtin::BI__sync_fetch_and_add_8: 5897 case Builtin::BI__sync_fetch_and_add_16: 5898 BuiltinIndex = 0; 5899 break; 5900 5901 case Builtin::BI__sync_fetch_and_sub: 5902 case Builtin::BI__sync_fetch_and_sub_1: 5903 case Builtin::BI__sync_fetch_and_sub_2: 5904 case Builtin::BI__sync_fetch_and_sub_4: 5905 case Builtin::BI__sync_fetch_and_sub_8: 5906 case Builtin::BI__sync_fetch_and_sub_16: 5907 BuiltinIndex = 1; 5908 break; 5909 5910 case Builtin::BI__sync_fetch_and_or: 5911 case Builtin::BI__sync_fetch_and_or_1: 5912 case Builtin::BI__sync_fetch_and_or_2: 5913 case Builtin::BI__sync_fetch_and_or_4: 5914 case Builtin::BI__sync_fetch_and_or_8: 5915 case Builtin::BI__sync_fetch_and_or_16: 5916 BuiltinIndex = 2; 5917 break; 5918 5919 case Builtin::BI__sync_fetch_and_and: 5920 case Builtin::BI__sync_fetch_and_and_1: 5921 case Builtin::BI__sync_fetch_and_and_2: 5922 case Builtin::BI__sync_fetch_and_and_4: 5923 case Builtin::BI__sync_fetch_and_and_8: 5924 case Builtin::BI__sync_fetch_and_and_16: 5925 BuiltinIndex = 3; 5926 break; 5927 5928 case Builtin::BI__sync_fetch_and_xor: 5929 case Builtin::BI__sync_fetch_and_xor_1: 5930 case Builtin::BI__sync_fetch_and_xor_2: 5931 case Builtin::BI__sync_fetch_and_xor_4: 5932 case Builtin::BI__sync_fetch_and_xor_8: 5933 case Builtin::BI__sync_fetch_and_xor_16: 5934 BuiltinIndex = 4; 5935 break; 5936 5937 case Builtin::BI__sync_fetch_and_nand: 5938 case Builtin::BI__sync_fetch_and_nand_1: 5939 case Builtin::BI__sync_fetch_and_nand_2: 5940 case Builtin::BI__sync_fetch_and_nand_4: 5941 case Builtin::BI__sync_fetch_and_nand_8: 5942 case Builtin::BI__sync_fetch_and_nand_16: 5943 BuiltinIndex = 5; 5944 WarnAboutSemanticsChange = true; 5945 break; 5946 5947 case Builtin::BI__sync_add_and_fetch: 5948 case Builtin::BI__sync_add_and_fetch_1: 5949 case Builtin::BI__sync_add_and_fetch_2: 5950 case Builtin::BI__sync_add_and_fetch_4: 5951 case Builtin::BI__sync_add_and_fetch_8: 5952 case Builtin::BI__sync_add_and_fetch_16: 5953 BuiltinIndex = 6; 5954 break; 5955 5956 case Builtin::BI__sync_sub_and_fetch: 5957 case Builtin::BI__sync_sub_and_fetch_1: 5958 case Builtin::BI__sync_sub_and_fetch_2: 5959 case Builtin::BI__sync_sub_and_fetch_4: 5960 case Builtin::BI__sync_sub_and_fetch_8: 5961 case Builtin::BI__sync_sub_and_fetch_16: 5962 BuiltinIndex = 7; 5963 break; 5964 5965 case Builtin::BI__sync_and_and_fetch: 5966 case Builtin::BI__sync_and_and_fetch_1: 5967 case Builtin::BI__sync_and_and_fetch_2: 5968 case Builtin::BI__sync_and_and_fetch_4: 5969 case Builtin::BI__sync_and_and_fetch_8: 5970 case Builtin::BI__sync_and_and_fetch_16: 5971 BuiltinIndex = 8; 5972 break; 5973 5974 case Builtin::BI__sync_or_and_fetch: 5975 case Builtin::BI__sync_or_and_fetch_1: 5976 case Builtin::BI__sync_or_and_fetch_2: 5977 case Builtin::BI__sync_or_and_fetch_4: 5978 case Builtin::BI__sync_or_and_fetch_8: 5979 case Builtin::BI__sync_or_and_fetch_16: 5980 BuiltinIndex = 9; 5981 break; 5982 5983 case Builtin::BI__sync_xor_and_fetch: 5984 case Builtin::BI__sync_xor_and_fetch_1: 5985 case Builtin::BI__sync_xor_and_fetch_2: 5986 case Builtin::BI__sync_xor_and_fetch_4: 5987 case Builtin::BI__sync_xor_and_fetch_8: 5988 case Builtin::BI__sync_xor_and_fetch_16: 5989 BuiltinIndex = 10; 5990 break; 5991 5992 case Builtin::BI__sync_nand_and_fetch: 5993 case Builtin::BI__sync_nand_and_fetch_1: 5994 case Builtin::BI__sync_nand_and_fetch_2: 5995 case Builtin::BI__sync_nand_and_fetch_4: 5996 case Builtin::BI__sync_nand_and_fetch_8: 5997 case Builtin::BI__sync_nand_and_fetch_16: 5998 BuiltinIndex = 11; 5999 WarnAboutSemanticsChange = true; 6000 break; 6001 6002 case Builtin::BI__sync_val_compare_and_swap: 6003 case Builtin::BI__sync_val_compare_and_swap_1: 6004 case Builtin::BI__sync_val_compare_and_swap_2: 6005 case Builtin::BI__sync_val_compare_and_swap_4: 6006 case Builtin::BI__sync_val_compare_and_swap_8: 6007 case Builtin::BI__sync_val_compare_and_swap_16: 6008 BuiltinIndex = 12; 6009 NumFixed = 2; 6010 break; 6011 6012 case Builtin::BI__sync_bool_compare_and_swap: 6013 case Builtin::BI__sync_bool_compare_and_swap_1: 6014 case Builtin::BI__sync_bool_compare_and_swap_2: 6015 case Builtin::BI__sync_bool_compare_and_swap_4: 6016 case Builtin::BI__sync_bool_compare_and_swap_8: 6017 case Builtin::BI__sync_bool_compare_and_swap_16: 6018 BuiltinIndex = 13; 6019 NumFixed = 2; 6020 ResultType = Context.BoolTy; 6021 break; 6022 6023 case Builtin::BI__sync_lock_test_and_set: 6024 case Builtin::BI__sync_lock_test_and_set_1: 6025 case Builtin::BI__sync_lock_test_and_set_2: 6026 case Builtin::BI__sync_lock_test_and_set_4: 6027 case Builtin::BI__sync_lock_test_and_set_8: 6028 case Builtin::BI__sync_lock_test_and_set_16: 6029 BuiltinIndex = 14; 6030 break; 6031 6032 case Builtin::BI__sync_lock_release: 6033 case Builtin::BI__sync_lock_release_1: 6034 case Builtin::BI__sync_lock_release_2: 6035 case Builtin::BI__sync_lock_release_4: 6036 case Builtin::BI__sync_lock_release_8: 6037 case Builtin::BI__sync_lock_release_16: 6038 BuiltinIndex = 15; 6039 NumFixed = 0; 6040 ResultType = Context.VoidTy; 6041 break; 6042 6043 case Builtin::BI__sync_swap: 6044 case Builtin::BI__sync_swap_1: 6045 case Builtin::BI__sync_swap_2: 6046 case Builtin::BI__sync_swap_4: 6047 case Builtin::BI__sync_swap_8: 6048 case Builtin::BI__sync_swap_16: 6049 BuiltinIndex = 16; 6050 break; 6051 } 6052 6053 // Now that we know how many fixed arguments we expect, first check that we 6054 // have at least that many. 6055 if (TheCall->getNumArgs() < 1+NumFixed) { 6056 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6057 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6058 << Callee->getSourceRange(); 6059 return ExprError(); 6060 } 6061 6062 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6063 << Callee->getSourceRange(); 6064 6065 if (WarnAboutSemanticsChange) { 6066 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6067 << Callee->getSourceRange(); 6068 } 6069 6070 // Get the decl for the concrete builtin from this, we can tell what the 6071 // concrete integer type we should convert to is. 6072 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6073 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6074 FunctionDecl *NewBuiltinDecl; 6075 if (NewBuiltinID == BuiltinID) 6076 NewBuiltinDecl = FDecl; 6077 else { 6078 // Perform builtin lookup to avoid redeclaring it. 6079 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6080 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6081 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6082 assert(Res.getFoundDecl()); 6083 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6084 if (!NewBuiltinDecl) 6085 return ExprError(); 6086 } 6087 6088 // The first argument --- the pointer --- has a fixed type; we 6089 // deduce the types of the rest of the arguments accordingly. Walk 6090 // the remaining arguments, converting them to the deduced value type. 6091 for (unsigned i = 0; i != NumFixed; ++i) { 6092 ExprResult Arg = TheCall->getArg(i+1); 6093 6094 // GCC does an implicit conversion to the pointer or integer ValType. This 6095 // can fail in some cases (1i -> int**), check for this error case now. 6096 // Initialize the argument. 6097 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6098 ValType, /*consume*/ false); 6099 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6100 if (Arg.isInvalid()) 6101 return ExprError(); 6102 6103 // Okay, we have something that *can* be converted to the right type. Check 6104 // to see if there is a potentially weird extension going on here. This can 6105 // happen when you do an atomic operation on something like an char* and 6106 // pass in 42. The 42 gets converted to char. This is even more strange 6107 // for things like 45.123 -> char, etc. 6108 // FIXME: Do this check. 6109 TheCall->setArg(i+1, Arg.get()); 6110 } 6111 6112 // Create a new DeclRefExpr to refer to the new decl. 6113 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6114 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6115 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6116 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6117 6118 // Set the callee in the CallExpr. 6119 // FIXME: This loses syntactic information. 6120 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6121 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6122 CK_BuiltinFnToFnPtr); 6123 TheCall->setCallee(PromotedCall.get()); 6124 6125 // Change the result type of the call to match the original value type. This 6126 // is arbitrary, but the codegen for these builtins ins design to handle it 6127 // gracefully. 6128 TheCall->setType(ResultType); 6129 6130 // Prohibit use of _ExtInt with atomic builtins. 6131 // The arguments would have already been converted to the first argument's 6132 // type, so only need to check the first argument. 6133 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6134 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6135 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6136 return ExprError(); 6137 } 6138 6139 return TheCallResult; 6140 } 6141 6142 /// SemaBuiltinNontemporalOverloaded - We have a call to 6143 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6144 /// overloaded function based on the pointer type of its last argument. 6145 /// 6146 /// This function goes through and does final semantic checking for these 6147 /// builtins. 6148 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6149 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6150 DeclRefExpr *DRE = 6151 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6152 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6153 unsigned BuiltinID = FDecl->getBuiltinID(); 6154 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6155 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6156 "Unexpected nontemporal load/store builtin!"); 6157 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6158 unsigned numArgs = isStore ? 2 : 1; 6159 6160 // Ensure that we have the proper number of arguments. 6161 if (checkArgCount(*this, TheCall, numArgs)) 6162 return ExprError(); 6163 6164 // Inspect the last argument of the nontemporal builtin. This should always 6165 // be a pointer type, from which we imply the type of the memory access. 6166 // Because it is a pointer type, we don't have to worry about any implicit 6167 // casts here. 6168 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6169 ExprResult PointerArgResult = 6170 DefaultFunctionArrayLvalueConversion(PointerArg); 6171 6172 if (PointerArgResult.isInvalid()) 6173 return ExprError(); 6174 PointerArg = PointerArgResult.get(); 6175 TheCall->setArg(numArgs - 1, PointerArg); 6176 6177 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6178 if (!pointerType) { 6179 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6180 << PointerArg->getType() << PointerArg->getSourceRange(); 6181 return ExprError(); 6182 } 6183 6184 QualType ValType = pointerType->getPointeeType(); 6185 6186 // Strip any qualifiers off ValType. 6187 ValType = ValType.getUnqualifiedType(); 6188 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6189 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6190 !ValType->isVectorType()) { 6191 Diag(DRE->getBeginLoc(), 6192 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6193 << PointerArg->getType() << PointerArg->getSourceRange(); 6194 return ExprError(); 6195 } 6196 6197 if (!isStore) { 6198 TheCall->setType(ValType); 6199 return TheCallResult; 6200 } 6201 6202 ExprResult ValArg = TheCall->getArg(0); 6203 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6204 Context, ValType, /*consume*/ false); 6205 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6206 if (ValArg.isInvalid()) 6207 return ExprError(); 6208 6209 TheCall->setArg(0, ValArg.get()); 6210 TheCall->setType(Context.VoidTy); 6211 return TheCallResult; 6212 } 6213 6214 /// CheckObjCString - Checks that the argument to the builtin 6215 /// CFString constructor is correct 6216 /// Note: It might also make sense to do the UTF-16 conversion here (would 6217 /// simplify the backend). 6218 bool Sema::CheckObjCString(Expr *Arg) { 6219 Arg = Arg->IgnoreParenCasts(); 6220 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6221 6222 if (!Literal || !Literal->isAscii()) { 6223 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6224 << Arg->getSourceRange(); 6225 return true; 6226 } 6227 6228 if (Literal->containsNonAsciiOrNull()) { 6229 StringRef String = Literal->getString(); 6230 unsigned NumBytes = String.size(); 6231 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6232 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6233 llvm::UTF16 *ToPtr = &ToBuf[0]; 6234 6235 llvm::ConversionResult Result = 6236 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6237 ToPtr + NumBytes, llvm::strictConversion); 6238 // Check for conversion failure. 6239 if (Result != llvm::conversionOK) 6240 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6241 << Arg->getSourceRange(); 6242 } 6243 return false; 6244 } 6245 6246 /// CheckObjCString - Checks that the format string argument to the os_log() 6247 /// and os_trace() functions is correct, and converts it to const char *. 6248 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6249 Arg = Arg->IgnoreParenCasts(); 6250 auto *Literal = dyn_cast<StringLiteral>(Arg); 6251 if (!Literal) { 6252 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6253 Literal = ObjcLiteral->getString(); 6254 } 6255 } 6256 6257 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6258 return ExprError( 6259 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6260 << Arg->getSourceRange()); 6261 } 6262 6263 ExprResult Result(Literal); 6264 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6265 InitializedEntity Entity = 6266 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6267 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6268 return Result; 6269 } 6270 6271 /// Check that the user is calling the appropriate va_start builtin for the 6272 /// target and calling convention. 6273 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6274 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6275 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6276 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6277 TT.getArch() == llvm::Triple::aarch64_32); 6278 bool IsWindows = TT.isOSWindows(); 6279 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6280 if (IsX64 || IsAArch64) { 6281 CallingConv CC = CC_C; 6282 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6283 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6284 if (IsMSVAStart) { 6285 // Don't allow this in System V ABI functions. 6286 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6287 return S.Diag(Fn->getBeginLoc(), 6288 diag::err_ms_va_start_used_in_sysv_function); 6289 } else { 6290 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6291 // On x64 Windows, don't allow this in System V ABI functions. 6292 // (Yes, that means there's no corresponding way to support variadic 6293 // System V ABI functions on Windows.) 6294 if ((IsWindows && CC == CC_X86_64SysV) || 6295 (!IsWindows && CC == CC_Win64)) 6296 return S.Diag(Fn->getBeginLoc(), 6297 diag::err_va_start_used_in_wrong_abi_function) 6298 << !IsWindows; 6299 } 6300 return false; 6301 } 6302 6303 if (IsMSVAStart) 6304 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6305 return false; 6306 } 6307 6308 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6309 ParmVarDecl **LastParam = nullptr) { 6310 // Determine whether the current function, block, or obj-c method is variadic 6311 // and get its parameter list. 6312 bool IsVariadic = false; 6313 ArrayRef<ParmVarDecl *> Params; 6314 DeclContext *Caller = S.CurContext; 6315 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6316 IsVariadic = Block->isVariadic(); 6317 Params = Block->parameters(); 6318 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6319 IsVariadic = FD->isVariadic(); 6320 Params = FD->parameters(); 6321 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6322 IsVariadic = MD->isVariadic(); 6323 // FIXME: This isn't correct for methods (results in bogus warning). 6324 Params = MD->parameters(); 6325 } else if (isa<CapturedDecl>(Caller)) { 6326 // We don't support va_start in a CapturedDecl. 6327 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6328 return true; 6329 } else { 6330 // This must be some other declcontext that parses exprs. 6331 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6332 return true; 6333 } 6334 6335 if (!IsVariadic) { 6336 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6337 return true; 6338 } 6339 6340 if (LastParam) 6341 *LastParam = Params.empty() ? nullptr : Params.back(); 6342 6343 return false; 6344 } 6345 6346 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6347 /// for validity. Emit an error and return true on failure; return false 6348 /// on success. 6349 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6350 Expr *Fn = TheCall->getCallee(); 6351 6352 if (checkVAStartABI(*this, BuiltinID, Fn)) 6353 return true; 6354 6355 if (checkArgCount(*this, TheCall, 2)) 6356 return true; 6357 6358 // Type-check the first argument normally. 6359 if (checkBuiltinArgument(*this, TheCall, 0)) 6360 return true; 6361 6362 // Check that the current function is variadic, and get its last parameter. 6363 ParmVarDecl *LastParam; 6364 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6365 return true; 6366 6367 // Verify that the second argument to the builtin is the last argument of the 6368 // current function or method. 6369 bool SecondArgIsLastNamedArgument = false; 6370 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6371 6372 // These are valid if SecondArgIsLastNamedArgument is false after the next 6373 // block. 6374 QualType Type; 6375 SourceLocation ParamLoc; 6376 bool IsCRegister = false; 6377 6378 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6379 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6380 SecondArgIsLastNamedArgument = PV == LastParam; 6381 6382 Type = PV->getType(); 6383 ParamLoc = PV->getLocation(); 6384 IsCRegister = 6385 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6386 } 6387 } 6388 6389 if (!SecondArgIsLastNamedArgument) 6390 Diag(TheCall->getArg(1)->getBeginLoc(), 6391 diag::warn_second_arg_of_va_start_not_last_named_param); 6392 else if (IsCRegister || Type->isReferenceType() || 6393 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6394 // Promotable integers are UB, but enumerations need a bit of 6395 // extra checking to see what their promotable type actually is. 6396 if (!Type->isPromotableIntegerType()) 6397 return false; 6398 if (!Type->isEnumeralType()) 6399 return true; 6400 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6401 return !(ED && 6402 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6403 }()) { 6404 unsigned Reason = 0; 6405 if (Type->isReferenceType()) Reason = 1; 6406 else if (IsCRegister) Reason = 2; 6407 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6408 Diag(ParamLoc, diag::note_parameter_type) << Type; 6409 } 6410 6411 TheCall->setType(Context.VoidTy); 6412 return false; 6413 } 6414 6415 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6416 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6417 // const char *named_addr); 6418 6419 Expr *Func = Call->getCallee(); 6420 6421 if (Call->getNumArgs() < 3) 6422 return Diag(Call->getEndLoc(), 6423 diag::err_typecheck_call_too_few_args_at_least) 6424 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6425 6426 // Type-check the first argument normally. 6427 if (checkBuiltinArgument(*this, Call, 0)) 6428 return true; 6429 6430 // Check that the current function is variadic. 6431 if (checkVAStartIsInVariadicFunction(*this, Func)) 6432 return true; 6433 6434 // __va_start on Windows does not validate the parameter qualifiers 6435 6436 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6437 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6438 6439 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6440 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6441 6442 const QualType &ConstCharPtrTy = 6443 Context.getPointerType(Context.CharTy.withConst()); 6444 if (!Arg1Ty->isPointerType() || 6445 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 6446 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6447 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6448 << 0 /* qualifier difference */ 6449 << 3 /* parameter mismatch */ 6450 << 2 << Arg1->getType() << ConstCharPtrTy; 6451 6452 const QualType SizeTy = Context.getSizeType(); 6453 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6454 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6455 << Arg2->getType() << SizeTy << 1 /* different class */ 6456 << 0 /* qualifier difference */ 6457 << 3 /* parameter mismatch */ 6458 << 3 << Arg2->getType() << SizeTy; 6459 6460 return false; 6461 } 6462 6463 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6464 /// friends. This is declared to take (...), so we have to check everything. 6465 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6466 if (checkArgCount(*this, TheCall, 2)) 6467 return true; 6468 6469 ExprResult OrigArg0 = TheCall->getArg(0); 6470 ExprResult OrigArg1 = TheCall->getArg(1); 6471 6472 // Do standard promotions between the two arguments, returning their common 6473 // type. 6474 QualType Res = UsualArithmeticConversions( 6475 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6476 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6477 return true; 6478 6479 // Make sure any conversions are pushed back into the call; this is 6480 // type safe since unordered compare builtins are declared as "_Bool 6481 // foo(...)". 6482 TheCall->setArg(0, OrigArg0.get()); 6483 TheCall->setArg(1, OrigArg1.get()); 6484 6485 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6486 return false; 6487 6488 // If the common type isn't a real floating type, then the arguments were 6489 // invalid for this operation. 6490 if (Res.isNull() || !Res->isRealFloatingType()) 6491 return Diag(OrigArg0.get()->getBeginLoc(), 6492 diag::err_typecheck_call_invalid_ordered_compare) 6493 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6494 << SourceRange(OrigArg0.get()->getBeginLoc(), 6495 OrigArg1.get()->getEndLoc()); 6496 6497 return false; 6498 } 6499 6500 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6501 /// __builtin_isnan and friends. This is declared to take (...), so we have 6502 /// to check everything. We expect the last argument to be a floating point 6503 /// value. 6504 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6505 if (checkArgCount(*this, TheCall, NumArgs)) 6506 return true; 6507 6508 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6509 // on all preceding parameters just being int. Try all of those. 6510 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6511 Expr *Arg = TheCall->getArg(i); 6512 6513 if (Arg->isTypeDependent()) 6514 return false; 6515 6516 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6517 6518 if (Res.isInvalid()) 6519 return true; 6520 TheCall->setArg(i, Res.get()); 6521 } 6522 6523 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6524 6525 if (OrigArg->isTypeDependent()) 6526 return false; 6527 6528 // Usual Unary Conversions will convert half to float, which we want for 6529 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6530 // type how it is, but do normal L->Rvalue conversions. 6531 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6532 OrigArg = UsualUnaryConversions(OrigArg).get(); 6533 else 6534 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6535 TheCall->setArg(NumArgs - 1, OrigArg); 6536 6537 // This operation requires a non-_Complex floating-point number. 6538 if (!OrigArg->getType()->isRealFloatingType()) 6539 return Diag(OrigArg->getBeginLoc(), 6540 diag::err_typecheck_call_invalid_unary_fp) 6541 << OrigArg->getType() << OrigArg->getSourceRange(); 6542 6543 return false; 6544 } 6545 6546 /// Perform semantic analysis for a call to __builtin_complex. 6547 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6548 if (checkArgCount(*this, TheCall, 2)) 6549 return true; 6550 6551 bool Dependent = false; 6552 for (unsigned I = 0; I != 2; ++I) { 6553 Expr *Arg = TheCall->getArg(I); 6554 QualType T = Arg->getType(); 6555 if (T->isDependentType()) { 6556 Dependent = true; 6557 continue; 6558 } 6559 6560 // Despite supporting _Complex int, GCC requires a real floating point type 6561 // for the operands of __builtin_complex. 6562 if (!T->isRealFloatingType()) { 6563 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6564 << Arg->getType() << Arg->getSourceRange(); 6565 } 6566 6567 ExprResult Converted = DefaultLvalueConversion(Arg); 6568 if (Converted.isInvalid()) 6569 return true; 6570 TheCall->setArg(I, Converted.get()); 6571 } 6572 6573 if (Dependent) { 6574 TheCall->setType(Context.DependentTy); 6575 return false; 6576 } 6577 6578 Expr *Real = TheCall->getArg(0); 6579 Expr *Imag = TheCall->getArg(1); 6580 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6581 return Diag(Real->getBeginLoc(), 6582 diag::err_typecheck_call_different_arg_types) 6583 << Real->getType() << Imag->getType() 6584 << Real->getSourceRange() << Imag->getSourceRange(); 6585 } 6586 6587 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6588 // don't allow this builtin to form those types either. 6589 // FIXME: Should we allow these types? 6590 if (Real->getType()->isFloat16Type()) 6591 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6592 << "_Float16"; 6593 if (Real->getType()->isHalfType()) 6594 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6595 << "half"; 6596 6597 TheCall->setType(Context.getComplexType(Real->getType())); 6598 return false; 6599 } 6600 6601 // Customized Sema Checking for VSX builtins that have the following signature: 6602 // vector [...] builtinName(vector [...], vector [...], const int); 6603 // Which takes the same type of vectors (any legal vector type) for the first 6604 // two arguments and takes compile time constant for the third argument. 6605 // Example builtins are : 6606 // vector double vec_xxpermdi(vector double, vector double, int); 6607 // vector short vec_xxsldwi(vector short, vector short, int); 6608 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6609 unsigned ExpectedNumArgs = 3; 6610 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6611 return true; 6612 6613 // Check the third argument is a compile time constant 6614 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6615 return Diag(TheCall->getBeginLoc(), 6616 diag::err_vsx_builtin_nonconstant_argument) 6617 << 3 /* argument index */ << TheCall->getDirectCallee() 6618 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6619 TheCall->getArg(2)->getEndLoc()); 6620 6621 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6622 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6623 6624 // Check the type of argument 1 and argument 2 are vectors. 6625 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6626 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6627 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6628 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6629 << TheCall->getDirectCallee() 6630 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6631 TheCall->getArg(1)->getEndLoc()); 6632 } 6633 6634 // Check the first two arguments are the same type. 6635 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6636 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6637 << TheCall->getDirectCallee() 6638 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6639 TheCall->getArg(1)->getEndLoc()); 6640 } 6641 6642 // When default clang type checking is turned off and the customized type 6643 // checking is used, the returning type of the function must be explicitly 6644 // set. Otherwise it is _Bool by default. 6645 TheCall->setType(Arg1Ty); 6646 6647 return false; 6648 } 6649 6650 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6651 // This is declared to take (...), so we have to check everything. 6652 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6653 if (TheCall->getNumArgs() < 2) 6654 return ExprError(Diag(TheCall->getEndLoc(), 6655 diag::err_typecheck_call_too_few_args_at_least) 6656 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6657 << TheCall->getSourceRange()); 6658 6659 // Determine which of the following types of shufflevector we're checking: 6660 // 1) unary, vector mask: (lhs, mask) 6661 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6662 QualType resType = TheCall->getArg(0)->getType(); 6663 unsigned numElements = 0; 6664 6665 if (!TheCall->getArg(0)->isTypeDependent() && 6666 !TheCall->getArg(1)->isTypeDependent()) { 6667 QualType LHSType = TheCall->getArg(0)->getType(); 6668 QualType RHSType = TheCall->getArg(1)->getType(); 6669 6670 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6671 return ExprError( 6672 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6673 << TheCall->getDirectCallee() 6674 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6675 TheCall->getArg(1)->getEndLoc())); 6676 6677 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6678 unsigned numResElements = TheCall->getNumArgs() - 2; 6679 6680 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6681 // with mask. If so, verify that RHS is an integer vector type with the 6682 // same number of elts as lhs. 6683 if (TheCall->getNumArgs() == 2) { 6684 if (!RHSType->hasIntegerRepresentation() || 6685 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6686 return ExprError(Diag(TheCall->getBeginLoc(), 6687 diag::err_vec_builtin_incompatible_vector) 6688 << TheCall->getDirectCallee() 6689 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6690 TheCall->getArg(1)->getEndLoc())); 6691 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6692 return ExprError(Diag(TheCall->getBeginLoc(), 6693 diag::err_vec_builtin_incompatible_vector) 6694 << TheCall->getDirectCallee() 6695 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6696 TheCall->getArg(1)->getEndLoc())); 6697 } else if (numElements != numResElements) { 6698 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6699 resType = Context.getVectorType(eltType, numResElements, 6700 VectorType::GenericVector); 6701 } 6702 } 6703 6704 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6705 if (TheCall->getArg(i)->isTypeDependent() || 6706 TheCall->getArg(i)->isValueDependent()) 6707 continue; 6708 6709 Optional<llvm::APSInt> Result; 6710 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6711 return ExprError(Diag(TheCall->getBeginLoc(), 6712 diag::err_shufflevector_nonconstant_argument) 6713 << TheCall->getArg(i)->getSourceRange()); 6714 6715 // Allow -1 which will be translated to undef in the IR. 6716 if (Result->isSigned() && Result->isAllOnesValue()) 6717 continue; 6718 6719 if (Result->getActiveBits() > 64 || 6720 Result->getZExtValue() >= numElements * 2) 6721 return ExprError(Diag(TheCall->getBeginLoc(), 6722 diag::err_shufflevector_argument_too_large) 6723 << TheCall->getArg(i)->getSourceRange()); 6724 } 6725 6726 SmallVector<Expr*, 32> exprs; 6727 6728 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6729 exprs.push_back(TheCall->getArg(i)); 6730 TheCall->setArg(i, nullptr); 6731 } 6732 6733 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6734 TheCall->getCallee()->getBeginLoc(), 6735 TheCall->getRParenLoc()); 6736 } 6737 6738 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6739 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6740 SourceLocation BuiltinLoc, 6741 SourceLocation RParenLoc) { 6742 ExprValueKind VK = VK_PRValue; 6743 ExprObjectKind OK = OK_Ordinary; 6744 QualType DstTy = TInfo->getType(); 6745 QualType SrcTy = E->getType(); 6746 6747 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6748 return ExprError(Diag(BuiltinLoc, 6749 diag::err_convertvector_non_vector) 6750 << E->getSourceRange()); 6751 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6752 return ExprError(Diag(BuiltinLoc, 6753 diag::err_convertvector_non_vector_type)); 6754 6755 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6756 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6757 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6758 if (SrcElts != DstElts) 6759 return ExprError(Diag(BuiltinLoc, 6760 diag::err_convertvector_incompatible_vector) 6761 << E->getSourceRange()); 6762 } 6763 6764 return new (Context) 6765 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6766 } 6767 6768 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6769 // This is declared to take (const void*, ...) and can take two 6770 // optional constant int args. 6771 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6772 unsigned NumArgs = TheCall->getNumArgs(); 6773 6774 if (NumArgs > 3) 6775 return Diag(TheCall->getEndLoc(), 6776 diag::err_typecheck_call_too_many_args_at_most) 6777 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6778 6779 // Argument 0 is checked for us and the remaining arguments must be 6780 // constant integers. 6781 for (unsigned i = 1; i != NumArgs; ++i) 6782 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6783 return true; 6784 6785 return false; 6786 } 6787 6788 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6789 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6790 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6791 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6792 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6793 if (checkArgCount(*this, TheCall, 1)) 6794 return true; 6795 Expr *Arg = TheCall->getArg(0); 6796 if (Arg->isInstantiationDependent()) 6797 return false; 6798 6799 QualType ArgTy = Arg->getType(); 6800 if (!ArgTy->hasFloatingRepresentation()) 6801 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6802 << ArgTy; 6803 if (Arg->isLValue()) { 6804 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6805 TheCall->setArg(0, FirstArg.get()); 6806 } 6807 TheCall->setType(TheCall->getArg(0)->getType()); 6808 return false; 6809 } 6810 6811 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6812 // __assume does not evaluate its arguments, and should warn if its argument 6813 // has side effects. 6814 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6815 Expr *Arg = TheCall->getArg(0); 6816 if (Arg->isInstantiationDependent()) return false; 6817 6818 if (Arg->HasSideEffects(Context)) 6819 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6820 << Arg->getSourceRange() 6821 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6822 6823 return false; 6824 } 6825 6826 /// Handle __builtin_alloca_with_align. This is declared 6827 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6828 /// than 8. 6829 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6830 // The alignment must be a constant integer. 6831 Expr *Arg = TheCall->getArg(1); 6832 6833 // We can't check the value of a dependent argument. 6834 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6835 if (const auto *UE = 6836 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6837 if (UE->getKind() == UETT_AlignOf || 6838 UE->getKind() == UETT_PreferredAlignOf) 6839 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6840 << Arg->getSourceRange(); 6841 6842 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6843 6844 if (!Result.isPowerOf2()) 6845 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6846 << Arg->getSourceRange(); 6847 6848 if (Result < Context.getCharWidth()) 6849 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6850 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6851 6852 if (Result > std::numeric_limits<int32_t>::max()) 6853 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6854 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6855 } 6856 6857 return false; 6858 } 6859 6860 /// Handle __builtin_assume_aligned. This is declared 6861 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6862 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6863 unsigned NumArgs = TheCall->getNumArgs(); 6864 6865 if (NumArgs > 3) 6866 return Diag(TheCall->getEndLoc(), 6867 diag::err_typecheck_call_too_many_args_at_most) 6868 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6869 6870 // The alignment must be a constant integer. 6871 Expr *Arg = TheCall->getArg(1); 6872 6873 // We can't check the value of a dependent argument. 6874 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6875 llvm::APSInt Result; 6876 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6877 return true; 6878 6879 if (!Result.isPowerOf2()) 6880 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6881 << Arg->getSourceRange(); 6882 6883 if (Result > Sema::MaximumAlignment) 6884 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6885 << Arg->getSourceRange() << Sema::MaximumAlignment; 6886 } 6887 6888 if (NumArgs > 2) { 6889 ExprResult Arg(TheCall->getArg(2)); 6890 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6891 Context.getSizeType(), false); 6892 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6893 if (Arg.isInvalid()) return true; 6894 TheCall->setArg(2, Arg.get()); 6895 } 6896 6897 return false; 6898 } 6899 6900 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6901 unsigned BuiltinID = 6902 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6903 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6904 6905 unsigned NumArgs = TheCall->getNumArgs(); 6906 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6907 if (NumArgs < NumRequiredArgs) { 6908 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6909 << 0 /* function call */ << NumRequiredArgs << NumArgs 6910 << TheCall->getSourceRange(); 6911 } 6912 if (NumArgs >= NumRequiredArgs + 0x100) { 6913 return Diag(TheCall->getEndLoc(), 6914 diag::err_typecheck_call_too_many_args_at_most) 6915 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6916 << TheCall->getSourceRange(); 6917 } 6918 unsigned i = 0; 6919 6920 // For formatting call, check buffer arg. 6921 if (!IsSizeCall) { 6922 ExprResult Arg(TheCall->getArg(i)); 6923 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6924 Context, Context.VoidPtrTy, false); 6925 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6926 if (Arg.isInvalid()) 6927 return true; 6928 TheCall->setArg(i, Arg.get()); 6929 i++; 6930 } 6931 6932 // Check string literal arg. 6933 unsigned FormatIdx = i; 6934 { 6935 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6936 if (Arg.isInvalid()) 6937 return true; 6938 TheCall->setArg(i, Arg.get()); 6939 i++; 6940 } 6941 6942 // Make sure variadic args are scalar. 6943 unsigned FirstDataArg = i; 6944 while (i < NumArgs) { 6945 ExprResult Arg = DefaultVariadicArgumentPromotion( 6946 TheCall->getArg(i), VariadicFunction, nullptr); 6947 if (Arg.isInvalid()) 6948 return true; 6949 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6950 if (ArgSize.getQuantity() >= 0x100) { 6951 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6952 << i << (int)ArgSize.getQuantity() << 0xff 6953 << TheCall->getSourceRange(); 6954 } 6955 TheCall->setArg(i, Arg.get()); 6956 i++; 6957 } 6958 6959 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6960 // call to avoid duplicate diagnostics. 6961 if (!IsSizeCall) { 6962 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6963 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6964 bool Success = CheckFormatArguments( 6965 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6966 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6967 CheckedVarArgs); 6968 if (!Success) 6969 return true; 6970 } 6971 6972 if (IsSizeCall) { 6973 TheCall->setType(Context.getSizeType()); 6974 } else { 6975 TheCall->setType(Context.VoidPtrTy); 6976 } 6977 return false; 6978 } 6979 6980 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6981 /// TheCall is a constant expression. 6982 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6983 llvm::APSInt &Result) { 6984 Expr *Arg = TheCall->getArg(ArgNum); 6985 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6986 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6987 6988 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6989 6990 Optional<llvm::APSInt> R; 6991 if (!(R = Arg->getIntegerConstantExpr(Context))) 6992 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6993 << FDecl->getDeclName() << Arg->getSourceRange(); 6994 Result = *R; 6995 return false; 6996 } 6997 6998 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6999 /// TheCall is a constant expression in the range [Low, High]. 7000 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7001 int Low, int High, bool RangeIsError) { 7002 if (isConstantEvaluated()) 7003 return false; 7004 llvm::APSInt Result; 7005 7006 // We can't check the value of a dependent argument. 7007 Expr *Arg = TheCall->getArg(ArgNum); 7008 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7009 return false; 7010 7011 // Check constant-ness first. 7012 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7013 return true; 7014 7015 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7016 if (RangeIsError) 7017 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7018 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7019 else 7020 // Defer the warning until we know if the code will be emitted so that 7021 // dead code can ignore this. 7022 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7023 PDiag(diag::warn_argument_invalid_range) 7024 << toString(Result, 10) << Low << High 7025 << Arg->getSourceRange()); 7026 } 7027 7028 return false; 7029 } 7030 7031 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7032 /// TheCall is a constant expression is a multiple of Num.. 7033 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7034 unsigned Num) { 7035 llvm::APSInt Result; 7036 7037 // We can't check the value of a dependent argument. 7038 Expr *Arg = TheCall->getArg(ArgNum); 7039 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7040 return false; 7041 7042 // Check constant-ness first. 7043 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7044 return true; 7045 7046 if (Result.getSExtValue() % Num != 0) 7047 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7048 << Num << Arg->getSourceRange(); 7049 7050 return false; 7051 } 7052 7053 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7054 /// constant expression representing a power of 2. 7055 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7056 llvm::APSInt Result; 7057 7058 // We can't check the value of a dependent argument. 7059 Expr *Arg = TheCall->getArg(ArgNum); 7060 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7061 return false; 7062 7063 // Check constant-ness first. 7064 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7065 return true; 7066 7067 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7068 // and only if x is a power of 2. 7069 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7070 return false; 7071 7072 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7073 << Arg->getSourceRange(); 7074 } 7075 7076 static bool IsShiftedByte(llvm::APSInt Value) { 7077 if (Value.isNegative()) 7078 return false; 7079 7080 // Check if it's a shifted byte, by shifting it down 7081 while (true) { 7082 // If the value fits in the bottom byte, the check passes. 7083 if (Value < 0x100) 7084 return true; 7085 7086 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7087 // fails. 7088 if ((Value & 0xFF) != 0) 7089 return false; 7090 7091 // If the bottom 8 bits are all 0, but something above that is nonzero, 7092 // then shifting the value right by 8 bits won't affect whether it's a 7093 // shifted byte or not. So do that, and go round again. 7094 Value >>= 8; 7095 } 7096 } 7097 7098 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7099 /// a constant expression representing an arbitrary byte value shifted left by 7100 /// a multiple of 8 bits. 7101 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7102 unsigned ArgBits) { 7103 llvm::APSInt Result; 7104 7105 // We can't check the value of a dependent argument. 7106 Expr *Arg = TheCall->getArg(ArgNum); 7107 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7108 return false; 7109 7110 // Check constant-ness first. 7111 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7112 return true; 7113 7114 // Truncate to the given size. 7115 Result = Result.getLoBits(ArgBits); 7116 Result.setIsUnsigned(true); 7117 7118 if (IsShiftedByte(Result)) 7119 return false; 7120 7121 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7122 << Arg->getSourceRange(); 7123 } 7124 7125 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7126 /// TheCall is a constant expression representing either a shifted byte value, 7127 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7128 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7129 /// Arm MVE intrinsics. 7130 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7131 int ArgNum, 7132 unsigned ArgBits) { 7133 llvm::APSInt Result; 7134 7135 // We can't check the value of a dependent argument. 7136 Expr *Arg = TheCall->getArg(ArgNum); 7137 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7138 return false; 7139 7140 // Check constant-ness first. 7141 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7142 return true; 7143 7144 // Truncate to the given size. 7145 Result = Result.getLoBits(ArgBits); 7146 Result.setIsUnsigned(true); 7147 7148 // Check to see if it's in either of the required forms. 7149 if (IsShiftedByte(Result) || 7150 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7151 return false; 7152 7153 return Diag(TheCall->getBeginLoc(), 7154 diag::err_argument_not_shifted_byte_or_xxff) 7155 << Arg->getSourceRange(); 7156 } 7157 7158 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7159 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7160 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7161 if (checkArgCount(*this, TheCall, 2)) 7162 return true; 7163 Expr *Arg0 = TheCall->getArg(0); 7164 Expr *Arg1 = TheCall->getArg(1); 7165 7166 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7167 if (FirstArg.isInvalid()) 7168 return true; 7169 QualType FirstArgType = FirstArg.get()->getType(); 7170 if (!FirstArgType->isAnyPointerType()) 7171 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7172 << "first" << FirstArgType << Arg0->getSourceRange(); 7173 TheCall->setArg(0, FirstArg.get()); 7174 7175 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7176 if (SecArg.isInvalid()) 7177 return true; 7178 QualType SecArgType = SecArg.get()->getType(); 7179 if (!SecArgType->isIntegerType()) 7180 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7181 << "second" << SecArgType << Arg1->getSourceRange(); 7182 7183 // Derive the return type from the pointer argument. 7184 TheCall->setType(FirstArgType); 7185 return false; 7186 } 7187 7188 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7189 if (checkArgCount(*this, TheCall, 2)) 7190 return true; 7191 7192 Expr *Arg0 = TheCall->getArg(0); 7193 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7194 if (FirstArg.isInvalid()) 7195 return true; 7196 QualType FirstArgType = FirstArg.get()->getType(); 7197 if (!FirstArgType->isAnyPointerType()) 7198 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7199 << "first" << FirstArgType << Arg0->getSourceRange(); 7200 TheCall->setArg(0, FirstArg.get()); 7201 7202 // Derive the return type from the pointer argument. 7203 TheCall->setType(FirstArgType); 7204 7205 // Second arg must be an constant in range [0,15] 7206 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7207 } 7208 7209 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7210 if (checkArgCount(*this, TheCall, 2)) 7211 return true; 7212 Expr *Arg0 = TheCall->getArg(0); 7213 Expr *Arg1 = TheCall->getArg(1); 7214 7215 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7216 if (FirstArg.isInvalid()) 7217 return true; 7218 QualType FirstArgType = FirstArg.get()->getType(); 7219 if (!FirstArgType->isAnyPointerType()) 7220 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7221 << "first" << FirstArgType << Arg0->getSourceRange(); 7222 7223 QualType SecArgType = Arg1->getType(); 7224 if (!SecArgType->isIntegerType()) 7225 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7226 << "second" << SecArgType << Arg1->getSourceRange(); 7227 TheCall->setType(Context.IntTy); 7228 return false; 7229 } 7230 7231 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7232 BuiltinID == AArch64::BI__builtin_arm_stg) { 7233 if (checkArgCount(*this, TheCall, 1)) 7234 return true; 7235 Expr *Arg0 = TheCall->getArg(0); 7236 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7237 if (FirstArg.isInvalid()) 7238 return true; 7239 7240 QualType FirstArgType = FirstArg.get()->getType(); 7241 if (!FirstArgType->isAnyPointerType()) 7242 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7243 << "first" << FirstArgType << Arg0->getSourceRange(); 7244 TheCall->setArg(0, FirstArg.get()); 7245 7246 // Derive the return type from the pointer argument. 7247 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7248 TheCall->setType(FirstArgType); 7249 return false; 7250 } 7251 7252 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7253 Expr *ArgA = TheCall->getArg(0); 7254 Expr *ArgB = TheCall->getArg(1); 7255 7256 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7257 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7258 7259 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7260 return true; 7261 7262 QualType ArgTypeA = ArgExprA.get()->getType(); 7263 QualType ArgTypeB = ArgExprB.get()->getType(); 7264 7265 auto isNull = [&] (Expr *E) -> bool { 7266 return E->isNullPointerConstant( 7267 Context, Expr::NPC_ValueDependentIsNotNull); }; 7268 7269 // argument should be either a pointer or null 7270 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7271 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7272 << "first" << ArgTypeA << ArgA->getSourceRange(); 7273 7274 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7275 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7276 << "second" << ArgTypeB << ArgB->getSourceRange(); 7277 7278 // Ensure Pointee types are compatible 7279 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7280 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7281 QualType pointeeA = ArgTypeA->getPointeeType(); 7282 QualType pointeeB = ArgTypeB->getPointeeType(); 7283 if (!Context.typesAreCompatible( 7284 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7285 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7286 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7287 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7288 << ArgB->getSourceRange(); 7289 } 7290 } 7291 7292 // at least one argument should be pointer type 7293 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7294 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7295 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7296 7297 if (isNull(ArgA)) // adopt type of the other pointer 7298 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7299 7300 if (isNull(ArgB)) 7301 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7302 7303 TheCall->setArg(0, ArgExprA.get()); 7304 TheCall->setArg(1, ArgExprB.get()); 7305 TheCall->setType(Context.LongLongTy); 7306 return false; 7307 } 7308 assert(false && "Unhandled ARM MTE intrinsic"); 7309 return true; 7310 } 7311 7312 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7313 /// TheCall is an ARM/AArch64 special register string literal. 7314 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7315 int ArgNum, unsigned ExpectedFieldNum, 7316 bool AllowName) { 7317 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7318 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7319 BuiltinID == ARM::BI__builtin_arm_rsr || 7320 BuiltinID == ARM::BI__builtin_arm_rsrp || 7321 BuiltinID == ARM::BI__builtin_arm_wsr || 7322 BuiltinID == ARM::BI__builtin_arm_wsrp; 7323 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7324 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7325 BuiltinID == AArch64::BI__builtin_arm_rsr || 7326 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7327 BuiltinID == AArch64::BI__builtin_arm_wsr || 7328 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7329 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7330 7331 // We can't check the value of a dependent argument. 7332 Expr *Arg = TheCall->getArg(ArgNum); 7333 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7334 return false; 7335 7336 // Check if the argument is a string literal. 7337 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7338 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7339 << Arg->getSourceRange(); 7340 7341 // Check the type of special register given. 7342 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7343 SmallVector<StringRef, 6> Fields; 7344 Reg.split(Fields, ":"); 7345 7346 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7347 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7348 << Arg->getSourceRange(); 7349 7350 // If the string is the name of a register then we cannot check that it is 7351 // valid here but if the string is of one the forms described in ACLE then we 7352 // can check that the supplied fields are integers and within the valid 7353 // ranges. 7354 if (Fields.size() > 1) { 7355 bool FiveFields = Fields.size() == 5; 7356 7357 bool ValidString = true; 7358 if (IsARMBuiltin) { 7359 ValidString &= Fields[0].startswith_insensitive("cp") || 7360 Fields[0].startswith_insensitive("p"); 7361 if (ValidString) 7362 Fields[0] = Fields[0].drop_front( 7363 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7364 7365 ValidString &= Fields[2].startswith_insensitive("c"); 7366 if (ValidString) 7367 Fields[2] = Fields[2].drop_front(1); 7368 7369 if (FiveFields) { 7370 ValidString &= Fields[3].startswith_insensitive("c"); 7371 if (ValidString) 7372 Fields[3] = Fields[3].drop_front(1); 7373 } 7374 } 7375 7376 SmallVector<int, 5> Ranges; 7377 if (FiveFields) 7378 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7379 else 7380 Ranges.append({15, 7, 15}); 7381 7382 for (unsigned i=0; i<Fields.size(); ++i) { 7383 int IntField; 7384 ValidString &= !Fields[i].getAsInteger(10, IntField); 7385 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7386 } 7387 7388 if (!ValidString) 7389 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7390 << Arg->getSourceRange(); 7391 } else if (IsAArch64Builtin && Fields.size() == 1) { 7392 // If the register name is one of those that appear in the condition below 7393 // and the special register builtin being used is one of the write builtins, 7394 // then we require that the argument provided for writing to the register 7395 // is an integer constant expression. This is because it will be lowered to 7396 // an MSR (immediate) instruction, so we need to know the immediate at 7397 // compile time. 7398 if (TheCall->getNumArgs() != 2) 7399 return false; 7400 7401 std::string RegLower = Reg.lower(); 7402 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7403 RegLower != "pan" && RegLower != "uao") 7404 return false; 7405 7406 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7407 } 7408 7409 return false; 7410 } 7411 7412 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7413 /// Emit an error and return true on failure; return false on success. 7414 /// TypeStr is a string containing the type descriptor of the value returned by 7415 /// the builtin and the descriptors of the expected type of the arguments. 7416 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 7417 7418 assert((TypeStr[0] != '\0') && 7419 "Invalid types in PPC MMA builtin declaration"); 7420 7421 unsigned Mask = 0; 7422 unsigned ArgNum = 0; 7423 7424 // The first type in TypeStr is the type of the value returned by the 7425 // builtin. So we first read that type and change the type of TheCall. 7426 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7427 TheCall->setType(type); 7428 7429 while (*TypeStr != '\0') { 7430 Mask = 0; 7431 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7432 if (ArgNum >= TheCall->getNumArgs()) { 7433 ArgNum++; 7434 break; 7435 } 7436 7437 Expr *Arg = TheCall->getArg(ArgNum); 7438 QualType ArgType = Arg->getType(); 7439 7440 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7441 (!ExpectedType->isVoidPointerType() && 7442 ArgType.getCanonicalType() != ExpectedType)) 7443 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7444 << ArgType << ExpectedType << 1 << 0 << 0; 7445 7446 // If the value of the Mask is not 0, we have a constraint in the size of 7447 // the integer argument so here we ensure the argument is a constant that 7448 // is in the valid range. 7449 if (Mask != 0 && 7450 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7451 return true; 7452 7453 ArgNum++; 7454 } 7455 7456 // In case we exited early from the previous loop, there are other types to 7457 // read from TypeStr. So we need to read them all to ensure we have the right 7458 // number of arguments in TheCall and if it is not the case, to display a 7459 // better error message. 7460 while (*TypeStr != '\0') { 7461 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7462 ArgNum++; 7463 } 7464 if (checkArgCount(*this, TheCall, ArgNum)) 7465 return true; 7466 7467 return false; 7468 } 7469 7470 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7471 /// This checks that the target supports __builtin_longjmp and 7472 /// that val is a constant 1. 7473 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7474 if (!Context.getTargetInfo().hasSjLjLowering()) 7475 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7476 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7477 7478 Expr *Arg = TheCall->getArg(1); 7479 llvm::APSInt Result; 7480 7481 // TODO: This is less than ideal. Overload this to take a value. 7482 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7483 return true; 7484 7485 if (Result != 1) 7486 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7487 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7488 7489 return false; 7490 } 7491 7492 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7493 /// This checks that the target supports __builtin_setjmp. 7494 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7495 if (!Context.getTargetInfo().hasSjLjLowering()) 7496 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7497 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7498 return false; 7499 } 7500 7501 namespace { 7502 7503 class UncoveredArgHandler { 7504 enum { Unknown = -1, AllCovered = -2 }; 7505 7506 signed FirstUncoveredArg = Unknown; 7507 SmallVector<const Expr *, 4> DiagnosticExprs; 7508 7509 public: 7510 UncoveredArgHandler() = default; 7511 7512 bool hasUncoveredArg() const { 7513 return (FirstUncoveredArg >= 0); 7514 } 7515 7516 unsigned getUncoveredArg() const { 7517 assert(hasUncoveredArg() && "no uncovered argument"); 7518 return FirstUncoveredArg; 7519 } 7520 7521 void setAllCovered() { 7522 // A string has been found with all arguments covered, so clear out 7523 // the diagnostics. 7524 DiagnosticExprs.clear(); 7525 FirstUncoveredArg = AllCovered; 7526 } 7527 7528 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7529 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7530 7531 // Don't update if a previous string covers all arguments. 7532 if (FirstUncoveredArg == AllCovered) 7533 return; 7534 7535 // UncoveredArgHandler tracks the highest uncovered argument index 7536 // and with it all the strings that match this index. 7537 if (NewFirstUncoveredArg == FirstUncoveredArg) 7538 DiagnosticExprs.push_back(StrExpr); 7539 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7540 DiagnosticExprs.clear(); 7541 DiagnosticExprs.push_back(StrExpr); 7542 FirstUncoveredArg = NewFirstUncoveredArg; 7543 } 7544 } 7545 7546 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7547 }; 7548 7549 enum StringLiteralCheckType { 7550 SLCT_NotALiteral, 7551 SLCT_UncheckedLiteral, 7552 SLCT_CheckedLiteral 7553 }; 7554 7555 } // namespace 7556 7557 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7558 BinaryOperatorKind BinOpKind, 7559 bool AddendIsRight) { 7560 unsigned BitWidth = Offset.getBitWidth(); 7561 unsigned AddendBitWidth = Addend.getBitWidth(); 7562 // There might be negative interim results. 7563 if (Addend.isUnsigned()) { 7564 Addend = Addend.zext(++AddendBitWidth); 7565 Addend.setIsSigned(true); 7566 } 7567 // Adjust the bit width of the APSInts. 7568 if (AddendBitWidth > BitWidth) { 7569 Offset = Offset.sext(AddendBitWidth); 7570 BitWidth = AddendBitWidth; 7571 } else if (BitWidth > AddendBitWidth) { 7572 Addend = Addend.sext(BitWidth); 7573 } 7574 7575 bool Ov = false; 7576 llvm::APSInt ResOffset = Offset; 7577 if (BinOpKind == BO_Add) 7578 ResOffset = Offset.sadd_ov(Addend, Ov); 7579 else { 7580 assert(AddendIsRight && BinOpKind == BO_Sub && 7581 "operator must be add or sub with addend on the right"); 7582 ResOffset = Offset.ssub_ov(Addend, Ov); 7583 } 7584 7585 // We add an offset to a pointer here so we should support an offset as big as 7586 // possible. 7587 if (Ov) { 7588 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7589 "index (intermediate) result too big"); 7590 Offset = Offset.sext(2 * BitWidth); 7591 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7592 return; 7593 } 7594 7595 Offset = ResOffset; 7596 } 7597 7598 namespace { 7599 7600 // This is a wrapper class around StringLiteral to support offsetted string 7601 // literals as format strings. It takes the offset into account when returning 7602 // the string and its length or the source locations to display notes correctly. 7603 class FormatStringLiteral { 7604 const StringLiteral *FExpr; 7605 int64_t Offset; 7606 7607 public: 7608 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7609 : FExpr(fexpr), Offset(Offset) {} 7610 7611 StringRef getString() const { 7612 return FExpr->getString().drop_front(Offset); 7613 } 7614 7615 unsigned getByteLength() const { 7616 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7617 } 7618 7619 unsigned getLength() const { return FExpr->getLength() - Offset; } 7620 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7621 7622 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7623 7624 QualType getType() const { return FExpr->getType(); } 7625 7626 bool isAscii() const { return FExpr->isAscii(); } 7627 bool isWide() const { return FExpr->isWide(); } 7628 bool isUTF8() const { return FExpr->isUTF8(); } 7629 bool isUTF16() const { return FExpr->isUTF16(); } 7630 bool isUTF32() const { return FExpr->isUTF32(); } 7631 bool isPascal() const { return FExpr->isPascal(); } 7632 7633 SourceLocation getLocationOfByte( 7634 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7635 const TargetInfo &Target, unsigned *StartToken = nullptr, 7636 unsigned *StartTokenByteOffset = nullptr) const { 7637 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7638 StartToken, StartTokenByteOffset); 7639 } 7640 7641 SourceLocation getBeginLoc() const LLVM_READONLY { 7642 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7643 } 7644 7645 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7646 }; 7647 7648 } // namespace 7649 7650 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7651 const Expr *OrigFormatExpr, 7652 ArrayRef<const Expr *> Args, 7653 bool HasVAListArg, unsigned format_idx, 7654 unsigned firstDataArg, 7655 Sema::FormatStringType Type, 7656 bool inFunctionCall, 7657 Sema::VariadicCallType CallType, 7658 llvm::SmallBitVector &CheckedVarArgs, 7659 UncoveredArgHandler &UncoveredArg, 7660 bool IgnoreStringsWithoutSpecifiers); 7661 7662 // Determine if an expression is a string literal or constant string. 7663 // If this function returns false on the arguments to a function expecting a 7664 // format string, we will usually need to emit a warning. 7665 // True string literals are then checked by CheckFormatString. 7666 static StringLiteralCheckType 7667 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7668 bool HasVAListArg, unsigned format_idx, 7669 unsigned firstDataArg, Sema::FormatStringType Type, 7670 Sema::VariadicCallType CallType, bool InFunctionCall, 7671 llvm::SmallBitVector &CheckedVarArgs, 7672 UncoveredArgHandler &UncoveredArg, 7673 llvm::APSInt Offset, 7674 bool IgnoreStringsWithoutSpecifiers = false) { 7675 if (S.isConstantEvaluated()) 7676 return SLCT_NotALiteral; 7677 tryAgain: 7678 assert(Offset.isSigned() && "invalid offset"); 7679 7680 if (E->isTypeDependent() || E->isValueDependent()) 7681 return SLCT_NotALiteral; 7682 7683 E = E->IgnoreParenCasts(); 7684 7685 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7686 // Technically -Wformat-nonliteral does not warn about this case. 7687 // The behavior of printf and friends in this case is implementation 7688 // dependent. Ideally if the format string cannot be null then 7689 // it should have a 'nonnull' attribute in the function prototype. 7690 return SLCT_UncheckedLiteral; 7691 7692 switch (E->getStmtClass()) { 7693 case Stmt::BinaryConditionalOperatorClass: 7694 case Stmt::ConditionalOperatorClass: { 7695 // The expression is a literal if both sub-expressions were, and it was 7696 // completely checked only if both sub-expressions were checked. 7697 const AbstractConditionalOperator *C = 7698 cast<AbstractConditionalOperator>(E); 7699 7700 // Determine whether it is necessary to check both sub-expressions, for 7701 // example, because the condition expression is a constant that can be 7702 // evaluated at compile time. 7703 bool CheckLeft = true, CheckRight = true; 7704 7705 bool Cond; 7706 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7707 S.isConstantEvaluated())) { 7708 if (Cond) 7709 CheckRight = false; 7710 else 7711 CheckLeft = false; 7712 } 7713 7714 // We need to maintain the offsets for the right and the left hand side 7715 // separately to check if every possible indexed expression is a valid 7716 // string literal. They might have different offsets for different string 7717 // literals in the end. 7718 StringLiteralCheckType Left; 7719 if (!CheckLeft) 7720 Left = SLCT_UncheckedLiteral; 7721 else { 7722 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7723 HasVAListArg, format_idx, firstDataArg, 7724 Type, CallType, InFunctionCall, 7725 CheckedVarArgs, UncoveredArg, Offset, 7726 IgnoreStringsWithoutSpecifiers); 7727 if (Left == SLCT_NotALiteral || !CheckRight) { 7728 return Left; 7729 } 7730 } 7731 7732 StringLiteralCheckType Right = checkFormatStringExpr( 7733 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7734 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7735 IgnoreStringsWithoutSpecifiers); 7736 7737 return (CheckLeft && Left < Right) ? Left : Right; 7738 } 7739 7740 case Stmt::ImplicitCastExprClass: 7741 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7742 goto tryAgain; 7743 7744 case Stmt::OpaqueValueExprClass: 7745 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7746 E = src; 7747 goto tryAgain; 7748 } 7749 return SLCT_NotALiteral; 7750 7751 case Stmt::PredefinedExprClass: 7752 // While __func__, etc., are technically not string literals, they 7753 // cannot contain format specifiers and thus are not a security 7754 // liability. 7755 return SLCT_UncheckedLiteral; 7756 7757 case Stmt::DeclRefExprClass: { 7758 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7759 7760 // As an exception, do not flag errors for variables binding to 7761 // const string literals. 7762 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7763 bool isConstant = false; 7764 QualType T = DR->getType(); 7765 7766 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7767 isConstant = AT->getElementType().isConstant(S.Context); 7768 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7769 isConstant = T.isConstant(S.Context) && 7770 PT->getPointeeType().isConstant(S.Context); 7771 } else if (T->isObjCObjectPointerType()) { 7772 // In ObjC, there is usually no "const ObjectPointer" type, 7773 // so don't check if the pointee type is constant. 7774 isConstant = T.isConstant(S.Context); 7775 } 7776 7777 if (isConstant) { 7778 if (const Expr *Init = VD->getAnyInitializer()) { 7779 // Look through initializers like const char c[] = { "foo" } 7780 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7781 if (InitList->isStringLiteralInit()) 7782 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7783 } 7784 return checkFormatStringExpr(S, Init, Args, 7785 HasVAListArg, format_idx, 7786 firstDataArg, Type, CallType, 7787 /*InFunctionCall*/ false, CheckedVarArgs, 7788 UncoveredArg, Offset); 7789 } 7790 } 7791 7792 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7793 // special check to see if the format string is a function parameter 7794 // of the function calling the printf function. If the function 7795 // has an attribute indicating it is a printf-like function, then we 7796 // should suppress warnings concerning non-literals being used in a call 7797 // to a vprintf function. For example: 7798 // 7799 // void 7800 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7801 // va_list ap; 7802 // va_start(ap, fmt); 7803 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7804 // ... 7805 // } 7806 if (HasVAListArg) { 7807 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7808 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7809 int PVIndex = PV->getFunctionScopeIndex() + 1; 7810 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7811 // adjust for implicit parameter 7812 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7813 if (MD->isInstance()) 7814 ++PVIndex; 7815 // We also check if the formats are compatible. 7816 // We can't pass a 'scanf' string to a 'printf' function. 7817 if (PVIndex == PVFormat->getFormatIdx() && 7818 Type == S.GetFormatStringType(PVFormat)) 7819 return SLCT_UncheckedLiteral; 7820 } 7821 } 7822 } 7823 } 7824 } 7825 7826 return SLCT_NotALiteral; 7827 } 7828 7829 case Stmt::CallExprClass: 7830 case Stmt::CXXMemberCallExprClass: { 7831 const CallExpr *CE = cast<CallExpr>(E); 7832 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7833 bool IsFirst = true; 7834 StringLiteralCheckType CommonResult; 7835 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7836 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7837 StringLiteralCheckType Result = checkFormatStringExpr( 7838 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7839 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7840 IgnoreStringsWithoutSpecifiers); 7841 if (IsFirst) { 7842 CommonResult = Result; 7843 IsFirst = false; 7844 } 7845 } 7846 if (!IsFirst) 7847 return CommonResult; 7848 7849 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7850 unsigned BuiltinID = FD->getBuiltinID(); 7851 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7852 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7853 const Expr *Arg = CE->getArg(0); 7854 return checkFormatStringExpr(S, Arg, Args, 7855 HasVAListArg, format_idx, 7856 firstDataArg, Type, CallType, 7857 InFunctionCall, CheckedVarArgs, 7858 UncoveredArg, Offset, 7859 IgnoreStringsWithoutSpecifiers); 7860 } 7861 } 7862 } 7863 7864 return SLCT_NotALiteral; 7865 } 7866 case Stmt::ObjCMessageExprClass: { 7867 const auto *ME = cast<ObjCMessageExpr>(E); 7868 if (const auto *MD = ME->getMethodDecl()) { 7869 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7870 // As a special case heuristic, if we're using the method -[NSBundle 7871 // localizedStringForKey:value:table:], ignore any key strings that lack 7872 // format specifiers. The idea is that if the key doesn't have any 7873 // format specifiers then its probably just a key to map to the 7874 // localized strings. If it does have format specifiers though, then its 7875 // likely that the text of the key is the format string in the 7876 // programmer's language, and should be checked. 7877 const ObjCInterfaceDecl *IFace; 7878 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7879 IFace->getIdentifier()->isStr("NSBundle") && 7880 MD->getSelector().isKeywordSelector( 7881 {"localizedStringForKey", "value", "table"})) { 7882 IgnoreStringsWithoutSpecifiers = true; 7883 } 7884 7885 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7886 return checkFormatStringExpr( 7887 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7888 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7889 IgnoreStringsWithoutSpecifiers); 7890 } 7891 } 7892 7893 return SLCT_NotALiteral; 7894 } 7895 case Stmt::ObjCStringLiteralClass: 7896 case Stmt::StringLiteralClass: { 7897 const StringLiteral *StrE = nullptr; 7898 7899 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7900 StrE = ObjCFExpr->getString(); 7901 else 7902 StrE = cast<StringLiteral>(E); 7903 7904 if (StrE) { 7905 if (Offset.isNegative() || Offset > StrE->getLength()) { 7906 // TODO: It would be better to have an explicit warning for out of 7907 // bounds literals. 7908 return SLCT_NotALiteral; 7909 } 7910 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7911 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7912 firstDataArg, Type, InFunctionCall, CallType, 7913 CheckedVarArgs, UncoveredArg, 7914 IgnoreStringsWithoutSpecifiers); 7915 return SLCT_CheckedLiteral; 7916 } 7917 7918 return SLCT_NotALiteral; 7919 } 7920 case Stmt::BinaryOperatorClass: { 7921 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7922 7923 // A string literal + an int offset is still a string literal. 7924 if (BinOp->isAdditiveOp()) { 7925 Expr::EvalResult LResult, RResult; 7926 7927 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7928 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7929 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7930 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7931 7932 if (LIsInt != RIsInt) { 7933 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7934 7935 if (LIsInt) { 7936 if (BinOpKind == BO_Add) { 7937 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7938 E = BinOp->getRHS(); 7939 goto tryAgain; 7940 } 7941 } else { 7942 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7943 E = BinOp->getLHS(); 7944 goto tryAgain; 7945 } 7946 } 7947 } 7948 7949 return SLCT_NotALiteral; 7950 } 7951 case Stmt::UnaryOperatorClass: { 7952 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7953 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7954 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7955 Expr::EvalResult IndexResult; 7956 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7957 Expr::SE_NoSideEffects, 7958 S.isConstantEvaluated())) { 7959 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7960 /*RHS is int*/ true); 7961 E = ASE->getBase(); 7962 goto tryAgain; 7963 } 7964 } 7965 7966 return SLCT_NotALiteral; 7967 } 7968 7969 default: 7970 return SLCT_NotALiteral; 7971 } 7972 } 7973 7974 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7975 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7976 .Case("scanf", FST_Scanf) 7977 .Cases("printf", "printf0", FST_Printf) 7978 .Cases("NSString", "CFString", FST_NSString) 7979 .Case("strftime", FST_Strftime) 7980 .Case("strfmon", FST_Strfmon) 7981 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7982 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7983 .Case("os_trace", FST_OSLog) 7984 .Case("os_log", FST_OSLog) 7985 .Default(FST_Unknown); 7986 } 7987 7988 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7989 /// functions) for correct use of format strings. 7990 /// Returns true if a format string has been fully checked. 7991 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7992 ArrayRef<const Expr *> Args, 7993 bool IsCXXMember, 7994 VariadicCallType CallType, 7995 SourceLocation Loc, SourceRange Range, 7996 llvm::SmallBitVector &CheckedVarArgs) { 7997 FormatStringInfo FSI; 7998 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7999 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8000 FSI.FirstDataArg, GetFormatStringType(Format), 8001 CallType, Loc, Range, CheckedVarArgs); 8002 return false; 8003 } 8004 8005 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8006 bool HasVAListArg, unsigned format_idx, 8007 unsigned firstDataArg, FormatStringType Type, 8008 VariadicCallType CallType, 8009 SourceLocation Loc, SourceRange Range, 8010 llvm::SmallBitVector &CheckedVarArgs) { 8011 // CHECK: printf/scanf-like function is called with no format string. 8012 if (format_idx >= Args.size()) { 8013 Diag(Loc, diag::warn_missing_format_string) << Range; 8014 return false; 8015 } 8016 8017 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8018 8019 // CHECK: format string is not a string literal. 8020 // 8021 // Dynamically generated format strings are difficult to 8022 // automatically vet at compile time. Requiring that format strings 8023 // are string literals: (1) permits the checking of format strings by 8024 // the compiler and thereby (2) can practically remove the source of 8025 // many format string exploits. 8026 8027 // Format string can be either ObjC string (e.g. @"%d") or 8028 // C string (e.g. "%d") 8029 // ObjC string uses the same format specifiers as C string, so we can use 8030 // the same format string checking logic for both ObjC and C strings. 8031 UncoveredArgHandler UncoveredArg; 8032 StringLiteralCheckType CT = 8033 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8034 format_idx, firstDataArg, Type, CallType, 8035 /*IsFunctionCall*/ true, CheckedVarArgs, 8036 UncoveredArg, 8037 /*no string offset*/ llvm::APSInt(64, false) = 0); 8038 8039 // Generate a diagnostic where an uncovered argument is detected. 8040 if (UncoveredArg.hasUncoveredArg()) { 8041 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8042 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8043 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8044 } 8045 8046 if (CT != SLCT_NotALiteral) 8047 // Literal format string found, check done! 8048 return CT == SLCT_CheckedLiteral; 8049 8050 // Strftime is particular as it always uses a single 'time' argument, 8051 // so it is safe to pass a non-literal string. 8052 if (Type == FST_Strftime) 8053 return false; 8054 8055 // Do not emit diag when the string param is a macro expansion and the 8056 // format is either NSString or CFString. This is a hack to prevent 8057 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8058 // which are usually used in place of NS and CF string literals. 8059 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8060 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8061 return false; 8062 8063 // If there are no arguments specified, warn with -Wformat-security, otherwise 8064 // warn only with -Wformat-nonliteral. 8065 if (Args.size() == firstDataArg) { 8066 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8067 << OrigFormatExpr->getSourceRange(); 8068 switch (Type) { 8069 default: 8070 break; 8071 case FST_Kprintf: 8072 case FST_FreeBSDKPrintf: 8073 case FST_Printf: 8074 Diag(FormatLoc, diag::note_format_security_fixit) 8075 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8076 break; 8077 case FST_NSString: 8078 Diag(FormatLoc, diag::note_format_security_fixit) 8079 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8080 break; 8081 } 8082 } else { 8083 Diag(FormatLoc, diag::warn_format_nonliteral) 8084 << OrigFormatExpr->getSourceRange(); 8085 } 8086 return false; 8087 } 8088 8089 namespace { 8090 8091 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8092 protected: 8093 Sema &S; 8094 const FormatStringLiteral *FExpr; 8095 const Expr *OrigFormatExpr; 8096 const Sema::FormatStringType FSType; 8097 const unsigned FirstDataArg; 8098 const unsigned NumDataArgs; 8099 const char *Beg; // Start of format string. 8100 const bool HasVAListArg; 8101 ArrayRef<const Expr *> Args; 8102 unsigned FormatIdx; 8103 llvm::SmallBitVector CoveredArgs; 8104 bool usesPositionalArgs = false; 8105 bool atFirstArg = true; 8106 bool inFunctionCall; 8107 Sema::VariadicCallType CallType; 8108 llvm::SmallBitVector &CheckedVarArgs; 8109 UncoveredArgHandler &UncoveredArg; 8110 8111 public: 8112 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8113 const Expr *origFormatExpr, 8114 const Sema::FormatStringType type, unsigned firstDataArg, 8115 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8116 ArrayRef<const Expr *> Args, unsigned formatIdx, 8117 bool inFunctionCall, Sema::VariadicCallType callType, 8118 llvm::SmallBitVector &CheckedVarArgs, 8119 UncoveredArgHandler &UncoveredArg) 8120 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8121 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8122 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8123 inFunctionCall(inFunctionCall), CallType(callType), 8124 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8125 CoveredArgs.resize(numDataArgs); 8126 CoveredArgs.reset(); 8127 } 8128 8129 void DoneProcessing(); 8130 8131 void HandleIncompleteSpecifier(const char *startSpecifier, 8132 unsigned specifierLen) override; 8133 8134 void HandleInvalidLengthModifier( 8135 const analyze_format_string::FormatSpecifier &FS, 8136 const analyze_format_string::ConversionSpecifier &CS, 8137 const char *startSpecifier, unsigned specifierLen, 8138 unsigned DiagID); 8139 8140 void HandleNonStandardLengthModifier( 8141 const analyze_format_string::FormatSpecifier &FS, 8142 const char *startSpecifier, unsigned specifierLen); 8143 8144 void HandleNonStandardConversionSpecifier( 8145 const analyze_format_string::ConversionSpecifier &CS, 8146 const char *startSpecifier, unsigned specifierLen); 8147 8148 void HandlePosition(const char *startPos, unsigned posLen) override; 8149 8150 void HandleInvalidPosition(const char *startSpecifier, 8151 unsigned specifierLen, 8152 analyze_format_string::PositionContext p) override; 8153 8154 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8155 8156 void HandleNullChar(const char *nullCharacter) override; 8157 8158 template <typename Range> 8159 static void 8160 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8161 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8162 bool IsStringLocation, Range StringRange, 8163 ArrayRef<FixItHint> Fixit = None); 8164 8165 protected: 8166 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8167 const char *startSpec, 8168 unsigned specifierLen, 8169 const char *csStart, unsigned csLen); 8170 8171 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8172 const char *startSpec, 8173 unsigned specifierLen); 8174 8175 SourceRange getFormatStringRange(); 8176 CharSourceRange getSpecifierRange(const char *startSpecifier, 8177 unsigned specifierLen); 8178 SourceLocation getLocationOfByte(const char *x); 8179 8180 const Expr *getDataArg(unsigned i) const; 8181 8182 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8183 const analyze_format_string::ConversionSpecifier &CS, 8184 const char *startSpecifier, unsigned specifierLen, 8185 unsigned argIndex); 8186 8187 template <typename Range> 8188 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8189 bool IsStringLocation, Range StringRange, 8190 ArrayRef<FixItHint> Fixit = None); 8191 }; 8192 8193 } // namespace 8194 8195 SourceRange CheckFormatHandler::getFormatStringRange() { 8196 return OrigFormatExpr->getSourceRange(); 8197 } 8198 8199 CharSourceRange CheckFormatHandler:: 8200 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8201 SourceLocation Start = getLocationOfByte(startSpecifier); 8202 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8203 8204 // Advance the end SourceLocation by one due to half-open ranges. 8205 End = End.getLocWithOffset(1); 8206 8207 return CharSourceRange::getCharRange(Start, End); 8208 } 8209 8210 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8211 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8212 S.getLangOpts(), S.Context.getTargetInfo()); 8213 } 8214 8215 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8216 unsigned specifierLen){ 8217 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8218 getLocationOfByte(startSpecifier), 8219 /*IsStringLocation*/true, 8220 getSpecifierRange(startSpecifier, specifierLen)); 8221 } 8222 8223 void CheckFormatHandler::HandleInvalidLengthModifier( 8224 const analyze_format_string::FormatSpecifier &FS, 8225 const analyze_format_string::ConversionSpecifier &CS, 8226 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8227 using namespace analyze_format_string; 8228 8229 const LengthModifier &LM = FS.getLengthModifier(); 8230 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8231 8232 // See if we know how to fix this length modifier. 8233 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8234 if (FixedLM) { 8235 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8236 getLocationOfByte(LM.getStart()), 8237 /*IsStringLocation*/true, 8238 getSpecifierRange(startSpecifier, specifierLen)); 8239 8240 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8241 << FixedLM->toString() 8242 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8243 8244 } else { 8245 FixItHint Hint; 8246 if (DiagID == diag::warn_format_nonsensical_length) 8247 Hint = FixItHint::CreateRemoval(LMRange); 8248 8249 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8250 getLocationOfByte(LM.getStart()), 8251 /*IsStringLocation*/true, 8252 getSpecifierRange(startSpecifier, specifierLen), 8253 Hint); 8254 } 8255 } 8256 8257 void CheckFormatHandler::HandleNonStandardLengthModifier( 8258 const analyze_format_string::FormatSpecifier &FS, 8259 const char *startSpecifier, unsigned specifierLen) { 8260 using namespace analyze_format_string; 8261 8262 const LengthModifier &LM = FS.getLengthModifier(); 8263 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8264 8265 // See if we know how to fix this length modifier. 8266 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8267 if (FixedLM) { 8268 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8269 << LM.toString() << 0, 8270 getLocationOfByte(LM.getStart()), 8271 /*IsStringLocation*/true, 8272 getSpecifierRange(startSpecifier, specifierLen)); 8273 8274 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8275 << FixedLM->toString() 8276 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8277 8278 } else { 8279 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8280 << LM.toString() << 0, 8281 getLocationOfByte(LM.getStart()), 8282 /*IsStringLocation*/true, 8283 getSpecifierRange(startSpecifier, specifierLen)); 8284 } 8285 } 8286 8287 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8288 const analyze_format_string::ConversionSpecifier &CS, 8289 const char *startSpecifier, unsigned specifierLen) { 8290 using namespace analyze_format_string; 8291 8292 // See if we know how to fix this conversion specifier. 8293 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8294 if (FixedCS) { 8295 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8296 << CS.toString() << /*conversion specifier*/1, 8297 getLocationOfByte(CS.getStart()), 8298 /*IsStringLocation*/true, 8299 getSpecifierRange(startSpecifier, specifierLen)); 8300 8301 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8302 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8303 << FixedCS->toString() 8304 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8305 } else { 8306 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8307 << CS.toString() << /*conversion specifier*/1, 8308 getLocationOfByte(CS.getStart()), 8309 /*IsStringLocation*/true, 8310 getSpecifierRange(startSpecifier, specifierLen)); 8311 } 8312 } 8313 8314 void CheckFormatHandler::HandlePosition(const char *startPos, 8315 unsigned posLen) { 8316 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8317 getLocationOfByte(startPos), 8318 /*IsStringLocation*/true, 8319 getSpecifierRange(startPos, posLen)); 8320 } 8321 8322 void 8323 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8324 analyze_format_string::PositionContext p) { 8325 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8326 << (unsigned) p, 8327 getLocationOfByte(startPos), /*IsStringLocation*/true, 8328 getSpecifierRange(startPos, posLen)); 8329 } 8330 8331 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8332 unsigned posLen) { 8333 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8334 getLocationOfByte(startPos), 8335 /*IsStringLocation*/true, 8336 getSpecifierRange(startPos, posLen)); 8337 } 8338 8339 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8340 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8341 // The presence of a null character is likely an error. 8342 EmitFormatDiagnostic( 8343 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8344 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8345 getFormatStringRange()); 8346 } 8347 } 8348 8349 // Note that this may return NULL if there was an error parsing or building 8350 // one of the argument expressions. 8351 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8352 return Args[FirstDataArg + i]; 8353 } 8354 8355 void CheckFormatHandler::DoneProcessing() { 8356 // Does the number of data arguments exceed the number of 8357 // format conversions in the format string? 8358 if (!HasVAListArg) { 8359 // Find any arguments that weren't covered. 8360 CoveredArgs.flip(); 8361 signed notCoveredArg = CoveredArgs.find_first(); 8362 if (notCoveredArg >= 0) { 8363 assert((unsigned)notCoveredArg < NumDataArgs); 8364 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8365 } else { 8366 UncoveredArg.setAllCovered(); 8367 } 8368 } 8369 } 8370 8371 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8372 const Expr *ArgExpr) { 8373 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8374 "Invalid state"); 8375 8376 if (!ArgExpr) 8377 return; 8378 8379 SourceLocation Loc = ArgExpr->getBeginLoc(); 8380 8381 if (S.getSourceManager().isInSystemMacro(Loc)) 8382 return; 8383 8384 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8385 for (auto E : DiagnosticExprs) 8386 PDiag << E->getSourceRange(); 8387 8388 CheckFormatHandler::EmitFormatDiagnostic( 8389 S, IsFunctionCall, DiagnosticExprs[0], 8390 PDiag, Loc, /*IsStringLocation*/false, 8391 DiagnosticExprs[0]->getSourceRange()); 8392 } 8393 8394 bool 8395 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8396 SourceLocation Loc, 8397 const char *startSpec, 8398 unsigned specifierLen, 8399 const char *csStart, 8400 unsigned csLen) { 8401 bool keepGoing = true; 8402 if (argIndex < NumDataArgs) { 8403 // Consider the argument coverered, even though the specifier doesn't 8404 // make sense. 8405 CoveredArgs.set(argIndex); 8406 } 8407 else { 8408 // If argIndex exceeds the number of data arguments we 8409 // don't issue a warning because that is just a cascade of warnings (and 8410 // they may have intended '%%' anyway). We don't want to continue processing 8411 // the format string after this point, however, as we will like just get 8412 // gibberish when trying to match arguments. 8413 keepGoing = false; 8414 } 8415 8416 StringRef Specifier(csStart, csLen); 8417 8418 // If the specifier in non-printable, it could be the first byte of a UTF-8 8419 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8420 // hex value. 8421 std::string CodePointStr; 8422 if (!llvm::sys::locale::isPrint(*csStart)) { 8423 llvm::UTF32 CodePoint; 8424 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8425 const llvm::UTF8 *E = 8426 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8427 llvm::ConversionResult Result = 8428 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8429 8430 if (Result != llvm::conversionOK) { 8431 unsigned char FirstChar = *csStart; 8432 CodePoint = (llvm::UTF32)FirstChar; 8433 } 8434 8435 llvm::raw_string_ostream OS(CodePointStr); 8436 if (CodePoint < 256) 8437 OS << "\\x" << llvm::format("%02x", CodePoint); 8438 else if (CodePoint <= 0xFFFF) 8439 OS << "\\u" << llvm::format("%04x", CodePoint); 8440 else 8441 OS << "\\U" << llvm::format("%08x", CodePoint); 8442 OS.flush(); 8443 Specifier = CodePointStr; 8444 } 8445 8446 EmitFormatDiagnostic( 8447 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8448 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8449 8450 return keepGoing; 8451 } 8452 8453 void 8454 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8455 const char *startSpec, 8456 unsigned specifierLen) { 8457 EmitFormatDiagnostic( 8458 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8459 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8460 } 8461 8462 bool 8463 CheckFormatHandler::CheckNumArgs( 8464 const analyze_format_string::FormatSpecifier &FS, 8465 const analyze_format_string::ConversionSpecifier &CS, 8466 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8467 8468 if (argIndex >= NumDataArgs) { 8469 PartialDiagnostic PDiag = FS.usesPositionalArg() 8470 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8471 << (argIndex+1) << NumDataArgs) 8472 : S.PDiag(diag::warn_printf_insufficient_data_args); 8473 EmitFormatDiagnostic( 8474 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8475 getSpecifierRange(startSpecifier, specifierLen)); 8476 8477 // Since more arguments than conversion tokens are given, by extension 8478 // all arguments are covered, so mark this as so. 8479 UncoveredArg.setAllCovered(); 8480 return false; 8481 } 8482 return true; 8483 } 8484 8485 template<typename Range> 8486 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8487 SourceLocation Loc, 8488 bool IsStringLocation, 8489 Range StringRange, 8490 ArrayRef<FixItHint> FixIt) { 8491 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8492 Loc, IsStringLocation, StringRange, FixIt); 8493 } 8494 8495 /// If the format string is not within the function call, emit a note 8496 /// so that the function call and string are in diagnostic messages. 8497 /// 8498 /// \param InFunctionCall if true, the format string is within the function 8499 /// call and only one diagnostic message will be produced. Otherwise, an 8500 /// extra note will be emitted pointing to location of the format string. 8501 /// 8502 /// \param ArgumentExpr the expression that is passed as the format string 8503 /// argument in the function call. Used for getting locations when two 8504 /// diagnostics are emitted. 8505 /// 8506 /// \param PDiag the callee should already have provided any strings for the 8507 /// diagnostic message. This function only adds locations and fixits 8508 /// to diagnostics. 8509 /// 8510 /// \param Loc primary location for diagnostic. If two diagnostics are 8511 /// required, one will be at Loc and a new SourceLocation will be created for 8512 /// the other one. 8513 /// 8514 /// \param IsStringLocation if true, Loc points to the format string should be 8515 /// used for the note. Otherwise, Loc points to the argument list and will 8516 /// be used with PDiag. 8517 /// 8518 /// \param StringRange some or all of the string to highlight. This is 8519 /// templated so it can accept either a CharSourceRange or a SourceRange. 8520 /// 8521 /// \param FixIt optional fix it hint for the format string. 8522 template <typename Range> 8523 void CheckFormatHandler::EmitFormatDiagnostic( 8524 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8525 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8526 Range StringRange, ArrayRef<FixItHint> FixIt) { 8527 if (InFunctionCall) { 8528 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8529 D << StringRange; 8530 D << FixIt; 8531 } else { 8532 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8533 << ArgumentExpr->getSourceRange(); 8534 8535 const Sema::SemaDiagnosticBuilder &Note = 8536 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8537 diag::note_format_string_defined); 8538 8539 Note << StringRange; 8540 Note << FixIt; 8541 } 8542 } 8543 8544 //===--- CHECK: Printf format string checking ------------------------------===// 8545 8546 namespace { 8547 8548 class CheckPrintfHandler : public CheckFormatHandler { 8549 public: 8550 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8551 const Expr *origFormatExpr, 8552 const Sema::FormatStringType type, unsigned firstDataArg, 8553 unsigned numDataArgs, bool isObjC, const char *beg, 8554 bool hasVAListArg, ArrayRef<const Expr *> Args, 8555 unsigned formatIdx, bool inFunctionCall, 8556 Sema::VariadicCallType CallType, 8557 llvm::SmallBitVector &CheckedVarArgs, 8558 UncoveredArgHandler &UncoveredArg) 8559 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8560 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8561 inFunctionCall, CallType, CheckedVarArgs, 8562 UncoveredArg) {} 8563 8564 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8565 8566 /// Returns true if '%@' specifiers are allowed in the format string. 8567 bool allowsObjCArg() const { 8568 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8569 FSType == Sema::FST_OSTrace; 8570 } 8571 8572 bool HandleInvalidPrintfConversionSpecifier( 8573 const analyze_printf::PrintfSpecifier &FS, 8574 const char *startSpecifier, 8575 unsigned specifierLen) override; 8576 8577 void handleInvalidMaskType(StringRef MaskType) override; 8578 8579 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8580 const char *startSpecifier, 8581 unsigned specifierLen) override; 8582 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8583 const char *StartSpecifier, 8584 unsigned SpecifierLen, 8585 const Expr *E); 8586 8587 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8588 const char *startSpecifier, unsigned specifierLen); 8589 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8590 const analyze_printf::OptionalAmount &Amt, 8591 unsigned type, 8592 const char *startSpecifier, unsigned specifierLen); 8593 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8594 const analyze_printf::OptionalFlag &flag, 8595 const char *startSpecifier, unsigned specifierLen); 8596 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8597 const analyze_printf::OptionalFlag &ignoredFlag, 8598 const analyze_printf::OptionalFlag &flag, 8599 const char *startSpecifier, unsigned specifierLen); 8600 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8601 const Expr *E); 8602 8603 void HandleEmptyObjCModifierFlag(const char *startFlag, 8604 unsigned flagLen) override; 8605 8606 void HandleInvalidObjCModifierFlag(const char *startFlag, 8607 unsigned flagLen) override; 8608 8609 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8610 const char *flagsEnd, 8611 const char *conversionPosition) 8612 override; 8613 }; 8614 8615 } // namespace 8616 8617 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8618 const analyze_printf::PrintfSpecifier &FS, 8619 const char *startSpecifier, 8620 unsigned specifierLen) { 8621 const analyze_printf::PrintfConversionSpecifier &CS = 8622 FS.getConversionSpecifier(); 8623 8624 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8625 getLocationOfByte(CS.getStart()), 8626 startSpecifier, specifierLen, 8627 CS.getStart(), CS.getLength()); 8628 } 8629 8630 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8631 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8632 } 8633 8634 bool CheckPrintfHandler::HandleAmount( 8635 const analyze_format_string::OptionalAmount &Amt, 8636 unsigned k, const char *startSpecifier, 8637 unsigned specifierLen) { 8638 if (Amt.hasDataArgument()) { 8639 if (!HasVAListArg) { 8640 unsigned argIndex = Amt.getArgIndex(); 8641 if (argIndex >= NumDataArgs) { 8642 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8643 << k, 8644 getLocationOfByte(Amt.getStart()), 8645 /*IsStringLocation*/true, 8646 getSpecifierRange(startSpecifier, specifierLen)); 8647 // Don't do any more checking. We will just emit 8648 // spurious errors. 8649 return false; 8650 } 8651 8652 // Type check the data argument. It should be an 'int'. 8653 // Although not in conformance with C99, we also allow the argument to be 8654 // an 'unsigned int' as that is a reasonably safe case. GCC also 8655 // doesn't emit a warning for that case. 8656 CoveredArgs.set(argIndex); 8657 const Expr *Arg = getDataArg(argIndex); 8658 if (!Arg) 8659 return false; 8660 8661 QualType T = Arg->getType(); 8662 8663 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8664 assert(AT.isValid()); 8665 8666 if (!AT.matchesType(S.Context, T)) { 8667 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8668 << k << AT.getRepresentativeTypeName(S.Context) 8669 << T << Arg->getSourceRange(), 8670 getLocationOfByte(Amt.getStart()), 8671 /*IsStringLocation*/true, 8672 getSpecifierRange(startSpecifier, specifierLen)); 8673 // Don't do any more checking. We will just emit 8674 // spurious errors. 8675 return false; 8676 } 8677 } 8678 } 8679 return true; 8680 } 8681 8682 void CheckPrintfHandler::HandleInvalidAmount( 8683 const analyze_printf::PrintfSpecifier &FS, 8684 const analyze_printf::OptionalAmount &Amt, 8685 unsigned type, 8686 const char *startSpecifier, 8687 unsigned specifierLen) { 8688 const analyze_printf::PrintfConversionSpecifier &CS = 8689 FS.getConversionSpecifier(); 8690 8691 FixItHint fixit = 8692 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8693 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8694 Amt.getConstantLength())) 8695 : FixItHint(); 8696 8697 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8698 << type << CS.toString(), 8699 getLocationOfByte(Amt.getStart()), 8700 /*IsStringLocation*/true, 8701 getSpecifierRange(startSpecifier, specifierLen), 8702 fixit); 8703 } 8704 8705 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8706 const analyze_printf::OptionalFlag &flag, 8707 const char *startSpecifier, 8708 unsigned specifierLen) { 8709 // Warn about pointless flag with a fixit removal. 8710 const analyze_printf::PrintfConversionSpecifier &CS = 8711 FS.getConversionSpecifier(); 8712 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8713 << flag.toString() << CS.toString(), 8714 getLocationOfByte(flag.getPosition()), 8715 /*IsStringLocation*/true, 8716 getSpecifierRange(startSpecifier, specifierLen), 8717 FixItHint::CreateRemoval( 8718 getSpecifierRange(flag.getPosition(), 1))); 8719 } 8720 8721 void CheckPrintfHandler::HandleIgnoredFlag( 8722 const analyze_printf::PrintfSpecifier &FS, 8723 const analyze_printf::OptionalFlag &ignoredFlag, 8724 const analyze_printf::OptionalFlag &flag, 8725 const char *startSpecifier, 8726 unsigned specifierLen) { 8727 // Warn about ignored flag with a fixit removal. 8728 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8729 << ignoredFlag.toString() << flag.toString(), 8730 getLocationOfByte(ignoredFlag.getPosition()), 8731 /*IsStringLocation*/true, 8732 getSpecifierRange(startSpecifier, specifierLen), 8733 FixItHint::CreateRemoval( 8734 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8735 } 8736 8737 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8738 unsigned flagLen) { 8739 // Warn about an empty flag. 8740 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8741 getLocationOfByte(startFlag), 8742 /*IsStringLocation*/true, 8743 getSpecifierRange(startFlag, flagLen)); 8744 } 8745 8746 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8747 unsigned flagLen) { 8748 // Warn about an invalid flag. 8749 auto Range = getSpecifierRange(startFlag, flagLen); 8750 StringRef flag(startFlag, flagLen); 8751 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8752 getLocationOfByte(startFlag), 8753 /*IsStringLocation*/true, 8754 Range, FixItHint::CreateRemoval(Range)); 8755 } 8756 8757 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8758 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8759 // Warn about using '[...]' without a '@' conversion. 8760 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8761 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8762 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8763 getLocationOfByte(conversionPosition), 8764 /*IsStringLocation*/true, 8765 Range, FixItHint::CreateRemoval(Range)); 8766 } 8767 8768 // Determines if the specified is a C++ class or struct containing 8769 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8770 // "c_str()"). 8771 template<typename MemberKind> 8772 static llvm::SmallPtrSet<MemberKind*, 1> 8773 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8774 const RecordType *RT = Ty->getAs<RecordType>(); 8775 llvm::SmallPtrSet<MemberKind*, 1> Results; 8776 8777 if (!RT) 8778 return Results; 8779 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8780 if (!RD || !RD->getDefinition()) 8781 return Results; 8782 8783 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8784 Sema::LookupMemberName); 8785 R.suppressDiagnostics(); 8786 8787 // We just need to include all members of the right kind turned up by the 8788 // filter, at this point. 8789 if (S.LookupQualifiedName(R, RT->getDecl())) 8790 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8791 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8792 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8793 Results.insert(FK); 8794 } 8795 return Results; 8796 } 8797 8798 /// Check if we could call '.c_str()' on an object. 8799 /// 8800 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8801 /// allow the call, or if it would be ambiguous). 8802 bool Sema::hasCStrMethod(const Expr *E) { 8803 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8804 8805 MethodSet Results = 8806 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8807 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8808 MI != ME; ++MI) 8809 if ((*MI)->getMinRequiredArguments() == 0) 8810 return true; 8811 return false; 8812 } 8813 8814 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8815 // better diagnostic if so. AT is assumed to be valid. 8816 // Returns true when a c_str() conversion method is found. 8817 bool CheckPrintfHandler::checkForCStrMembers( 8818 const analyze_printf::ArgType &AT, const Expr *E) { 8819 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8820 8821 MethodSet Results = 8822 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8823 8824 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8825 MI != ME; ++MI) { 8826 const CXXMethodDecl *Method = *MI; 8827 if (Method->getMinRequiredArguments() == 0 && 8828 AT.matchesType(S.Context, Method->getReturnType())) { 8829 // FIXME: Suggest parens if the expression needs them. 8830 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8831 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8832 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8833 return true; 8834 } 8835 } 8836 8837 return false; 8838 } 8839 8840 bool 8841 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8842 &FS, 8843 const char *startSpecifier, 8844 unsigned specifierLen) { 8845 using namespace analyze_format_string; 8846 using namespace analyze_printf; 8847 8848 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8849 8850 if (FS.consumesDataArgument()) { 8851 if (atFirstArg) { 8852 atFirstArg = false; 8853 usesPositionalArgs = FS.usesPositionalArg(); 8854 } 8855 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8856 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8857 startSpecifier, specifierLen); 8858 return false; 8859 } 8860 } 8861 8862 // First check if the field width, precision, and conversion specifier 8863 // have matching data arguments. 8864 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8865 startSpecifier, specifierLen)) { 8866 return false; 8867 } 8868 8869 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8870 startSpecifier, specifierLen)) { 8871 return false; 8872 } 8873 8874 if (!CS.consumesDataArgument()) { 8875 // FIXME: Technically specifying a precision or field width here 8876 // makes no sense. Worth issuing a warning at some point. 8877 return true; 8878 } 8879 8880 // Consume the argument. 8881 unsigned argIndex = FS.getArgIndex(); 8882 if (argIndex < NumDataArgs) { 8883 // The check to see if the argIndex is valid will come later. 8884 // We set the bit here because we may exit early from this 8885 // function if we encounter some other error. 8886 CoveredArgs.set(argIndex); 8887 } 8888 8889 // FreeBSD kernel extensions. 8890 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8891 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8892 // We need at least two arguments. 8893 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8894 return false; 8895 8896 // Claim the second argument. 8897 CoveredArgs.set(argIndex + 1); 8898 8899 // Type check the first argument (int for %b, pointer for %D) 8900 const Expr *Ex = getDataArg(argIndex); 8901 const analyze_printf::ArgType &AT = 8902 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8903 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8904 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8905 EmitFormatDiagnostic( 8906 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8907 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8908 << false << Ex->getSourceRange(), 8909 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8910 getSpecifierRange(startSpecifier, specifierLen)); 8911 8912 // Type check the second argument (char * for both %b and %D) 8913 Ex = getDataArg(argIndex + 1); 8914 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8915 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8916 EmitFormatDiagnostic( 8917 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8918 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8919 << false << Ex->getSourceRange(), 8920 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8921 getSpecifierRange(startSpecifier, specifierLen)); 8922 8923 return true; 8924 } 8925 8926 // Check for using an Objective-C specific conversion specifier 8927 // in a non-ObjC literal. 8928 if (!allowsObjCArg() && CS.isObjCArg()) { 8929 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8930 specifierLen); 8931 } 8932 8933 // %P can only be used with os_log. 8934 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8935 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8936 specifierLen); 8937 } 8938 8939 // %n is not allowed with os_log. 8940 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8941 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8942 getLocationOfByte(CS.getStart()), 8943 /*IsStringLocation*/ false, 8944 getSpecifierRange(startSpecifier, specifierLen)); 8945 8946 return true; 8947 } 8948 8949 // Only scalars are allowed for os_trace. 8950 if (FSType == Sema::FST_OSTrace && 8951 (CS.getKind() == ConversionSpecifier::PArg || 8952 CS.getKind() == ConversionSpecifier::sArg || 8953 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8954 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8955 specifierLen); 8956 } 8957 8958 // Check for use of public/private annotation outside of os_log(). 8959 if (FSType != Sema::FST_OSLog) { 8960 if (FS.isPublic().isSet()) { 8961 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8962 << "public", 8963 getLocationOfByte(FS.isPublic().getPosition()), 8964 /*IsStringLocation*/ false, 8965 getSpecifierRange(startSpecifier, specifierLen)); 8966 } 8967 if (FS.isPrivate().isSet()) { 8968 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8969 << "private", 8970 getLocationOfByte(FS.isPrivate().getPosition()), 8971 /*IsStringLocation*/ false, 8972 getSpecifierRange(startSpecifier, specifierLen)); 8973 } 8974 } 8975 8976 // Check for invalid use of field width 8977 if (!FS.hasValidFieldWidth()) { 8978 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8979 startSpecifier, specifierLen); 8980 } 8981 8982 // Check for invalid use of precision 8983 if (!FS.hasValidPrecision()) { 8984 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8985 startSpecifier, specifierLen); 8986 } 8987 8988 // Precision is mandatory for %P specifier. 8989 if (CS.getKind() == ConversionSpecifier::PArg && 8990 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8991 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8992 getLocationOfByte(startSpecifier), 8993 /*IsStringLocation*/ false, 8994 getSpecifierRange(startSpecifier, specifierLen)); 8995 } 8996 8997 // Check each flag does not conflict with any other component. 8998 if (!FS.hasValidThousandsGroupingPrefix()) 8999 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9000 if (!FS.hasValidLeadingZeros()) 9001 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9002 if (!FS.hasValidPlusPrefix()) 9003 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9004 if (!FS.hasValidSpacePrefix()) 9005 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9006 if (!FS.hasValidAlternativeForm()) 9007 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9008 if (!FS.hasValidLeftJustified()) 9009 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9010 9011 // Check that flags are not ignored by another flag 9012 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9013 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9014 startSpecifier, specifierLen); 9015 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9016 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9017 startSpecifier, specifierLen); 9018 9019 // Check the length modifier is valid with the given conversion specifier. 9020 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9021 S.getLangOpts())) 9022 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9023 diag::warn_format_nonsensical_length); 9024 else if (!FS.hasStandardLengthModifier()) 9025 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9026 else if (!FS.hasStandardLengthConversionCombination()) 9027 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9028 diag::warn_format_non_standard_conversion_spec); 9029 9030 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9031 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9032 9033 // The remaining checks depend on the data arguments. 9034 if (HasVAListArg) 9035 return true; 9036 9037 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9038 return false; 9039 9040 const Expr *Arg = getDataArg(argIndex); 9041 if (!Arg) 9042 return true; 9043 9044 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9045 } 9046 9047 static bool requiresParensToAddCast(const Expr *E) { 9048 // FIXME: We should have a general way to reason about operator 9049 // precedence and whether parens are actually needed here. 9050 // Take care of a few common cases where they aren't. 9051 const Expr *Inside = E->IgnoreImpCasts(); 9052 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9053 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9054 9055 switch (Inside->getStmtClass()) { 9056 case Stmt::ArraySubscriptExprClass: 9057 case Stmt::CallExprClass: 9058 case Stmt::CharacterLiteralClass: 9059 case Stmt::CXXBoolLiteralExprClass: 9060 case Stmt::DeclRefExprClass: 9061 case Stmt::FloatingLiteralClass: 9062 case Stmt::IntegerLiteralClass: 9063 case Stmt::MemberExprClass: 9064 case Stmt::ObjCArrayLiteralClass: 9065 case Stmt::ObjCBoolLiteralExprClass: 9066 case Stmt::ObjCBoxedExprClass: 9067 case Stmt::ObjCDictionaryLiteralClass: 9068 case Stmt::ObjCEncodeExprClass: 9069 case Stmt::ObjCIvarRefExprClass: 9070 case Stmt::ObjCMessageExprClass: 9071 case Stmt::ObjCPropertyRefExprClass: 9072 case Stmt::ObjCStringLiteralClass: 9073 case Stmt::ObjCSubscriptRefExprClass: 9074 case Stmt::ParenExprClass: 9075 case Stmt::StringLiteralClass: 9076 case Stmt::UnaryOperatorClass: 9077 return false; 9078 default: 9079 return true; 9080 } 9081 } 9082 9083 static std::pair<QualType, StringRef> 9084 shouldNotPrintDirectly(const ASTContext &Context, 9085 QualType IntendedTy, 9086 const Expr *E) { 9087 // Use a 'while' to peel off layers of typedefs. 9088 QualType TyTy = IntendedTy; 9089 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9090 StringRef Name = UserTy->getDecl()->getName(); 9091 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9092 .Case("CFIndex", Context.getNSIntegerType()) 9093 .Case("NSInteger", Context.getNSIntegerType()) 9094 .Case("NSUInteger", Context.getNSUIntegerType()) 9095 .Case("SInt32", Context.IntTy) 9096 .Case("UInt32", Context.UnsignedIntTy) 9097 .Default(QualType()); 9098 9099 if (!CastTy.isNull()) 9100 return std::make_pair(CastTy, Name); 9101 9102 TyTy = UserTy->desugar(); 9103 } 9104 9105 // Strip parens if necessary. 9106 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9107 return shouldNotPrintDirectly(Context, 9108 PE->getSubExpr()->getType(), 9109 PE->getSubExpr()); 9110 9111 // If this is a conditional expression, then its result type is constructed 9112 // via usual arithmetic conversions and thus there might be no necessary 9113 // typedef sugar there. Recurse to operands to check for NSInteger & 9114 // Co. usage condition. 9115 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9116 QualType TrueTy, FalseTy; 9117 StringRef TrueName, FalseName; 9118 9119 std::tie(TrueTy, TrueName) = 9120 shouldNotPrintDirectly(Context, 9121 CO->getTrueExpr()->getType(), 9122 CO->getTrueExpr()); 9123 std::tie(FalseTy, FalseName) = 9124 shouldNotPrintDirectly(Context, 9125 CO->getFalseExpr()->getType(), 9126 CO->getFalseExpr()); 9127 9128 if (TrueTy == FalseTy) 9129 return std::make_pair(TrueTy, TrueName); 9130 else if (TrueTy.isNull()) 9131 return std::make_pair(FalseTy, FalseName); 9132 else if (FalseTy.isNull()) 9133 return std::make_pair(TrueTy, TrueName); 9134 } 9135 9136 return std::make_pair(QualType(), StringRef()); 9137 } 9138 9139 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9140 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9141 /// type do not count. 9142 static bool 9143 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9144 QualType From = ICE->getSubExpr()->getType(); 9145 QualType To = ICE->getType(); 9146 // It's an integer promotion if the destination type is the promoted 9147 // source type. 9148 if (ICE->getCastKind() == CK_IntegralCast && 9149 From->isPromotableIntegerType() && 9150 S.Context.getPromotedIntegerType(From) == To) 9151 return true; 9152 // Look through vector types, since we do default argument promotion for 9153 // those in OpenCL. 9154 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9155 From = VecTy->getElementType(); 9156 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9157 To = VecTy->getElementType(); 9158 // It's a floating promotion if the source type is a lower rank. 9159 return ICE->getCastKind() == CK_FloatingCast && 9160 S.Context.getFloatingTypeOrder(From, To) < 0; 9161 } 9162 9163 bool 9164 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9165 const char *StartSpecifier, 9166 unsigned SpecifierLen, 9167 const Expr *E) { 9168 using namespace analyze_format_string; 9169 using namespace analyze_printf; 9170 9171 // Now type check the data expression that matches the 9172 // format specifier. 9173 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9174 if (!AT.isValid()) 9175 return true; 9176 9177 QualType ExprTy = E->getType(); 9178 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9179 ExprTy = TET->getUnderlyingExpr()->getType(); 9180 } 9181 9182 // Diagnose attempts to print a boolean value as a character. Unlike other 9183 // -Wformat diagnostics, this is fine from a type perspective, but it still 9184 // doesn't make sense. 9185 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9186 E->isKnownToHaveBooleanValue()) { 9187 const CharSourceRange &CSR = 9188 getSpecifierRange(StartSpecifier, SpecifierLen); 9189 SmallString<4> FSString; 9190 llvm::raw_svector_ostream os(FSString); 9191 FS.toString(os); 9192 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9193 << FSString, 9194 E->getExprLoc(), false, CSR); 9195 return true; 9196 } 9197 9198 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9199 if (Match == analyze_printf::ArgType::Match) 9200 return true; 9201 9202 // Look through argument promotions for our error message's reported type. 9203 // This includes the integral and floating promotions, but excludes array 9204 // and function pointer decay (seeing that an argument intended to be a 9205 // string has type 'char [6]' is probably more confusing than 'char *') and 9206 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9207 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9208 if (isArithmeticArgumentPromotion(S, ICE)) { 9209 E = ICE->getSubExpr(); 9210 ExprTy = E->getType(); 9211 9212 // Check if we didn't match because of an implicit cast from a 'char' 9213 // or 'short' to an 'int'. This is done because printf is a varargs 9214 // function. 9215 if (ICE->getType() == S.Context.IntTy || 9216 ICE->getType() == S.Context.UnsignedIntTy) { 9217 // All further checking is done on the subexpression 9218 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9219 AT.matchesType(S.Context, ExprTy); 9220 if (ImplicitMatch == analyze_printf::ArgType::Match) 9221 return true; 9222 if (ImplicitMatch == ArgType::NoMatchPedantic || 9223 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9224 Match = ImplicitMatch; 9225 } 9226 } 9227 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9228 // Special case for 'a', which has type 'int' in C. 9229 // Note, however, that we do /not/ want to treat multibyte constants like 9230 // 'MooV' as characters! This form is deprecated but still exists. In 9231 // addition, don't treat expressions as of type 'char' if one byte length 9232 // modifier is provided. 9233 if (ExprTy == S.Context.IntTy && 9234 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9235 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9236 ExprTy = S.Context.CharTy; 9237 } 9238 9239 // Look through enums to their underlying type. 9240 bool IsEnum = false; 9241 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9242 ExprTy = EnumTy->getDecl()->getIntegerType(); 9243 IsEnum = true; 9244 } 9245 9246 // %C in an Objective-C context prints a unichar, not a wchar_t. 9247 // If the argument is an integer of some kind, believe the %C and suggest 9248 // a cast instead of changing the conversion specifier. 9249 QualType IntendedTy = ExprTy; 9250 if (isObjCContext() && 9251 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9252 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9253 !ExprTy->isCharType()) { 9254 // 'unichar' is defined as a typedef of unsigned short, but we should 9255 // prefer using the typedef if it is visible. 9256 IntendedTy = S.Context.UnsignedShortTy; 9257 9258 // While we are here, check if the value is an IntegerLiteral that happens 9259 // to be within the valid range. 9260 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9261 const llvm::APInt &V = IL->getValue(); 9262 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9263 return true; 9264 } 9265 9266 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9267 Sema::LookupOrdinaryName); 9268 if (S.LookupName(Result, S.getCurScope())) { 9269 NamedDecl *ND = Result.getFoundDecl(); 9270 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9271 if (TD->getUnderlyingType() == IntendedTy) 9272 IntendedTy = S.Context.getTypedefType(TD); 9273 } 9274 } 9275 } 9276 9277 // Special-case some of Darwin's platform-independence types by suggesting 9278 // casts to primitive types that are known to be large enough. 9279 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9280 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9281 QualType CastTy; 9282 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9283 if (!CastTy.isNull()) { 9284 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9285 // (long in ASTContext). Only complain to pedants. 9286 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9287 (AT.isSizeT() || AT.isPtrdiffT()) && 9288 AT.matchesType(S.Context, CastTy)) 9289 Match = ArgType::NoMatchPedantic; 9290 IntendedTy = CastTy; 9291 ShouldNotPrintDirectly = true; 9292 } 9293 } 9294 9295 // We may be able to offer a FixItHint if it is a supported type. 9296 PrintfSpecifier fixedFS = FS; 9297 bool Success = 9298 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9299 9300 if (Success) { 9301 // Get the fix string from the fixed format specifier 9302 SmallString<16> buf; 9303 llvm::raw_svector_ostream os(buf); 9304 fixedFS.toString(os); 9305 9306 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9307 9308 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9309 unsigned Diag; 9310 switch (Match) { 9311 case ArgType::Match: llvm_unreachable("expected non-matching"); 9312 case ArgType::NoMatchPedantic: 9313 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9314 break; 9315 case ArgType::NoMatchTypeConfusion: 9316 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9317 break; 9318 case ArgType::NoMatch: 9319 Diag = diag::warn_format_conversion_argument_type_mismatch; 9320 break; 9321 } 9322 9323 // In this case, the specifier is wrong and should be changed to match 9324 // the argument. 9325 EmitFormatDiagnostic(S.PDiag(Diag) 9326 << AT.getRepresentativeTypeName(S.Context) 9327 << IntendedTy << IsEnum << E->getSourceRange(), 9328 E->getBeginLoc(), 9329 /*IsStringLocation*/ false, SpecRange, 9330 FixItHint::CreateReplacement(SpecRange, os.str())); 9331 } else { 9332 // The canonical type for formatting this value is different from the 9333 // actual type of the expression. (This occurs, for example, with Darwin's 9334 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9335 // should be printed as 'long' for 64-bit compatibility.) 9336 // Rather than emitting a normal format/argument mismatch, we want to 9337 // add a cast to the recommended type (and correct the format string 9338 // if necessary). 9339 SmallString<16> CastBuf; 9340 llvm::raw_svector_ostream CastFix(CastBuf); 9341 CastFix << "("; 9342 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9343 CastFix << ")"; 9344 9345 SmallVector<FixItHint,4> Hints; 9346 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9347 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9348 9349 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9350 // If there's already a cast present, just replace it. 9351 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9352 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9353 9354 } else if (!requiresParensToAddCast(E)) { 9355 // If the expression has high enough precedence, 9356 // just write the C-style cast. 9357 Hints.push_back( 9358 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9359 } else { 9360 // Otherwise, add parens around the expression as well as the cast. 9361 CastFix << "("; 9362 Hints.push_back( 9363 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9364 9365 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9366 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9367 } 9368 9369 if (ShouldNotPrintDirectly) { 9370 // The expression has a type that should not be printed directly. 9371 // We extract the name from the typedef because we don't want to show 9372 // the underlying type in the diagnostic. 9373 StringRef Name; 9374 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9375 Name = TypedefTy->getDecl()->getName(); 9376 else 9377 Name = CastTyName; 9378 unsigned Diag = Match == ArgType::NoMatchPedantic 9379 ? diag::warn_format_argument_needs_cast_pedantic 9380 : diag::warn_format_argument_needs_cast; 9381 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9382 << E->getSourceRange(), 9383 E->getBeginLoc(), /*IsStringLocation=*/false, 9384 SpecRange, Hints); 9385 } else { 9386 // In this case, the expression could be printed using a different 9387 // specifier, but we've decided that the specifier is probably correct 9388 // and we should cast instead. Just use the normal warning message. 9389 EmitFormatDiagnostic( 9390 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9391 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9392 << E->getSourceRange(), 9393 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9394 } 9395 } 9396 } else { 9397 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9398 SpecifierLen); 9399 // Since the warning for passing non-POD types to variadic functions 9400 // was deferred until now, we emit a warning for non-POD 9401 // arguments here. 9402 switch (S.isValidVarArgType(ExprTy)) { 9403 case Sema::VAK_Valid: 9404 case Sema::VAK_ValidInCXX11: { 9405 unsigned Diag; 9406 switch (Match) { 9407 case ArgType::Match: llvm_unreachable("expected non-matching"); 9408 case ArgType::NoMatchPedantic: 9409 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9410 break; 9411 case ArgType::NoMatchTypeConfusion: 9412 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9413 break; 9414 case ArgType::NoMatch: 9415 Diag = diag::warn_format_conversion_argument_type_mismatch; 9416 break; 9417 } 9418 9419 EmitFormatDiagnostic( 9420 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9421 << IsEnum << CSR << E->getSourceRange(), 9422 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9423 break; 9424 } 9425 case Sema::VAK_Undefined: 9426 case Sema::VAK_MSVCUndefined: 9427 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9428 << S.getLangOpts().CPlusPlus11 << ExprTy 9429 << CallType 9430 << AT.getRepresentativeTypeName(S.Context) << CSR 9431 << E->getSourceRange(), 9432 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9433 checkForCStrMembers(AT, E); 9434 break; 9435 9436 case Sema::VAK_Invalid: 9437 if (ExprTy->isObjCObjectType()) 9438 EmitFormatDiagnostic( 9439 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9440 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9441 << AT.getRepresentativeTypeName(S.Context) << CSR 9442 << E->getSourceRange(), 9443 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9444 else 9445 // FIXME: If this is an initializer list, suggest removing the braces 9446 // or inserting a cast to the target type. 9447 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9448 << isa<InitListExpr>(E) << ExprTy << CallType 9449 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9450 break; 9451 } 9452 9453 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9454 "format string specifier index out of range"); 9455 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9456 } 9457 9458 return true; 9459 } 9460 9461 //===--- CHECK: Scanf format string checking ------------------------------===// 9462 9463 namespace { 9464 9465 class CheckScanfHandler : public CheckFormatHandler { 9466 public: 9467 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9468 const Expr *origFormatExpr, Sema::FormatStringType type, 9469 unsigned firstDataArg, unsigned numDataArgs, 9470 const char *beg, bool hasVAListArg, 9471 ArrayRef<const Expr *> Args, unsigned formatIdx, 9472 bool inFunctionCall, Sema::VariadicCallType CallType, 9473 llvm::SmallBitVector &CheckedVarArgs, 9474 UncoveredArgHandler &UncoveredArg) 9475 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9476 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9477 inFunctionCall, CallType, CheckedVarArgs, 9478 UncoveredArg) {} 9479 9480 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9481 const char *startSpecifier, 9482 unsigned specifierLen) override; 9483 9484 bool HandleInvalidScanfConversionSpecifier( 9485 const analyze_scanf::ScanfSpecifier &FS, 9486 const char *startSpecifier, 9487 unsigned specifierLen) override; 9488 9489 void HandleIncompleteScanList(const char *start, const char *end) override; 9490 }; 9491 9492 } // namespace 9493 9494 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9495 const char *end) { 9496 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9497 getLocationOfByte(end), /*IsStringLocation*/true, 9498 getSpecifierRange(start, end - start)); 9499 } 9500 9501 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9502 const analyze_scanf::ScanfSpecifier &FS, 9503 const char *startSpecifier, 9504 unsigned specifierLen) { 9505 const analyze_scanf::ScanfConversionSpecifier &CS = 9506 FS.getConversionSpecifier(); 9507 9508 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9509 getLocationOfByte(CS.getStart()), 9510 startSpecifier, specifierLen, 9511 CS.getStart(), CS.getLength()); 9512 } 9513 9514 bool CheckScanfHandler::HandleScanfSpecifier( 9515 const analyze_scanf::ScanfSpecifier &FS, 9516 const char *startSpecifier, 9517 unsigned specifierLen) { 9518 using namespace analyze_scanf; 9519 using namespace analyze_format_string; 9520 9521 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9522 9523 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9524 // be used to decide if we are using positional arguments consistently. 9525 if (FS.consumesDataArgument()) { 9526 if (atFirstArg) { 9527 atFirstArg = false; 9528 usesPositionalArgs = FS.usesPositionalArg(); 9529 } 9530 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9531 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9532 startSpecifier, specifierLen); 9533 return false; 9534 } 9535 } 9536 9537 // Check if the field with is non-zero. 9538 const OptionalAmount &Amt = FS.getFieldWidth(); 9539 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9540 if (Amt.getConstantAmount() == 0) { 9541 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9542 Amt.getConstantLength()); 9543 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9544 getLocationOfByte(Amt.getStart()), 9545 /*IsStringLocation*/true, R, 9546 FixItHint::CreateRemoval(R)); 9547 } 9548 } 9549 9550 if (!FS.consumesDataArgument()) { 9551 // FIXME: Technically specifying a precision or field width here 9552 // makes no sense. Worth issuing a warning at some point. 9553 return true; 9554 } 9555 9556 // Consume the argument. 9557 unsigned argIndex = FS.getArgIndex(); 9558 if (argIndex < NumDataArgs) { 9559 // The check to see if the argIndex is valid will come later. 9560 // We set the bit here because we may exit early from this 9561 // function if we encounter some other error. 9562 CoveredArgs.set(argIndex); 9563 } 9564 9565 // Check the length modifier is valid with the given conversion specifier. 9566 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9567 S.getLangOpts())) 9568 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9569 diag::warn_format_nonsensical_length); 9570 else if (!FS.hasStandardLengthModifier()) 9571 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9572 else if (!FS.hasStandardLengthConversionCombination()) 9573 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9574 diag::warn_format_non_standard_conversion_spec); 9575 9576 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9577 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9578 9579 // The remaining checks depend on the data arguments. 9580 if (HasVAListArg) 9581 return true; 9582 9583 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9584 return false; 9585 9586 // Check that the argument type matches the format specifier. 9587 const Expr *Ex = getDataArg(argIndex); 9588 if (!Ex) 9589 return true; 9590 9591 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9592 9593 if (!AT.isValid()) { 9594 return true; 9595 } 9596 9597 analyze_format_string::ArgType::MatchKind Match = 9598 AT.matchesType(S.Context, Ex->getType()); 9599 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9600 if (Match == analyze_format_string::ArgType::Match) 9601 return true; 9602 9603 ScanfSpecifier fixedFS = FS; 9604 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9605 S.getLangOpts(), S.Context); 9606 9607 unsigned Diag = 9608 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9609 : diag::warn_format_conversion_argument_type_mismatch; 9610 9611 if (Success) { 9612 // Get the fix string from the fixed format specifier. 9613 SmallString<128> buf; 9614 llvm::raw_svector_ostream os(buf); 9615 fixedFS.toString(os); 9616 9617 EmitFormatDiagnostic( 9618 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9619 << Ex->getType() << false << Ex->getSourceRange(), 9620 Ex->getBeginLoc(), 9621 /*IsStringLocation*/ false, 9622 getSpecifierRange(startSpecifier, specifierLen), 9623 FixItHint::CreateReplacement( 9624 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9625 } else { 9626 EmitFormatDiagnostic(S.PDiag(Diag) 9627 << AT.getRepresentativeTypeName(S.Context) 9628 << Ex->getType() << false << Ex->getSourceRange(), 9629 Ex->getBeginLoc(), 9630 /*IsStringLocation*/ false, 9631 getSpecifierRange(startSpecifier, specifierLen)); 9632 } 9633 9634 return true; 9635 } 9636 9637 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9638 const Expr *OrigFormatExpr, 9639 ArrayRef<const Expr *> Args, 9640 bool HasVAListArg, unsigned format_idx, 9641 unsigned firstDataArg, 9642 Sema::FormatStringType Type, 9643 bool inFunctionCall, 9644 Sema::VariadicCallType CallType, 9645 llvm::SmallBitVector &CheckedVarArgs, 9646 UncoveredArgHandler &UncoveredArg, 9647 bool IgnoreStringsWithoutSpecifiers) { 9648 // CHECK: is the format string a wide literal? 9649 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9650 CheckFormatHandler::EmitFormatDiagnostic( 9651 S, inFunctionCall, Args[format_idx], 9652 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9653 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9654 return; 9655 } 9656 9657 // Str - The format string. NOTE: this is NOT null-terminated! 9658 StringRef StrRef = FExpr->getString(); 9659 const char *Str = StrRef.data(); 9660 // Account for cases where the string literal is truncated in a declaration. 9661 const ConstantArrayType *T = 9662 S.Context.getAsConstantArrayType(FExpr->getType()); 9663 assert(T && "String literal not of constant array type!"); 9664 size_t TypeSize = T->getSize().getZExtValue(); 9665 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9666 const unsigned numDataArgs = Args.size() - firstDataArg; 9667 9668 if (IgnoreStringsWithoutSpecifiers && 9669 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9670 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9671 return; 9672 9673 // Emit a warning if the string literal is truncated and does not contain an 9674 // embedded null character. 9675 if (TypeSize <= StrRef.size() && 9676 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9677 CheckFormatHandler::EmitFormatDiagnostic( 9678 S, inFunctionCall, Args[format_idx], 9679 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9680 FExpr->getBeginLoc(), 9681 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9682 return; 9683 } 9684 9685 // CHECK: empty format string? 9686 if (StrLen == 0 && numDataArgs > 0) { 9687 CheckFormatHandler::EmitFormatDiagnostic( 9688 S, inFunctionCall, Args[format_idx], 9689 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9690 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9691 return; 9692 } 9693 9694 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9695 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9696 Type == Sema::FST_OSTrace) { 9697 CheckPrintfHandler H( 9698 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9699 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9700 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9701 CheckedVarArgs, UncoveredArg); 9702 9703 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9704 S.getLangOpts(), 9705 S.Context.getTargetInfo(), 9706 Type == Sema::FST_FreeBSDKPrintf)) 9707 H.DoneProcessing(); 9708 } else if (Type == Sema::FST_Scanf) { 9709 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9710 numDataArgs, Str, HasVAListArg, Args, format_idx, 9711 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9712 9713 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9714 S.getLangOpts(), 9715 S.Context.getTargetInfo())) 9716 H.DoneProcessing(); 9717 } // TODO: handle other formats 9718 } 9719 9720 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9721 // Str - The format string. NOTE: this is NOT null-terminated! 9722 StringRef StrRef = FExpr->getString(); 9723 const char *Str = StrRef.data(); 9724 // Account for cases where the string literal is truncated in a declaration. 9725 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9726 assert(T && "String literal not of constant array type!"); 9727 size_t TypeSize = T->getSize().getZExtValue(); 9728 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9729 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9730 getLangOpts(), 9731 Context.getTargetInfo()); 9732 } 9733 9734 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9735 9736 // Returns the related absolute value function that is larger, of 0 if one 9737 // does not exist. 9738 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9739 switch (AbsFunction) { 9740 default: 9741 return 0; 9742 9743 case Builtin::BI__builtin_abs: 9744 return Builtin::BI__builtin_labs; 9745 case Builtin::BI__builtin_labs: 9746 return Builtin::BI__builtin_llabs; 9747 case Builtin::BI__builtin_llabs: 9748 return 0; 9749 9750 case Builtin::BI__builtin_fabsf: 9751 return Builtin::BI__builtin_fabs; 9752 case Builtin::BI__builtin_fabs: 9753 return Builtin::BI__builtin_fabsl; 9754 case Builtin::BI__builtin_fabsl: 9755 return 0; 9756 9757 case Builtin::BI__builtin_cabsf: 9758 return Builtin::BI__builtin_cabs; 9759 case Builtin::BI__builtin_cabs: 9760 return Builtin::BI__builtin_cabsl; 9761 case Builtin::BI__builtin_cabsl: 9762 return 0; 9763 9764 case Builtin::BIabs: 9765 return Builtin::BIlabs; 9766 case Builtin::BIlabs: 9767 return Builtin::BIllabs; 9768 case Builtin::BIllabs: 9769 return 0; 9770 9771 case Builtin::BIfabsf: 9772 return Builtin::BIfabs; 9773 case Builtin::BIfabs: 9774 return Builtin::BIfabsl; 9775 case Builtin::BIfabsl: 9776 return 0; 9777 9778 case Builtin::BIcabsf: 9779 return Builtin::BIcabs; 9780 case Builtin::BIcabs: 9781 return Builtin::BIcabsl; 9782 case Builtin::BIcabsl: 9783 return 0; 9784 } 9785 } 9786 9787 // Returns the argument type of the absolute value function. 9788 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9789 unsigned AbsType) { 9790 if (AbsType == 0) 9791 return QualType(); 9792 9793 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9794 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9795 if (Error != ASTContext::GE_None) 9796 return QualType(); 9797 9798 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9799 if (!FT) 9800 return QualType(); 9801 9802 if (FT->getNumParams() != 1) 9803 return QualType(); 9804 9805 return FT->getParamType(0); 9806 } 9807 9808 // Returns the best absolute value function, or zero, based on type and 9809 // current absolute value function. 9810 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9811 unsigned AbsFunctionKind) { 9812 unsigned BestKind = 0; 9813 uint64_t ArgSize = Context.getTypeSize(ArgType); 9814 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9815 Kind = getLargerAbsoluteValueFunction(Kind)) { 9816 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9817 if (Context.getTypeSize(ParamType) >= ArgSize) { 9818 if (BestKind == 0) 9819 BestKind = Kind; 9820 else if (Context.hasSameType(ParamType, ArgType)) { 9821 BestKind = Kind; 9822 break; 9823 } 9824 } 9825 } 9826 return BestKind; 9827 } 9828 9829 enum AbsoluteValueKind { 9830 AVK_Integer, 9831 AVK_Floating, 9832 AVK_Complex 9833 }; 9834 9835 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9836 if (T->isIntegralOrEnumerationType()) 9837 return AVK_Integer; 9838 if (T->isRealFloatingType()) 9839 return AVK_Floating; 9840 if (T->isAnyComplexType()) 9841 return AVK_Complex; 9842 9843 llvm_unreachable("Type not integer, floating, or complex"); 9844 } 9845 9846 // Changes the absolute value function to a different type. Preserves whether 9847 // the function is a builtin. 9848 static unsigned changeAbsFunction(unsigned AbsKind, 9849 AbsoluteValueKind ValueKind) { 9850 switch (ValueKind) { 9851 case AVK_Integer: 9852 switch (AbsKind) { 9853 default: 9854 return 0; 9855 case Builtin::BI__builtin_fabsf: 9856 case Builtin::BI__builtin_fabs: 9857 case Builtin::BI__builtin_fabsl: 9858 case Builtin::BI__builtin_cabsf: 9859 case Builtin::BI__builtin_cabs: 9860 case Builtin::BI__builtin_cabsl: 9861 return Builtin::BI__builtin_abs; 9862 case Builtin::BIfabsf: 9863 case Builtin::BIfabs: 9864 case Builtin::BIfabsl: 9865 case Builtin::BIcabsf: 9866 case Builtin::BIcabs: 9867 case Builtin::BIcabsl: 9868 return Builtin::BIabs; 9869 } 9870 case AVK_Floating: 9871 switch (AbsKind) { 9872 default: 9873 return 0; 9874 case Builtin::BI__builtin_abs: 9875 case Builtin::BI__builtin_labs: 9876 case Builtin::BI__builtin_llabs: 9877 case Builtin::BI__builtin_cabsf: 9878 case Builtin::BI__builtin_cabs: 9879 case Builtin::BI__builtin_cabsl: 9880 return Builtin::BI__builtin_fabsf; 9881 case Builtin::BIabs: 9882 case Builtin::BIlabs: 9883 case Builtin::BIllabs: 9884 case Builtin::BIcabsf: 9885 case Builtin::BIcabs: 9886 case Builtin::BIcabsl: 9887 return Builtin::BIfabsf; 9888 } 9889 case AVK_Complex: 9890 switch (AbsKind) { 9891 default: 9892 return 0; 9893 case Builtin::BI__builtin_abs: 9894 case Builtin::BI__builtin_labs: 9895 case Builtin::BI__builtin_llabs: 9896 case Builtin::BI__builtin_fabsf: 9897 case Builtin::BI__builtin_fabs: 9898 case Builtin::BI__builtin_fabsl: 9899 return Builtin::BI__builtin_cabsf; 9900 case Builtin::BIabs: 9901 case Builtin::BIlabs: 9902 case Builtin::BIllabs: 9903 case Builtin::BIfabsf: 9904 case Builtin::BIfabs: 9905 case Builtin::BIfabsl: 9906 return Builtin::BIcabsf; 9907 } 9908 } 9909 llvm_unreachable("Unable to convert function"); 9910 } 9911 9912 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9913 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9914 if (!FnInfo) 9915 return 0; 9916 9917 switch (FDecl->getBuiltinID()) { 9918 default: 9919 return 0; 9920 case Builtin::BI__builtin_abs: 9921 case Builtin::BI__builtin_fabs: 9922 case Builtin::BI__builtin_fabsf: 9923 case Builtin::BI__builtin_fabsl: 9924 case Builtin::BI__builtin_labs: 9925 case Builtin::BI__builtin_llabs: 9926 case Builtin::BI__builtin_cabs: 9927 case Builtin::BI__builtin_cabsf: 9928 case Builtin::BI__builtin_cabsl: 9929 case Builtin::BIabs: 9930 case Builtin::BIlabs: 9931 case Builtin::BIllabs: 9932 case Builtin::BIfabs: 9933 case Builtin::BIfabsf: 9934 case Builtin::BIfabsl: 9935 case Builtin::BIcabs: 9936 case Builtin::BIcabsf: 9937 case Builtin::BIcabsl: 9938 return FDecl->getBuiltinID(); 9939 } 9940 llvm_unreachable("Unknown Builtin type"); 9941 } 9942 9943 // If the replacement is valid, emit a note with replacement function. 9944 // Additionally, suggest including the proper header if not already included. 9945 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9946 unsigned AbsKind, QualType ArgType) { 9947 bool EmitHeaderHint = true; 9948 const char *HeaderName = nullptr; 9949 const char *FunctionName = nullptr; 9950 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9951 FunctionName = "std::abs"; 9952 if (ArgType->isIntegralOrEnumerationType()) { 9953 HeaderName = "cstdlib"; 9954 } else if (ArgType->isRealFloatingType()) { 9955 HeaderName = "cmath"; 9956 } else { 9957 llvm_unreachable("Invalid Type"); 9958 } 9959 9960 // Lookup all std::abs 9961 if (NamespaceDecl *Std = S.getStdNamespace()) { 9962 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9963 R.suppressDiagnostics(); 9964 S.LookupQualifiedName(R, Std); 9965 9966 for (const auto *I : R) { 9967 const FunctionDecl *FDecl = nullptr; 9968 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9969 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9970 } else { 9971 FDecl = dyn_cast<FunctionDecl>(I); 9972 } 9973 if (!FDecl) 9974 continue; 9975 9976 // Found std::abs(), check that they are the right ones. 9977 if (FDecl->getNumParams() != 1) 9978 continue; 9979 9980 // Check that the parameter type can handle the argument. 9981 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9982 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9983 S.Context.getTypeSize(ArgType) <= 9984 S.Context.getTypeSize(ParamType)) { 9985 // Found a function, don't need the header hint. 9986 EmitHeaderHint = false; 9987 break; 9988 } 9989 } 9990 } 9991 } else { 9992 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9993 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9994 9995 if (HeaderName) { 9996 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9997 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9998 R.suppressDiagnostics(); 9999 S.LookupName(R, S.getCurScope()); 10000 10001 if (R.isSingleResult()) { 10002 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10003 if (FD && FD->getBuiltinID() == AbsKind) { 10004 EmitHeaderHint = false; 10005 } else { 10006 return; 10007 } 10008 } else if (!R.empty()) { 10009 return; 10010 } 10011 } 10012 } 10013 10014 S.Diag(Loc, diag::note_replace_abs_function) 10015 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10016 10017 if (!HeaderName) 10018 return; 10019 10020 if (!EmitHeaderHint) 10021 return; 10022 10023 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10024 << FunctionName; 10025 } 10026 10027 template <std::size_t StrLen> 10028 static bool IsStdFunction(const FunctionDecl *FDecl, 10029 const char (&Str)[StrLen]) { 10030 if (!FDecl) 10031 return false; 10032 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10033 return false; 10034 if (!FDecl->isInStdNamespace()) 10035 return false; 10036 10037 return true; 10038 } 10039 10040 // Warn when using the wrong abs() function. 10041 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10042 const FunctionDecl *FDecl) { 10043 if (Call->getNumArgs() != 1) 10044 return; 10045 10046 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10047 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10048 if (AbsKind == 0 && !IsStdAbs) 10049 return; 10050 10051 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10052 QualType ParamType = Call->getArg(0)->getType(); 10053 10054 // Unsigned types cannot be negative. Suggest removing the absolute value 10055 // function call. 10056 if (ArgType->isUnsignedIntegerType()) { 10057 const char *FunctionName = 10058 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10059 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10060 Diag(Call->getExprLoc(), diag::note_remove_abs) 10061 << FunctionName 10062 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10063 return; 10064 } 10065 10066 // Taking the absolute value of a pointer is very suspicious, they probably 10067 // wanted to index into an array, dereference a pointer, call a function, etc. 10068 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10069 unsigned DiagType = 0; 10070 if (ArgType->isFunctionType()) 10071 DiagType = 1; 10072 else if (ArgType->isArrayType()) 10073 DiagType = 2; 10074 10075 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10076 return; 10077 } 10078 10079 // std::abs has overloads which prevent most of the absolute value problems 10080 // from occurring. 10081 if (IsStdAbs) 10082 return; 10083 10084 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10085 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10086 10087 // The argument and parameter are the same kind. Check if they are the right 10088 // size. 10089 if (ArgValueKind == ParamValueKind) { 10090 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10091 return; 10092 10093 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10094 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10095 << FDecl << ArgType << ParamType; 10096 10097 if (NewAbsKind == 0) 10098 return; 10099 10100 emitReplacement(*this, Call->getExprLoc(), 10101 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10102 return; 10103 } 10104 10105 // ArgValueKind != ParamValueKind 10106 // The wrong type of absolute value function was used. Attempt to find the 10107 // proper one. 10108 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10109 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10110 if (NewAbsKind == 0) 10111 return; 10112 10113 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10114 << FDecl << ParamValueKind << ArgValueKind; 10115 10116 emitReplacement(*this, Call->getExprLoc(), 10117 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10118 } 10119 10120 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10121 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10122 const FunctionDecl *FDecl) { 10123 if (!Call || !FDecl) return; 10124 10125 // Ignore template specializations and macros. 10126 if (inTemplateInstantiation()) return; 10127 if (Call->getExprLoc().isMacroID()) return; 10128 10129 // Only care about the one template argument, two function parameter std::max 10130 if (Call->getNumArgs() != 2) return; 10131 if (!IsStdFunction(FDecl, "max")) return; 10132 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10133 if (!ArgList) return; 10134 if (ArgList->size() != 1) return; 10135 10136 // Check that template type argument is unsigned integer. 10137 const auto& TA = ArgList->get(0); 10138 if (TA.getKind() != TemplateArgument::Type) return; 10139 QualType ArgType = TA.getAsType(); 10140 if (!ArgType->isUnsignedIntegerType()) return; 10141 10142 // See if either argument is a literal zero. 10143 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10144 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10145 if (!MTE) return false; 10146 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10147 if (!Num) return false; 10148 if (Num->getValue() != 0) return false; 10149 return true; 10150 }; 10151 10152 const Expr *FirstArg = Call->getArg(0); 10153 const Expr *SecondArg = Call->getArg(1); 10154 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10155 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10156 10157 // Only warn when exactly one argument is zero. 10158 if (IsFirstArgZero == IsSecondArgZero) return; 10159 10160 SourceRange FirstRange = FirstArg->getSourceRange(); 10161 SourceRange SecondRange = SecondArg->getSourceRange(); 10162 10163 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10164 10165 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10166 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10167 10168 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10169 SourceRange RemovalRange; 10170 if (IsFirstArgZero) { 10171 RemovalRange = SourceRange(FirstRange.getBegin(), 10172 SecondRange.getBegin().getLocWithOffset(-1)); 10173 } else { 10174 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10175 SecondRange.getEnd()); 10176 } 10177 10178 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10179 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10180 << FixItHint::CreateRemoval(RemovalRange); 10181 } 10182 10183 //===--- CHECK: Standard memory functions ---------------------------------===// 10184 10185 /// Takes the expression passed to the size_t parameter of functions 10186 /// such as memcmp, strncat, etc and warns if it's a comparison. 10187 /// 10188 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10189 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10190 IdentifierInfo *FnName, 10191 SourceLocation FnLoc, 10192 SourceLocation RParenLoc) { 10193 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10194 if (!Size) 10195 return false; 10196 10197 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10198 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10199 return false; 10200 10201 SourceRange SizeRange = Size->getSourceRange(); 10202 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10203 << SizeRange << FnName; 10204 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10205 << FnName 10206 << FixItHint::CreateInsertion( 10207 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10208 << FixItHint::CreateRemoval(RParenLoc); 10209 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10210 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10211 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10212 ")"); 10213 10214 return true; 10215 } 10216 10217 /// Determine whether the given type is or contains a dynamic class type 10218 /// (e.g., whether it has a vtable). 10219 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10220 bool &IsContained) { 10221 // Look through array types while ignoring qualifiers. 10222 const Type *Ty = T->getBaseElementTypeUnsafe(); 10223 IsContained = false; 10224 10225 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10226 RD = RD ? RD->getDefinition() : nullptr; 10227 if (!RD || RD->isInvalidDecl()) 10228 return nullptr; 10229 10230 if (RD->isDynamicClass()) 10231 return RD; 10232 10233 // Check all the fields. If any bases were dynamic, the class is dynamic. 10234 // It's impossible for a class to transitively contain itself by value, so 10235 // infinite recursion is impossible. 10236 for (auto *FD : RD->fields()) { 10237 bool SubContained; 10238 if (const CXXRecordDecl *ContainedRD = 10239 getContainedDynamicClass(FD->getType(), SubContained)) { 10240 IsContained = true; 10241 return ContainedRD; 10242 } 10243 } 10244 10245 return nullptr; 10246 } 10247 10248 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10249 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10250 if (Unary->getKind() == UETT_SizeOf) 10251 return Unary; 10252 return nullptr; 10253 } 10254 10255 /// If E is a sizeof expression, returns its argument expression, 10256 /// otherwise returns NULL. 10257 static const Expr *getSizeOfExprArg(const Expr *E) { 10258 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10259 if (!SizeOf->isArgumentType()) 10260 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10261 return nullptr; 10262 } 10263 10264 /// If E is a sizeof expression, returns its argument type. 10265 static QualType getSizeOfArgType(const Expr *E) { 10266 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10267 return SizeOf->getTypeOfArgument(); 10268 return QualType(); 10269 } 10270 10271 namespace { 10272 10273 struct SearchNonTrivialToInitializeField 10274 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10275 using Super = 10276 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10277 10278 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10279 10280 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10281 SourceLocation SL) { 10282 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10283 asDerived().visitArray(PDIK, AT, SL); 10284 return; 10285 } 10286 10287 Super::visitWithKind(PDIK, FT, SL); 10288 } 10289 10290 void visitARCStrong(QualType FT, SourceLocation SL) { 10291 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10292 } 10293 void visitARCWeak(QualType FT, SourceLocation SL) { 10294 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10295 } 10296 void visitStruct(QualType FT, SourceLocation SL) { 10297 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10298 visit(FD->getType(), FD->getLocation()); 10299 } 10300 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10301 const ArrayType *AT, SourceLocation SL) { 10302 visit(getContext().getBaseElementType(AT), SL); 10303 } 10304 void visitTrivial(QualType FT, SourceLocation SL) {} 10305 10306 static void diag(QualType RT, const Expr *E, Sema &S) { 10307 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10308 } 10309 10310 ASTContext &getContext() { return S.getASTContext(); } 10311 10312 const Expr *E; 10313 Sema &S; 10314 }; 10315 10316 struct SearchNonTrivialToCopyField 10317 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10318 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10319 10320 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10321 10322 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10323 SourceLocation SL) { 10324 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10325 asDerived().visitArray(PCK, AT, SL); 10326 return; 10327 } 10328 10329 Super::visitWithKind(PCK, FT, SL); 10330 } 10331 10332 void visitARCStrong(QualType FT, SourceLocation SL) { 10333 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10334 } 10335 void visitARCWeak(QualType FT, SourceLocation SL) { 10336 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10337 } 10338 void visitStruct(QualType FT, SourceLocation SL) { 10339 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10340 visit(FD->getType(), FD->getLocation()); 10341 } 10342 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10343 SourceLocation SL) { 10344 visit(getContext().getBaseElementType(AT), SL); 10345 } 10346 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10347 SourceLocation SL) {} 10348 void visitTrivial(QualType FT, SourceLocation SL) {} 10349 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10350 10351 static void diag(QualType RT, const Expr *E, Sema &S) { 10352 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10353 } 10354 10355 ASTContext &getContext() { return S.getASTContext(); } 10356 10357 const Expr *E; 10358 Sema &S; 10359 }; 10360 10361 } 10362 10363 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10364 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10365 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10366 10367 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10368 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10369 return false; 10370 10371 return doesExprLikelyComputeSize(BO->getLHS()) || 10372 doesExprLikelyComputeSize(BO->getRHS()); 10373 } 10374 10375 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10376 } 10377 10378 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10379 /// 10380 /// \code 10381 /// #define MACRO 0 10382 /// foo(MACRO); 10383 /// foo(0); 10384 /// \endcode 10385 /// 10386 /// This should return true for the first call to foo, but not for the second 10387 /// (regardless of whether foo is a macro or function). 10388 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10389 SourceLocation CallLoc, 10390 SourceLocation ArgLoc) { 10391 if (!CallLoc.isMacroID()) 10392 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10393 10394 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10395 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10396 } 10397 10398 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10399 /// last two arguments transposed. 10400 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10401 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10402 return; 10403 10404 const Expr *SizeArg = 10405 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10406 10407 auto isLiteralZero = [](const Expr *E) { 10408 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10409 }; 10410 10411 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10412 SourceLocation CallLoc = Call->getRParenLoc(); 10413 SourceManager &SM = S.getSourceManager(); 10414 if (isLiteralZero(SizeArg) && 10415 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10416 10417 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10418 10419 // Some platforms #define bzero to __builtin_memset. See if this is the 10420 // case, and if so, emit a better diagnostic. 10421 if (BId == Builtin::BIbzero || 10422 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10423 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10424 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10425 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10426 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10427 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10428 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10429 } 10430 return; 10431 } 10432 10433 // If the second argument to a memset is a sizeof expression and the third 10434 // isn't, this is also likely an error. This should catch 10435 // 'memset(buf, sizeof(buf), 0xff)'. 10436 if (BId == Builtin::BImemset && 10437 doesExprLikelyComputeSize(Call->getArg(1)) && 10438 !doesExprLikelyComputeSize(Call->getArg(2))) { 10439 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10440 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10441 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10442 return; 10443 } 10444 } 10445 10446 /// Check for dangerous or invalid arguments to memset(). 10447 /// 10448 /// This issues warnings on known problematic, dangerous or unspecified 10449 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10450 /// function calls. 10451 /// 10452 /// \param Call The call expression to diagnose. 10453 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10454 unsigned BId, 10455 IdentifierInfo *FnName) { 10456 assert(BId != 0); 10457 10458 // It is possible to have a non-standard definition of memset. Validate 10459 // we have enough arguments, and if not, abort further checking. 10460 unsigned ExpectedNumArgs = 10461 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10462 if (Call->getNumArgs() < ExpectedNumArgs) 10463 return; 10464 10465 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10466 BId == Builtin::BIstrndup ? 1 : 2); 10467 unsigned LenArg = 10468 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10469 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10470 10471 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10472 Call->getBeginLoc(), Call->getRParenLoc())) 10473 return; 10474 10475 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10476 CheckMemaccessSize(*this, BId, Call); 10477 10478 // We have special checking when the length is a sizeof expression. 10479 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10480 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10481 llvm::FoldingSetNodeID SizeOfArgID; 10482 10483 // Although widely used, 'bzero' is not a standard function. Be more strict 10484 // with the argument types before allowing diagnostics and only allow the 10485 // form bzero(ptr, sizeof(...)). 10486 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10487 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10488 return; 10489 10490 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10491 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10492 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10493 10494 QualType DestTy = Dest->getType(); 10495 QualType PointeeTy; 10496 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10497 PointeeTy = DestPtrTy->getPointeeType(); 10498 10499 // Never warn about void type pointers. This can be used to suppress 10500 // false positives. 10501 if (PointeeTy->isVoidType()) 10502 continue; 10503 10504 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10505 // actually comparing the expressions for equality. Because computing the 10506 // expression IDs can be expensive, we only do this if the diagnostic is 10507 // enabled. 10508 if (SizeOfArg && 10509 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10510 SizeOfArg->getExprLoc())) { 10511 // We only compute IDs for expressions if the warning is enabled, and 10512 // cache the sizeof arg's ID. 10513 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10514 SizeOfArg->Profile(SizeOfArgID, Context, true); 10515 llvm::FoldingSetNodeID DestID; 10516 Dest->Profile(DestID, Context, true); 10517 if (DestID == SizeOfArgID) { 10518 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10519 // over sizeof(src) as well. 10520 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10521 StringRef ReadableName = FnName->getName(); 10522 10523 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10524 if (UnaryOp->getOpcode() == UO_AddrOf) 10525 ActionIdx = 1; // If its an address-of operator, just remove it. 10526 if (!PointeeTy->isIncompleteType() && 10527 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10528 ActionIdx = 2; // If the pointee's size is sizeof(char), 10529 // suggest an explicit length. 10530 10531 // If the function is defined as a builtin macro, do not show macro 10532 // expansion. 10533 SourceLocation SL = SizeOfArg->getExprLoc(); 10534 SourceRange DSR = Dest->getSourceRange(); 10535 SourceRange SSR = SizeOfArg->getSourceRange(); 10536 SourceManager &SM = getSourceManager(); 10537 10538 if (SM.isMacroArgExpansion(SL)) { 10539 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10540 SL = SM.getSpellingLoc(SL); 10541 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10542 SM.getSpellingLoc(DSR.getEnd())); 10543 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10544 SM.getSpellingLoc(SSR.getEnd())); 10545 } 10546 10547 DiagRuntimeBehavior(SL, SizeOfArg, 10548 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10549 << ReadableName 10550 << PointeeTy 10551 << DestTy 10552 << DSR 10553 << SSR); 10554 DiagRuntimeBehavior(SL, SizeOfArg, 10555 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10556 << ActionIdx 10557 << SSR); 10558 10559 break; 10560 } 10561 } 10562 10563 // Also check for cases where the sizeof argument is the exact same 10564 // type as the memory argument, and where it points to a user-defined 10565 // record type. 10566 if (SizeOfArgTy != QualType()) { 10567 if (PointeeTy->isRecordType() && 10568 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10569 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10570 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10571 << FnName << SizeOfArgTy << ArgIdx 10572 << PointeeTy << Dest->getSourceRange() 10573 << LenExpr->getSourceRange()); 10574 break; 10575 } 10576 } 10577 } else if (DestTy->isArrayType()) { 10578 PointeeTy = DestTy; 10579 } 10580 10581 if (PointeeTy == QualType()) 10582 continue; 10583 10584 // Always complain about dynamic classes. 10585 bool IsContained; 10586 if (const CXXRecordDecl *ContainedRD = 10587 getContainedDynamicClass(PointeeTy, IsContained)) { 10588 10589 unsigned OperationType = 0; 10590 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10591 // "overwritten" if we're warning about the destination for any call 10592 // but memcmp; otherwise a verb appropriate to the call. 10593 if (ArgIdx != 0 || IsCmp) { 10594 if (BId == Builtin::BImemcpy) 10595 OperationType = 1; 10596 else if(BId == Builtin::BImemmove) 10597 OperationType = 2; 10598 else if (IsCmp) 10599 OperationType = 3; 10600 } 10601 10602 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10603 PDiag(diag::warn_dyn_class_memaccess) 10604 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10605 << IsContained << ContainedRD << OperationType 10606 << Call->getCallee()->getSourceRange()); 10607 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10608 BId != Builtin::BImemset) 10609 DiagRuntimeBehavior( 10610 Dest->getExprLoc(), Dest, 10611 PDiag(diag::warn_arc_object_memaccess) 10612 << ArgIdx << FnName << PointeeTy 10613 << Call->getCallee()->getSourceRange()); 10614 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10615 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10616 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10617 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10618 PDiag(diag::warn_cstruct_memaccess) 10619 << ArgIdx << FnName << PointeeTy << 0); 10620 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10621 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10622 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10623 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10624 PDiag(diag::warn_cstruct_memaccess) 10625 << ArgIdx << FnName << PointeeTy << 1); 10626 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10627 } else { 10628 continue; 10629 } 10630 } else 10631 continue; 10632 10633 DiagRuntimeBehavior( 10634 Dest->getExprLoc(), Dest, 10635 PDiag(diag::note_bad_memaccess_silence) 10636 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10637 break; 10638 } 10639 } 10640 10641 // A little helper routine: ignore addition and subtraction of integer literals. 10642 // This intentionally does not ignore all integer constant expressions because 10643 // we don't want to remove sizeof(). 10644 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10645 Ex = Ex->IgnoreParenCasts(); 10646 10647 while (true) { 10648 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10649 if (!BO || !BO->isAdditiveOp()) 10650 break; 10651 10652 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10653 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10654 10655 if (isa<IntegerLiteral>(RHS)) 10656 Ex = LHS; 10657 else if (isa<IntegerLiteral>(LHS)) 10658 Ex = RHS; 10659 else 10660 break; 10661 } 10662 10663 return Ex; 10664 } 10665 10666 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10667 ASTContext &Context) { 10668 // Only handle constant-sized or VLAs, but not flexible members. 10669 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10670 // Only issue the FIXIT for arrays of size > 1. 10671 if (CAT->getSize().getSExtValue() <= 1) 10672 return false; 10673 } else if (!Ty->isVariableArrayType()) { 10674 return false; 10675 } 10676 return true; 10677 } 10678 10679 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10680 // be the size of the source, instead of the destination. 10681 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10682 IdentifierInfo *FnName) { 10683 10684 // Don't crash if the user has the wrong number of arguments 10685 unsigned NumArgs = Call->getNumArgs(); 10686 if ((NumArgs != 3) && (NumArgs != 4)) 10687 return; 10688 10689 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10690 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10691 const Expr *CompareWithSrc = nullptr; 10692 10693 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10694 Call->getBeginLoc(), Call->getRParenLoc())) 10695 return; 10696 10697 // Look for 'strlcpy(dst, x, sizeof(x))' 10698 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10699 CompareWithSrc = Ex; 10700 else { 10701 // Look for 'strlcpy(dst, x, strlen(x))' 10702 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10703 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10704 SizeCall->getNumArgs() == 1) 10705 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10706 } 10707 } 10708 10709 if (!CompareWithSrc) 10710 return; 10711 10712 // Determine if the argument to sizeof/strlen is equal to the source 10713 // argument. In principle there's all kinds of things you could do 10714 // here, for instance creating an == expression and evaluating it with 10715 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10716 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10717 if (!SrcArgDRE) 10718 return; 10719 10720 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10721 if (!CompareWithSrcDRE || 10722 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10723 return; 10724 10725 const Expr *OriginalSizeArg = Call->getArg(2); 10726 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10727 << OriginalSizeArg->getSourceRange() << FnName; 10728 10729 // Output a FIXIT hint if the destination is an array (rather than a 10730 // pointer to an array). This could be enhanced to handle some 10731 // pointers if we know the actual size, like if DstArg is 'array+2' 10732 // we could say 'sizeof(array)-2'. 10733 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10734 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10735 return; 10736 10737 SmallString<128> sizeString; 10738 llvm::raw_svector_ostream OS(sizeString); 10739 OS << "sizeof("; 10740 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10741 OS << ")"; 10742 10743 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10744 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10745 OS.str()); 10746 } 10747 10748 /// Check if two expressions refer to the same declaration. 10749 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10750 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10751 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10752 return D1->getDecl() == D2->getDecl(); 10753 return false; 10754 } 10755 10756 static const Expr *getStrlenExprArg(const Expr *E) { 10757 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10758 const FunctionDecl *FD = CE->getDirectCallee(); 10759 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10760 return nullptr; 10761 return CE->getArg(0)->IgnoreParenCasts(); 10762 } 10763 return nullptr; 10764 } 10765 10766 // Warn on anti-patterns as the 'size' argument to strncat. 10767 // The correct size argument should look like following: 10768 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10769 void Sema::CheckStrncatArguments(const CallExpr *CE, 10770 IdentifierInfo *FnName) { 10771 // Don't crash if the user has the wrong number of arguments. 10772 if (CE->getNumArgs() < 3) 10773 return; 10774 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10775 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10776 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10777 10778 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10779 CE->getRParenLoc())) 10780 return; 10781 10782 // Identify common expressions, which are wrongly used as the size argument 10783 // to strncat and may lead to buffer overflows. 10784 unsigned PatternType = 0; 10785 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10786 // - sizeof(dst) 10787 if (referToTheSameDecl(SizeOfArg, DstArg)) 10788 PatternType = 1; 10789 // - sizeof(src) 10790 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10791 PatternType = 2; 10792 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10793 if (BE->getOpcode() == BO_Sub) { 10794 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10795 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10796 // - sizeof(dst) - strlen(dst) 10797 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10798 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10799 PatternType = 1; 10800 // - sizeof(src) - (anything) 10801 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10802 PatternType = 2; 10803 } 10804 } 10805 10806 if (PatternType == 0) 10807 return; 10808 10809 // Generate the diagnostic. 10810 SourceLocation SL = LenArg->getBeginLoc(); 10811 SourceRange SR = LenArg->getSourceRange(); 10812 SourceManager &SM = getSourceManager(); 10813 10814 // If the function is defined as a builtin macro, do not show macro expansion. 10815 if (SM.isMacroArgExpansion(SL)) { 10816 SL = SM.getSpellingLoc(SL); 10817 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10818 SM.getSpellingLoc(SR.getEnd())); 10819 } 10820 10821 // Check if the destination is an array (rather than a pointer to an array). 10822 QualType DstTy = DstArg->getType(); 10823 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10824 Context); 10825 if (!isKnownSizeArray) { 10826 if (PatternType == 1) 10827 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10828 else 10829 Diag(SL, diag::warn_strncat_src_size) << SR; 10830 return; 10831 } 10832 10833 if (PatternType == 1) 10834 Diag(SL, diag::warn_strncat_large_size) << SR; 10835 else 10836 Diag(SL, diag::warn_strncat_src_size) << SR; 10837 10838 SmallString<128> sizeString; 10839 llvm::raw_svector_ostream OS(sizeString); 10840 OS << "sizeof("; 10841 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10842 OS << ") - "; 10843 OS << "strlen("; 10844 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10845 OS << ") - 1"; 10846 10847 Diag(SL, diag::note_strncat_wrong_size) 10848 << FixItHint::CreateReplacement(SR, OS.str()); 10849 } 10850 10851 namespace { 10852 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10853 const UnaryOperator *UnaryExpr, const Decl *D) { 10854 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10855 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10856 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10857 return; 10858 } 10859 } 10860 10861 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10862 const UnaryOperator *UnaryExpr) { 10863 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10864 const Decl *D = Lvalue->getDecl(); 10865 if (isa<DeclaratorDecl>(D)) 10866 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10867 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10868 } 10869 10870 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10871 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10872 Lvalue->getMemberDecl()); 10873 } 10874 10875 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10876 const UnaryOperator *UnaryExpr) { 10877 const auto *Lambda = dyn_cast<LambdaExpr>( 10878 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10879 if (!Lambda) 10880 return; 10881 10882 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10883 << CalleeName << 2 /*object: lambda expression*/; 10884 } 10885 10886 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10887 const DeclRefExpr *Lvalue) { 10888 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10889 if (Var == nullptr) 10890 return; 10891 10892 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10893 << CalleeName << 0 /*object: */ << Var; 10894 } 10895 10896 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10897 const CastExpr *Cast) { 10898 SmallString<128> SizeString; 10899 llvm::raw_svector_ostream OS(SizeString); 10900 10901 clang::CastKind Kind = Cast->getCastKind(); 10902 if (Kind == clang::CK_BitCast && 10903 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10904 return; 10905 if (Kind == clang::CK_IntegralToPointer && 10906 !isa<IntegerLiteral>( 10907 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10908 return; 10909 10910 switch (Cast->getCastKind()) { 10911 case clang::CK_BitCast: 10912 case clang::CK_IntegralToPointer: 10913 case clang::CK_FunctionToPointerDecay: 10914 OS << '\''; 10915 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10916 OS << '\''; 10917 break; 10918 default: 10919 return; 10920 } 10921 10922 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10923 << CalleeName << 0 /*object: */ << OS.str(); 10924 } 10925 } // namespace 10926 10927 /// Alerts the user that they are attempting to free a non-malloc'd object. 10928 void Sema::CheckFreeArguments(const CallExpr *E) { 10929 const std::string CalleeName = 10930 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10931 10932 { // Prefer something that doesn't involve a cast to make things simpler. 10933 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10934 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10935 switch (UnaryExpr->getOpcode()) { 10936 case UnaryOperator::Opcode::UO_AddrOf: 10937 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10938 case UnaryOperator::Opcode::UO_Plus: 10939 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10940 default: 10941 break; 10942 } 10943 10944 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10945 if (Lvalue->getType()->isArrayType()) 10946 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10947 10948 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10949 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10950 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10951 return; 10952 } 10953 10954 if (isa<BlockExpr>(Arg)) { 10955 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10956 << CalleeName << 1 /*object: block*/; 10957 return; 10958 } 10959 } 10960 // Maybe the cast was important, check after the other cases. 10961 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10962 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10963 } 10964 10965 void 10966 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10967 SourceLocation ReturnLoc, 10968 bool isObjCMethod, 10969 const AttrVec *Attrs, 10970 const FunctionDecl *FD) { 10971 // Check if the return value is null but should not be. 10972 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10973 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10974 CheckNonNullExpr(*this, RetValExp)) 10975 Diag(ReturnLoc, diag::warn_null_ret) 10976 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10977 10978 // C++11 [basic.stc.dynamic.allocation]p4: 10979 // If an allocation function declared with a non-throwing 10980 // exception-specification fails to allocate storage, it shall return 10981 // a null pointer. Any other allocation function that fails to allocate 10982 // storage shall indicate failure only by throwing an exception [...] 10983 if (FD) { 10984 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10985 if (Op == OO_New || Op == OO_Array_New) { 10986 const FunctionProtoType *Proto 10987 = FD->getType()->castAs<FunctionProtoType>(); 10988 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10989 CheckNonNullExpr(*this, RetValExp)) 10990 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10991 << FD << getLangOpts().CPlusPlus11; 10992 } 10993 } 10994 10995 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10996 // here prevent the user from using a PPC MMA type as trailing return type. 10997 if (Context.getTargetInfo().getTriple().isPPC64()) 10998 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10999 } 11000 11001 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11002 11003 /// Check for comparisons of floating point operands using != and ==. 11004 /// Issue a warning if these are no self-comparisons, as they are not likely 11005 /// to do what the programmer intended. 11006 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11007 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11008 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11009 11010 // Special case: check for x == x (which is OK). 11011 // Do not emit warnings for such cases. 11012 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11013 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11014 if (DRL->getDecl() == DRR->getDecl()) 11015 return; 11016 11017 // Special case: check for comparisons against literals that can be exactly 11018 // represented by APFloat. In such cases, do not emit a warning. This 11019 // is a heuristic: often comparison against such literals are used to 11020 // detect if a value in a variable has not changed. This clearly can 11021 // lead to false negatives. 11022 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11023 if (FLL->isExact()) 11024 return; 11025 } else 11026 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11027 if (FLR->isExact()) 11028 return; 11029 11030 // Check for comparisons with builtin types. 11031 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11032 if (CL->getBuiltinCallee()) 11033 return; 11034 11035 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11036 if (CR->getBuiltinCallee()) 11037 return; 11038 11039 // Emit the diagnostic. 11040 Diag(Loc, diag::warn_floatingpoint_eq) 11041 << LHS->getSourceRange() << RHS->getSourceRange(); 11042 } 11043 11044 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11045 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11046 11047 namespace { 11048 11049 /// Structure recording the 'active' range of an integer-valued 11050 /// expression. 11051 struct IntRange { 11052 /// The number of bits active in the int. Note that this includes exactly one 11053 /// sign bit if !NonNegative. 11054 unsigned Width; 11055 11056 /// True if the int is known not to have negative values. If so, all leading 11057 /// bits before Width are known zero, otherwise they are known to be the 11058 /// same as the MSB within Width. 11059 bool NonNegative; 11060 11061 IntRange(unsigned Width, bool NonNegative) 11062 : Width(Width), NonNegative(NonNegative) {} 11063 11064 /// Number of bits excluding the sign bit. 11065 unsigned valueBits() const { 11066 return NonNegative ? Width : Width - 1; 11067 } 11068 11069 /// Returns the range of the bool type. 11070 static IntRange forBoolType() { 11071 return IntRange(1, true); 11072 } 11073 11074 /// Returns the range of an opaque value of the given integral type. 11075 static IntRange forValueOfType(ASTContext &C, QualType T) { 11076 return forValueOfCanonicalType(C, 11077 T->getCanonicalTypeInternal().getTypePtr()); 11078 } 11079 11080 /// Returns the range of an opaque value of a canonical integral type. 11081 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11082 assert(T->isCanonicalUnqualified()); 11083 11084 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11085 T = VT->getElementType().getTypePtr(); 11086 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11087 T = CT->getElementType().getTypePtr(); 11088 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11089 T = AT->getValueType().getTypePtr(); 11090 11091 if (!C.getLangOpts().CPlusPlus) { 11092 // For enum types in C code, use the underlying datatype. 11093 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11094 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11095 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11096 // For enum types in C++, use the known bit width of the enumerators. 11097 EnumDecl *Enum = ET->getDecl(); 11098 // In C++11, enums can have a fixed underlying type. Use this type to 11099 // compute the range. 11100 if (Enum->isFixed()) { 11101 return IntRange(C.getIntWidth(QualType(T, 0)), 11102 !ET->isSignedIntegerOrEnumerationType()); 11103 } 11104 11105 unsigned NumPositive = Enum->getNumPositiveBits(); 11106 unsigned NumNegative = Enum->getNumNegativeBits(); 11107 11108 if (NumNegative == 0) 11109 return IntRange(NumPositive, true/*NonNegative*/); 11110 else 11111 return IntRange(std::max(NumPositive + 1, NumNegative), 11112 false/*NonNegative*/); 11113 } 11114 11115 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11116 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11117 11118 const BuiltinType *BT = cast<BuiltinType>(T); 11119 assert(BT->isInteger()); 11120 11121 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11122 } 11123 11124 /// Returns the "target" range of a canonical integral type, i.e. 11125 /// the range of values expressible in the type. 11126 /// 11127 /// This matches forValueOfCanonicalType except that enums have the 11128 /// full range of their type, not the range of their enumerators. 11129 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11130 assert(T->isCanonicalUnqualified()); 11131 11132 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11133 T = VT->getElementType().getTypePtr(); 11134 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11135 T = CT->getElementType().getTypePtr(); 11136 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11137 T = AT->getValueType().getTypePtr(); 11138 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11139 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11140 11141 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11142 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11143 11144 const BuiltinType *BT = cast<BuiltinType>(T); 11145 assert(BT->isInteger()); 11146 11147 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11148 } 11149 11150 /// Returns the supremum of two ranges: i.e. their conservative merge. 11151 static IntRange join(IntRange L, IntRange R) { 11152 bool Unsigned = L.NonNegative && R.NonNegative; 11153 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11154 L.NonNegative && R.NonNegative); 11155 } 11156 11157 /// Return the range of a bitwise-AND of the two ranges. 11158 static IntRange bit_and(IntRange L, IntRange R) { 11159 unsigned Bits = std::max(L.Width, R.Width); 11160 bool NonNegative = false; 11161 if (L.NonNegative) { 11162 Bits = std::min(Bits, L.Width); 11163 NonNegative = true; 11164 } 11165 if (R.NonNegative) { 11166 Bits = std::min(Bits, R.Width); 11167 NonNegative = true; 11168 } 11169 return IntRange(Bits, NonNegative); 11170 } 11171 11172 /// Return the range of a sum of the two ranges. 11173 static IntRange sum(IntRange L, IntRange R) { 11174 bool Unsigned = L.NonNegative && R.NonNegative; 11175 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11176 Unsigned); 11177 } 11178 11179 /// Return the range of a difference of the two ranges. 11180 static IntRange difference(IntRange L, IntRange R) { 11181 // We need a 1-bit-wider range if: 11182 // 1) LHS can be negative: least value can be reduced. 11183 // 2) RHS can be negative: greatest value can be increased. 11184 bool CanWiden = !L.NonNegative || !R.NonNegative; 11185 bool Unsigned = L.NonNegative && R.Width == 0; 11186 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11187 !Unsigned, 11188 Unsigned); 11189 } 11190 11191 /// Return the range of a product of the two ranges. 11192 static IntRange product(IntRange L, IntRange R) { 11193 // If both LHS and RHS can be negative, we can form 11194 // -2^L * -2^R = 2^(L + R) 11195 // which requires L + R + 1 value bits to represent. 11196 bool CanWiden = !L.NonNegative && !R.NonNegative; 11197 bool Unsigned = L.NonNegative && R.NonNegative; 11198 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11199 Unsigned); 11200 } 11201 11202 /// Return the range of a remainder operation between the two ranges. 11203 static IntRange rem(IntRange L, IntRange R) { 11204 // The result of a remainder can't be larger than the result of 11205 // either side. The sign of the result is the sign of the LHS. 11206 bool Unsigned = L.NonNegative; 11207 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11208 Unsigned); 11209 } 11210 }; 11211 11212 } // namespace 11213 11214 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11215 unsigned MaxWidth) { 11216 if (value.isSigned() && value.isNegative()) 11217 return IntRange(value.getMinSignedBits(), false); 11218 11219 if (value.getBitWidth() > MaxWidth) 11220 value = value.trunc(MaxWidth); 11221 11222 // isNonNegative() just checks the sign bit without considering 11223 // signedness. 11224 return IntRange(value.getActiveBits(), true); 11225 } 11226 11227 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11228 unsigned MaxWidth) { 11229 if (result.isInt()) 11230 return GetValueRange(C, result.getInt(), MaxWidth); 11231 11232 if (result.isVector()) { 11233 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11234 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11235 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11236 R = IntRange::join(R, El); 11237 } 11238 return R; 11239 } 11240 11241 if (result.isComplexInt()) { 11242 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11243 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11244 return IntRange::join(R, I); 11245 } 11246 11247 // This can happen with lossless casts to intptr_t of "based" lvalues. 11248 // Assume it might use arbitrary bits. 11249 // FIXME: The only reason we need to pass the type in here is to get 11250 // the sign right on this one case. It would be nice if APValue 11251 // preserved this. 11252 assert(result.isLValue() || result.isAddrLabelDiff()); 11253 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11254 } 11255 11256 static QualType GetExprType(const Expr *E) { 11257 QualType Ty = E->getType(); 11258 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11259 Ty = AtomicRHS->getValueType(); 11260 return Ty; 11261 } 11262 11263 /// Pseudo-evaluate the given integer expression, estimating the 11264 /// range of values it might take. 11265 /// 11266 /// \param MaxWidth The width to which the value will be truncated. 11267 /// \param Approximate If \c true, return a likely range for the result: in 11268 /// particular, assume that aritmetic on narrower types doesn't leave 11269 /// those types. If \c false, return a range including all possible 11270 /// result values. 11271 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11272 bool InConstantContext, bool Approximate) { 11273 E = E->IgnoreParens(); 11274 11275 // Try a full evaluation first. 11276 Expr::EvalResult result; 11277 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11278 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11279 11280 // I think we only want to look through implicit casts here; if the 11281 // user has an explicit widening cast, we should treat the value as 11282 // being of the new, wider type. 11283 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11284 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11285 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11286 Approximate); 11287 11288 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11289 11290 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11291 CE->getCastKind() == CK_BooleanToSignedIntegral; 11292 11293 // Assume that non-integer casts can span the full range of the type. 11294 if (!isIntegerCast) 11295 return OutputTypeRange; 11296 11297 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11298 std::min(MaxWidth, OutputTypeRange.Width), 11299 InConstantContext, Approximate); 11300 11301 // Bail out if the subexpr's range is as wide as the cast type. 11302 if (SubRange.Width >= OutputTypeRange.Width) 11303 return OutputTypeRange; 11304 11305 // Otherwise, we take the smaller width, and we're non-negative if 11306 // either the output type or the subexpr is. 11307 return IntRange(SubRange.Width, 11308 SubRange.NonNegative || OutputTypeRange.NonNegative); 11309 } 11310 11311 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11312 // If we can fold the condition, just take that operand. 11313 bool CondResult; 11314 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11315 return GetExprRange(C, 11316 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11317 MaxWidth, InConstantContext, Approximate); 11318 11319 // Otherwise, conservatively merge. 11320 // GetExprRange requires an integer expression, but a throw expression 11321 // results in a void type. 11322 Expr *E = CO->getTrueExpr(); 11323 IntRange L = E->getType()->isVoidType() 11324 ? IntRange{0, true} 11325 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11326 E = CO->getFalseExpr(); 11327 IntRange R = E->getType()->isVoidType() 11328 ? IntRange{0, true} 11329 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11330 return IntRange::join(L, R); 11331 } 11332 11333 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11334 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11335 11336 switch (BO->getOpcode()) { 11337 case BO_Cmp: 11338 llvm_unreachable("builtin <=> should have class type"); 11339 11340 // Boolean-valued operations are single-bit and positive. 11341 case BO_LAnd: 11342 case BO_LOr: 11343 case BO_LT: 11344 case BO_GT: 11345 case BO_LE: 11346 case BO_GE: 11347 case BO_EQ: 11348 case BO_NE: 11349 return IntRange::forBoolType(); 11350 11351 // The type of the assignments is the type of the LHS, so the RHS 11352 // is not necessarily the same type. 11353 case BO_MulAssign: 11354 case BO_DivAssign: 11355 case BO_RemAssign: 11356 case BO_AddAssign: 11357 case BO_SubAssign: 11358 case BO_XorAssign: 11359 case BO_OrAssign: 11360 // TODO: bitfields? 11361 return IntRange::forValueOfType(C, GetExprType(E)); 11362 11363 // Simple assignments just pass through the RHS, which will have 11364 // been coerced to the LHS type. 11365 case BO_Assign: 11366 // TODO: bitfields? 11367 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11368 Approximate); 11369 11370 // Operations with opaque sources are black-listed. 11371 case BO_PtrMemD: 11372 case BO_PtrMemI: 11373 return IntRange::forValueOfType(C, GetExprType(E)); 11374 11375 // Bitwise-and uses the *infinum* of the two source ranges. 11376 case BO_And: 11377 case BO_AndAssign: 11378 Combine = IntRange::bit_and; 11379 break; 11380 11381 // Left shift gets black-listed based on a judgement call. 11382 case BO_Shl: 11383 // ...except that we want to treat '1 << (blah)' as logically 11384 // positive. It's an important idiom. 11385 if (IntegerLiteral *I 11386 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11387 if (I->getValue() == 1) { 11388 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11389 return IntRange(R.Width, /*NonNegative*/ true); 11390 } 11391 } 11392 LLVM_FALLTHROUGH; 11393 11394 case BO_ShlAssign: 11395 return IntRange::forValueOfType(C, GetExprType(E)); 11396 11397 // Right shift by a constant can narrow its left argument. 11398 case BO_Shr: 11399 case BO_ShrAssign: { 11400 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11401 Approximate); 11402 11403 // If the shift amount is a positive constant, drop the width by 11404 // that much. 11405 if (Optional<llvm::APSInt> shift = 11406 BO->getRHS()->getIntegerConstantExpr(C)) { 11407 if (shift->isNonNegative()) { 11408 unsigned zext = shift->getZExtValue(); 11409 if (zext >= L.Width) 11410 L.Width = (L.NonNegative ? 0 : 1); 11411 else 11412 L.Width -= zext; 11413 } 11414 } 11415 11416 return L; 11417 } 11418 11419 // Comma acts as its right operand. 11420 case BO_Comma: 11421 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11422 Approximate); 11423 11424 case BO_Add: 11425 if (!Approximate) 11426 Combine = IntRange::sum; 11427 break; 11428 11429 case BO_Sub: 11430 if (BO->getLHS()->getType()->isPointerType()) 11431 return IntRange::forValueOfType(C, GetExprType(E)); 11432 if (!Approximate) 11433 Combine = IntRange::difference; 11434 break; 11435 11436 case BO_Mul: 11437 if (!Approximate) 11438 Combine = IntRange::product; 11439 break; 11440 11441 // The width of a division result is mostly determined by the size 11442 // of the LHS. 11443 case BO_Div: { 11444 // Don't 'pre-truncate' the operands. 11445 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11446 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11447 Approximate); 11448 11449 // If the divisor is constant, use that. 11450 if (Optional<llvm::APSInt> divisor = 11451 BO->getRHS()->getIntegerConstantExpr(C)) { 11452 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11453 if (log2 >= L.Width) 11454 L.Width = (L.NonNegative ? 0 : 1); 11455 else 11456 L.Width = std::min(L.Width - log2, MaxWidth); 11457 return L; 11458 } 11459 11460 // Otherwise, just use the LHS's width. 11461 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11462 // could be -1. 11463 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11464 Approximate); 11465 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11466 } 11467 11468 case BO_Rem: 11469 Combine = IntRange::rem; 11470 break; 11471 11472 // The default behavior is okay for these. 11473 case BO_Xor: 11474 case BO_Or: 11475 break; 11476 } 11477 11478 // Combine the two ranges, but limit the result to the type in which we 11479 // performed the computation. 11480 QualType T = GetExprType(E); 11481 unsigned opWidth = C.getIntWidth(T); 11482 IntRange L = 11483 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11484 IntRange R = 11485 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11486 IntRange C = Combine(L, R); 11487 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11488 C.Width = std::min(C.Width, MaxWidth); 11489 return C; 11490 } 11491 11492 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11493 switch (UO->getOpcode()) { 11494 // Boolean-valued operations are white-listed. 11495 case UO_LNot: 11496 return IntRange::forBoolType(); 11497 11498 // Operations with opaque sources are black-listed. 11499 case UO_Deref: 11500 case UO_AddrOf: // should be impossible 11501 return IntRange::forValueOfType(C, GetExprType(E)); 11502 11503 default: 11504 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11505 Approximate); 11506 } 11507 } 11508 11509 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11510 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11511 Approximate); 11512 11513 if (const auto *BitField = E->getSourceBitField()) 11514 return IntRange(BitField->getBitWidthValue(C), 11515 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11516 11517 return IntRange::forValueOfType(C, GetExprType(E)); 11518 } 11519 11520 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11521 bool InConstantContext, bool Approximate) { 11522 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11523 Approximate); 11524 } 11525 11526 /// Checks whether the given value, which currently has the given 11527 /// source semantics, has the same value when coerced through the 11528 /// target semantics. 11529 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11530 const llvm::fltSemantics &Src, 11531 const llvm::fltSemantics &Tgt) { 11532 llvm::APFloat truncated = value; 11533 11534 bool ignored; 11535 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11536 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11537 11538 return truncated.bitwiseIsEqual(value); 11539 } 11540 11541 /// Checks whether the given value, which currently has the given 11542 /// source semantics, has the same value when coerced through the 11543 /// target semantics. 11544 /// 11545 /// The value might be a vector of floats (or a complex number). 11546 static bool IsSameFloatAfterCast(const APValue &value, 11547 const llvm::fltSemantics &Src, 11548 const llvm::fltSemantics &Tgt) { 11549 if (value.isFloat()) 11550 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11551 11552 if (value.isVector()) { 11553 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11554 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11555 return false; 11556 return true; 11557 } 11558 11559 assert(value.isComplexFloat()); 11560 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11561 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11562 } 11563 11564 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11565 bool IsListInit = false); 11566 11567 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11568 // Suppress cases where we are comparing against an enum constant. 11569 if (const DeclRefExpr *DR = 11570 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11571 if (isa<EnumConstantDecl>(DR->getDecl())) 11572 return true; 11573 11574 // Suppress cases where the value is expanded from a macro, unless that macro 11575 // is how a language represents a boolean literal. This is the case in both C 11576 // and Objective-C. 11577 SourceLocation BeginLoc = E->getBeginLoc(); 11578 if (BeginLoc.isMacroID()) { 11579 StringRef MacroName = Lexer::getImmediateMacroName( 11580 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11581 return MacroName != "YES" && MacroName != "NO" && 11582 MacroName != "true" && MacroName != "false"; 11583 } 11584 11585 return false; 11586 } 11587 11588 static bool isKnownToHaveUnsignedValue(Expr *E) { 11589 return E->getType()->isIntegerType() && 11590 (!E->getType()->isSignedIntegerType() || 11591 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11592 } 11593 11594 namespace { 11595 /// The promoted range of values of a type. In general this has the 11596 /// following structure: 11597 /// 11598 /// |-----------| . . . |-----------| 11599 /// ^ ^ ^ ^ 11600 /// Min HoleMin HoleMax Max 11601 /// 11602 /// ... where there is only a hole if a signed type is promoted to unsigned 11603 /// (in which case Min and Max are the smallest and largest representable 11604 /// values). 11605 struct PromotedRange { 11606 // Min, or HoleMax if there is a hole. 11607 llvm::APSInt PromotedMin; 11608 // Max, or HoleMin if there is a hole. 11609 llvm::APSInt PromotedMax; 11610 11611 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11612 if (R.Width == 0) 11613 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11614 else if (R.Width >= BitWidth && !Unsigned) { 11615 // Promotion made the type *narrower*. This happens when promoting 11616 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11617 // Treat all values of 'signed int' as being in range for now. 11618 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11619 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11620 } else { 11621 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11622 .extOrTrunc(BitWidth); 11623 PromotedMin.setIsUnsigned(Unsigned); 11624 11625 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11626 .extOrTrunc(BitWidth); 11627 PromotedMax.setIsUnsigned(Unsigned); 11628 } 11629 } 11630 11631 // Determine whether this range is contiguous (has no hole). 11632 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11633 11634 // Where a constant value is within the range. 11635 enum ComparisonResult { 11636 LT = 0x1, 11637 LE = 0x2, 11638 GT = 0x4, 11639 GE = 0x8, 11640 EQ = 0x10, 11641 NE = 0x20, 11642 InRangeFlag = 0x40, 11643 11644 Less = LE | LT | NE, 11645 Min = LE | InRangeFlag, 11646 InRange = InRangeFlag, 11647 Max = GE | InRangeFlag, 11648 Greater = GE | GT | NE, 11649 11650 OnlyValue = LE | GE | EQ | InRangeFlag, 11651 InHole = NE 11652 }; 11653 11654 ComparisonResult compare(const llvm::APSInt &Value) const { 11655 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11656 Value.isUnsigned() == PromotedMin.isUnsigned()); 11657 if (!isContiguous()) { 11658 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11659 if (Value.isMinValue()) return Min; 11660 if (Value.isMaxValue()) return Max; 11661 if (Value >= PromotedMin) return InRange; 11662 if (Value <= PromotedMax) return InRange; 11663 return InHole; 11664 } 11665 11666 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11667 case -1: return Less; 11668 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11669 case 1: 11670 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11671 case -1: return InRange; 11672 case 0: return Max; 11673 case 1: return Greater; 11674 } 11675 } 11676 11677 llvm_unreachable("impossible compare result"); 11678 } 11679 11680 static llvm::Optional<StringRef> 11681 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11682 if (Op == BO_Cmp) { 11683 ComparisonResult LTFlag = LT, GTFlag = GT; 11684 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11685 11686 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11687 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11688 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11689 return llvm::None; 11690 } 11691 11692 ComparisonResult TrueFlag, FalseFlag; 11693 if (Op == BO_EQ) { 11694 TrueFlag = EQ; 11695 FalseFlag = NE; 11696 } else if (Op == BO_NE) { 11697 TrueFlag = NE; 11698 FalseFlag = EQ; 11699 } else { 11700 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11701 TrueFlag = LT; 11702 FalseFlag = GE; 11703 } else { 11704 TrueFlag = GT; 11705 FalseFlag = LE; 11706 } 11707 if (Op == BO_GE || Op == BO_LE) 11708 std::swap(TrueFlag, FalseFlag); 11709 } 11710 if (R & TrueFlag) 11711 return StringRef("true"); 11712 if (R & FalseFlag) 11713 return StringRef("false"); 11714 return llvm::None; 11715 } 11716 }; 11717 } 11718 11719 static bool HasEnumType(Expr *E) { 11720 // Strip off implicit integral promotions. 11721 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11722 if (ICE->getCastKind() != CK_IntegralCast && 11723 ICE->getCastKind() != CK_NoOp) 11724 break; 11725 E = ICE->getSubExpr(); 11726 } 11727 11728 return E->getType()->isEnumeralType(); 11729 } 11730 11731 static int classifyConstantValue(Expr *Constant) { 11732 // The values of this enumeration are used in the diagnostics 11733 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11734 enum ConstantValueKind { 11735 Miscellaneous = 0, 11736 LiteralTrue, 11737 LiteralFalse 11738 }; 11739 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11740 return BL->getValue() ? ConstantValueKind::LiteralTrue 11741 : ConstantValueKind::LiteralFalse; 11742 return ConstantValueKind::Miscellaneous; 11743 } 11744 11745 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11746 Expr *Constant, Expr *Other, 11747 const llvm::APSInt &Value, 11748 bool RhsConstant) { 11749 if (S.inTemplateInstantiation()) 11750 return false; 11751 11752 Expr *OriginalOther = Other; 11753 11754 Constant = Constant->IgnoreParenImpCasts(); 11755 Other = Other->IgnoreParenImpCasts(); 11756 11757 // Suppress warnings on tautological comparisons between values of the same 11758 // enumeration type. There are only two ways we could warn on this: 11759 // - If the constant is outside the range of representable values of 11760 // the enumeration. In such a case, we should warn about the cast 11761 // to enumeration type, not about the comparison. 11762 // - If the constant is the maximum / minimum in-range value. For an 11763 // enumeratin type, such comparisons can be meaningful and useful. 11764 if (Constant->getType()->isEnumeralType() && 11765 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11766 return false; 11767 11768 IntRange OtherValueRange = GetExprRange( 11769 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11770 11771 QualType OtherT = Other->getType(); 11772 if (const auto *AT = OtherT->getAs<AtomicType>()) 11773 OtherT = AT->getValueType(); 11774 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11775 11776 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11777 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11778 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11779 S.NSAPIObj->isObjCBOOLType(OtherT) && 11780 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11781 11782 // Whether we're treating Other as being a bool because of the form of 11783 // expression despite it having another type (typically 'int' in C). 11784 bool OtherIsBooleanDespiteType = 11785 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11786 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11787 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11788 11789 // Check if all values in the range of possible values of this expression 11790 // lead to the same comparison outcome. 11791 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11792 Value.isUnsigned()); 11793 auto Cmp = OtherPromotedValueRange.compare(Value); 11794 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11795 if (!Result) 11796 return false; 11797 11798 // Also consider the range determined by the type alone. This allows us to 11799 // classify the warning under the proper diagnostic group. 11800 bool TautologicalTypeCompare = false; 11801 { 11802 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11803 Value.isUnsigned()); 11804 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11805 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11806 RhsConstant)) { 11807 TautologicalTypeCompare = true; 11808 Cmp = TypeCmp; 11809 Result = TypeResult; 11810 } 11811 } 11812 11813 // Don't warn if the non-constant operand actually always evaluates to the 11814 // same value. 11815 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11816 return false; 11817 11818 // Suppress the diagnostic for an in-range comparison if the constant comes 11819 // from a macro or enumerator. We don't want to diagnose 11820 // 11821 // some_long_value <= INT_MAX 11822 // 11823 // when sizeof(int) == sizeof(long). 11824 bool InRange = Cmp & PromotedRange::InRangeFlag; 11825 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11826 return false; 11827 11828 // A comparison of an unsigned bit-field against 0 is really a type problem, 11829 // even though at the type level the bit-field might promote to 'signed int'. 11830 if (Other->refersToBitField() && InRange && Value == 0 && 11831 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11832 TautologicalTypeCompare = true; 11833 11834 // If this is a comparison to an enum constant, include that 11835 // constant in the diagnostic. 11836 const EnumConstantDecl *ED = nullptr; 11837 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11838 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11839 11840 // Should be enough for uint128 (39 decimal digits) 11841 SmallString<64> PrettySourceValue; 11842 llvm::raw_svector_ostream OS(PrettySourceValue); 11843 if (ED) { 11844 OS << '\'' << *ED << "' (" << Value << ")"; 11845 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11846 Constant->IgnoreParenImpCasts())) { 11847 OS << (BL->getValue() ? "YES" : "NO"); 11848 } else { 11849 OS << Value; 11850 } 11851 11852 if (!TautologicalTypeCompare) { 11853 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11854 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11855 << E->getOpcodeStr() << OS.str() << *Result 11856 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11857 return true; 11858 } 11859 11860 if (IsObjCSignedCharBool) { 11861 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11862 S.PDiag(diag::warn_tautological_compare_objc_bool) 11863 << OS.str() << *Result); 11864 return true; 11865 } 11866 11867 // FIXME: We use a somewhat different formatting for the in-range cases and 11868 // cases involving boolean values for historical reasons. We should pick a 11869 // consistent way of presenting these diagnostics. 11870 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11871 11872 S.DiagRuntimeBehavior( 11873 E->getOperatorLoc(), E, 11874 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11875 : diag::warn_tautological_bool_compare) 11876 << OS.str() << classifyConstantValue(Constant) << OtherT 11877 << OtherIsBooleanDespiteType << *Result 11878 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11879 } else { 11880 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11881 unsigned Diag = 11882 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11883 ? (HasEnumType(OriginalOther) 11884 ? diag::warn_unsigned_enum_always_true_comparison 11885 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11886 : diag::warn_unsigned_always_true_comparison) 11887 : diag::warn_tautological_constant_compare; 11888 11889 S.Diag(E->getOperatorLoc(), Diag) 11890 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11891 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11892 } 11893 11894 return true; 11895 } 11896 11897 /// Analyze the operands of the given comparison. Implements the 11898 /// fallback case from AnalyzeComparison. 11899 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11900 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11901 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11902 } 11903 11904 /// Implements -Wsign-compare. 11905 /// 11906 /// \param E the binary operator to check for warnings 11907 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11908 // The type the comparison is being performed in. 11909 QualType T = E->getLHS()->getType(); 11910 11911 // Only analyze comparison operators where both sides have been converted to 11912 // the same type. 11913 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11914 return AnalyzeImpConvsInComparison(S, E); 11915 11916 // Don't analyze value-dependent comparisons directly. 11917 if (E->isValueDependent()) 11918 return AnalyzeImpConvsInComparison(S, E); 11919 11920 Expr *LHS = E->getLHS(); 11921 Expr *RHS = E->getRHS(); 11922 11923 if (T->isIntegralType(S.Context)) { 11924 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11925 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11926 11927 // We don't care about expressions whose result is a constant. 11928 if (RHSValue && LHSValue) 11929 return AnalyzeImpConvsInComparison(S, E); 11930 11931 // We only care about expressions where just one side is literal 11932 if ((bool)RHSValue ^ (bool)LHSValue) { 11933 // Is the constant on the RHS or LHS? 11934 const bool RhsConstant = (bool)RHSValue; 11935 Expr *Const = RhsConstant ? RHS : LHS; 11936 Expr *Other = RhsConstant ? LHS : RHS; 11937 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11938 11939 // Check whether an integer constant comparison results in a value 11940 // of 'true' or 'false'. 11941 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11942 return AnalyzeImpConvsInComparison(S, E); 11943 } 11944 } 11945 11946 if (!T->hasUnsignedIntegerRepresentation()) { 11947 // We don't do anything special if this isn't an unsigned integral 11948 // comparison: we're only interested in integral comparisons, and 11949 // signed comparisons only happen in cases we don't care to warn about. 11950 return AnalyzeImpConvsInComparison(S, E); 11951 } 11952 11953 LHS = LHS->IgnoreParenImpCasts(); 11954 RHS = RHS->IgnoreParenImpCasts(); 11955 11956 if (!S.getLangOpts().CPlusPlus) { 11957 // Avoid warning about comparison of integers with different signs when 11958 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11959 // the type of `E`. 11960 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11961 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11962 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11963 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11964 } 11965 11966 // Check to see if one of the (unmodified) operands is of different 11967 // signedness. 11968 Expr *signedOperand, *unsignedOperand; 11969 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11970 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11971 "unsigned comparison between two signed integer expressions?"); 11972 signedOperand = LHS; 11973 unsignedOperand = RHS; 11974 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11975 signedOperand = RHS; 11976 unsignedOperand = LHS; 11977 } else { 11978 return AnalyzeImpConvsInComparison(S, E); 11979 } 11980 11981 // Otherwise, calculate the effective range of the signed operand. 11982 IntRange signedRange = GetExprRange( 11983 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11984 11985 // Go ahead and analyze implicit conversions in the operands. Note 11986 // that we skip the implicit conversions on both sides. 11987 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11988 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11989 11990 // If the signed range is non-negative, -Wsign-compare won't fire. 11991 if (signedRange.NonNegative) 11992 return; 11993 11994 // For (in)equality comparisons, if the unsigned operand is a 11995 // constant which cannot collide with a overflowed signed operand, 11996 // then reinterpreting the signed operand as unsigned will not 11997 // change the result of the comparison. 11998 if (E->isEqualityOp()) { 11999 unsigned comparisonWidth = S.Context.getIntWidth(T); 12000 IntRange unsignedRange = 12001 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12002 /*Approximate*/ true); 12003 12004 // We should never be unable to prove that the unsigned operand is 12005 // non-negative. 12006 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12007 12008 if (unsignedRange.Width < comparisonWidth) 12009 return; 12010 } 12011 12012 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12013 S.PDiag(diag::warn_mixed_sign_comparison) 12014 << LHS->getType() << RHS->getType() 12015 << LHS->getSourceRange() << RHS->getSourceRange()); 12016 } 12017 12018 /// Analyzes an attempt to assign the given value to a bitfield. 12019 /// 12020 /// Returns true if there was something fishy about the attempt. 12021 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12022 SourceLocation InitLoc) { 12023 assert(Bitfield->isBitField()); 12024 if (Bitfield->isInvalidDecl()) 12025 return false; 12026 12027 // White-list bool bitfields. 12028 QualType BitfieldType = Bitfield->getType(); 12029 if (BitfieldType->isBooleanType()) 12030 return false; 12031 12032 if (BitfieldType->isEnumeralType()) { 12033 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12034 // If the underlying enum type was not explicitly specified as an unsigned 12035 // type and the enum contain only positive values, MSVC++ will cause an 12036 // inconsistency by storing this as a signed type. 12037 if (S.getLangOpts().CPlusPlus11 && 12038 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12039 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12040 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12041 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12042 << BitfieldEnumDecl; 12043 } 12044 } 12045 12046 if (Bitfield->getType()->isBooleanType()) 12047 return false; 12048 12049 // Ignore value- or type-dependent expressions. 12050 if (Bitfield->getBitWidth()->isValueDependent() || 12051 Bitfield->getBitWidth()->isTypeDependent() || 12052 Init->isValueDependent() || 12053 Init->isTypeDependent()) 12054 return false; 12055 12056 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12057 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12058 12059 Expr::EvalResult Result; 12060 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12061 Expr::SE_AllowSideEffects)) { 12062 // The RHS is not constant. If the RHS has an enum type, make sure the 12063 // bitfield is wide enough to hold all the values of the enum without 12064 // truncation. 12065 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12066 EnumDecl *ED = EnumTy->getDecl(); 12067 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12068 12069 // Enum types are implicitly signed on Windows, so check if there are any 12070 // negative enumerators to see if the enum was intended to be signed or 12071 // not. 12072 bool SignedEnum = ED->getNumNegativeBits() > 0; 12073 12074 // Check for surprising sign changes when assigning enum values to a 12075 // bitfield of different signedness. If the bitfield is signed and we 12076 // have exactly the right number of bits to store this unsigned enum, 12077 // suggest changing the enum to an unsigned type. This typically happens 12078 // on Windows where unfixed enums always use an underlying type of 'int'. 12079 unsigned DiagID = 0; 12080 if (SignedEnum && !SignedBitfield) { 12081 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12082 } else if (SignedBitfield && !SignedEnum && 12083 ED->getNumPositiveBits() == FieldWidth) { 12084 DiagID = diag::warn_signed_bitfield_enum_conversion; 12085 } 12086 12087 if (DiagID) { 12088 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12089 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12090 SourceRange TypeRange = 12091 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12092 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12093 << SignedEnum << TypeRange; 12094 } 12095 12096 // Compute the required bitwidth. If the enum has negative values, we need 12097 // one more bit than the normal number of positive bits to represent the 12098 // sign bit. 12099 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12100 ED->getNumNegativeBits()) 12101 : ED->getNumPositiveBits(); 12102 12103 // Check the bitwidth. 12104 if (BitsNeeded > FieldWidth) { 12105 Expr *WidthExpr = Bitfield->getBitWidth(); 12106 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12107 << Bitfield << ED; 12108 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12109 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12110 } 12111 } 12112 12113 return false; 12114 } 12115 12116 llvm::APSInt Value = Result.Val.getInt(); 12117 12118 unsigned OriginalWidth = Value.getBitWidth(); 12119 12120 if (!Value.isSigned() || Value.isNegative()) 12121 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12122 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12123 OriginalWidth = Value.getMinSignedBits(); 12124 12125 if (OriginalWidth <= FieldWidth) 12126 return false; 12127 12128 // Compute the value which the bitfield will contain. 12129 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12130 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12131 12132 // Check whether the stored value is equal to the original value. 12133 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12134 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12135 return false; 12136 12137 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12138 // therefore don't strictly fit into a signed bitfield of width 1. 12139 if (FieldWidth == 1 && Value == 1) 12140 return false; 12141 12142 std::string PrettyValue = toString(Value, 10); 12143 std::string PrettyTrunc = toString(TruncatedValue, 10); 12144 12145 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12146 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12147 << Init->getSourceRange(); 12148 12149 return true; 12150 } 12151 12152 /// Analyze the given simple or compound assignment for warning-worthy 12153 /// operations. 12154 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12155 // Just recurse on the LHS. 12156 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12157 12158 // We want to recurse on the RHS as normal unless we're assigning to 12159 // a bitfield. 12160 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12161 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12162 E->getOperatorLoc())) { 12163 // Recurse, ignoring any implicit conversions on the RHS. 12164 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12165 E->getOperatorLoc()); 12166 } 12167 } 12168 12169 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12170 12171 // Diagnose implicitly sequentially-consistent atomic assignment. 12172 if (E->getLHS()->getType()->isAtomicType()) 12173 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12174 } 12175 12176 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12177 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12178 SourceLocation CContext, unsigned diag, 12179 bool pruneControlFlow = false) { 12180 if (pruneControlFlow) { 12181 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12182 S.PDiag(diag) 12183 << SourceType << T << E->getSourceRange() 12184 << SourceRange(CContext)); 12185 return; 12186 } 12187 S.Diag(E->getExprLoc(), diag) 12188 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12189 } 12190 12191 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12192 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12193 SourceLocation CContext, 12194 unsigned diag, bool pruneControlFlow = false) { 12195 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12196 } 12197 12198 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12199 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12200 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12201 } 12202 12203 static void adornObjCBoolConversionDiagWithTernaryFixit( 12204 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12205 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12206 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12207 Ignored = OVE->getSourceExpr(); 12208 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12209 isa<BinaryOperator>(Ignored) || 12210 isa<CXXOperatorCallExpr>(Ignored); 12211 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12212 if (NeedsParens) 12213 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12214 << FixItHint::CreateInsertion(EndLoc, ")"); 12215 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12216 } 12217 12218 /// Diagnose an implicit cast from a floating point value to an integer value. 12219 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12220 SourceLocation CContext) { 12221 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12222 const bool PruneWarnings = S.inTemplateInstantiation(); 12223 12224 Expr *InnerE = E->IgnoreParenImpCasts(); 12225 // We also want to warn on, e.g., "int i = -1.234" 12226 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12227 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12228 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12229 12230 const bool IsLiteral = 12231 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12232 12233 llvm::APFloat Value(0.0); 12234 bool IsConstant = 12235 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12236 if (!IsConstant) { 12237 if (isObjCSignedCharBool(S, T)) { 12238 return adornObjCBoolConversionDiagWithTernaryFixit( 12239 S, E, 12240 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12241 << E->getType()); 12242 } 12243 12244 return DiagnoseImpCast(S, E, T, CContext, 12245 diag::warn_impcast_float_integer, PruneWarnings); 12246 } 12247 12248 bool isExact = false; 12249 12250 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12251 T->hasUnsignedIntegerRepresentation()); 12252 llvm::APFloat::opStatus Result = Value.convertToInteger( 12253 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12254 12255 // FIXME: Force the precision of the source value down so we don't print 12256 // digits which are usually useless (we don't really care here if we 12257 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12258 // would automatically print the shortest representation, but it's a bit 12259 // tricky to implement. 12260 SmallString<16> PrettySourceValue; 12261 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12262 precision = (precision * 59 + 195) / 196; 12263 Value.toString(PrettySourceValue, precision); 12264 12265 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12266 return adornObjCBoolConversionDiagWithTernaryFixit( 12267 S, E, 12268 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12269 << PrettySourceValue); 12270 } 12271 12272 if (Result == llvm::APFloat::opOK && isExact) { 12273 if (IsLiteral) return; 12274 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12275 PruneWarnings); 12276 } 12277 12278 // Conversion of a floating-point value to a non-bool integer where the 12279 // integral part cannot be represented by the integer type is undefined. 12280 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12281 return DiagnoseImpCast( 12282 S, E, T, CContext, 12283 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12284 : diag::warn_impcast_float_to_integer_out_of_range, 12285 PruneWarnings); 12286 12287 unsigned DiagID = 0; 12288 if (IsLiteral) { 12289 // Warn on floating point literal to integer. 12290 DiagID = diag::warn_impcast_literal_float_to_integer; 12291 } else if (IntegerValue == 0) { 12292 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12293 return DiagnoseImpCast(S, E, T, CContext, 12294 diag::warn_impcast_float_integer, PruneWarnings); 12295 } 12296 // Warn on non-zero to zero conversion. 12297 DiagID = diag::warn_impcast_float_to_integer_zero; 12298 } else { 12299 if (IntegerValue.isUnsigned()) { 12300 if (!IntegerValue.isMaxValue()) { 12301 return DiagnoseImpCast(S, E, T, CContext, 12302 diag::warn_impcast_float_integer, PruneWarnings); 12303 } 12304 } else { // IntegerValue.isSigned() 12305 if (!IntegerValue.isMaxSignedValue() && 12306 !IntegerValue.isMinSignedValue()) { 12307 return DiagnoseImpCast(S, E, T, CContext, 12308 diag::warn_impcast_float_integer, PruneWarnings); 12309 } 12310 } 12311 // Warn on evaluatable floating point expression to integer conversion. 12312 DiagID = diag::warn_impcast_float_to_integer; 12313 } 12314 12315 SmallString<16> PrettyTargetValue; 12316 if (IsBool) 12317 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12318 else 12319 IntegerValue.toString(PrettyTargetValue); 12320 12321 if (PruneWarnings) { 12322 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12323 S.PDiag(DiagID) 12324 << E->getType() << T.getUnqualifiedType() 12325 << PrettySourceValue << PrettyTargetValue 12326 << E->getSourceRange() << SourceRange(CContext)); 12327 } else { 12328 S.Diag(E->getExprLoc(), DiagID) 12329 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12330 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12331 } 12332 } 12333 12334 /// Analyze the given compound assignment for the possible losing of 12335 /// floating-point precision. 12336 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12337 assert(isa<CompoundAssignOperator>(E) && 12338 "Must be compound assignment operation"); 12339 // Recurse on the LHS and RHS in here 12340 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12341 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12342 12343 if (E->getLHS()->getType()->isAtomicType()) 12344 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12345 12346 // Now check the outermost expression 12347 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12348 const auto *RBT = cast<CompoundAssignOperator>(E) 12349 ->getComputationResultType() 12350 ->getAs<BuiltinType>(); 12351 12352 // The below checks assume source is floating point. 12353 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12354 12355 // If source is floating point but target is an integer. 12356 if (ResultBT->isInteger()) 12357 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12358 E->getExprLoc(), diag::warn_impcast_float_integer); 12359 12360 if (!ResultBT->isFloatingPoint()) 12361 return; 12362 12363 // If both source and target are floating points, warn about losing precision. 12364 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12365 QualType(ResultBT, 0), QualType(RBT, 0)); 12366 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12367 // warn about dropping FP rank. 12368 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12369 diag::warn_impcast_float_result_precision); 12370 } 12371 12372 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12373 IntRange Range) { 12374 if (!Range.Width) return "0"; 12375 12376 llvm::APSInt ValueInRange = Value; 12377 ValueInRange.setIsSigned(!Range.NonNegative); 12378 ValueInRange = ValueInRange.trunc(Range.Width); 12379 return toString(ValueInRange, 10); 12380 } 12381 12382 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12383 if (!isa<ImplicitCastExpr>(Ex)) 12384 return false; 12385 12386 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12387 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12388 const Type *Source = 12389 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12390 if (Target->isDependentType()) 12391 return false; 12392 12393 const BuiltinType *FloatCandidateBT = 12394 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12395 const Type *BoolCandidateType = ToBool ? Target : Source; 12396 12397 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12398 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12399 } 12400 12401 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12402 SourceLocation CC) { 12403 unsigned NumArgs = TheCall->getNumArgs(); 12404 for (unsigned i = 0; i < NumArgs; ++i) { 12405 Expr *CurrA = TheCall->getArg(i); 12406 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12407 continue; 12408 12409 bool IsSwapped = ((i > 0) && 12410 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12411 IsSwapped |= ((i < (NumArgs - 1)) && 12412 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12413 if (IsSwapped) { 12414 // Warn on this floating-point to bool conversion. 12415 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12416 CurrA->getType(), CC, 12417 diag::warn_impcast_floating_point_to_bool); 12418 } 12419 } 12420 } 12421 12422 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12423 SourceLocation CC) { 12424 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12425 E->getExprLoc())) 12426 return; 12427 12428 // Don't warn on functions which have return type nullptr_t. 12429 if (isa<CallExpr>(E)) 12430 return; 12431 12432 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12433 const Expr::NullPointerConstantKind NullKind = 12434 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12435 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12436 return; 12437 12438 // Return if target type is a safe conversion. 12439 if (T->isAnyPointerType() || T->isBlockPointerType() || 12440 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12441 return; 12442 12443 SourceLocation Loc = E->getSourceRange().getBegin(); 12444 12445 // Venture through the macro stacks to get to the source of macro arguments. 12446 // The new location is a better location than the complete location that was 12447 // passed in. 12448 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12449 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12450 12451 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12452 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12453 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12454 Loc, S.SourceMgr, S.getLangOpts()); 12455 if (MacroName == "NULL") 12456 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12457 } 12458 12459 // Only warn if the null and context location are in the same macro expansion. 12460 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12461 return; 12462 12463 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12464 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12465 << FixItHint::CreateReplacement(Loc, 12466 S.getFixItZeroLiteralForType(T, Loc)); 12467 } 12468 12469 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12470 ObjCArrayLiteral *ArrayLiteral); 12471 12472 static void 12473 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12474 ObjCDictionaryLiteral *DictionaryLiteral); 12475 12476 /// Check a single element within a collection literal against the 12477 /// target element type. 12478 static void checkObjCCollectionLiteralElement(Sema &S, 12479 QualType TargetElementType, 12480 Expr *Element, 12481 unsigned ElementKind) { 12482 // Skip a bitcast to 'id' or qualified 'id'. 12483 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12484 if (ICE->getCastKind() == CK_BitCast && 12485 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12486 Element = ICE->getSubExpr(); 12487 } 12488 12489 QualType ElementType = Element->getType(); 12490 ExprResult ElementResult(Element); 12491 if (ElementType->getAs<ObjCObjectPointerType>() && 12492 S.CheckSingleAssignmentConstraints(TargetElementType, 12493 ElementResult, 12494 false, false) 12495 != Sema::Compatible) { 12496 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12497 << ElementType << ElementKind << TargetElementType 12498 << Element->getSourceRange(); 12499 } 12500 12501 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12502 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12503 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12504 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12505 } 12506 12507 /// Check an Objective-C array literal being converted to the given 12508 /// target type. 12509 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12510 ObjCArrayLiteral *ArrayLiteral) { 12511 if (!S.NSArrayDecl) 12512 return; 12513 12514 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12515 if (!TargetObjCPtr) 12516 return; 12517 12518 if (TargetObjCPtr->isUnspecialized() || 12519 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12520 != S.NSArrayDecl->getCanonicalDecl()) 12521 return; 12522 12523 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12524 if (TypeArgs.size() != 1) 12525 return; 12526 12527 QualType TargetElementType = TypeArgs[0]; 12528 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12529 checkObjCCollectionLiteralElement(S, TargetElementType, 12530 ArrayLiteral->getElement(I), 12531 0); 12532 } 12533 } 12534 12535 /// Check an Objective-C dictionary literal being converted to the given 12536 /// target type. 12537 static void 12538 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12539 ObjCDictionaryLiteral *DictionaryLiteral) { 12540 if (!S.NSDictionaryDecl) 12541 return; 12542 12543 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12544 if (!TargetObjCPtr) 12545 return; 12546 12547 if (TargetObjCPtr->isUnspecialized() || 12548 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12549 != S.NSDictionaryDecl->getCanonicalDecl()) 12550 return; 12551 12552 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12553 if (TypeArgs.size() != 2) 12554 return; 12555 12556 QualType TargetKeyType = TypeArgs[0]; 12557 QualType TargetObjectType = TypeArgs[1]; 12558 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12559 auto Element = DictionaryLiteral->getKeyValueElement(I); 12560 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12561 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12562 } 12563 } 12564 12565 // Helper function to filter out cases for constant width constant conversion. 12566 // Don't warn on char array initialization or for non-decimal values. 12567 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12568 SourceLocation CC) { 12569 // If initializing from a constant, and the constant starts with '0', 12570 // then it is a binary, octal, or hexadecimal. Allow these constants 12571 // to fill all the bits, even if there is a sign change. 12572 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12573 const char FirstLiteralCharacter = 12574 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12575 if (FirstLiteralCharacter == '0') 12576 return false; 12577 } 12578 12579 // If the CC location points to a '{', and the type is char, then assume 12580 // assume it is an array initialization. 12581 if (CC.isValid() && T->isCharType()) { 12582 const char FirstContextCharacter = 12583 S.getSourceManager().getCharacterData(CC)[0]; 12584 if (FirstContextCharacter == '{') 12585 return false; 12586 } 12587 12588 return true; 12589 } 12590 12591 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12592 const auto *IL = dyn_cast<IntegerLiteral>(E); 12593 if (!IL) { 12594 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12595 if (UO->getOpcode() == UO_Minus) 12596 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12597 } 12598 } 12599 12600 return IL; 12601 } 12602 12603 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12604 E = E->IgnoreParenImpCasts(); 12605 SourceLocation ExprLoc = E->getExprLoc(); 12606 12607 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12608 BinaryOperator::Opcode Opc = BO->getOpcode(); 12609 Expr::EvalResult Result; 12610 // Do not diagnose unsigned shifts. 12611 if (Opc == BO_Shl) { 12612 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12613 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12614 if (LHS && LHS->getValue() == 0) 12615 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12616 else if (!E->isValueDependent() && LHS && RHS && 12617 RHS->getValue().isNonNegative() && 12618 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12619 S.Diag(ExprLoc, diag::warn_left_shift_always) 12620 << (Result.Val.getInt() != 0); 12621 else if (E->getType()->isSignedIntegerType()) 12622 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12623 } 12624 } 12625 12626 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12627 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12628 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12629 if (!LHS || !RHS) 12630 return; 12631 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12632 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12633 // Do not diagnose common idioms. 12634 return; 12635 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12636 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12637 } 12638 } 12639 12640 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12641 SourceLocation CC, 12642 bool *ICContext = nullptr, 12643 bool IsListInit = false) { 12644 if (E->isTypeDependent() || E->isValueDependent()) return; 12645 12646 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12647 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12648 if (Source == Target) return; 12649 if (Target->isDependentType()) return; 12650 12651 // If the conversion context location is invalid don't complain. We also 12652 // don't want to emit a warning if the issue occurs from the expansion of 12653 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12654 // delay this check as long as possible. Once we detect we are in that 12655 // scenario, we just return. 12656 if (CC.isInvalid()) 12657 return; 12658 12659 if (Source->isAtomicType()) 12660 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12661 12662 // Diagnose implicit casts to bool. 12663 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12664 if (isa<StringLiteral>(E)) 12665 // Warn on string literal to bool. Checks for string literals in logical 12666 // and expressions, for instance, assert(0 && "error here"), are 12667 // prevented by a check in AnalyzeImplicitConversions(). 12668 return DiagnoseImpCast(S, E, T, CC, 12669 diag::warn_impcast_string_literal_to_bool); 12670 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12671 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12672 // This covers the literal expressions that evaluate to Objective-C 12673 // objects. 12674 return DiagnoseImpCast(S, E, T, CC, 12675 diag::warn_impcast_objective_c_literal_to_bool); 12676 } 12677 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12678 // Warn on pointer to bool conversion that is always true. 12679 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12680 SourceRange(CC)); 12681 } 12682 } 12683 12684 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12685 // is a typedef for signed char (macOS), then that constant value has to be 1 12686 // or 0. 12687 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12688 Expr::EvalResult Result; 12689 if (E->EvaluateAsInt(Result, S.getASTContext(), 12690 Expr::SE_AllowSideEffects)) { 12691 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12692 adornObjCBoolConversionDiagWithTernaryFixit( 12693 S, E, 12694 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12695 << toString(Result.Val.getInt(), 10)); 12696 } 12697 return; 12698 } 12699 } 12700 12701 // Check implicit casts from Objective-C collection literals to specialized 12702 // collection types, e.g., NSArray<NSString *> *. 12703 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12704 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12705 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12706 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12707 12708 // Strip vector types. 12709 if (isa<VectorType>(Source)) { 12710 if (Target->isVLSTBuiltinType() && 12711 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12712 QualType(Source, 0)) || 12713 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12714 QualType(Source, 0)))) 12715 return; 12716 12717 if (!isa<VectorType>(Target)) { 12718 if (S.SourceMgr.isInSystemMacro(CC)) 12719 return; 12720 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12721 } 12722 12723 // If the vector cast is cast between two vectors of the same size, it is 12724 // a bitcast, not a conversion. 12725 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12726 return; 12727 12728 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12729 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12730 } 12731 if (auto VecTy = dyn_cast<VectorType>(Target)) 12732 Target = VecTy->getElementType().getTypePtr(); 12733 12734 // Strip complex types. 12735 if (isa<ComplexType>(Source)) { 12736 if (!isa<ComplexType>(Target)) { 12737 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12738 return; 12739 12740 return DiagnoseImpCast(S, E, T, CC, 12741 S.getLangOpts().CPlusPlus 12742 ? diag::err_impcast_complex_scalar 12743 : diag::warn_impcast_complex_scalar); 12744 } 12745 12746 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12747 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12748 } 12749 12750 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12751 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12752 12753 // If the source is floating point... 12754 if (SourceBT && SourceBT->isFloatingPoint()) { 12755 // ...and the target is floating point... 12756 if (TargetBT && TargetBT->isFloatingPoint()) { 12757 // ...then warn if we're dropping FP rank. 12758 12759 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12760 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12761 if (Order > 0) { 12762 // Don't warn about float constants that are precisely 12763 // representable in the target type. 12764 Expr::EvalResult result; 12765 if (E->EvaluateAsRValue(result, S.Context)) { 12766 // Value might be a float, a float vector, or a float complex. 12767 if (IsSameFloatAfterCast(result.Val, 12768 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12769 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12770 return; 12771 } 12772 12773 if (S.SourceMgr.isInSystemMacro(CC)) 12774 return; 12775 12776 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12777 } 12778 // ... or possibly if we're increasing rank, too 12779 else if (Order < 0) { 12780 if (S.SourceMgr.isInSystemMacro(CC)) 12781 return; 12782 12783 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12784 } 12785 return; 12786 } 12787 12788 // If the target is integral, always warn. 12789 if (TargetBT && TargetBT->isInteger()) { 12790 if (S.SourceMgr.isInSystemMacro(CC)) 12791 return; 12792 12793 DiagnoseFloatingImpCast(S, E, T, CC); 12794 } 12795 12796 // Detect the case where a call result is converted from floating-point to 12797 // to bool, and the final argument to the call is converted from bool, to 12798 // discover this typo: 12799 // 12800 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12801 // 12802 // FIXME: This is an incredibly special case; is there some more general 12803 // way to detect this class of misplaced-parentheses bug? 12804 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12805 // Check last argument of function call to see if it is an 12806 // implicit cast from a type matching the type the result 12807 // is being cast to. 12808 CallExpr *CEx = cast<CallExpr>(E); 12809 if (unsigned NumArgs = CEx->getNumArgs()) { 12810 Expr *LastA = CEx->getArg(NumArgs - 1); 12811 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12812 if (isa<ImplicitCastExpr>(LastA) && 12813 InnerE->getType()->isBooleanType()) { 12814 // Warn on this floating-point to bool conversion 12815 DiagnoseImpCast(S, E, T, CC, 12816 diag::warn_impcast_floating_point_to_bool); 12817 } 12818 } 12819 } 12820 return; 12821 } 12822 12823 // Valid casts involving fixed point types should be accounted for here. 12824 if (Source->isFixedPointType()) { 12825 if (Target->isUnsaturatedFixedPointType()) { 12826 Expr::EvalResult Result; 12827 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12828 S.isConstantEvaluated())) { 12829 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12830 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12831 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12832 if (Value > MaxVal || Value < MinVal) { 12833 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12834 S.PDiag(diag::warn_impcast_fixed_point_range) 12835 << Value.toString() << T 12836 << E->getSourceRange() 12837 << clang::SourceRange(CC)); 12838 return; 12839 } 12840 } 12841 } else if (Target->isIntegerType()) { 12842 Expr::EvalResult Result; 12843 if (!S.isConstantEvaluated() && 12844 E->EvaluateAsFixedPoint(Result, S.Context, 12845 Expr::SE_AllowSideEffects)) { 12846 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12847 12848 bool Overflowed; 12849 llvm::APSInt IntResult = FXResult.convertToInt( 12850 S.Context.getIntWidth(T), 12851 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12852 12853 if (Overflowed) { 12854 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12855 S.PDiag(diag::warn_impcast_fixed_point_range) 12856 << FXResult.toString() << T 12857 << E->getSourceRange() 12858 << clang::SourceRange(CC)); 12859 return; 12860 } 12861 } 12862 } 12863 } else if (Target->isUnsaturatedFixedPointType()) { 12864 if (Source->isIntegerType()) { 12865 Expr::EvalResult Result; 12866 if (!S.isConstantEvaluated() && 12867 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12868 llvm::APSInt Value = Result.Val.getInt(); 12869 12870 bool Overflowed; 12871 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12872 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12873 12874 if (Overflowed) { 12875 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12876 S.PDiag(diag::warn_impcast_fixed_point_range) 12877 << toString(Value, /*Radix=*/10) << T 12878 << E->getSourceRange() 12879 << clang::SourceRange(CC)); 12880 return; 12881 } 12882 } 12883 } 12884 } 12885 12886 // If we are casting an integer type to a floating point type without 12887 // initialization-list syntax, we might lose accuracy if the floating 12888 // point type has a narrower significand than the integer type. 12889 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12890 TargetBT->isFloatingType() && !IsListInit) { 12891 // Determine the number of precision bits in the source integer type. 12892 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12893 /*Approximate*/ true); 12894 unsigned int SourcePrecision = SourceRange.Width; 12895 12896 // Determine the number of precision bits in the 12897 // target floating point type. 12898 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12899 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12900 12901 if (SourcePrecision > 0 && TargetPrecision > 0 && 12902 SourcePrecision > TargetPrecision) { 12903 12904 if (Optional<llvm::APSInt> SourceInt = 12905 E->getIntegerConstantExpr(S.Context)) { 12906 // If the source integer is a constant, convert it to the target 12907 // floating point type. Issue a warning if the value changes 12908 // during the whole conversion. 12909 llvm::APFloat TargetFloatValue( 12910 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12911 llvm::APFloat::opStatus ConversionStatus = 12912 TargetFloatValue.convertFromAPInt( 12913 *SourceInt, SourceBT->isSignedInteger(), 12914 llvm::APFloat::rmNearestTiesToEven); 12915 12916 if (ConversionStatus != llvm::APFloat::opOK) { 12917 SmallString<32> PrettySourceValue; 12918 SourceInt->toString(PrettySourceValue, 10); 12919 SmallString<32> PrettyTargetValue; 12920 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12921 12922 S.DiagRuntimeBehavior( 12923 E->getExprLoc(), E, 12924 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12925 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12926 << E->getSourceRange() << clang::SourceRange(CC)); 12927 } 12928 } else { 12929 // Otherwise, the implicit conversion may lose precision. 12930 DiagnoseImpCast(S, E, T, CC, 12931 diag::warn_impcast_integer_float_precision); 12932 } 12933 } 12934 } 12935 12936 DiagnoseNullConversion(S, E, T, CC); 12937 12938 S.DiscardMisalignedMemberAddress(Target, E); 12939 12940 if (Target->isBooleanType()) 12941 DiagnoseIntInBoolContext(S, E); 12942 12943 if (!Source->isIntegerType() || !Target->isIntegerType()) 12944 return; 12945 12946 // TODO: remove this early return once the false positives for constant->bool 12947 // in templates, macros, etc, are reduced or removed. 12948 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12949 return; 12950 12951 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12952 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12953 return adornObjCBoolConversionDiagWithTernaryFixit( 12954 S, E, 12955 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12956 << E->getType()); 12957 } 12958 12959 IntRange SourceTypeRange = 12960 IntRange::forTargetOfCanonicalType(S.Context, Source); 12961 IntRange LikelySourceRange = 12962 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12963 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12964 12965 if (LikelySourceRange.Width > TargetRange.Width) { 12966 // If the source is a constant, use a default-on diagnostic. 12967 // TODO: this should happen for bitfield stores, too. 12968 Expr::EvalResult Result; 12969 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12970 S.isConstantEvaluated())) { 12971 llvm::APSInt Value(32); 12972 Value = Result.Val.getInt(); 12973 12974 if (S.SourceMgr.isInSystemMacro(CC)) 12975 return; 12976 12977 std::string PrettySourceValue = toString(Value, 10); 12978 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12979 12980 S.DiagRuntimeBehavior( 12981 E->getExprLoc(), E, 12982 S.PDiag(diag::warn_impcast_integer_precision_constant) 12983 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12984 << E->getSourceRange() << SourceRange(CC)); 12985 return; 12986 } 12987 12988 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12989 if (S.SourceMgr.isInSystemMacro(CC)) 12990 return; 12991 12992 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12993 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12994 /* pruneControlFlow */ true); 12995 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12996 } 12997 12998 if (TargetRange.Width > SourceTypeRange.Width) { 12999 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13000 if (UO->getOpcode() == UO_Minus) 13001 if (Source->isUnsignedIntegerType()) { 13002 if (Target->isUnsignedIntegerType()) 13003 return DiagnoseImpCast(S, E, T, CC, 13004 diag::warn_impcast_high_order_zero_bits); 13005 if (Target->isSignedIntegerType()) 13006 return DiagnoseImpCast(S, E, T, CC, 13007 diag::warn_impcast_nonnegative_result); 13008 } 13009 } 13010 13011 if (TargetRange.Width == LikelySourceRange.Width && 13012 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13013 Source->isSignedIntegerType()) { 13014 // Warn when doing a signed to signed conversion, warn if the positive 13015 // source value is exactly the width of the target type, which will 13016 // cause a negative value to be stored. 13017 13018 Expr::EvalResult Result; 13019 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13020 !S.SourceMgr.isInSystemMacro(CC)) { 13021 llvm::APSInt Value = Result.Val.getInt(); 13022 if (isSameWidthConstantConversion(S, E, T, CC)) { 13023 std::string PrettySourceValue = toString(Value, 10); 13024 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13025 13026 S.DiagRuntimeBehavior( 13027 E->getExprLoc(), E, 13028 S.PDiag(diag::warn_impcast_integer_precision_constant) 13029 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13030 << E->getSourceRange() << SourceRange(CC)); 13031 return; 13032 } 13033 } 13034 13035 // Fall through for non-constants to give a sign conversion warning. 13036 } 13037 13038 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13039 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13040 LikelySourceRange.Width == TargetRange.Width)) { 13041 if (S.SourceMgr.isInSystemMacro(CC)) 13042 return; 13043 13044 unsigned DiagID = diag::warn_impcast_integer_sign; 13045 13046 // Traditionally, gcc has warned about this under -Wsign-compare. 13047 // We also want to warn about it in -Wconversion. 13048 // So if -Wconversion is off, use a completely identical diagnostic 13049 // in the sign-compare group. 13050 // The conditional-checking code will 13051 if (ICContext) { 13052 DiagID = diag::warn_impcast_integer_sign_conditional; 13053 *ICContext = true; 13054 } 13055 13056 return DiagnoseImpCast(S, E, T, CC, DiagID); 13057 } 13058 13059 // Diagnose conversions between different enumeration types. 13060 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13061 // type, to give us better diagnostics. 13062 QualType SourceType = E->getType(); 13063 if (!S.getLangOpts().CPlusPlus) { 13064 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13065 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13066 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13067 SourceType = S.Context.getTypeDeclType(Enum); 13068 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13069 } 13070 } 13071 13072 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13073 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13074 if (SourceEnum->getDecl()->hasNameForLinkage() && 13075 TargetEnum->getDecl()->hasNameForLinkage() && 13076 SourceEnum != TargetEnum) { 13077 if (S.SourceMgr.isInSystemMacro(CC)) 13078 return; 13079 13080 return DiagnoseImpCast(S, E, SourceType, T, CC, 13081 diag::warn_impcast_different_enum_types); 13082 } 13083 } 13084 13085 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13086 SourceLocation CC, QualType T); 13087 13088 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13089 SourceLocation CC, bool &ICContext) { 13090 E = E->IgnoreParenImpCasts(); 13091 13092 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13093 return CheckConditionalOperator(S, CO, CC, T); 13094 13095 AnalyzeImplicitConversions(S, E, CC); 13096 if (E->getType() != T) 13097 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13098 } 13099 13100 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13101 SourceLocation CC, QualType T) { 13102 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13103 13104 Expr *TrueExpr = E->getTrueExpr(); 13105 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13106 TrueExpr = BCO->getCommon(); 13107 13108 bool Suspicious = false; 13109 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13110 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13111 13112 if (T->isBooleanType()) 13113 DiagnoseIntInBoolContext(S, E); 13114 13115 // If -Wconversion would have warned about either of the candidates 13116 // for a signedness conversion to the context type... 13117 if (!Suspicious) return; 13118 13119 // ...but it's currently ignored... 13120 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13121 return; 13122 13123 // ...then check whether it would have warned about either of the 13124 // candidates for a signedness conversion to the condition type. 13125 if (E->getType() == T) return; 13126 13127 Suspicious = false; 13128 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13129 E->getType(), CC, &Suspicious); 13130 if (!Suspicious) 13131 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13132 E->getType(), CC, &Suspicious); 13133 } 13134 13135 /// Check conversion of given expression to boolean. 13136 /// Input argument E is a logical expression. 13137 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13138 if (S.getLangOpts().Bool) 13139 return; 13140 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13141 return; 13142 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13143 } 13144 13145 namespace { 13146 struct AnalyzeImplicitConversionsWorkItem { 13147 Expr *E; 13148 SourceLocation CC; 13149 bool IsListInit; 13150 }; 13151 } 13152 13153 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13154 /// that should be visited are added to WorkList. 13155 static void AnalyzeImplicitConversions( 13156 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13157 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13158 Expr *OrigE = Item.E; 13159 SourceLocation CC = Item.CC; 13160 13161 QualType T = OrigE->getType(); 13162 Expr *E = OrigE->IgnoreParenImpCasts(); 13163 13164 // Propagate whether we are in a C++ list initialization expression. 13165 // If so, we do not issue warnings for implicit int-float conversion 13166 // precision loss, because C++11 narrowing already handles it. 13167 bool IsListInit = Item.IsListInit || 13168 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13169 13170 if (E->isTypeDependent() || E->isValueDependent()) 13171 return; 13172 13173 Expr *SourceExpr = E; 13174 // Examine, but don't traverse into the source expression of an 13175 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13176 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13177 // evaluate it in the context of checking the specific conversion to T though. 13178 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13179 if (auto *Src = OVE->getSourceExpr()) 13180 SourceExpr = Src; 13181 13182 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13183 if (UO->getOpcode() == UO_Not && 13184 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13185 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13186 << OrigE->getSourceRange() << T->isBooleanType() 13187 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13188 13189 // For conditional operators, we analyze the arguments as if they 13190 // were being fed directly into the output. 13191 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13192 CheckConditionalOperator(S, CO, CC, T); 13193 return; 13194 } 13195 13196 // Check implicit argument conversions for function calls. 13197 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13198 CheckImplicitArgumentConversions(S, Call, CC); 13199 13200 // Go ahead and check any implicit conversions we might have skipped. 13201 // The non-canonical typecheck is just an optimization; 13202 // CheckImplicitConversion will filter out dead implicit conversions. 13203 if (SourceExpr->getType() != T) 13204 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13205 13206 // Now continue drilling into this expression. 13207 13208 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13209 // The bound subexpressions in a PseudoObjectExpr are not reachable 13210 // as transitive children. 13211 // FIXME: Use a more uniform representation for this. 13212 for (auto *SE : POE->semantics()) 13213 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13214 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13215 } 13216 13217 // Skip past explicit casts. 13218 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13219 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13220 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13221 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13222 WorkList.push_back({E, CC, IsListInit}); 13223 return; 13224 } 13225 13226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13227 // Do a somewhat different check with comparison operators. 13228 if (BO->isComparisonOp()) 13229 return AnalyzeComparison(S, BO); 13230 13231 // And with simple assignments. 13232 if (BO->getOpcode() == BO_Assign) 13233 return AnalyzeAssignment(S, BO); 13234 // And with compound assignments. 13235 if (BO->isAssignmentOp()) 13236 return AnalyzeCompoundAssignment(S, BO); 13237 } 13238 13239 // These break the otherwise-useful invariant below. Fortunately, 13240 // we don't really need to recurse into them, because any internal 13241 // expressions should have been analyzed already when they were 13242 // built into statements. 13243 if (isa<StmtExpr>(E)) return; 13244 13245 // Don't descend into unevaluated contexts. 13246 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13247 13248 // Now just recurse over the expression's children. 13249 CC = E->getExprLoc(); 13250 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13251 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13252 for (Stmt *SubStmt : E->children()) { 13253 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13254 if (!ChildExpr) 13255 continue; 13256 13257 if (IsLogicalAndOperator && 13258 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13259 // Ignore checking string literals that are in logical and operators. 13260 // This is a common pattern for asserts. 13261 continue; 13262 WorkList.push_back({ChildExpr, CC, IsListInit}); 13263 } 13264 13265 if (BO && BO->isLogicalOp()) { 13266 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13267 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13268 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13269 13270 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13271 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13272 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13273 } 13274 13275 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13276 if (U->getOpcode() == UO_LNot) { 13277 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13278 } else if (U->getOpcode() != UO_AddrOf) { 13279 if (U->getSubExpr()->getType()->isAtomicType()) 13280 S.Diag(U->getSubExpr()->getBeginLoc(), 13281 diag::warn_atomic_implicit_seq_cst); 13282 } 13283 } 13284 } 13285 13286 /// AnalyzeImplicitConversions - Find and report any interesting 13287 /// implicit conversions in the given expression. There are a couple 13288 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13289 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13290 bool IsListInit/*= false*/) { 13291 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13292 WorkList.push_back({OrigE, CC, IsListInit}); 13293 while (!WorkList.empty()) 13294 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13295 } 13296 13297 /// Diagnose integer type and any valid implicit conversion to it. 13298 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13299 // Taking into account implicit conversions, 13300 // allow any integer. 13301 if (!E->getType()->isIntegerType()) { 13302 S.Diag(E->getBeginLoc(), 13303 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13304 return true; 13305 } 13306 // Potentially emit standard warnings for implicit conversions if enabled 13307 // using -Wconversion. 13308 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13309 return false; 13310 } 13311 13312 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13313 // Returns true when emitting a warning about taking the address of a reference. 13314 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13315 const PartialDiagnostic &PD) { 13316 E = E->IgnoreParenImpCasts(); 13317 13318 const FunctionDecl *FD = nullptr; 13319 13320 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13321 if (!DRE->getDecl()->getType()->isReferenceType()) 13322 return false; 13323 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13324 if (!M->getMemberDecl()->getType()->isReferenceType()) 13325 return false; 13326 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13327 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13328 return false; 13329 FD = Call->getDirectCallee(); 13330 } else { 13331 return false; 13332 } 13333 13334 SemaRef.Diag(E->getExprLoc(), PD); 13335 13336 // If possible, point to location of function. 13337 if (FD) { 13338 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13339 } 13340 13341 return true; 13342 } 13343 13344 // Returns true if the SourceLocation is expanded from any macro body. 13345 // Returns false if the SourceLocation is invalid, is from not in a macro 13346 // expansion, or is from expanded from a top-level macro argument. 13347 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13348 if (Loc.isInvalid()) 13349 return false; 13350 13351 while (Loc.isMacroID()) { 13352 if (SM.isMacroBodyExpansion(Loc)) 13353 return true; 13354 Loc = SM.getImmediateMacroCallerLoc(Loc); 13355 } 13356 13357 return false; 13358 } 13359 13360 /// Diagnose pointers that are always non-null. 13361 /// \param E the expression containing the pointer 13362 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13363 /// compared to a null pointer 13364 /// \param IsEqual True when the comparison is equal to a null pointer 13365 /// \param Range Extra SourceRange to highlight in the diagnostic 13366 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13367 Expr::NullPointerConstantKind NullKind, 13368 bool IsEqual, SourceRange Range) { 13369 if (!E) 13370 return; 13371 13372 // Don't warn inside macros. 13373 if (E->getExprLoc().isMacroID()) { 13374 const SourceManager &SM = getSourceManager(); 13375 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13376 IsInAnyMacroBody(SM, Range.getBegin())) 13377 return; 13378 } 13379 E = E->IgnoreImpCasts(); 13380 13381 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13382 13383 if (isa<CXXThisExpr>(E)) { 13384 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13385 : diag::warn_this_bool_conversion; 13386 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13387 return; 13388 } 13389 13390 bool IsAddressOf = false; 13391 13392 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13393 if (UO->getOpcode() != UO_AddrOf) 13394 return; 13395 IsAddressOf = true; 13396 E = UO->getSubExpr(); 13397 } 13398 13399 if (IsAddressOf) { 13400 unsigned DiagID = IsCompare 13401 ? diag::warn_address_of_reference_null_compare 13402 : diag::warn_address_of_reference_bool_conversion; 13403 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13404 << IsEqual; 13405 if (CheckForReference(*this, E, PD)) { 13406 return; 13407 } 13408 } 13409 13410 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13411 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13412 std::string Str; 13413 llvm::raw_string_ostream S(Str); 13414 E->printPretty(S, nullptr, getPrintingPolicy()); 13415 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13416 : diag::warn_cast_nonnull_to_bool; 13417 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13418 << E->getSourceRange() << Range << IsEqual; 13419 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13420 }; 13421 13422 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13423 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13424 if (auto *Callee = Call->getDirectCallee()) { 13425 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13426 ComplainAboutNonnullParamOrCall(A); 13427 return; 13428 } 13429 } 13430 } 13431 13432 // Expect to find a single Decl. Skip anything more complicated. 13433 ValueDecl *D = nullptr; 13434 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13435 D = R->getDecl(); 13436 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13437 D = M->getMemberDecl(); 13438 } 13439 13440 // Weak Decls can be null. 13441 if (!D || D->isWeak()) 13442 return; 13443 13444 // Check for parameter decl with nonnull attribute 13445 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13446 if (getCurFunction() && 13447 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13448 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13449 ComplainAboutNonnullParamOrCall(A); 13450 return; 13451 } 13452 13453 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13454 // Skip function template not specialized yet. 13455 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13456 return; 13457 auto ParamIter = llvm::find(FD->parameters(), PV); 13458 assert(ParamIter != FD->param_end()); 13459 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13460 13461 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13462 if (!NonNull->args_size()) { 13463 ComplainAboutNonnullParamOrCall(NonNull); 13464 return; 13465 } 13466 13467 for (const ParamIdx &ArgNo : NonNull->args()) { 13468 if (ArgNo.getASTIndex() == ParamNo) { 13469 ComplainAboutNonnullParamOrCall(NonNull); 13470 return; 13471 } 13472 } 13473 } 13474 } 13475 } 13476 } 13477 13478 QualType T = D->getType(); 13479 const bool IsArray = T->isArrayType(); 13480 const bool IsFunction = T->isFunctionType(); 13481 13482 // Address of function is used to silence the function warning. 13483 if (IsAddressOf && IsFunction) { 13484 return; 13485 } 13486 13487 // Found nothing. 13488 if (!IsAddressOf && !IsFunction && !IsArray) 13489 return; 13490 13491 // Pretty print the expression for the diagnostic. 13492 std::string Str; 13493 llvm::raw_string_ostream S(Str); 13494 E->printPretty(S, nullptr, getPrintingPolicy()); 13495 13496 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13497 : diag::warn_impcast_pointer_to_bool; 13498 enum { 13499 AddressOf, 13500 FunctionPointer, 13501 ArrayPointer 13502 } DiagType; 13503 if (IsAddressOf) 13504 DiagType = AddressOf; 13505 else if (IsFunction) 13506 DiagType = FunctionPointer; 13507 else if (IsArray) 13508 DiagType = ArrayPointer; 13509 else 13510 llvm_unreachable("Could not determine diagnostic."); 13511 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13512 << Range << IsEqual; 13513 13514 if (!IsFunction) 13515 return; 13516 13517 // Suggest '&' to silence the function warning. 13518 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13519 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13520 13521 // Check to see if '()' fixit should be emitted. 13522 QualType ReturnType; 13523 UnresolvedSet<4> NonTemplateOverloads; 13524 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13525 if (ReturnType.isNull()) 13526 return; 13527 13528 if (IsCompare) { 13529 // There are two cases here. If there is null constant, the only suggest 13530 // for a pointer return type. If the null is 0, then suggest if the return 13531 // type is a pointer or an integer type. 13532 if (!ReturnType->isPointerType()) { 13533 if (NullKind == Expr::NPCK_ZeroExpression || 13534 NullKind == Expr::NPCK_ZeroLiteral) { 13535 if (!ReturnType->isIntegerType()) 13536 return; 13537 } else { 13538 return; 13539 } 13540 } 13541 } else { // !IsCompare 13542 // For function to bool, only suggest if the function pointer has bool 13543 // return type. 13544 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13545 return; 13546 } 13547 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13548 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13549 } 13550 13551 /// Diagnoses "dangerous" implicit conversions within the given 13552 /// expression (which is a full expression). Implements -Wconversion 13553 /// and -Wsign-compare. 13554 /// 13555 /// \param CC the "context" location of the implicit conversion, i.e. 13556 /// the most location of the syntactic entity requiring the implicit 13557 /// conversion 13558 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13559 // Don't diagnose in unevaluated contexts. 13560 if (isUnevaluatedContext()) 13561 return; 13562 13563 // Don't diagnose for value- or type-dependent expressions. 13564 if (E->isTypeDependent() || E->isValueDependent()) 13565 return; 13566 13567 // Check for array bounds violations in cases where the check isn't triggered 13568 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13569 // ArraySubscriptExpr is on the RHS of a variable initialization. 13570 CheckArrayAccess(E); 13571 13572 // This is not the right CC for (e.g.) a variable initialization. 13573 AnalyzeImplicitConversions(*this, E, CC); 13574 } 13575 13576 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13577 /// Input argument E is a logical expression. 13578 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13579 ::CheckBoolLikeConversion(*this, E, CC); 13580 } 13581 13582 /// Diagnose when expression is an integer constant expression and its evaluation 13583 /// results in integer overflow 13584 void Sema::CheckForIntOverflow (Expr *E) { 13585 // Use a work list to deal with nested struct initializers. 13586 SmallVector<Expr *, 2> Exprs(1, E); 13587 13588 do { 13589 Expr *OriginalE = Exprs.pop_back_val(); 13590 Expr *E = OriginalE->IgnoreParenCasts(); 13591 13592 if (isa<BinaryOperator>(E)) { 13593 E->EvaluateForOverflow(Context); 13594 continue; 13595 } 13596 13597 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13598 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13599 else if (isa<ObjCBoxedExpr>(OriginalE)) 13600 E->EvaluateForOverflow(Context); 13601 else if (auto Call = dyn_cast<CallExpr>(E)) 13602 Exprs.append(Call->arg_begin(), Call->arg_end()); 13603 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13604 Exprs.append(Message->arg_begin(), Message->arg_end()); 13605 } while (!Exprs.empty()); 13606 } 13607 13608 namespace { 13609 13610 /// Visitor for expressions which looks for unsequenced operations on the 13611 /// same object. 13612 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13613 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13614 13615 /// A tree of sequenced regions within an expression. Two regions are 13616 /// unsequenced if one is an ancestor or a descendent of the other. When we 13617 /// finish processing an expression with sequencing, such as a comma 13618 /// expression, we fold its tree nodes into its parent, since they are 13619 /// unsequenced with respect to nodes we will visit later. 13620 class SequenceTree { 13621 struct Value { 13622 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13623 unsigned Parent : 31; 13624 unsigned Merged : 1; 13625 }; 13626 SmallVector<Value, 8> Values; 13627 13628 public: 13629 /// A region within an expression which may be sequenced with respect 13630 /// to some other region. 13631 class Seq { 13632 friend class SequenceTree; 13633 13634 unsigned Index; 13635 13636 explicit Seq(unsigned N) : Index(N) {} 13637 13638 public: 13639 Seq() : Index(0) {} 13640 }; 13641 13642 SequenceTree() { Values.push_back(Value(0)); } 13643 Seq root() const { return Seq(0); } 13644 13645 /// Create a new sequence of operations, which is an unsequenced 13646 /// subset of \p Parent. This sequence of operations is sequenced with 13647 /// respect to other children of \p Parent. 13648 Seq allocate(Seq Parent) { 13649 Values.push_back(Value(Parent.Index)); 13650 return Seq(Values.size() - 1); 13651 } 13652 13653 /// Merge a sequence of operations into its parent. 13654 void merge(Seq S) { 13655 Values[S.Index].Merged = true; 13656 } 13657 13658 /// Determine whether two operations are unsequenced. This operation 13659 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13660 /// should have been merged into its parent as appropriate. 13661 bool isUnsequenced(Seq Cur, Seq Old) { 13662 unsigned C = representative(Cur.Index); 13663 unsigned Target = representative(Old.Index); 13664 while (C >= Target) { 13665 if (C == Target) 13666 return true; 13667 C = Values[C].Parent; 13668 } 13669 return false; 13670 } 13671 13672 private: 13673 /// Pick a representative for a sequence. 13674 unsigned representative(unsigned K) { 13675 if (Values[K].Merged) 13676 // Perform path compression as we go. 13677 return Values[K].Parent = representative(Values[K].Parent); 13678 return K; 13679 } 13680 }; 13681 13682 /// An object for which we can track unsequenced uses. 13683 using Object = const NamedDecl *; 13684 13685 /// Different flavors of object usage which we track. We only track the 13686 /// least-sequenced usage of each kind. 13687 enum UsageKind { 13688 /// A read of an object. Multiple unsequenced reads are OK. 13689 UK_Use, 13690 13691 /// A modification of an object which is sequenced before the value 13692 /// computation of the expression, such as ++n in C++. 13693 UK_ModAsValue, 13694 13695 /// A modification of an object which is not sequenced before the value 13696 /// computation of the expression, such as n++. 13697 UK_ModAsSideEffect, 13698 13699 UK_Count = UK_ModAsSideEffect + 1 13700 }; 13701 13702 /// Bundle together a sequencing region and the expression corresponding 13703 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13704 struct Usage { 13705 const Expr *UsageExpr; 13706 SequenceTree::Seq Seq; 13707 13708 Usage() : UsageExpr(nullptr), Seq() {} 13709 }; 13710 13711 struct UsageInfo { 13712 Usage Uses[UK_Count]; 13713 13714 /// Have we issued a diagnostic for this object already? 13715 bool Diagnosed; 13716 13717 UsageInfo() : Uses(), Diagnosed(false) {} 13718 }; 13719 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13720 13721 Sema &SemaRef; 13722 13723 /// Sequenced regions within the expression. 13724 SequenceTree Tree; 13725 13726 /// Declaration modifications and references which we have seen. 13727 UsageInfoMap UsageMap; 13728 13729 /// The region we are currently within. 13730 SequenceTree::Seq Region; 13731 13732 /// Filled in with declarations which were modified as a side-effect 13733 /// (that is, post-increment operations). 13734 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13735 13736 /// Expressions to check later. We defer checking these to reduce 13737 /// stack usage. 13738 SmallVectorImpl<const Expr *> &WorkList; 13739 13740 /// RAII object wrapping the visitation of a sequenced subexpression of an 13741 /// expression. At the end of this process, the side-effects of the evaluation 13742 /// become sequenced with respect to the value computation of the result, so 13743 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13744 /// UK_ModAsValue. 13745 struct SequencedSubexpression { 13746 SequencedSubexpression(SequenceChecker &Self) 13747 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13748 Self.ModAsSideEffect = &ModAsSideEffect; 13749 } 13750 13751 ~SequencedSubexpression() { 13752 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13753 // Add a new usage with usage kind UK_ModAsValue, and then restore 13754 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13755 // the previous one was empty). 13756 UsageInfo &UI = Self.UsageMap[M.first]; 13757 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13758 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13759 SideEffectUsage = M.second; 13760 } 13761 Self.ModAsSideEffect = OldModAsSideEffect; 13762 } 13763 13764 SequenceChecker &Self; 13765 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13766 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13767 }; 13768 13769 /// RAII object wrapping the visitation of a subexpression which we might 13770 /// choose to evaluate as a constant. If any subexpression is evaluated and 13771 /// found to be non-constant, this allows us to suppress the evaluation of 13772 /// the outer expression. 13773 class EvaluationTracker { 13774 public: 13775 EvaluationTracker(SequenceChecker &Self) 13776 : Self(Self), Prev(Self.EvalTracker) { 13777 Self.EvalTracker = this; 13778 } 13779 13780 ~EvaluationTracker() { 13781 Self.EvalTracker = Prev; 13782 if (Prev) 13783 Prev->EvalOK &= EvalOK; 13784 } 13785 13786 bool evaluate(const Expr *E, bool &Result) { 13787 if (!EvalOK || E->isValueDependent()) 13788 return false; 13789 EvalOK = E->EvaluateAsBooleanCondition( 13790 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13791 return EvalOK; 13792 } 13793 13794 private: 13795 SequenceChecker &Self; 13796 EvaluationTracker *Prev; 13797 bool EvalOK = true; 13798 } *EvalTracker = nullptr; 13799 13800 /// Find the object which is produced by the specified expression, 13801 /// if any. 13802 Object getObject(const Expr *E, bool Mod) const { 13803 E = E->IgnoreParenCasts(); 13804 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13805 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13806 return getObject(UO->getSubExpr(), Mod); 13807 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13808 if (BO->getOpcode() == BO_Comma) 13809 return getObject(BO->getRHS(), Mod); 13810 if (Mod && BO->isAssignmentOp()) 13811 return getObject(BO->getLHS(), Mod); 13812 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13813 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13814 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13815 return ME->getMemberDecl(); 13816 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13817 // FIXME: If this is a reference, map through to its value. 13818 return DRE->getDecl(); 13819 return nullptr; 13820 } 13821 13822 /// Note that an object \p O was modified or used by an expression 13823 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13824 /// the object \p O as obtained via the \p UsageMap. 13825 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13826 // Get the old usage for the given object and usage kind. 13827 Usage &U = UI.Uses[UK]; 13828 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13829 // If we have a modification as side effect and are in a sequenced 13830 // subexpression, save the old Usage so that we can restore it later 13831 // in SequencedSubexpression::~SequencedSubexpression. 13832 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13833 ModAsSideEffect->push_back(std::make_pair(O, U)); 13834 // Then record the new usage with the current sequencing region. 13835 U.UsageExpr = UsageExpr; 13836 U.Seq = Region; 13837 } 13838 } 13839 13840 /// Check whether a modification or use of an object \p O in an expression 13841 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13842 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13843 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13844 /// usage and false we are checking for a mod-use unsequenced usage. 13845 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13846 UsageKind OtherKind, bool IsModMod) { 13847 if (UI.Diagnosed) 13848 return; 13849 13850 const Usage &U = UI.Uses[OtherKind]; 13851 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13852 return; 13853 13854 const Expr *Mod = U.UsageExpr; 13855 const Expr *ModOrUse = UsageExpr; 13856 if (OtherKind == UK_Use) 13857 std::swap(Mod, ModOrUse); 13858 13859 SemaRef.DiagRuntimeBehavior( 13860 Mod->getExprLoc(), {Mod, ModOrUse}, 13861 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13862 : diag::warn_unsequenced_mod_use) 13863 << O << SourceRange(ModOrUse->getExprLoc())); 13864 UI.Diagnosed = true; 13865 } 13866 13867 // A note on note{Pre, Post}{Use, Mod}: 13868 // 13869 // (It helps to follow the algorithm with an expression such as 13870 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13871 // operations before C++17 and both are well-defined in C++17). 13872 // 13873 // When visiting a node which uses/modify an object we first call notePreUse 13874 // or notePreMod before visiting its sub-expression(s). At this point the 13875 // children of the current node have not yet been visited and so the eventual 13876 // uses/modifications resulting from the children of the current node have not 13877 // been recorded yet. 13878 // 13879 // We then visit the children of the current node. After that notePostUse or 13880 // notePostMod is called. These will 1) detect an unsequenced modification 13881 // as side effect (as in "k++ + k") and 2) add a new usage with the 13882 // appropriate usage kind. 13883 // 13884 // We also have to be careful that some operation sequences modification as 13885 // side effect as well (for example: || or ,). To account for this we wrap 13886 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13887 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13888 // which record usages which are modifications as side effect, and then 13889 // downgrade them (or more accurately restore the previous usage which was a 13890 // modification as side effect) when exiting the scope of the sequenced 13891 // subexpression. 13892 13893 void notePreUse(Object O, const Expr *UseExpr) { 13894 UsageInfo &UI = UsageMap[O]; 13895 // Uses conflict with other modifications. 13896 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13897 } 13898 13899 void notePostUse(Object O, const Expr *UseExpr) { 13900 UsageInfo &UI = UsageMap[O]; 13901 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13902 /*IsModMod=*/false); 13903 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13904 } 13905 13906 void notePreMod(Object O, const Expr *ModExpr) { 13907 UsageInfo &UI = UsageMap[O]; 13908 // Modifications conflict with other modifications and with uses. 13909 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13910 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13911 } 13912 13913 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13914 UsageInfo &UI = UsageMap[O]; 13915 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13916 /*IsModMod=*/true); 13917 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13918 } 13919 13920 public: 13921 SequenceChecker(Sema &S, const Expr *E, 13922 SmallVectorImpl<const Expr *> &WorkList) 13923 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13924 Visit(E); 13925 // Silence a -Wunused-private-field since WorkList is now unused. 13926 // TODO: Evaluate if it can be used, and if not remove it. 13927 (void)this->WorkList; 13928 } 13929 13930 void VisitStmt(const Stmt *S) { 13931 // Skip all statements which aren't expressions for now. 13932 } 13933 13934 void VisitExpr(const Expr *E) { 13935 // By default, just recurse to evaluated subexpressions. 13936 Base::VisitStmt(E); 13937 } 13938 13939 void VisitCastExpr(const CastExpr *E) { 13940 Object O = Object(); 13941 if (E->getCastKind() == CK_LValueToRValue) 13942 O = getObject(E->getSubExpr(), false); 13943 13944 if (O) 13945 notePreUse(O, E); 13946 VisitExpr(E); 13947 if (O) 13948 notePostUse(O, E); 13949 } 13950 13951 void VisitSequencedExpressions(const Expr *SequencedBefore, 13952 const Expr *SequencedAfter) { 13953 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13954 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13955 SequenceTree::Seq OldRegion = Region; 13956 13957 { 13958 SequencedSubexpression SeqBefore(*this); 13959 Region = BeforeRegion; 13960 Visit(SequencedBefore); 13961 } 13962 13963 Region = AfterRegion; 13964 Visit(SequencedAfter); 13965 13966 Region = OldRegion; 13967 13968 Tree.merge(BeforeRegion); 13969 Tree.merge(AfterRegion); 13970 } 13971 13972 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13973 // C++17 [expr.sub]p1: 13974 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13975 // expression E1 is sequenced before the expression E2. 13976 if (SemaRef.getLangOpts().CPlusPlus17) 13977 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13978 else { 13979 Visit(ASE->getLHS()); 13980 Visit(ASE->getRHS()); 13981 } 13982 } 13983 13984 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13985 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13986 void VisitBinPtrMem(const BinaryOperator *BO) { 13987 // C++17 [expr.mptr.oper]p4: 13988 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13989 // the expression E1 is sequenced before the expression E2. 13990 if (SemaRef.getLangOpts().CPlusPlus17) 13991 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13992 else { 13993 Visit(BO->getLHS()); 13994 Visit(BO->getRHS()); 13995 } 13996 } 13997 13998 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13999 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14000 void VisitBinShlShr(const BinaryOperator *BO) { 14001 // C++17 [expr.shift]p4: 14002 // The expression E1 is sequenced before the expression E2. 14003 if (SemaRef.getLangOpts().CPlusPlus17) 14004 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14005 else { 14006 Visit(BO->getLHS()); 14007 Visit(BO->getRHS()); 14008 } 14009 } 14010 14011 void VisitBinComma(const BinaryOperator *BO) { 14012 // C++11 [expr.comma]p1: 14013 // Every value computation and side effect associated with the left 14014 // expression is sequenced before every value computation and side 14015 // effect associated with the right expression. 14016 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14017 } 14018 14019 void VisitBinAssign(const BinaryOperator *BO) { 14020 SequenceTree::Seq RHSRegion; 14021 SequenceTree::Seq LHSRegion; 14022 if (SemaRef.getLangOpts().CPlusPlus17) { 14023 RHSRegion = Tree.allocate(Region); 14024 LHSRegion = Tree.allocate(Region); 14025 } else { 14026 RHSRegion = Region; 14027 LHSRegion = Region; 14028 } 14029 SequenceTree::Seq OldRegion = Region; 14030 14031 // C++11 [expr.ass]p1: 14032 // [...] the assignment is sequenced after the value computation 14033 // of the right and left operands, [...] 14034 // 14035 // so check it before inspecting the operands and update the 14036 // map afterwards. 14037 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14038 if (O) 14039 notePreMod(O, BO); 14040 14041 if (SemaRef.getLangOpts().CPlusPlus17) { 14042 // C++17 [expr.ass]p1: 14043 // [...] The right operand is sequenced before the left operand. [...] 14044 { 14045 SequencedSubexpression SeqBefore(*this); 14046 Region = RHSRegion; 14047 Visit(BO->getRHS()); 14048 } 14049 14050 Region = LHSRegion; 14051 Visit(BO->getLHS()); 14052 14053 if (O && isa<CompoundAssignOperator>(BO)) 14054 notePostUse(O, BO); 14055 14056 } else { 14057 // C++11 does not specify any sequencing between the LHS and RHS. 14058 Region = LHSRegion; 14059 Visit(BO->getLHS()); 14060 14061 if (O && isa<CompoundAssignOperator>(BO)) 14062 notePostUse(O, BO); 14063 14064 Region = RHSRegion; 14065 Visit(BO->getRHS()); 14066 } 14067 14068 // C++11 [expr.ass]p1: 14069 // the assignment is sequenced [...] before the value computation of the 14070 // assignment expression. 14071 // C11 6.5.16/3 has no such rule. 14072 Region = OldRegion; 14073 if (O) 14074 notePostMod(O, BO, 14075 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14076 : UK_ModAsSideEffect); 14077 if (SemaRef.getLangOpts().CPlusPlus17) { 14078 Tree.merge(RHSRegion); 14079 Tree.merge(LHSRegion); 14080 } 14081 } 14082 14083 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14084 VisitBinAssign(CAO); 14085 } 14086 14087 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14088 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14089 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14090 Object O = getObject(UO->getSubExpr(), true); 14091 if (!O) 14092 return VisitExpr(UO); 14093 14094 notePreMod(O, UO); 14095 Visit(UO->getSubExpr()); 14096 // C++11 [expr.pre.incr]p1: 14097 // the expression ++x is equivalent to x+=1 14098 notePostMod(O, UO, 14099 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14100 : UK_ModAsSideEffect); 14101 } 14102 14103 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14104 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14105 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14106 Object O = getObject(UO->getSubExpr(), true); 14107 if (!O) 14108 return VisitExpr(UO); 14109 14110 notePreMod(O, UO); 14111 Visit(UO->getSubExpr()); 14112 notePostMod(O, UO, UK_ModAsSideEffect); 14113 } 14114 14115 void VisitBinLOr(const BinaryOperator *BO) { 14116 // C++11 [expr.log.or]p2: 14117 // If the second expression is evaluated, every value computation and 14118 // side effect associated with the first expression is sequenced before 14119 // every value computation and side effect associated with the 14120 // second expression. 14121 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14122 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14123 SequenceTree::Seq OldRegion = Region; 14124 14125 EvaluationTracker Eval(*this); 14126 { 14127 SequencedSubexpression Sequenced(*this); 14128 Region = LHSRegion; 14129 Visit(BO->getLHS()); 14130 } 14131 14132 // C++11 [expr.log.or]p1: 14133 // [...] the second operand is not evaluated if the first operand 14134 // evaluates to true. 14135 bool EvalResult = false; 14136 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14137 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14138 if (ShouldVisitRHS) { 14139 Region = RHSRegion; 14140 Visit(BO->getRHS()); 14141 } 14142 14143 Region = OldRegion; 14144 Tree.merge(LHSRegion); 14145 Tree.merge(RHSRegion); 14146 } 14147 14148 void VisitBinLAnd(const BinaryOperator *BO) { 14149 // C++11 [expr.log.and]p2: 14150 // If the second expression is evaluated, every value computation and 14151 // side effect associated with the first expression is sequenced before 14152 // every value computation and side effect associated with the 14153 // second expression. 14154 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14155 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14156 SequenceTree::Seq OldRegion = Region; 14157 14158 EvaluationTracker Eval(*this); 14159 { 14160 SequencedSubexpression Sequenced(*this); 14161 Region = LHSRegion; 14162 Visit(BO->getLHS()); 14163 } 14164 14165 // C++11 [expr.log.and]p1: 14166 // [...] the second operand is not evaluated if the first operand is false. 14167 bool EvalResult = false; 14168 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14169 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14170 if (ShouldVisitRHS) { 14171 Region = RHSRegion; 14172 Visit(BO->getRHS()); 14173 } 14174 14175 Region = OldRegion; 14176 Tree.merge(LHSRegion); 14177 Tree.merge(RHSRegion); 14178 } 14179 14180 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14181 // C++11 [expr.cond]p1: 14182 // [...] Every value computation and side effect associated with the first 14183 // expression is sequenced before every value computation and side effect 14184 // associated with the second or third expression. 14185 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14186 14187 // No sequencing is specified between the true and false expression. 14188 // However since exactly one of both is going to be evaluated we can 14189 // consider them to be sequenced. This is needed to avoid warning on 14190 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14191 // both the true and false expressions because we can't evaluate x. 14192 // This will still allow us to detect an expression like (pre C++17) 14193 // "(x ? y += 1 : y += 2) = y". 14194 // 14195 // We don't wrap the visitation of the true and false expression with 14196 // SequencedSubexpression because we don't want to downgrade modifications 14197 // as side effect in the true and false expressions after the visition 14198 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14199 // not warn between the two "y++", but we should warn between the "y++" 14200 // and the "y". 14201 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14202 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14203 SequenceTree::Seq OldRegion = Region; 14204 14205 EvaluationTracker Eval(*this); 14206 { 14207 SequencedSubexpression Sequenced(*this); 14208 Region = ConditionRegion; 14209 Visit(CO->getCond()); 14210 } 14211 14212 // C++11 [expr.cond]p1: 14213 // [...] The first expression is contextually converted to bool (Clause 4). 14214 // It is evaluated and if it is true, the result of the conditional 14215 // expression is the value of the second expression, otherwise that of the 14216 // third expression. Only one of the second and third expressions is 14217 // evaluated. [...] 14218 bool EvalResult = false; 14219 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14220 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14221 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14222 if (ShouldVisitTrueExpr) { 14223 Region = TrueRegion; 14224 Visit(CO->getTrueExpr()); 14225 } 14226 if (ShouldVisitFalseExpr) { 14227 Region = FalseRegion; 14228 Visit(CO->getFalseExpr()); 14229 } 14230 14231 Region = OldRegion; 14232 Tree.merge(ConditionRegion); 14233 Tree.merge(TrueRegion); 14234 Tree.merge(FalseRegion); 14235 } 14236 14237 void VisitCallExpr(const CallExpr *CE) { 14238 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14239 14240 if (CE->isUnevaluatedBuiltinCall(Context)) 14241 return; 14242 14243 // C++11 [intro.execution]p15: 14244 // When calling a function [...], every value computation and side effect 14245 // associated with any argument expression, or with the postfix expression 14246 // designating the called function, is sequenced before execution of every 14247 // expression or statement in the body of the function [and thus before 14248 // the value computation of its result]. 14249 SequencedSubexpression Sequenced(*this); 14250 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14251 // C++17 [expr.call]p5 14252 // The postfix-expression is sequenced before each expression in the 14253 // expression-list and any default argument. [...] 14254 SequenceTree::Seq CalleeRegion; 14255 SequenceTree::Seq OtherRegion; 14256 if (SemaRef.getLangOpts().CPlusPlus17) { 14257 CalleeRegion = Tree.allocate(Region); 14258 OtherRegion = Tree.allocate(Region); 14259 } else { 14260 CalleeRegion = Region; 14261 OtherRegion = Region; 14262 } 14263 SequenceTree::Seq OldRegion = Region; 14264 14265 // Visit the callee expression first. 14266 Region = CalleeRegion; 14267 if (SemaRef.getLangOpts().CPlusPlus17) { 14268 SequencedSubexpression Sequenced(*this); 14269 Visit(CE->getCallee()); 14270 } else { 14271 Visit(CE->getCallee()); 14272 } 14273 14274 // Then visit the argument expressions. 14275 Region = OtherRegion; 14276 for (const Expr *Argument : CE->arguments()) 14277 Visit(Argument); 14278 14279 Region = OldRegion; 14280 if (SemaRef.getLangOpts().CPlusPlus17) { 14281 Tree.merge(CalleeRegion); 14282 Tree.merge(OtherRegion); 14283 } 14284 }); 14285 } 14286 14287 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14288 // C++17 [over.match.oper]p2: 14289 // [...] the operator notation is first transformed to the equivalent 14290 // function-call notation as summarized in Table 12 (where @ denotes one 14291 // of the operators covered in the specified subclause). However, the 14292 // operands are sequenced in the order prescribed for the built-in 14293 // operator (Clause 8). 14294 // 14295 // From the above only overloaded binary operators and overloaded call 14296 // operators have sequencing rules in C++17 that we need to handle 14297 // separately. 14298 if (!SemaRef.getLangOpts().CPlusPlus17 || 14299 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14300 return VisitCallExpr(CXXOCE); 14301 14302 enum { 14303 NoSequencing, 14304 LHSBeforeRHS, 14305 RHSBeforeLHS, 14306 LHSBeforeRest 14307 } SequencingKind; 14308 switch (CXXOCE->getOperator()) { 14309 case OO_Equal: 14310 case OO_PlusEqual: 14311 case OO_MinusEqual: 14312 case OO_StarEqual: 14313 case OO_SlashEqual: 14314 case OO_PercentEqual: 14315 case OO_CaretEqual: 14316 case OO_AmpEqual: 14317 case OO_PipeEqual: 14318 case OO_LessLessEqual: 14319 case OO_GreaterGreaterEqual: 14320 SequencingKind = RHSBeforeLHS; 14321 break; 14322 14323 case OO_LessLess: 14324 case OO_GreaterGreater: 14325 case OO_AmpAmp: 14326 case OO_PipePipe: 14327 case OO_Comma: 14328 case OO_ArrowStar: 14329 case OO_Subscript: 14330 SequencingKind = LHSBeforeRHS; 14331 break; 14332 14333 case OO_Call: 14334 SequencingKind = LHSBeforeRest; 14335 break; 14336 14337 default: 14338 SequencingKind = NoSequencing; 14339 break; 14340 } 14341 14342 if (SequencingKind == NoSequencing) 14343 return VisitCallExpr(CXXOCE); 14344 14345 // This is a call, so all subexpressions are sequenced before the result. 14346 SequencedSubexpression Sequenced(*this); 14347 14348 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14349 assert(SemaRef.getLangOpts().CPlusPlus17 && 14350 "Should only get there with C++17 and above!"); 14351 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14352 "Should only get there with an overloaded binary operator" 14353 " or an overloaded call operator!"); 14354 14355 if (SequencingKind == LHSBeforeRest) { 14356 assert(CXXOCE->getOperator() == OO_Call && 14357 "We should only have an overloaded call operator here!"); 14358 14359 // This is very similar to VisitCallExpr, except that we only have the 14360 // C++17 case. The postfix-expression is the first argument of the 14361 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14362 // are in the following arguments. 14363 // 14364 // Note that we intentionally do not visit the callee expression since 14365 // it is just a decayed reference to a function. 14366 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14367 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14368 SequenceTree::Seq OldRegion = Region; 14369 14370 assert(CXXOCE->getNumArgs() >= 1 && 14371 "An overloaded call operator must have at least one argument" 14372 " for the postfix-expression!"); 14373 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14374 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14375 CXXOCE->getNumArgs() - 1); 14376 14377 // Visit the postfix-expression first. 14378 { 14379 Region = PostfixExprRegion; 14380 SequencedSubexpression Sequenced(*this); 14381 Visit(PostfixExpr); 14382 } 14383 14384 // Then visit the argument expressions. 14385 Region = ArgsRegion; 14386 for (const Expr *Arg : Args) 14387 Visit(Arg); 14388 14389 Region = OldRegion; 14390 Tree.merge(PostfixExprRegion); 14391 Tree.merge(ArgsRegion); 14392 } else { 14393 assert(CXXOCE->getNumArgs() == 2 && 14394 "Should only have two arguments here!"); 14395 assert((SequencingKind == LHSBeforeRHS || 14396 SequencingKind == RHSBeforeLHS) && 14397 "Unexpected sequencing kind!"); 14398 14399 // We do not visit the callee expression since it is just a decayed 14400 // reference to a function. 14401 const Expr *E1 = CXXOCE->getArg(0); 14402 const Expr *E2 = CXXOCE->getArg(1); 14403 if (SequencingKind == RHSBeforeLHS) 14404 std::swap(E1, E2); 14405 14406 return VisitSequencedExpressions(E1, E2); 14407 } 14408 }); 14409 } 14410 14411 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14412 // This is a call, so all subexpressions are sequenced before the result. 14413 SequencedSubexpression Sequenced(*this); 14414 14415 if (!CCE->isListInitialization()) 14416 return VisitExpr(CCE); 14417 14418 // In C++11, list initializations are sequenced. 14419 SmallVector<SequenceTree::Seq, 32> Elts; 14420 SequenceTree::Seq Parent = Region; 14421 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14422 E = CCE->arg_end(); 14423 I != E; ++I) { 14424 Region = Tree.allocate(Parent); 14425 Elts.push_back(Region); 14426 Visit(*I); 14427 } 14428 14429 // Forget that the initializers are sequenced. 14430 Region = Parent; 14431 for (unsigned I = 0; I < Elts.size(); ++I) 14432 Tree.merge(Elts[I]); 14433 } 14434 14435 void VisitInitListExpr(const InitListExpr *ILE) { 14436 if (!SemaRef.getLangOpts().CPlusPlus11) 14437 return VisitExpr(ILE); 14438 14439 // In C++11, list initializations are sequenced. 14440 SmallVector<SequenceTree::Seq, 32> Elts; 14441 SequenceTree::Seq Parent = Region; 14442 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14443 const Expr *E = ILE->getInit(I); 14444 if (!E) 14445 continue; 14446 Region = Tree.allocate(Parent); 14447 Elts.push_back(Region); 14448 Visit(E); 14449 } 14450 14451 // Forget that the initializers are sequenced. 14452 Region = Parent; 14453 for (unsigned I = 0; I < Elts.size(); ++I) 14454 Tree.merge(Elts[I]); 14455 } 14456 }; 14457 14458 } // namespace 14459 14460 void Sema::CheckUnsequencedOperations(const Expr *E) { 14461 SmallVector<const Expr *, 8> WorkList; 14462 WorkList.push_back(E); 14463 while (!WorkList.empty()) { 14464 const Expr *Item = WorkList.pop_back_val(); 14465 SequenceChecker(*this, Item, WorkList); 14466 } 14467 } 14468 14469 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14470 bool IsConstexpr) { 14471 llvm::SaveAndRestore<bool> ConstantContext( 14472 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14473 CheckImplicitConversions(E, CheckLoc); 14474 if (!E->isInstantiationDependent()) 14475 CheckUnsequencedOperations(E); 14476 if (!IsConstexpr && !E->isValueDependent()) 14477 CheckForIntOverflow(E); 14478 DiagnoseMisalignedMembers(); 14479 } 14480 14481 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14482 FieldDecl *BitField, 14483 Expr *Init) { 14484 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14485 } 14486 14487 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14488 SourceLocation Loc) { 14489 if (!PType->isVariablyModifiedType()) 14490 return; 14491 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14492 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14493 return; 14494 } 14495 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14496 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14497 return; 14498 } 14499 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14500 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14501 return; 14502 } 14503 14504 const ArrayType *AT = S.Context.getAsArrayType(PType); 14505 if (!AT) 14506 return; 14507 14508 if (AT->getSizeModifier() != ArrayType::Star) { 14509 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14510 return; 14511 } 14512 14513 S.Diag(Loc, diag::err_array_star_in_function_definition); 14514 } 14515 14516 /// CheckParmsForFunctionDef - Check that the parameters of the given 14517 /// function are appropriate for the definition of a function. This 14518 /// takes care of any checks that cannot be performed on the 14519 /// declaration itself, e.g., that the types of each of the function 14520 /// parameters are complete. 14521 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14522 bool CheckParameterNames) { 14523 bool HasInvalidParm = false; 14524 for (ParmVarDecl *Param : Parameters) { 14525 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14526 // function declarator that is part of a function definition of 14527 // that function shall not have incomplete type. 14528 // 14529 // This is also C++ [dcl.fct]p6. 14530 if (!Param->isInvalidDecl() && 14531 RequireCompleteType(Param->getLocation(), Param->getType(), 14532 diag::err_typecheck_decl_incomplete_type)) { 14533 Param->setInvalidDecl(); 14534 HasInvalidParm = true; 14535 } 14536 14537 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14538 // declaration of each parameter shall include an identifier. 14539 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14540 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14541 // Diagnose this as an extension in C17 and earlier. 14542 if (!getLangOpts().C2x) 14543 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14544 } 14545 14546 // C99 6.7.5.3p12: 14547 // If the function declarator is not part of a definition of that 14548 // function, parameters may have incomplete type and may use the [*] 14549 // notation in their sequences of declarator specifiers to specify 14550 // variable length array types. 14551 QualType PType = Param->getOriginalType(); 14552 // FIXME: This diagnostic should point the '[*]' if source-location 14553 // information is added for it. 14554 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14555 14556 // If the parameter is a c++ class type and it has to be destructed in the 14557 // callee function, declare the destructor so that it can be called by the 14558 // callee function. Do not perform any direct access check on the dtor here. 14559 if (!Param->isInvalidDecl()) { 14560 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14561 if (!ClassDecl->isInvalidDecl() && 14562 !ClassDecl->hasIrrelevantDestructor() && 14563 !ClassDecl->isDependentContext() && 14564 ClassDecl->isParamDestroyedInCallee()) { 14565 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14566 MarkFunctionReferenced(Param->getLocation(), Destructor); 14567 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14568 } 14569 } 14570 } 14571 14572 // Parameters with the pass_object_size attribute only need to be marked 14573 // constant at function definitions. Because we lack information about 14574 // whether we're on a declaration or definition when we're instantiating the 14575 // attribute, we need to check for constness here. 14576 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14577 if (!Param->getType().isConstQualified()) 14578 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14579 << Attr->getSpelling() << 1; 14580 14581 // Check for parameter names shadowing fields from the class. 14582 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14583 // The owning context for the parameter should be the function, but we 14584 // want to see if this function's declaration context is a record. 14585 DeclContext *DC = Param->getDeclContext(); 14586 if (DC && DC->isFunctionOrMethod()) { 14587 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14588 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14589 RD, /*DeclIsField*/ false); 14590 } 14591 } 14592 } 14593 14594 return HasInvalidParm; 14595 } 14596 14597 Optional<std::pair<CharUnits, CharUnits>> 14598 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14599 14600 /// Compute the alignment and offset of the base class object given the 14601 /// derived-to-base cast expression and the alignment and offset of the derived 14602 /// class object. 14603 static std::pair<CharUnits, CharUnits> 14604 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14605 CharUnits BaseAlignment, CharUnits Offset, 14606 ASTContext &Ctx) { 14607 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14608 ++PathI) { 14609 const CXXBaseSpecifier *Base = *PathI; 14610 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14611 if (Base->isVirtual()) { 14612 // The complete object may have a lower alignment than the non-virtual 14613 // alignment of the base, in which case the base may be misaligned. Choose 14614 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14615 // conservative lower bound of the complete object alignment. 14616 CharUnits NonVirtualAlignment = 14617 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14618 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14619 Offset = CharUnits::Zero(); 14620 } else { 14621 const ASTRecordLayout &RL = 14622 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14623 Offset += RL.getBaseClassOffset(BaseDecl); 14624 } 14625 DerivedType = Base->getType(); 14626 } 14627 14628 return std::make_pair(BaseAlignment, Offset); 14629 } 14630 14631 /// Compute the alignment and offset of a binary additive operator. 14632 static Optional<std::pair<CharUnits, CharUnits>> 14633 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14634 bool IsSub, ASTContext &Ctx) { 14635 QualType PointeeType = PtrE->getType()->getPointeeType(); 14636 14637 if (!PointeeType->isConstantSizeType()) 14638 return llvm::None; 14639 14640 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14641 14642 if (!P) 14643 return llvm::None; 14644 14645 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14646 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14647 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14648 if (IsSub) 14649 Offset = -Offset; 14650 return std::make_pair(P->first, P->second + Offset); 14651 } 14652 14653 // If the integer expression isn't a constant expression, compute the lower 14654 // bound of the alignment using the alignment and offset of the pointer 14655 // expression and the element size. 14656 return std::make_pair( 14657 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14658 CharUnits::Zero()); 14659 } 14660 14661 /// This helper function takes an lvalue expression and returns the alignment of 14662 /// a VarDecl and a constant offset from the VarDecl. 14663 Optional<std::pair<CharUnits, CharUnits>> 14664 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14665 E = E->IgnoreParens(); 14666 switch (E->getStmtClass()) { 14667 default: 14668 break; 14669 case Stmt::CStyleCastExprClass: 14670 case Stmt::CXXStaticCastExprClass: 14671 case Stmt::ImplicitCastExprClass: { 14672 auto *CE = cast<CastExpr>(E); 14673 const Expr *From = CE->getSubExpr(); 14674 switch (CE->getCastKind()) { 14675 default: 14676 break; 14677 case CK_NoOp: 14678 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14679 case CK_UncheckedDerivedToBase: 14680 case CK_DerivedToBase: { 14681 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14682 if (!P) 14683 break; 14684 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14685 P->second, Ctx); 14686 } 14687 } 14688 break; 14689 } 14690 case Stmt::ArraySubscriptExprClass: { 14691 auto *ASE = cast<ArraySubscriptExpr>(E); 14692 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14693 false, Ctx); 14694 } 14695 case Stmt::DeclRefExprClass: { 14696 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14697 // FIXME: If VD is captured by copy or is an escaping __block variable, 14698 // use the alignment of VD's type. 14699 if (!VD->getType()->isReferenceType()) 14700 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14701 if (VD->hasInit()) 14702 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14703 } 14704 break; 14705 } 14706 case Stmt::MemberExprClass: { 14707 auto *ME = cast<MemberExpr>(E); 14708 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14709 if (!FD || FD->getType()->isReferenceType() || 14710 FD->getParent()->isInvalidDecl()) 14711 break; 14712 Optional<std::pair<CharUnits, CharUnits>> P; 14713 if (ME->isArrow()) 14714 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14715 else 14716 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14717 if (!P) 14718 break; 14719 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14720 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14721 return std::make_pair(P->first, 14722 P->second + CharUnits::fromQuantity(Offset)); 14723 } 14724 case Stmt::UnaryOperatorClass: { 14725 auto *UO = cast<UnaryOperator>(E); 14726 switch (UO->getOpcode()) { 14727 default: 14728 break; 14729 case UO_Deref: 14730 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14731 } 14732 break; 14733 } 14734 case Stmt::BinaryOperatorClass: { 14735 auto *BO = cast<BinaryOperator>(E); 14736 auto Opcode = BO->getOpcode(); 14737 switch (Opcode) { 14738 default: 14739 break; 14740 case BO_Comma: 14741 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14742 } 14743 break; 14744 } 14745 } 14746 return llvm::None; 14747 } 14748 14749 /// This helper function takes a pointer expression and returns the alignment of 14750 /// a VarDecl and a constant offset from the VarDecl. 14751 Optional<std::pair<CharUnits, CharUnits>> 14752 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14753 E = E->IgnoreParens(); 14754 switch (E->getStmtClass()) { 14755 default: 14756 break; 14757 case Stmt::CStyleCastExprClass: 14758 case Stmt::CXXStaticCastExprClass: 14759 case Stmt::ImplicitCastExprClass: { 14760 auto *CE = cast<CastExpr>(E); 14761 const Expr *From = CE->getSubExpr(); 14762 switch (CE->getCastKind()) { 14763 default: 14764 break; 14765 case CK_NoOp: 14766 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14767 case CK_ArrayToPointerDecay: 14768 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14769 case CK_UncheckedDerivedToBase: 14770 case CK_DerivedToBase: { 14771 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14772 if (!P) 14773 break; 14774 return getDerivedToBaseAlignmentAndOffset( 14775 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14776 } 14777 } 14778 break; 14779 } 14780 case Stmt::CXXThisExprClass: { 14781 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14782 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14783 return std::make_pair(Alignment, CharUnits::Zero()); 14784 } 14785 case Stmt::UnaryOperatorClass: { 14786 auto *UO = cast<UnaryOperator>(E); 14787 if (UO->getOpcode() == UO_AddrOf) 14788 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14789 break; 14790 } 14791 case Stmt::BinaryOperatorClass: { 14792 auto *BO = cast<BinaryOperator>(E); 14793 auto Opcode = BO->getOpcode(); 14794 switch (Opcode) { 14795 default: 14796 break; 14797 case BO_Add: 14798 case BO_Sub: { 14799 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14800 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14801 std::swap(LHS, RHS); 14802 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14803 Ctx); 14804 } 14805 case BO_Comma: 14806 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14807 } 14808 break; 14809 } 14810 } 14811 return llvm::None; 14812 } 14813 14814 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14815 // See if we can compute the alignment of a VarDecl and an offset from it. 14816 Optional<std::pair<CharUnits, CharUnits>> P = 14817 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14818 14819 if (P) 14820 return P->first.alignmentAtOffset(P->second); 14821 14822 // If that failed, return the type's alignment. 14823 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14824 } 14825 14826 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14827 /// pointer cast increases the alignment requirements. 14828 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14829 // This is actually a lot of work to potentially be doing on every 14830 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14831 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14832 return; 14833 14834 // Ignore dependent types. 14835 if (T->isDependentType() || Op->getType()->isDependentType()) 14836 return; 14837 14838 // Require that the destination be a pointer type. 14839 const PointerType *DestPtr = T->getAs<PointerType>(); 14840 if (!DestPtr) return; 14841 14842 // If the destination has alignment 1, we're done. 14843 QualType DestPointee = DestPtr->getPointeeType(); 14844 if (DestPointee->isIncompleteType()) return; 14845 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14846 if (DestAlign.isOne()) return; 14847 14848 // Require that the source be a pointer type. 14849 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14850 if (!SrcPtr) return; 14851 QualType SrcPointee = SrcPtr->getPointeeType(); 14852 14853 // Explicitly allow casts from cv void*. We already implicitly 14854 // allowed casts to cv void*, since they have alignment 1. 14855 // Also allow casts involving incomplete types, which implicitly 14856 // includes 'void'. 14857 if (SrcPointee->isIncompleteType()) return; 14858 14859 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14860 14861 if (SrcAlign >= DestAlign) return; 14862 14863 Diag(TRange.getBegin(), diag::warn_cast_align) 14864 << Op->getType() << T 14865 << static_cast<unsigned>(SrcAlign.getQuantity()) 14866 << static_cast<unsigned>(DestAlign.getQuantity()) 14867 << TRange << Op->getSourceRange(); 14868 } 14869 14870 /// Check whether this array fits the idiom of a size-one tail padded 14871 /// array member of a struct. 14872 /// 14873 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14874 /// commonly used to emulate flexible arrays in C89 code. 14875 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14876 const NamedDecl *ND) { 14877 if (Size != 1 || !ND) return false; 14878 14879 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14880 if (!FD) return false; 14881 14882 // Don't consider sizes resulting from macro expansions or template argument 14883 // substitution to form C89 tail-padded arrays. 14884 14885 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14886 while (TInfo) { 14887 TypeLoc TL = TInfo->getTypeLoc(); 14888 // Look through typedefs. 14889 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14890 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14891 TInfo = TDL->getTypeSourceInfo(); 14892 continue; 14893 } 14894 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14895 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14896 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14897 return false; 14898 } 14899 break; 14900 } 14901 14902 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14903 if (!RD) return false; 14904 if (RD->isUnion()) return false; 14905 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14906 if (!CRD->isStandardLayout()) return false; 14907 } 14908 14909 // See if this is the last field decl in the record. 14910 const Decl *D = FD; 14911 while ((D = D->getNextDeclInContext())) 14912 if (isa<FieldDecl>(D)) 14913 return false; 14914 return true; 14915 } 14916 14917 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14918 const ArraySubscriptExpr *ASE, 14919 bool AllowOnePastEnd, bool IndexNegated) { 14920 // Already diagnosed by the constant evaluator. 14921 if (isConstantEvaluated()) 14922 return; 14923 14924 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14925 if (IndexExpr->isValueDependent()) 14926 return; 14927 14928 const Type *EffectiveType = 14929 BaseExpr->getType()->getPointeeOrArrayElementType(); 14930 BaseExpr = BaseExpr->IgnoreParenCasts(); 14931 const ConstantArrayType *ArrayTy = 14932 Context.getAsConstantArrayType(BaseExpr->getType()); 14933 14934 const Type *BaseType = 14935 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 14936 bool IsUnboundedArray = (BaseType == nullptr); 14937 if (EffectiveType->isDependentType() || 14938 (!IsUnboundedArray && BaseType->isDependentType())) 14939 return; 14940 14941 Expr::EvalResult Result; 14942 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14943 return; 14944 14945 llvm::APSInt index = Result.Val.getInt(); 14946 if (IndexNegated) { 14947 index.setIsUnsigned(false); 14948 index = -index; 14949 } 14950 14951 const NamedDecl *ND = nullptr; 14952 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14953 ND = DRE->getDecl(); 14954 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14955 ND = ME->getMemberDecl(); 14956 14957 if (IsUnboundedArray) { 14958 if (index.isUnsigned() || !index.isNegative()) { 14959 const auto &ASTC = getASTContext(); 14960 unsigned AddrBits = 14961 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 14962 EffectiveType->getCanonicalTypeInternal())); 14963 if (index.getBitWidth() < AddrBits) 14964 index = index.zext(AddrBits); 14965 Optional<CharUnits> ElemCharUnits = 14966 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 14967 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 14968 // pointer) bounds-checking isn't meaningful. 14969 if (!ElemCharUnits) 14970 return; 14971 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 14972 // If index has more active bits than address space, we already know 14973 // we have a bounds violation to warn about. Otherwise, compute 14974 // address of (index + 1)th element, and warn about bounds violation 14975 // only if that address exceeds address space. 14976 if (index.getActiveBits() <= AddrBits) { 14977 bool Overflow; 14978 llvm::APInt Product(index); 14979 Product += 1; 14980 Product = Product.umul_ov(ElemBytes, Overflow); 14981 if (!Overflow && Product.getActiveBits() <= AddrBits) 14982 return; 14983 } 14984 14985 // Need to compute max possible elements in address space, since that 14986 // is included in diag message. 14987 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 14988 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 14989 MaxElems += 1; 14990 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 14991 MaxElems = MaxElems.udiv(ElemBytes); 14992 14993 unsigned DiagID = 14994 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 14995 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 14996 14997 // Diag message shows element size in bits and in "bytes" (platform- 14998 // dependent CharUnits) 14999 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15000 PDiag(DiagID) 15001 << toString(index, 10, true) << AddrBits 15002 << (unsigned)ASTC.toBits(*ElemCharUnits) 15003 << toString(ElemBytes, 10, false) 15004 << toString(MaxElems, 10, false) 15005 << (unsigned)MaxElems.getLimitedValue(~0U) 15006 << IndexExpr->getSourceRange()); 15007 15008 if (!ND) { 15009 // Try harder to find a NamedDecl to point at in the note. 15010 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15011 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15012 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15013 ND = DRE->getDecl(); 15014 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15015 ND = ME->getMemberDecl(); 15016 } 15017 15018 if (ND) 15019 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15020 PDiag(diag::note_array_declared_here) << ND); 15021 } 15022 return; 15023 } 15024 15025 if (index.isUnsigned() || !index.isNegative()) { 15026 // It is possible that the type of the base expression after 15027 // IgnoreParenCasts is incomplete, even though the type of the base 15028 // expression before IgnoreParenCasts is complete (see PR39746 for an 15029 // example). In this case we have no information about whether the array 15030 // access exceeds the array bounds. However we can still diagnose an array 15031 // access which precedes the array bounds. 15032 if (BaseType->isIncompleteType()) 15033 return; 15034 15035 llvm::APInt size = ArrayTy->getSize(); 15036 if (!size.isStrictlyPositive()) 15037 return; 15038 15039 if (BaseType != EffectiveType) { 15040 // Make sure we're comparing apples to apples when comparing index to size 15041 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15042 uint64_t array_typesize = Context.getTypeSize(BaseType); 15043 // Handle ptrarith_typesize being zero, such as when casting to void* 15044 if (!ptrarith_typesize) ptrarith_typesize = 1; 15045 if (ptrarith_typesize != array_typesize) { 15046 // There's a cast to a different size type involved 15047 uint64_t ratio = array_typesize / ptrarith_typesize; 15048 // TODO: Be smarter about handling cases where array_typesize is not a 15049 // multiple of ptrarith_typesize 15050 if (ptrarith_typesize * ratio == array_typesize) 15051 size *= llvm::APInt(size.getBitWidth(), ratio); 15052 } 15053 } 15054 15055 if (size.getBitWidth() > index.getBitWidth()) 15056 index = index.zext(size.getBitWidth()); 15057 else if (size.getBitWidth() < index.getBitWidth()) 15058 size = size.zext(index.getBitWidth()); 15059 15060 // For array subscripting the index must be less than size, but for pointer 15061 // arithmetic also allow the index (offset) to be equal to size since 15062 // computing the next address after the end of the array is legal and 15063 // commonly done e.g. in C++ iterators and range-based for loops. 15064 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15065 return; 15066 15067 // Also don't warn for arrays of size 1 which are members of some 15068 // structure. These are often used to approximate flexible arrays in C89 15069 // code. 15070 if (IsTailPaddedMemberArray(*this, size, ND)) 15071 return; 15072 15073 // Suppress the warning if the subscript expression (as identified by the 15074 // ']' location) and the index expression are both from macro expansions 15075 // within a system header. 15076 if (ASE) { 15077 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15078 ASE->getRBracketLoc()); 15079 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15080 SourceLocation IndexLoc = 15081 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15082 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15083 return; 15084 } 15085 } 15086 15087 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15088 : diag::warn_ptr_arith_exceeds_bounds; 15089 15090 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15091 PDiag(DiagID) << toString(index, 10, true) 15092 << toString(size, 10, true) 15093 << (unsigned)size.getLimitedValue(~0U) 15094 << IndexExpr->getSourceRange()); 15095 } else { 15096 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15097 if (!ASE) { 15098 DiagID = diag::warn_ptr_arith_precedes_bounds; 15099 if (index.isNegative()) index = -index; 15100 } 15101 15102 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15103 PDiag(DiagID) << toString(index, 10, true) 15104 << IndexExpr->getSourceRange()); 15105 } 15106 15107 if (!ND) { 15108 // Try harder to find a NamedDecl to point at in the note. 15109 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15110 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15111 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15112 ND = DRE->getDecl(); 15113 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15114 ND = ME->getMemberDecl(); 15115 } 15116 15117 if (ND) 15118 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15119 PDiag(diag::note_array_declared_here) << ND); 15120 } 15121 15122 void Sema::CheckArrayAccess(const Expr *expr) { 15123 int AllowOnePastEnd = 0; 15124 while (expr) { 15125 expr = expr->IgnoreParenImpCasts(); 15126 switch (expr->getStmtClass()) { 15127 case Stmt::ArraySubscriptExprClass: { 15128 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15129 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15130 AllowOnePastEnd > 0); 15131 expr = ASE->getBase(); 15132 break; 15133 } 15134 case Stmt::MemberExprClass: { 15135 expr = cast<MemberExpr>(expr)->getBase(); 15136 break; 15137 } 15138 case Stmt::OMPArraySectionExprClass: { 15139 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15140 if (ASE->getLowerBound()) 15141 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15142 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15143 return; 15144 } 15145 case Stmt::UnaryOperatorClass: { 15146 // Only unwrap the * and & unary operators 15147 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15148 expr = UO->getSubExpr(); 15149 switch (UO->getOpcode()) { 15150 case UO_AddrOf: 15151 AllowOnePastEnd++; 15152 break; 15153 case UO_Deref: 15154 AllowOnePastEnd--; 15155 break; 15156 default: 15157 return; 15158 } 15159 break; 15160 } 15161 case Stmt::ConditionalOperatorClass: { 15162 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15163 if (const Expr *lhs = cond->getLHS()) 15164 CheckArrayAccess(lhs); 15165 if (const Expr *rhs = cond->getRHS()) 15166 CheckArrayAccess(rhs); 15167 return; 15168 } 15169 case Stmt::CXXOperatorCallExprClass: { 15170 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15171 for (const auto *Arg : OCE->arguments()) 15172 CheckArrayAccess(Arg); 15173 return; 15174 } 15175 default: 15176 return; 15177 } 15178 } 15179 } 15180 15181 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15182 15183 namespace { 15184 15185 struct RetainCycleOwner { 15186 VarDecl *Variable = nullptr; 15187 SourceRange Range; 15188 SourceLocation Loc; 15189 bool Indirect = false; 15190 15191 RetainCycleOwner() = default; 15192 15193 void setLocsFrom(Expr *e) { 15194 Loc = e->getExprLoc(); 15195 Range = e->getSourceRange(); 15196 } 15197 }; 15198 15199 } // namespace 15200 15201 /// Consider whether capturing the given variable can possibly lead to 15202 /// a retain cycle. 15203 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15204 // In ARC, it's captured strongly iff the variable has __strong 15205 // lifetime. In MRR, it's captured strongly if the variable is 15206 // __block and has an appropriate type. 15207 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15208 return false; 15209 15210 owner.Variable = var; 15211 if (ref) 15212 owner.setLocsFrom(ref); 15213 return true; 15214 } 15215 15216 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15217 while (true) { 15218 e = e->IgnoreParens(); 15219 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15220 switch (cast->getCastKind()) { 15221 case CK_BitCast: 15222 case CK_LValueBitCast: 15223 case CK_LValueToRValue: 15224 case CK_ARCReclaimReturnedObject: 15225 e = cast->getSubExpr(); 15226 continue; 15227 15228 default: 15229 return false; 15230 } 15231 } 15232 15233 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15234 ObjCIvarDecl *ivar = ref->getDecl(); 15235 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15236 return false; 15237 15238 // Try to find a retain cycle in the base. 15239 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15240 return false; 15241 15242 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15243 owner.Indirect = true; 15244 return true; 15245 } 15246 15247 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15248 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15249 if (!var) return false; 15250 return considerVariable(var, ref, owner); 15251 } 15252 15253 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15254 if (member->isArrow()) return false; 15255 15256 // Don't count this as an indirect ownership. 15257 e = member->getBase(); 15258 continue; 15259 } 15260 15261 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15262 // Only pay attention to pseudo-objects on property references. 15263 ObjCPropertyRefExpr *pre 15264 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15265 ->IgnoreParens()); 15266 if (!pre) return false; 15267 if (pre->isImplicitProperty()) return false; 15268 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15269 if (!property->isRetaining() && 15270 !(property->getPropertyIvarDecl() && 15271 property->getPropertyIvarDecl()->getType() 15272 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15273 return false; 15274 15275 owner.Indirect = true; 15276 if (pre->isSuperReceiver()) { 15277 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15278 if (!owner.Variable) 15279 return false; 15280 owner.Loc = pre->getLocation(); 15281 owner.Range = pre->getSourceRange(); 15282 return true; 15283 } 15284 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15285 ->getSourceExpr()); 15286 continue; 15287 } 15288 15289 // Array ivars? 15290 15291 return false; 15292 } 15293 } 15294 15295 namespace { 15296 15297 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15298 ASTContext &Context; 15299 VarDecl *Variable; 15300 Expr *Capturer = nullptr; 15301 bool VarWillBeReased = false; 15302 15303 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15304 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15305 Context(Context), Variable(variable) {} 15306 15307 void VisitDeclRefExpr(DeclRefExpr *ref) { 15308 if (ref->getDecl() == Variable && !Capturer) 15309 Capturer = ref; 15310 } 15311 15312 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15313 if (Capturer) return; 15314 Visit(ref->getBase()); 15315 if (Capturer && ref->isFreeIvar()) 15316 Capturer = ref; 15317 } 15318 15319 void VisitBlockExpr(BlockExpr *block) { 15320 // Look inside nested blocks 15321 if (block->getBlockDecl()->capturesVariable(Variable)) 15322 Visit(block->getBlockDecl()->getBody()); 15323 } 15324 15325 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15326 if (Capturer) return; 15327 if (OVE->getSourceExpr()) 15328 Visit(OVE->getSourceExpr()); 15329 } 15330 15331 void VisitBinaryOperator(BinaryOperator *BinOp) { 15332 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15333 return; 15334 Expr *LHS = BinOp->getLHS(); 15335 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15336 if (DRE->getDecl() != Variable) 15337 return; 15338 if (Expr *RHS = BinOp->getRHS()) { 15339 RHS = RHS->IgnoreParenCasts(); 15340 Optional<llvm::APSInt> Value; 15341 VarWillBeReased = 15342 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15343 *Value == 0); 15344 } 15345 } 15346 } 15347 }; 15348 15349 } // namespace 15350 15351 /// Check whether the given argument is a block which captures a 15352 /// variable. 15353 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15354 assert(owner.Variable && owner.Loc.isValid()); 15355 15356 e = e->IgnoreParenCasts(); 15357 15358 // Look through [^{...} copy] and Block_copy(^{...}). 15359 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15360 Selector Cmd = ME->getSelector(); 15361 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15362 e = ME->getInstanceReceiver(); 15363 if (!e) 15364 return nullptr; 15365 e = e->IgnoreParenCasts(); 15366 } 15367 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15368 if (CE->getNumArgs() == 1) { 15369 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15370 if (Fn) { 15371 const IdentifierInfo *FnI = Fn->getIdentifier(); 15372 if (FnI && FnI->isStr("_Block_copy")) { 15373 e = CE->getArg(0)->IgnoreParenCasts(); 15374 } 15375 } 15376 } 15377 } 15378 15379 BlockExpr *block = dyn_cast<BlockExpr>(e); 15380 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15381 return nullptr; 15382 15383 FindCaptureVisitor visitor(S.Context, owner.Variable); 15384 visitor.Visit(block->getBlockDecl()->getBody()); 15385 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15386 } 15387 15388 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15389 RetainCycleOwner &owner) { 15390 assert(capturer); 15391 assert(owner.Variable && owner.Loc.isValid()); 15392 15393 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15394 << owner.Variable << capturer->getSourceRange(); 15395 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15396 << owner.Indirect << owner.Range; 15397 } 15398 15399 /// Check for a keyword selector that starts with the word 'add' or 15400 /// 'set'. 15401 static bool isSetterLikeSelector(Selector sel) { 15402 if (sel.isUnarySelector()) return false; 15403 15404 StringRef str = sel.getNameForSlot(0); 15405 while (!str.empty() && str.front() == '_') str = str.substr(1); 15406 if (str.startswith("set")) 15407 str = str.substr(3); 15408 else if (str.startswith("add")) { 15409 // Specially allow 'addOperationWithBlock:'. 15410 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15411 return false; 15412 str = str.substr(3); 15413 } 15414 else 15415 return false; 15416 15417 if (str.empty()) return true; 15418 return !isLowercase(str.front()); 15419 } 15420 15421 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15422 ObjCMessageExpr *Message) { 15423 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15424 Message->getReceiverInterface(), 15425 NSAPI::ClassId_NSMutableArray); 15426 if (!IsMutableArray) { 15427 return None; 15428 } 15429 15430 Selector Sel = Message->getSelector(); 15431 15432 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15433 S.NSAPIObj->getNSArrayMethodKind(Sel); 15434 if (!MKOpt) { 15435 return None; 15436 } 15437 15438 NSAPI::NSArrayMethodKind MK = *MKOpt; 15439 15440 switch (MK) { 15441 case NSAPI::NSMutableArr_addObject: 15442 case NSAPI::NSMutableArr_insertObjectAtIndex: 15443 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15444 return 0; 15445 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15446 return 1; 15447 15448 default: 15449 return None; 15450 } 15451 15452 return None; 15453 } 15454 15455 static 15456 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15457 ObjCMessageExpr *Message) { 15458 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15459 Message->getReceiverInterface(), 15460 NSAPI::ClassId_NSMutableDictionary); 15461 if (!IsMutableDictionary) { 15462 return None; 15463 } 15464 15465 Selector Sel = Message->getSelector(); 15466 15467 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15468 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15469 if (!MKOpt) { 15470 return None; 15471 } 15472 15473 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15474 15475 switch (MK) { 15476 case NSAPI::NSMutableDict_setObjectForKey: 15477 case NSAPI::NSMutableDict_setValueForKey: 15478 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15479 return 0; 15480 15481 default: 15482 return None; 15483 } 15484 15485 return None; 15486 } 15487 15488 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15489 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15490 Message->getReceiverInterface(), 15491 NSAPI::ClassId_NSMutableSet); 15492 15493 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15494 Message->getReceiverInterface(), 15495 NSAPI::ClassId_NSMutableOrderedSet); 15496 if (!IsMutableSet && !IsMutableOrderedSet) { 15497 return None; 15498 } 15499 15500 Selector Sel = Message->getSelector(); 15501 15502 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15503 if (!MKOpt) { 15504 return None; 15505 } 15506 15507 NSAPI::NSSetMethodKind MK = *MKOpt; 15508 15509 switch (MK) { 15510 case NSAPI::NSMutableSet_addObject: 15511 case NSAPI::NSOrderedSet_setObjectAtIndex: 15512 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15513 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15514 return 0; 15515 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15516 return 1; 15517 } 15518 15519 return None; 15520 } 15521 15522 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15523 if (!Message->isInstanceMessage()) { 15524 return; 15525 } 15526 15527 Optional<int> ArgOpt; 15528 15529 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15530 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15531 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15532 return; 15533 } 15534 15535 int ArgIndex = *ArgOpt; 15536 15537 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15538 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15539 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15540 } 15541 15542 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15543 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15544 if (ArgRE->isObjCSelfExpr()) { 15545 Diag(Message->getSourceRange().getBegin(), 15546 diag::warn_objc_circular_container) 15547 << ArgRE->getDecl() << StringRef("'super'"); 15548 } 15549 } 15550 } else { 15551 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15552 15553 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15554 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15555 } 15556 15557 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15558 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15559 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15560 ValueDecl *Decl = ReceiverRE->getDecl(); 15561 Diag(Message->getSourceRange().getBegin(), 15562 diag::warn_objc_circular_container) 15563 << Decl << Decl; 15564 if (!ArgRE->isObjCSelfExpr()) { 15565 Diag(Decl->getLocation(), 15566 diag::note_objc_circular_container_declared_here) 15567 << Decl; 15568 } 15569 } 15570 } 15571 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15572 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15573 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15574 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15575 Diag(Message->getSourceRange().getBegin(), 15576 diag::warn_objc_circular_container) 15577 << Decl << Decl; 15578 Diag(Decl->getLocation(), 15579 diag::note_objc_circular_container_declared_here) 15580 << Decl; 15581 } 15582 } 15583 } 15584 } 15585 } 15586 15587 /// Check a message send to see if it's likely to cause a retain cycle. 15588 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15589 // Only check instance methods whose selector looks like a setter. 15590 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15591 return; 15592 15593 // Try to find a variable that the receiver is strongly owned by. 15594 RetainCycleOwner owner; 15595 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15596 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15597 return; 15598 } else { 15599 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15600 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15601 owner.Loc = msg->getSuperLoc(); 15602 owner.Range = msg->getSuperLoc(); 15603 } 15604 15605 // Check whether the receiver is captured by any of the arguments. 15606 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15607 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15608 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15609 // noescape blocks should not be retained by the method. 15610 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15611 continue; 15612 return diagnoseRetainCycle(*this, capturer, owner); 15613 } 15614 } 15615 } 15616 15617 /// Check a property assign to see if it's likely to cause a retain cycle. 15618 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15619 RetainCycleOwner owner; 15620 if (!findRetainCycleOwner(*this, receiver, owner)) 15621 return; 15622 15623 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15624 diagnoseRetainCycle(*this, capturer, owner); 15625 } 15626 15627 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15628 RetainCycleOwner Owner; 15629 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15630 return; 15631 15632 // Because we don't have an expression for the variable, we have to set the 15633 // location explicitly here. 15634 Owner.Loc = Var->getLocation(); 15635 Owner.Range = Var->getSourceRange(); 15636 15637 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15638 diagnoseRetainCycle(*this, Capturer, Owner); 15639 } 15640 15641 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15642 Expr *RHS, bool isProperty) { 15643 // Check if RHS is an Objective-C object literal, which also can get 15644 // immediately zapped in a weak reference. Note that we explicitly 15645 // allow ObjCStringLiterals, since those are designed to never really die. 15646 RHS = RHS->IgnoreParenImpCasts(); 15647 15648 // This enum needs to match with the 'select' in 15649 // warn_objc_arc_literal_assign (off-by-1). 15650 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15651 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15652 return false; 15653 15654 S.Diag(Loc, diag::warn_arc_literal_assign) 15655 << (unsigned) Kind 15656 << (isProperty ? 0 : 1) 15657 << RHS->getSourceRange(); 15658 15659 return true; 15660 } 15661 15662 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15663 Qualifiers::ObjCLifetime LT, 15664 Expr *RHS, bool isProperty) { 15665 // Strip off any implicit cast added to get to the one ARC-specific. 15666 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15667 if (cast->getCastKind() == CK_ARCConsumeObject) { 15668 S.Diag(Loc, diag::warn_arc_retained_assign) 15669 << (LT == Qualifiers::OCL_ExplicitNone) 15670 << (isProperty ? 0 : 1) 15671 << RHS->getSourceRange(); 15672 return true; 15673 } 15674 RHS = cast->getSubExpr(); 15675 } 15676 15677 if (LT == Qualifiers::OCL_Weak && 15678 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15679 return true; 15680 15681 return false; 15682 } 15683 15684 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15685 QualType LHS, Expr *RHS) { 15686 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15687 15688 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15689 return false; 15690 15691 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15692 return true; 15693 15694 return false; 15695 } 15696 15697 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15698 Expr *LHS, Expr *RHS) { 15699 QualType LHSType; 15700 // PropertyRef on LHS type need be directly obtained from 15701 // its declaration as it has a PseudoType. 15702 ObjCPropertyRefExpr *PRE 15703 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15704 if (PRE && !PRE->isImplicitProperty()) { 15705 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15706 if (PD) 15707 LHSType = PD->getType(); 15708 } 15709 15710 if (LHSType.isNull()) 15711 LHSType = LHS->getType(); 15712 15713 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15714 15715 if (LT == Qualifiers::OCL_Weak) { 15716 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15717 getCurFunction()->markSafeWeakUse(LHS); 15718 } 15719 15720 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15721 return; 15722 15723 // FIXME. Check for other life times. 15724 if (LT != Qualifiers::OCL_None) 15725 return; 15726 15727 if (PRE) { 15728 if (PRE->isImplicitProperty()) 15729 return; 15730 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15731 if (!PD) 15732 return; 15733 15734 unsigned Attributes = PD->getPropertyAttributes(); 15735 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15736 // when 'assign' attribute was not explicitly specified 15737 // by user, ignore it and rely on property type itself 15738 // for lifetime info. 15739 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15740 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15741 LHSType->isObjCRetainableType()) 15742 return; 15743 15744 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15745 if (cast->getCastKind() == CK_ARCConsumeObject) { 15746 Diag(Loc, diag::warn_arc_retained_property_assign) 15747 << RHS->getSourceRange(); 15748 return; 15749 } 15750 RHS = cast->getSubExpr(); 15751 } 15752 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15753 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15754 return; 15755 } 15756 } 15757 } 15758 15759 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15760 15761 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15762 SourceLocation StmtLoc, 15763 const NullStmt *Body) { 15764 // Do not warn if the body is a macro that expands to nothing, e.g: 15765 // 15766 // #define CALL(x) 15767 // if (condition) 15768 // CALL(0); 15769 if (Body->hasLeadingEmptyMacro()) 15770 return false; 15771 15772 // Get line numbers of statement and body. 15773 bool StmtLineInvalid; 15774 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15775 &StmtLineInvalid); 15776 if (StmtLineInvalid) 15777 return false; 15778 15779 bool BodyLineInvalid; 15780 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15781 &BodyLineInvalid); 15782 if (BodyLineInvalid) 15783 return false; 15784 15785 // Warn if null statement and body are on the same line. 15786 if (StmtLine != BodyLine) 15787 return false; 15788 15789 return true; 15790 } 15791 15792 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15793 const Stmt *Body, 15794 unsigned DiagID) { 15795 // Since this is a syntactic check, don't emit diagnostic for template 15796 // instantiations, this just adds noise. 15797 if (CurrentInstantiationScope) 15798 return; 15799 15800 // The body should be a null statement. 15801 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15802 if (!NBody) 15803 return; 15804 15805 // Do the usual checks. 15806 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15807 return; 15808 15809 Diag(NBody->getSemiLoc(), DiagID); 15810 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15811 } 15812 15813 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15814 const Stmt *PossibleBody) { 15815 assert(!CurrentInstantiationScope); // Ensured by caller 15816 15817 SourceLocation StmtLoc; 15818 const Stmt *Body; 15819 unsigned DiagID; 15820 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15821 StmtLoc = FS->getRParenLoc(); 15822 Body = FS->getBody(); 15823 DiagID = diag::warn_empty_for_body; 15824 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15825 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15826 Body = WS->getBody(); 15827 DiagID = diag::warn_empty_while_body; 15828 } else 15829 return; // Neither `for' nor `while'. 15830 15831 // The body should be a null statement. 15832 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15833 if (!NBody) 15834 return; 15835 15836 // Skip expensive checks if diagnostic is disabled. 15837 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15838 return; 15839 15840 // Do the usual checks. 15841 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15842 return; 15843 15844 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15845 // noise level low, emit diagnostics only if for/while is followed by a 15846 // CompoundStmt, e.g.: 15847 // for (int i = 0; i < n; i++); 15848 // { 15849 // a(i); 15850 // } 15851 // or if for/while is followed by a statement with more indentation 15852 // than for/while itself: 15853 // for (int i = 0; i < n; i++); 15854 // a(i); 15855 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15856 if (!ProbableTypo) { 15857 bool BodyColInvalid; 15858 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15859 PossibleBody->getBeginLoc(), &BodyColInvalid); 15860 if (BodyColInvalid) 15861 return; 15862 15863 bool StmtColInvalid; 15864 unsigned StmtCol = 15865 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15866 if (StmtColInvalid) 15867 return; 15868 15869 if (BodyCol > StmtCol) 15870 ProbableTypo = true; 15871 } 15872 15873 if (ProbableTypo) { 15874 Diag(NBody->getSemiLoc(), DiagID); 15875 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15876 } 15877 } 15878 15879 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15880 15881 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15882 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15883 SourceLocation OpLoc) { 15884 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15885 return; 15886 15887 if (inTemplateInstantiation()) 15888 return; 15889 15890 // Strip parens and casts away. 15891 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15892 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15893 15894 // Check for a call expression 15895 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15896 if (!CE || CE->getNumArgs() != 1) 15897 return; 15898 15899 // Check for a call to std::move 15900 if (!CE->isCallToStdMove()) 15901 return; 15902 15903 // Get argument from std::move 15904 RHSExpr = CE->getArg(0); 15905 15906 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15907 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15908 15909 // Two DeclRefExpr's, check that the decls are the same. 15910 if (LHSDeclRef && RHSDeclRef) { 15911 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15912 return; 15913 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15914 RHSDeclRef->getDecl()->getCanonicalDecl()) 15915 return; 15916 15917 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15918 << LHSExpr->getSourceRange() 15919 << RHSExpr->getSourceRange(); 15920 return; 15921 } 15922 15923 // Member variables require a different approach to check for self moves. 15924 // MemberExpr's are the same if every nested MemberExpr refers to the same 15925 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15926 // the base Expr's are CXXThisExpr's. 15927 const Expr *LHSBase = LHSExpr; 15928 const Expr *RHSBase = RHSExpr; 15929 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15930 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15931 if (!LHSME || !RHSME) 15932 return; 15933 15934 while (LHSME && RHSME) { 15935 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15936 RHSME->getMemberDecl()->getCanonicalDecl()) 15937 return; 15938 15939 LHSBase = LHSME->getBase(); 15940 RHSBase = RHSME->getBase(); 15941 LHSME = dyn_cast<MemberExpr>(LHSBase); 15942 RHSME = dyn_cast<MemberExpr>(RHSBase); 15943 } 15944 15945 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15946 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15947 if (LHSDeclRef && RHSDeclRef) { 15948 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15949 return; 15950 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15951 RHSDeclRef->getDecl()->getCanonicalDecl()) 15952 return; 15953 15954 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15955 << LHSExpr->getSourceRange() 15956 << RHSExpr->getSourceRange(); 15957 return; 15958 } 15959 15960 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15961 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15962 << LHSExpr->getSourceRange() 15963 << RHSExpr->getSourceRange(); 15964 } 15965 15966 //===--- Layout compatibility ----------------------------------------------// 15967 15968 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15969 15970 /// Check if two enumeration types are layout-compatible. 15971 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15972 // C++11 [dcl.enum] p8: 15973 // Two enumeration types are layout-compatible if they have the same 15974 // underlying type. 15975 return ED1->isComplete() && ED2->isComplete() && 15976 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15977 } 15978 15979 /// Check if two fields are layout-compatible. 15980 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15981 FieldDecl *Field2) { 15982 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15983 return false; 15984 15985 if (Field1->isBitField() != Field2->isBitField()) 15986 return false; 15987 15988 if (Field1->isBitField()) { 15989 // Make sure that the bit-fields are the same length. 15990 unsigned Bits1 = Field1->getBitWidthValue(C); 15991 unsigned Bits2 = Field2->getBitWidthValue(C); 15992 15993 if (Bits1 != Bits2) 15994 return false; 15995 } 15996 15997 return true; 15998 } 15999 16000 /// Check if two standard-layout structs are layout-compatible. 16001 /// (C++11 [class.mem] p17) 16002 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16003 RecordDecl *RD2) { 16004 // If both records are C++ classes, check that base classes match. 16005 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16006 // If one of records is a CXXRecordDecl we are in C++ mode, 16007 // thus the other one is a CXXRecordDecl, too. 16008 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16009 // Check number of base classes. 16010 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16011 return false; 16012 16013 // Check the base classes. 16014 for (CXXRecordDecl::base_class_const_iterator 16015 Base1 = D1CXX->bases_begin(), 16016 BaseEnd1 = D1CXX->bases_end(), 16017 Base2 = D2CXX->bases_begin(); 16018 Base1 != BaseEnd1; 16019 ++Base1, ++Base2) { 16020 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16021 return false; 16022 } 16023 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16024 // If only RD2 is a C++ class, it should have zero base classes. 16025 if (D2CXX->getNumBases() > 0) 16026 return false; 16027 } 16028 16029 // Check the fields. 16030 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16031 Field2End = RD2->field_end(), 16032 Field1 = RD1->field_begin(), 16033 Field1End = RD1->field_end(); 16034 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16035 if (!isLayoutCompatible(C, *Field1, *Field2)) 16036 return false; 16037 } 16038 if (Field1 != Field1End || Field2 != Field2End) 16039 return false; 16040 16041 return true; 16042 } 16043 16044 /// Check if two standard-layout unions are layout-compatible. 16045 /// (C++11 [class.mem] p18) 16046 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16047 RecordDecl *RD2) { 16048 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16049 for (auto *Field2 : RD2->fields()) 16050 UnmatchedFields.insert(Field2); 16051 16052 for (auto *Field1 : RD1->fields()) { 16053 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16054 I = UnmatchedFields.begin(), 16055 E = UnmatchedFields.end(); 16056 16057 for ( ; I != E; ++I) { 16058 if (isLayoutCompatible(C, Field1, *I)) { 16059 bool Result = UnmatchedFields.erase(*I); 16060 (void) Result; 16061 assert(Result); 16062 break; 16063 } 16064 } 16065 if (I == E) 16066 return false; 16067 } 16068 16069 return UnmatchedFields.empty(); 16070 } 16071 16072 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16073 RecordDecl *RD2) { 16074 if (RD1->isUnion() != RD2->isUnion()) 16075 return false; 16076 16077 if (RD1->isUnion()) 16078 return isLayoutCompatibleUnion(C, RD1, RD2); 16079 else 16080 return isLayoutCompatibleStruct(C, RD1, RD2); 16081 } 16082 16083 /// Check if two types are layout-compatible in C++11 sense. 16084 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16085 if (T1.isNull() || T2.isNull()) 16086 return false; 16087 16088 // C++11 [basic.types] p11: 16089 // If two types T1 and T2 are the same type, then T1 and T2 are 16090 // layout-compatible types. 16091 if (C.hasSameType(T1, T2)) 16092 return true; 16093 16094 T1 = T1.getCanonicalType().getUnqualifiedType(); 16095 T2 = T2.getCanonicalType().getUnqualifiedType(); 16096 16097 const Type::TypeClass TC1 = T1->getTypeClass(); 16098 const Type::TypeClass TC2 = T2->getTypeClass(); 16099 16100 if (TC1 != TC2) 16101 return false; 16102 16103 if (TC1 == Type::Enum) { 16104 return isLayoutCompatible(C, 16105 cast<EnumType>(T1)->getDecl(), 16106 cast<EnumType>(T2)->getDecl()); 16107 } else if (TC1 == Type::Record) { 16108 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16109 return false; 16110 16111 return isLayoutCompatible(C, 16112 cast<RecordType>(T1)->getDecl(), 16113 cast<RecordType>(T2)->getDecl()); 16114 } 16115 16116 return false; 16117 } 16118 16119 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16120 16121 /// Given a type tag expression find the type tag itself. 16122 /// 16123 /// \param TypeExpr Type tag expression, as it appears in user's code. 16124 /// 16125 /// \param VD Declaration of an identifier that appears in a type tag. 16126 /// 16127 /// \param MagicValue Type tag magic value. 16128 /// 16129 /// \param isConstantEvaluated whether the evalaution should be performed in 16130 16131 /// constant context. 16132 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16133 const ValueDecl **VD, uint64_t *MagicValue, 16134 bool isConstantEvaluated) { 16135 while(true) { 16136 if (!TypeExpr) 16137 return false; 16138 16139 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16140 16141 switch (TypeExpr->getStmtClass()) { 16142 case Stmt::UnaryOperatorClass: { 16143 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16144 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16145 TypeExpr = UO->getSubExpr(); 16146 continue; 16147 } 16148 return false; 16149 } 16150 16151 case Stmt::DeclRefExprClass: { 16152 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16153 *VD = DRE->getDecl(); 16154 return true; 16155 } 16156 16157 case Stmt::IntegerLiteralClass: { 16158 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16159 llvm::APInt MagicValueAPInt = IL->getValue(); 16160 if (MagicValueAPInt.getActiveBits() <= 64) { 16161 *MagicValue = MagicValueAPInt.getZExtValue(); 16162 return true; 16163 } else 16164 return false; 16165 } 16166 16167 case Stmt::BinaryConditionalOperatorClass: 16168 case Stmt::ConditionalOperatorClass: { 16169 const AbstractConditionalOperator *ACO = 16170 cast<AbstractConditionalOperator>(TypeExpr); 16171 bool Result; 16172 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16173 isConstantEvaluated)) { 16174 if (Result) 16175 TypeExpr = ACO->getTrueExpr(); 16176 else 16177 TypeExpr = ACO->getFalseExpr(); 16178 continue; 16179 } 16180 return false; 16181 } 16182 16183 case Stmt::BinaryOperatorClass: { 16184 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16185 if (BO->getOpcode() == BO_Comma) { 16186 TypeExpr = BO->getRHS(); 16187 continue; 16188 } 16189 return false; 16190 } 16191 16192 default: 16193 return false; 16194 } 16195 } 16196 } 16197 16198 /// Retrieve the C type corresponding to type tag TypeExpr. 16199 /// 16200 /// \param TypeExpr Expression that specifies a type tag. 16201 /// 16202 /// \param MagicValues Registered magic values. 16203 /// 16204 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16205 /// kind. 16206 /// 16207 /// \param TypeInfo Information about the corresponding C type. 16208 /// 16209 /// \param isConstantEvaluated whether the evalaution should be performed in 16210 /// constant context. 16211 /// 16212 /// \returns true if the corresponding C type was found. 16213 static bool GetMatchingCType( 16214 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16215 const ASTContext &Ctx, 16216 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16217 *MagicValues, 16218 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16219 bool isConstantEvaluated) { 16220 FoundWrongKind = false; 16221 16222 // Variable declaration that has type_tag_for_datatype attribute. 16223 const ValueDecl *VD = nullptr; 16224 16225 uint64_t MagicValue; 16226 16227 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16228 return false; 16229 16230 if (VD) { 16231 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16232 if (I->getArgumentKind() != ArgumentKind) { 16233 FoundWrongKind = true; 16234 return false; 16235 } 16236 TypeInfo.Type = I->getMatchingCType(); 16237 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16238 TypeInfo.MustBeNull = I->getMustBeNull(); 16239 return true; 16240 } 16241 return false; 16242 } 16243 16244 if (!MagicValues) 16245 return false; 16246 16247 llvm::DenseMap<Sema::TypeTagMagicValue, 16248 Sema::TypeTagData>::const_iterator I = 16249 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16250 if (I == MagicValues->end()) 16251 return false; 16252 16253 TypeInfo = I->second; 16254 return true; 16255 } 16256 16257 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16258 uint64_t MagicValue, QualType Type, 16259 bool LayoutCompatible, 16260 bool MustBeNull) { 16261 if (!TypeTagForDatatypeMagicValues) 16262 TypeTagForDatatypeMagicValues.reset( 16263 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16264 16265 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16266 (*TypeTagForDatatypeMagicValues)[Magic] = 16267 TypeTagData(Type, LayoutCompatible, MustBeNull); 16268 } 16269 16270 static bool IsSameCharType(QualType T1, QualType T2) { 16271 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16272 if (!BT1) 16273 return false; 16274 16275 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16276 if (!BT2) 16277 return false; 16278 16279 BuiltinType::Kind T1Kind = BT1->getKind(); 16280 BuiltinType::Kind T2Kind = BT2->getKind(); 16281 16282 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16283 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16284 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16285 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16286 } 16287 16288 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16289 const ArrayRef<const Expr *> ExprArgs, 16290 SourceLocation CallSiteLoc) { 16291 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16292 bool IsPointerAttr = Attr->getIsPointer(); 16293 16294 // Retrieve the argument representing the 'type_tag'. 16295 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16296 if (TypeTagIdxAST >= ExprArgs.size()) { 16297 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16298 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16299 return; 16300 } 16301 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16302 bool FoundWrongKind; 16303 TypeTagData TypeInfo; 16304 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16305 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16306 TypeInfo, isConstantEvaluated())) { 16307 if (FoundWrongKind) 16308 Diag(TypeTagExpr->getExprLoc(), 16309 diag::warn_type_tag_for_datatype_wrong_kind) 16310 << TypeTagExpr->getSourceRange(); 16311 return; 16312 } 16313 16314 // Retrieve the argument representing the 'arg_idx'. 16315 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16316 if (ArgumentIdxAST >= ExprArgs.size()) { 16317 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16318 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16319 return; 16320 } 16321 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16322 if (IsPointerAttr) { 16323 // Skip implicit cast of pointer to `void *' (as a function argument). 16324 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16325 if (ICE->getType()->isVoidPointerType() && 16326 ICE->getCastKind() == CK_BitCast) 16327 ArgumentExpr = ICE->getSubExpr(); 16328 } 16329 QualType ArgumentType = ArgumentExpr->getType(); 16330 16331 // Passing a `void*' pointer shouldn't trigger a warning. 16332 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16333 return; 16334 16335 if (TypeInfo.MustBeNull) { 16336 // Type tag with matching void type requires a null pointer. 16337 if (!ArgumentExpr->isNullPointerConstant(Context, 16338 Expr::NPC_ValueDependentIsNotNull)) { 16339 Diag(ArgumentExpr->getExprLoc(), 16340 diag::warn_type_safety_null_pointer_required) 16341 << ArgumentKind->getName() 16342 << ArgumentExpr->getSourceRange() 16343 << TypeTagExpr->getSourceRange(); 16344 } 16345 return; 16346 } 16347 16348 QualType RequiredType = TypeInfo.Type; 16349 if (IsPointerAttr) 16350 RequiredType = Context.getPointerType(RequiredType); 16351 16352 bool mismatch = false; 16353 if (!TypeInfo.LayoutCompatible) { 16354 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16355 16356 // C++11 [basic.fundamental] p1: 16357 // Plain char, signed char, and unsigned char are three distinct types. 16358 // 16359 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16360 // char' depending on the current char signedness mode. 16361 if (mismatch) 16362 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16363 RequiredType->getPointeeType())) || 16364 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16365 mismatch = false; 16366 } else 16367 if (IsPointerAttr) 16368 mismatch = !isLayoutCompatible(Context, 16369 ArgumentType->getPointeeType(), 16370 RequiredType->getPointeeType()); 16371 else 16372 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16373 16374 if (mismatch) 16375 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16376 << ArgumentType << ArgumentKind 16377 << TypeInfo.LayoutCompatible << RequiredType 16378 << ArgumentExpr->getSourceRange() 16379 << TypeTagExpr->getSourceRange(); 16380 } 16381 16382 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16383 CharUnits Alignment) { 16384 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16385 } 16386 16387 void Sema::DiagnoseMisalignedMembers() { 16388 for (MisalignedMember &m : MisalignedMembers) { 16389 const NamedDecl *ND = m.RD; 16390 if (ND->getName().empty()) { 16391 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16392 ND = TD; 16393 } 16394 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16395 << m.MD << ND << m.E->getSourceRange(); 16396 } 16397 MisalignedMembers.clear(); 16398 } 16399 16400 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16401 E = E->IgnoreParens(); 16402 if (!T->isPointerType() && !T->isIntegerType()) 16403 return; 16404 if (isa<UnaryOperator>(E) && 16405 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16406 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16407 if (isa<MemberExpr>(Op)) { 16408 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16409 if (MA != MisalignedMembers.end() && 16410 (T->isIntegerType() || 16411 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16412 Context.getTypeAlignInChars( 16413 T->getPointeeType()) <= MA->Alignment)))) 16414 MisalignedMembers.erase(MA); 16415 } 16416 } 16417 } 16418 16419 void Sema::RefersToMemberWithReducedAlignment( 16420 Expr *E, 16421 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16422 Action) { 16423 const auto *ME = dyn_cast<MemberExpr>(E); 16424 if (!ME) 16425 return; 16426 16427 // No need to check expressions with an __unaligned-qualified type. 16428 if (E->getType().getQualifiers().hasUnaligned()) 16429 return; 16430 16431 // For a chain of MemberExpr like "a.b.c.d" this list 16432 // will keep FieldDecl's like [d, c, b]. 16433 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16434 const MemberExpr *TopME = nullptr; 16435 bool AnyIsPacked = false; 16436 do { 16437 QualType BaseType = ME->getBase()->getType(); 16438 if (BaseType->isDependentType()) 16439 return; 16440 if (ME->isArrow()) 16441 BaseType = BaseType->getPointeeType(); 16442 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16443 if (RD->isInvalidDecl()) 16444 return; 16445 16446 ValueDecl *MD = ME->getMemberDecl(); 16447 auto *FD = dyn_cast<FieldDecl>(MD); 16448 // We do not care about non-data members. 16449 if (!FD || FD->isInvalidDecl()) 16450 return; 16451 16452 AnyIsPacked = 16453 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16454 ReverseMemberChain.push_back(FD); 16455 16456 TopME = ME; 16457 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16458 } while (ME); 16459 assert(TopME && "We did not compute a topmost MemberExpr!"); 16460 16461 // Not the scope of this diagnostic. 16462 if (!AnyIsPacked) 16463 return; 16464 16465 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16466 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16467 // TODO: The innermost base of the member expression may be too complicated. 16468 // For now, just disregard these cases. This is left for future 16469 // improvement. 16470 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16471 return; 16472 16473 // Alignment expected by the whole expression. 16474 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16475 16476 // No need to do anything else with this case. 16477 if (ExpectedAlignment.isOne()) 16478 return; 16479 16480 // Synthesize offset of the whole access. 16481 CharUnits Offset; 16482 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16483 I++) { 16484 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16485 } 16486 16487 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16488 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16489 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16490 16491 // The base expression of the innermost MemberExpr may give 16492 // stronger guarantees than the class containing the member. 16493 if (DRE && !TopME->isArrow()) { 16494 const ValueDecl *VD = DRE->getDecl(); 16495 if (!VD->getType()->isReferenceType()) 16496 CompleteObjectAlignment = 16497 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16498 } 16499 16500 // Check if the synthesized offset fulfills the alignment. 16501 if (Offset % ExpectedAlignment != 0 || 16502 // It may fulfill the offset it but the effective alignment may still be 16503 // lower than the expected expression alignment. 16504 CompleteObjectAlignment < ExpectedAlignment) { 16505 // If this happens, we want to determine a sensible culprit of this. 16506 // Intuitively, watching the chain of member expressions from right to 16507 // left, we start with the required alignment (as required by the field 16508 // type) but some packed attribute in that chain has reduced the alignment. 16509 // It may happen that another packed structure increases it again. But if 16510 // we are here such increase has not been enough. So pointing the first 16511 // FieldDecl that either is packed or else its RecordDecl is, 16512 // seems reasonable. 16513 FieldDecl *FD = nullptr; 16514 CharUnits Alignment; 16515 for (FieldDecl *FDI : ReverseMemberChain) { 16516 if (FDI->hasAttr<PackedAttr>() || 16517 FDI->getParent()->hasAttr<PackedAttr>()) { 16518 FD = FDI; 16519 Alignment = std::min( 16520 Context.getTypeAlignInChars(FD->getType()), 16521 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16522 break; 16523 } 16524 } 16525 assert(FD && "We did not find a packed FieldDecl!"); 16526 Action(E, FD->getParent(), FD, Alignment); 16527 } 16528 } 16529 16530 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16531 using namespace std::placeholders; 16532 16533 RefersToMemberWithReducedAlignment( 16534 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16535 _2, _3, _4)); 16536 } 16537 16538 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16539 ExprResult CallResult) { 16540 if (checkArgCount(*this, TheCall, 1)) 16541 return ExprError(); 16542 16543 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16544 if (MatrixArg.isInvalid()) 16545 return MatrixArg; 16546 Expr *Matrix = MatrixArg.get(); 16547 16548 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16549 if (!MType) { 16550 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16551 return ExprError(); 16552 } 16553 16554 // Create returned matrix type by swapping rows and columns of the argument 16555 // matrix type. 16556 QualType ResultType = Context.getConstantMatrixType( 16557 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16558 16559 // Change the return type to the type of the returned matrix. 16560 TheCall->setType(ResultType); 16561 16562 // Update call argument to use the possibly converted matrix argument. 16563 TheCall->setArg(0, Matrix); 16564 return CallResult; 16565 } 16566 16567 // Get and verify the matrix dimensions. 16568 static llvm::Optional<unsigned> 16569 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16570 SourceLocation ErrorPos; 16571 Optional<llvm::APSInt> Value = 16572 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16573 if (!Value) { 16574 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16575 << Name; 16576 return {}; 16577 } 16578 uint64_t Dim = Value->getZExtValue(); 16579 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16580 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16581 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16582 return {}; 16583 } 16584 return Dim; 16585 } 16586 16587 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16588 ExprResult CallResult) { 16589 if (!getLangOpts().MatrixTypes) { 16590 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16591 return ExprError(); 16592 } 16593 16594 if (checkArgCount(*this, TheCall, 4)) 16595 return ExprError(); 16596 16597 unsigned PtrArgIdx = 0; 16598 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16599 Expr *RowsExpr = TheCall->getArg(1); 16600 Expr *ColumnsExpr = TheCall->getArg(2); 16601 Expr *StrideExpr = TheCall->getArg(3); 16602 16603 bool ArgError = false; 16604 16605 // Check pointer argument. 16606 { 16607 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16608 if (PtrConv.isInvalid()) 16609 return PtrConv; 16610 PtrExpr = PtrConv.get(); 16611 TheCall->setArg(0, PtrExpr); 16612 if (PtrExpr->isTypeDependent()) { 16613 TheCall->setType(Context.DependentTy); 16614 return TheCall; 16615 } 16616 } 16617 16618 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16619 QualType ElementTy; 16620 if (!PtrTy) { 16621 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16622 << PtrArgIdx + 1; 16623 ArgError = true; 16624 } else { 16625 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16626 16627 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16628 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16629 << PtrArgIdx + 1; 16630 ArgError = true; 16631 } 16632 } 16633 16634 // Apply default Lvalue conversions and convert the expression to size_t. 16635 auto ApplyArgumentConversions = [this](Expr *E) { 16636 ExprResult Conv = DefaultLvalueConversion(E); 16637 if (Conv.isInvalid()) 16638 return Conv; 16639 16640 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16641 }; 16642 16643 // Apply conversion to row and column expressions. 16644 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16645 if (!RowsConv.isInvalid()) { 16646 RowsExpr = RowsConv.get(); 16647 TheCall->setArg(1, RowsExpr); 16648 } else 16649 RowsExpr = nullptr; 16650 16651 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16652 if (!ColumnsConv.isInvalid()) { 16653 ColumnsExpr = ColumnsConv.get(); 16654 TheCall->setArg(2, ColumnsExpr); 16655 } else 16656 ColumnsExpr = nullptr; 16657 16658 // If any any part of the result matrix type is still pending, just use 16659 // Context.DependentTy, until all parts are resolved. 16660 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16661 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16662 TheCall->setType(Context.DependentTy); 16663 return CallResult; 16664 } 16665 16666 // Check row and column dimenions. 16667 llvm::Optional<unsigned> MaybeRows; 16668 if (RowsExpr) 16669 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16670 16671 llvm::Optional<unsigned> MaybeColumns; 16672 if (ColumnsExpr) 16673 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16674 16675 // Check stride argument. 16676 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16677 if (StrideConv.isInvalid()) 16678 return ExprError(); 16679 StrideExpr = StrideConv.get(); 16680 TheCall->setArg(3, StrideExpr); 16681 16682 if (MaybeRows) { 16683 if (Optional<llvm::APSInt> Value = 16684 StrideExpr->getIntegerConstantExpr(Context)) { 16685 uint64_t Stride = Value->getZExtValue(); 16686 if (Stride < *MaybeRows) { 16687 Diag(StrideExpr->getBeginLoc(), 16688 diag::err_builtin_matrix_stride_too_small); 16689 ArgError = true; 16690 } 16691 } 16692 } 16693 16694 if (ArgError || !MaybeRows || !MaybeColumns) 16695 return ExprError(); 16696 16697 TheCall->setType( 16698 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16699 return CallResult; 16700 } 16701 16702 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16703 ExprResult CallResult) { 16704 if (checkArgCount(*this, TheCall, 3)) 16705 return ExprError(); 16706 16707 unsigned PtrArgIdx = 1; 16708 Expr *MatrixExpr = TheCall->getArg(0); 16709 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16710 Expr *StrideExpr = TheCall->getArg(2); 16711 16712 bool ArgError = false; 16713 16714 { 16715 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16716 if (MatrixConv.isInvalid()) 16717 return MatrixConv; 16718 MatrixExpr = MatrixConv.get(); 16719 TheCall->setArg(0, MatrixExpr); 16720 } 16721 if (MatrixExpr->isTypeDependent()) { 16722 TheCall->setType(Context.DependentTy); 16723 return TheCall; 16724 } 16725 16726 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16727 if (!MatrixTy) { 16728 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16729 ArgError = true; 16730 } 16731 16732 { 16733 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16734 if (PtrConv.isInvalid()) 16735 return PtrConv; 16736 PtrExpr = PtrConv.get(); 16737 TheCall->setArg(1, PtrExpr); 16738 if (PtrExpr->isTypeDependent()) { 16739 TheCall->setType(Context.DependentTy); 16740 return TheCall; 16741 } 16742 } 16743 16744 // Check pointer argument. 16745 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16746 if (!PtrTy) { 16747 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16748 << PtrArgIdx + 1; 16749 ArgError = true; 16750 } else { 16751 QualType ElementTy = PtrTy->getPointeeType(); 16752 if (ElementTy.isConstQualified()) { 16753 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16754 ArgError = true; 16755 } 16756 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16757 if (MatrixTy && 16758 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16759 Diag(PtrExpr->getBeginLoc(), 16760 diag::err_builtin_matrix_pointer_arg_mismatch) 16761 << ElementTy << MatrixTy->getElementType(); 16762 ArgError = true; 16763 } 16764 } 16765 16766 // Apply default Lvalue conversions and convert the stride expression to 16767 // size_t. 16768 { 16769 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16770 if (StrideConv.isInvalid()) 16771 return StrideConv; 16772 16773 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16774 if (StrideConv.isInvalid()) 16775 return StrideConv; 16776 StrideExpr = StrideConv.get(); 16777 TheCall->setArg(2, StrideExpr); 16778 } 16779 16780 // Check stride argument. 16781 if (MatrixTy) { 16782 if (Optional<llvm::APSInt> Value = 16783 StrideExpr->getIntegerConstantExpr(Context)) { 16784 uint64_t Stride = Value->getZExtValue(); 16785 if (Stride < MatrixTy->getNumRows()) { 16786 Diag(StrideExpr->getBeginLoc(), 16787 diag::err_builtin_matrix_stride_too_small); 16788 ArgError = true; 16789 } 16790 } 16791 } 16792 16793 if (ArgError) 16794 return ExprError(); 16795 16796 return CallResult; 16797 } 16798 16799 /// \brief Enforce the bounds of a TCB 16800 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16801 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16802 /// and enforce_tcb_leaf attributes. 16803 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16804 const FunctionDecl *Callee) { 16805 const FunctionDecl *Caller = getCurFunctionDecl(); 16806 16807 // Calls to builtins are not enforced. 16808 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16809 Callee->getBuiltinID() != 0) 16810 return; 16811 16812 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16813 // all TCBs the callee is a part of. 16814 llvm::StringSet<> CalleeTCBs; 16815 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16816 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16817 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16818 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16819 16820 // Go through the TCBs the caller is a part of and emit warnings if Caller 16821 // is in a TCB that the Callee is not. 16822 for_each( 16823 Caller->specific_attrs<EnforceTCBAttr>(), 16824 [&](const auto *A) { 16825 StringRef CallerTCB = A->getTCBName(); 16826 if (CalleeTCBs.count(CallerTCB) == 0) { 16827 this->Diag(TheCall->getExprLoc(), 16828 diag::warn_tcb_enforcement_violation) << Callee 16829 << CallerTCB; 16830 } 16831 }); 16832 } 16833