1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/SaveAndRestore.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <bitset> 92 #include <cassert> 93 #include <cstddef> 94 #include <cstdint> 95 #include <functional> 96 #include <limits> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 using namespace sema; 103 104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 105 unsigned ByteNo) const { 106 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 107 Context.getTargetInfo()); 108 } 109 110 /// Checks that a call expression's argument count is the desired number. 111 /// This is useful when doing custom type-checking. Returns true on error. 112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 113 unsigned argCount = call->getNumArgs(); 114 if (argCount == desiredArgCount) return false; 115 116 if (argCount < desiredArgCount) 117 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 118 << 0 /*function call*/ << desiredArgCount << argCount 119 << call->getSourceRange(); 120 121 // Highlight all the excess arguments. 122 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 123 call->getArg(argCount - 1)->getEndLoc()); 124 125 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 126 << 0 /*function call*/ << desiredArgCount << argCount 127 << call->getArg(1)->getSourceRange(); 128 } 129 130 /// Check that the first argument to __builtin_annotation is an integer 131 /// and the second argument is a non-wide string literal. 132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 133 if (checkArgCount(S, TheCall, 2)) 134 return true; 135 136 // First argument should be an integer. 137 Expr *ValArg = TheCall->getArg(0); 138 QualType Ty = ValArg->getType(); 139 if (!Ty->isIntegerType()) { 140 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 141 << ValArg->getSourceRange(); 142 return true; 143 } 144 145 // Second argument should be a constant string. 146 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 147 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 148 if (!Literal || !Literal->isAscii()) { 149 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 150 << StrArg->getSourceRange(); 151 return true; 152 } 153 154 TheCall->setType(Ty); 155 return false; 156 } 157 158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 159 // We need at least one argument. 160 if (TheCall->getNumArgs() < 1) { 161 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 162 << 0 << 1 << TheCall->getNumArgs() 163 << TheCall->getCallee()->getSourceRange(); 164 return true; 165 } 166 167 // All arguments should be wide string literals. 168 for (Expr *Arg : TheCall->arguments()) { 169 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 170 if (!Literal || !Literal->isWide()) { 171 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 172 << Arg->getSourceRange(); 173 return true; 174 } 175 } 176 177 return false; 178 } 179 180 /// Check that the argument to __builtin_addressof is a glvalue, and set the 181 /// result type to the corresponding pointer type. 182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 183 if (checkArgCount(S, TheCall, 1)) 184 return true; 185 186 ExprResult Arg(TheCall->getArg(0)); 187 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 188 if (ResultType.isNull()) 189 return true; 190 191 TheCall->setArg(0, Arg.get()); 192 TheCall->setType(ResultType); 193 return false; 194 } 195 196 /// Check the number of arguments and set the result type to 197 /// the argument type. 198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 199 if (checkArgCount(S, TheCall, 1)) 200 return true; 201 202 TheCall->setType(TheCall->getArg(0)->getType()); 203 return false; 204 } 205 206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 208 /// type (but not a function pointer) and that the alignment is a power-of-two. 209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 210 if (checkArgCount(S, TheCall, 2)) 211 return true; 212 213 clang::Expr *Source = TheCall->getArg(0); 214 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 215 216 auto IsValidIntegerType = [](QualType Ty) { 217 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 218 }; 219 QualType SrcTy = Source->getType(); 220 // We should also be able to use it with arrays (but not functions!). 221 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 222 SrcTy = S.Context.getDecayedType(SrcTy); 223 } 224 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 225 SrcTy->isFunctionPointerType()) { 226 // FIXME: this is not quite the right error message since we don't allow 227 // floating point types, or member pointers. 228 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 229 << SrcTy; 230 return true; 231 } 232 233 clang::Expr *AlignOp = TheCall->getArg(1); 234 if (!IsValidIntegerType(AlignOp->getType())) { 235 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 236 << AlignOp->getType(); 237 return true; 238 } 239 Expr::EvalResult AlignResult; 240 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 241 // We can't check validity of alignment if it is value dependent. 242 if (!AlignOp->isValueDependent() && 243 AlignOp->EvaluateAsInt(AlignResult, S.Context, 244 Expr::SE_AllowSideEffects)) { 245 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 246 llvm::APSInt MaxValue( 247 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 248 if (AlignValue < 1) { 249 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 250 return true; 251 } 252 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 253 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 254 << MaxValue.toString(10); 255 return true; 256 } 257 if (!AlignValue.isPowerOf2()) { 258 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 259 return true; 260 } 261 if (AlignValue == 1) { 262 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 263 << IsBooleanAlignBuiltin; 264 } 265 } 266 267 ExprResult SrcArg = S.PerformCopyInitialization( 268 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 269 SourceLocation(), Source); 270 if (SrcArg.isInvalid()) 271 return true; 272 TheCall->setArg(0, SrcArg.get()); 273 ExprResult AlignArg = 274 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 275 S.Context, AlignOp->getType(), false), 276 SourceLocation(), AlignOp); 277 if (AlignArg.isInvalid()) 278 return true; 279 TheCall->setArg(1, AlignArg.get()); 280 // For align_up/align_down, the return type is the same as the (potentially 281 // decayed) argument type including qualifiers. For is_aligned(), the result 282 // is always bool. 283 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 284 return false; 285 } 286 287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 288 unsigned BuiltinID) { 289 if (checkArgCount(S, TheCall, 3)) 290 return true; 291 292 // First two arguments should be integers. 293 for (unsigned I = 0; I < 2; ++I) { 294 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 295 if (Arg.isInvalid()) return true; 296 TheCall->setArg(I, Arg.get()); 297 298 QualType Ty = Arg.get()->getType(); 299 if (!Ty->isIntegerType()) { 300 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 301 << Ty << Arg.get()->getSourceRange(); 302 return true; 303 } 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 311 if (Arg.isInvalid()) return true; 312 TheCall->setArg(2, Arg.get()); 313 314 QualType Ty = Arg.get()->getType(); 315 const auto *PtrTy = Ty->getAs<PointerType>(); 316 if (!PtrTy || 317 !PtrTy->getPointeeType()->isIntegerType() || 318 PtrTy->getPointeeType().isConstQualified()) { 319 S.Diag(Arg.get()->getBeginLoc(), 320 diag::err_overflow_builtin_must_be_ptr_int) 321 << Ty << Arg.get()->getSourceRange(); 322 return true; 323 } 324 } 325 326 // Disallow signed ExtIntType args larger than 128 bits to mul function until 327 // we improve backend support. 328 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 329 for (unsigned I = 0; I < 3; ++I) { 330 const auto Arg = TheCall->getArg(I); 331 // Third argument will be a pointer. 332 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 333 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 334 S.getASTContext().getIntWidth(Ty) > 128) 335 return S.Diag(Arg->getBeginLoc(), 336 diag::err_overflow_builtin_ext_int_max_size) 337 << 128; 338 } 339 } 340 341 return false; 342 } 343 344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 345 if (checkArgCount(S, BuiltinCall, 2)) 346 return true; 347 348 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 349 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 350 Expr *Call = BuiltinCall->getArg(0); 351 Expr *Chain = BuiltinCall->getArg(1); 352 353 if (Call->getStmtClass() != Stmt::CallExprClass) { 354 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 355 << Call->getSourceRange(); 356 return true; 357 } 358 359 auto CE = cast<CallExpr>(Call); 360 if (CE->getCallee()->getType()->isBlockPointerType()) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 const Decl *TargetDecl = CE->getCalleeDecl(); 367 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 368 if (FD->getBuiltinID()) { 369 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 370 << Call->getSourceRange(); 371 return true; 372 } 373 374 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 375 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 376 << Call->getSourceRange(); 377 return true; 378 } 379 380 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 381 if (ChainResult.isInvalid()) 382 return true; 383 if (!ChainResult.get()->getType()->isPointerType()) { 384 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 385 << Chain->getSourceRange(); 386 return true; 387 } 388 389 QualType ReturnTy = CE->getCallReturnType(S.Context); 390 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 391 QualType BuiltinTy = S.Context.getFunctionType( 392 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 393 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 394 395 Builtin = 396 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 397 398 BuiltinCall->setType(CE->getType()); 399 BuiltinCall->setValueKind(CE->getValueKind()); 400 BuiltinCall->setObjectKind(CE->getObjectKind()); 401 BuiltinCall->setCallee(Builtin); 402 BuiltinCall->setArg(1, ChainResult.get()); 403 404 return false; 405 } 406 407 namespace { 408 409 class EstimateSizeFormatHandler 410 : public analyze_format_string::FormatStringHandler { 411 size_t Size; 412 413 public: 414 EstimateSizeFormatHandler(StringRef Format) 415 : Size(std::min(Format.find(0), Format.size()) + 416 1 /* null byte always written by sprintf */) {} 417 418 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 419 const char *, unsigned SpecifierLen) override { 420 421 const size_t FieldWidth = computeFieldWidth(FS); 422 const size_t Precision = computePrecision(FS); 423 424 // The actual format. 425 switch (FS.getConversionSpecifier().getKind()) { 426 // Just a char. 427 case analyze_format_string::ConversionSpecifier::cArg: 428 case analyze_format_string::ConversionSpecifier::CArg: 429 Size += std::max(FieldWidth, (size_t)1); 430 break; 431 // Just an integer. 432 case analyze_format_string::ConversionSpecifier::dArg: 433 case analyze_format_string::ConversionSpecifier::DArg: 434 case analyze_format_string::ConversionSpecifier::iArg: 435 case analyze_format_string::ConversionSpecifier::oArg: 436 case analyze_format_string::ConversionSpecifier::OArg: 437 case analyze_format_string::ConversionSpecifier::uArg: 438 case analyze_format_string::ConversionSpecifier::UArg: 439 case analyze_format_string::ConversionSpecifier::xArg: 440 case analyze_format_string::ConversionSpecifier::XArg: 441 Size += std::max(FieldWidth, Precision); 442 break; 443 444 // %g style conversion switches between %f or %e style dynamically. 445 // %f always takes less space, so default to it. 446 case analyze_format_string::ConversionSpecifier::gArg: 447 case analyze_format_string::ConversionSpecifier::GArg: 448 449 // Floating point number in the form '[+]ddd.ddd'. 450 case analyze_format_string::ConversionSpecifier::fArg: 451 case analyze_format_string::ConversionSpecifier::FArg: 452 Size += std::max(FieldWidth, 1 /* integer part */ + 453 (Precision ? 1 + Precision 454 : 0) /* period + decimal */); 455 break; 456 457 // Floating point number in the form '[-]d.ddde[+-]dd'. 458 case analyze_format_string::ConversionSpecifier::eArg: 459 case analyze_format_string::ConversionSpecifier::EArg: 460 Size += 461 std::max(FieldWidth, 462 1 /* integer part */ + 463 (Precision ? 1 + Precision : 0) /* period + decimal */ + 464 1 /* e or E letter */ + 2 /* exponent */); 465 break; 466 467 // Floating point number in the form '[-]0xh.hhhhp±dd'. 468 case analyze_format_string::ConversionSpecifier::aArg: 469 case analyze_format_string::ConversionSpecifier::AArg: 470 Size += 471 std::max(FieldWidth, 472 2 /* 0x */ + 1 /* integer part */ + 473 (Precision ? 1 + Precision : 0) /* period + decimal */ + 474 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 475 break; 476 477 // Just a string. 478 case analyze_format_string::ConversionSpecifier::sArg: 479 case analyze_format_string::ConversionSpecifier::SArg: 480 Size += FieldWidth; 481 break; 482 483 // Just a pointer in the form '0xddd'. 484 case analyze_format_string::ConversionSpecifier::pArg: 485 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 486 break; 487 488 // A plain percent. 489 case analyze_format_string::ConversionSpecifier::PercentArg: 490 Size += 1; 491 break; 492 493 default: 494 break; 495 } 496 497 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 498 499 if (FS.hasAlternativeForm()) { 500 switch (FS.getConversionSpecifier().getKind()) { 501 default: 502 break; 503 // Force a leading '0'. 504 case analyze_format_string::ConversionSpecifier::oArg: 505 Size += 1; 506 break; 507 // Force a leading '0x'. 508 case analyze_format_string::ConversionSpecifier::xArg: 509 case analyze_format_string::ConversionSpecifier::XArg: 510 Size += 2; 511 break; 512 // Force a period '.' before decimal, even if precision is 0. 513 case analyze_format_string::ConversionSpecifier::aArg: 514 case analyze_format_string::ConversionSpecifier::AArg: 515 case analyze_format_string::ConversionSpecifier::eArg: 516 case analyze_format_string::ConversionSpecifier::EArg: 517 case analyze_format_string::ConversionSpecifier::fArg: 518 case analyze_format_string::ConversionSpecifier::FArg: 519 case analyze_format_string::ConversionSpecifier::gArg: 520 case analyze_format_string::ConversionSpecifier::GArg: 521 Size += (Precision ? 0 : 1); 522 break; 523 } 524 } 525 assert(SpecifierLen <= Size && "no underflow"); 526 Size -= SpecifierLen; 527 return true; 528 } 529 530 size_t getSizeLowerBound() const { return Size; } 531 532 private: 533 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 534 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 535 size_t FieldWidth = 0; 536 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 537 FieldWidth = FW.getConstantAmount(); 538 return FieldWidth; 539 } 540 541 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 542 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 543 size_t Precision = 0; 544 545 // See man 3 printf for default precision value based on the specifier. 546 switch (FW.getHowSpecified()) { 547 case analyze_format_string::OptionalAmount::NotSpecified: 548 switch (FS.getConversionSpecifier().getKind()) { 549 default: 550 break; 551 case analyze_format_string::ConversionSpecifier::dArg: // %d 552 case analyze_format_string::ConversionSpecifier::DArg: // %D 553 case analyze_format_string::ConversionSpecifier::iArg: // %i 554 Precision = 1; 555 break; 556 case analyze_format_string::ConversionSpecifier::oArg: // %d 557 case analyze_format_string::ConversionSpecifier::OArg: // %D 558 case analyze_format_string::ConversionSpecifier::uArg: // %d 559 case analyze_format_string::ConversionSpecifier::UArg: // %D 560 case analyze_format_string::ConversionSpecifier::xArg: // %d 561 case analyze_format_string::ConversionSpecifier::XArg: // %D 562 Precision = 1; 563 break; 564 case analyze_format_string::ConversionSpecifier::fArg: // %f 565 case analyze_format_string::ConversionSpecifier::FArg: // %F 566 case analyze_format_string::ConversionSpecifier::eArg: // %e 567 case analyze_format_string::ConversionSpecifier::EArg: // %E 568 case analyze_format_string::ConversionSpecifier::gArg: // %g 569 case analyze_format_string::ConversionSpecifier::GArg: // %G 570 Precision = 6; 571 break; 572 case analyze_format_string::ConversionSpecifier::pArg: // %d 573 Precision = 1; 574 break; 575 } 576 break; 577 case analyze_format_string::OptionalAmount::Constant: 578 Precision = FW.getConstantAmount(); 579 break; 580 default: 581 break; 582 } 583 return Precision; 584 } 585 }; 586 587 } // namespace 588 589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 590 /// __builtin_*_chk function, then use the object size argument specified in the 591 /// source. Otherwise, infer the object size using __builtin_object_size. 592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 593 CallExpr *TheCall) { 594 // FIXME: There are some more useful checks we could be doing here: 595 // - Evaluate strlen of strcpy arguments, use as object size. 596 597 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 598 isConstantEvaluated()) 599 return; 600 601 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 602 if (!BuiltinID) 603 return; 604 605 const TargetInfo &TI = getASTContext().getTargetInfo(); 606 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 607 608 unsigned DiagID = 0; 609 bool IsChkVariant = false; 610 Optional<llvm::APSInt> UsedSize; 611 unsigned SizeIndex, ObjectIndex; 612 switch (BuiltinID) { 613 default: 614 return; 615 case Builtin::BIsprintf: 616 case Builtin::BI__builtin___sprintf_chk: { 617 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 618 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 619 620 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 621 622 if (!Format->isAscii() && !Format->isUTF8()) 623 return; 624 625 StringRef FormatStrRef = Format->getString(); 626 EstimateSizeFormatHandler H(FormatStrRef); 627 const char *FormatBytes = FormatStrRef.data(); 628 const ConstantArrayType *T = 629 Context.getAsConstantArrayType(Format->getType()); 630 assert(T && "String literal not of constant array type!"); 631 size_t TypeSize = T->getSize().getZExtValue(); 632 633 // In case there's a null byte somewhere. 634 size_t StrLen = 635 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 636 if (!analyze_format_string::ParsePrintfString( 637 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 638 Context.getTargetInfo(), false)) { 639 DiagID = diag::warn_fortify_source_format_overflow; 640 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 641 .extOrTrunc(SizeTypeWidth); 642 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 643 IsChkVariant = true; 644 ObjectIndex = 2; 645 } else { 646 IsChkVariant = false; 647 ObjectIndex = 0; 648 } 649 break; 650 } 651 } 652 return; 653 } 654 case Builtin::BI__builtin___memcpy_chk: 655 case Builtin::BI__builtin___memmove_chk: 656 case Builtin::BI__builtin___memset_chk: 657 case Builtin::BI__builtin___strlcat_chk: 658 case Builtin::BI__builtin___strlcpy_chk: 659 case Builtin::BI__builtin___strncat_chk: 660 case Builtin::BI__builtin___strncpy_chk: 661 case Builtin::BI__builtin___stpncpy_chk: 662 case Builtin::BI__builtin___memccpy_chk: 663 case Builtin::BI__builtin___mempcpy_chk: { 664 DiagID = diag::warn_builtin_chk_overflow; 665 IsChkVariant = true; 666 SizeIndex = TheCall->getNumArgs() - 2; 667 ObjectIndex = TheCall->getNumArgs() - 1; 668 break; 669 } 670 671 case Builtin::BI__builtin___snprintf_chk: 672 case Builtin::BI__builtin___vsnprintf_chk: { 673 DiagID = diag::warn_builtin_chk_overflow; 674 IsChkVariant = true; 675 SizeIndex = 1; 676 ObjectIndex = 3; 677 break; 678 } 679 680 case Builtin::BIstrncat: 681 case Builtin::BI__builtin_strncat: 682 case Builtin::BIstrncpy: 683 case Builtin::BI__builtin_strncpy: 684 case Builtin::BIstpncpy: 685 case Builtin::BI__builtin_stpncpy: { 686 // Whether these functions overflow depends on the runtime strlen of the 687 // string, not just the buffer size, so emitting the "always overflow" 688 // diagnostic isn't quite right. We should still diagnose passing a buffer 689 // size larger than the destination buffer though; this is a runtime abort 690 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 691 DiagID = diag::warn_fortify_source_size_mismatch; 692 SizeIndex = TheCall->getNumArgs() - 1; 693 ObjectIndex = 0; 694 break; 695 } 696 697 case Builtin::BImemcpy: 698 case Builtin::BI__builtin_memcpy: 699 case Builtin::BImemmove: 700 case Builtin::BI__builtin_memmove: 701 case Builtin::BImemset: 702 case Builtin::BI__builtin_memset: 703 case Builtin::BImempcpy: 704 case Builtin::BI__builtin_mempcpy: { 705 DiagID = diag::warn_fortify_source_overflow; 706 SizeIndex = TheCall->getNumArgs() - 1; 707 ObjectIndex = 0; 708 break; 709 } 710 case Builtin::BIsnprintf: 711 case Builtin::BI__builtin_snprintf: 712 case Builtin::BIvsnprintf: 713 case Builtin::BI__builtin_vsnprintf: { 714 DiagID = diag::warn_fortify_source_size_mismatch; 715 SizeIndex = 1; 716 ObjectIndex = 0; 717 break; 718 } 719 } 720 721 llvm::APSInt ObjectSize; 722 // For __builtin___*_chk, the object size is explicitly provided by the caller 723 // (usually using __builtin_object_size). Use that value to check this call. 724 if (IsChkVariant) { 725 Expr::EvalResult Result; 726 Expr *SizeArg = TheCall->getArg(ObjectIndex); 727 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 728 return; 729 ObjectSize = Result.Val.getInt(); 730 731 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 732 } else { 733 // If the parameter has a pass_object_size attribute, then we should use its 734 // (potentially) more strict checking mode. Otherwise, conservatively assume 735 // type 0. 736 int BOSType = 0; 737 if (const auto *POS = 738 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 739 BOSType = POS->getType(); 740 741 Expr *ObjArg = TheCall->getArg(ObjectIndex); 742 uint64_t Result; 743 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 744 return; 745 // Get the object size in the target's size_t width. 746 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 747 } 748 749 // Evaluate the number of bytes of the object that this call will use. 750 if (!UsedSize) { 751 Expr::EvalResult Result; 752 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 753 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 754 return; 755 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 756 } 757 758 if (UsedSize.getValue().ule(ObjectSize)) 759 return; 760 761 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 762 // Skim off the details of whichever builtin was called to produce a better 763 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 764 if (IsChkVariant) { 765 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 766 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 767 } else if (FunctionName.startswith("__builtin_")) { 768 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 769 } 770 771 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 772 PDiag(DiagID) 773 << FunctionName << ObjectSize.toString(/*Radix=*/10) 774 << UsedSize.getValue().toString(/*Radix=*/10)); 775 } 776 777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 778 Scope::ScopeFlags NeededScopeFlags, 779 unsigned DiagID) { 780 // Scopes aren't available during instantiation. Fortunately, builtin 781 // functions cannot be template args so they cannot be formed through template 782 // instantiation. Therefore checking once during the parse is sufficient. 783 if (SemaRef.inTemplateInstantiation()) 784 return false; 785 786 Scope *S = SemaRef.getCurScope(); 787 while (S && !S->isSEHExceptScope()) 788 S = S->getParent(); 789 if (!S || !(S->getFlags() & NeededScopeFlags)) { 790 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 791 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 792 << DRE->getDecl()->getIdentifier(); 793 return true; 794 } 795 796 return false; 797 } 798 799 static inline bool isBlockPointer(Expr *Arg) { 800 return Arg->getType()->isBlockPointerType(); 801 } 802 803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 804 /// void*, which is a requirement of device side enqueue. 805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 806 const BlockPointerType *BPT = 807 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 808 ArrayRef<QualType> Params = 809 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 810 unsigned ArgCounter = 0; 811 bool IllegalParams = false; 812 // Iterate through the block parameters until either one is found that is not 813 // a local void*, or the block is valid. 814 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 815 I != E; ++I, ++ArgCounter) { 816 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 817 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 818 LangAS::opencl_local) { 819 // Get the location of the error. If a block literal has been passed 820 // (BlockExpr) then we can point straight to the offending argument, 821 // else we just point to the variable reference. 822 SourceLocation ErrorLoc; 823 if (isa<BlockExpr>(BlockArg)) { 824 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 825 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 826 } else if (isa<DeclRefExpr>(BlockArg)) { 827 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 828 } 829 S.Diag(ErrorLoc, 830 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 831 IllegalParams = true; 832 } 833 } 834 835 return IllegalParams; 836 } 837 838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 839 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 840 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 841 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 842 return true; 843 } 844 return false; 845 } 846 847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 848 if (checkArgCount(S, TheCall, 2)) 849 return true; 850 851 if (checkOpenCLSubgroupExt(S, TheCall)) 852 return true; 853 854 // First argument is an ndrange_t type. 855 Expr *NDRangeArg = TheCall->getArg(0); 856 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 857 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 858 << TheCall->getDirectCallee() << "'ndrange_t'"; 859 return true; 860 } 861 862 Expr *BlockArg = TheCall->getArg(1); 863 if (!isBlockPointer(BlockArg)) { 864 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 865 << TheCall->getDirectCallee() << "block"; 866 return true; 867 } 868 return checkOpenCLBlockArgs(S, BlockArg); 869 } 870 871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 872 /// get_kernel_work_group_size 873 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 875 if (checkArgCount(S, TheCall, 1)) 876 return true; 877 878 Expr *BlockArg = TheCall->getArg(0); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// Diagnose integer type and any valid implicit conversion to it. 888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 889 const QualType &IntType); 890 891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 892 unsigned Start, unsigned End) { 893 bool IllegalParams = false; 894 for (unsigned I = Start; I <= End; ++I) 895 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 896 S.Context.getSizeType()); 897 return IllegalParams; 898 } 899 900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 901 /// 'local void*' parameter of passed block. 902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 903 Expr *BlockArg, 904 unsigned NumNonVarArgs) { 905 const BlockPointerType *BPT = 906 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 907 unsigned NumBlockParams = 908 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 909 unsigned TotalNumArgs = TheCall->getNumArgs(); 910 911 // For each argument passed to the block, a corresponding uint needs to 912 // be passed to describe the size of the local memory. 913 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 914 S.Diag(TheCall->getBeginLoc(), 915 diag::err_opencl_enqueue_kernel_local_size_args); 916 return true; 917 } 918 919 // Check that the sizes of the local memory are specified by integers. 920 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 921 TotalNumArgs - 1); 922 } 923 924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 925 /// overload formats specified in Table 6.13.17.1. 926 /// int enqueue_kernel(queue_t queue, 927 /// kernel_enqueue_flags_t flags, 928 /// const ndrange_t ndrange, 929 /// void (^block)(void)) 930 /// int enqueue_kernel(queue_t queue, 931 /// kernel_enqueue_flags_t flags, 932 /// const ndrange_t ndrange, 933 /// uint num_events_in_wait_list, 934 /// clk_event_t *event_wait_list, 935 /// clk_event_t *event_ret, 936 /// void (^block)(void)) 937 /// int enqueue_kernel(queue_t queue, 938 /// kernel_enqueue_flags_t flags, 939 /// const ndrange_t ndrange, 940 /// void (^block)(local void*, ...), 941 /// uint size0, ...) 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// uint num_events_in_wait_list, 946 /// clk_event_t *event_wait_list, 947 /// clk_event_t *event_ret, 948 /// void (^block)(local void*, ...), 949 /// uint size0, ...) 950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 951 unsigned NumArgs = TheCall->getNumArgs(); 952 953 if (NumArgs < 4) { 954 S.Diag(TheCall->getBeginLoc(), 955 diag::err_typecheck_call_too_few_args_at_least) 956 << 0 << 4 << NumArgs; 957 return true; 958 } 959 960 Expr *Arg0 = TheCall->getArg(0); 961 Expr *Arg1 = TheCall->getArg(1); 962 Expr *Arg2 = TheCall->getArg(2); 963 Expr *Arg3 = TheCall->getArg(3); 964 965 // First argument always needs to be a queue_t type. 966 if (!Arg0->getType()->isQueueT()) { 967 S.Diag(TheCall->getArg(0)->getBeginLoc(), 968 diag::err_opencl_builtin_expected_type) 969 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 970 return true; 971 } 972 973 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 974 if (!Arg1->getType()->isIntegerType()) { 975 S.Diag(TheCall->getArg(1)->getBeginLoc(), 976 diag::err_opencl_builtin_expected_type) 977 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 978 return true; 979 } 980 981 // Third argument is always an ndrange_t type. 982 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 983 S.Diag(TheCall->getArg(2)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << "'ndrange_t'"; 986 return true; 987 } 988 989 // With four arguments, there is only one form that the function could be 990 // called in: no events and no variable arguments. 991 if (NumArgs == 4) { 992 // check that the last argument is the right block type. 993 if (!isBlockPointer(Arg3)) { 994 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 995 << TheCall->getDirectCallee() << "block"; 996 return true; 997 } 998 // we have a block type, check the prototype 999 const BlockPointerType *BPT = 1000 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1001 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1002 S.Diag(Arg3->getBeginLoc(), 1003 diag::err_opencl_enqueue_kernel_blocks_no_args); 1004 return true; 1005 } 1006 return false; 1007 } 1008 // we can have block + varargs. 1009 if (isBlockPointer(Arg3)) 1010 return (checkOpenCLBlockArgs(S, Arg3) || 1011 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1012 // last two cases with either exactly 7 args or 7 args and varargs. 1013 if (NumArgs >= 7) { 1014 // check common block argument. 1015 Expr *Arg6 = TheCall->getArg(6); 1016 if (!isBlockPointer(Arg6)) { 1017 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1018 << TheCall->getDirectCallee() << "block"; 1019 return true; 1020 } 1021 if (checkOpenCLBlockArgs(S, Arg6)) 1022 return true; 1023 1024 // Forth argument has to be any integer type. 1025 if (!Arg3->getType()->isIntegerType()) { 1026 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1027 diag::err_opencl_builtin_expected_type) 1028 << TheCall->getDirectCallee() << "integer"; 1029 return true; 1030 } 1031 // check remaining common arguments. 1032 Expr *Arg4 = TheCall->getArg(4); 1033 Expr *Arg5 = TheCall->getArg(5); 1034 1035 // Fifth argument is always passed as a pointer to clk_event_t. 1036 if (!Arg4->isNullPointerConstant(S.Context, 1037 Expr::NPC_ValueDependentIsNotNull) && 1038 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1039 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1040 diag::err_opencl_builtin_expected_type) 1041 << TheCall->getDirectCallee() 1042 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1043 return true; 1044 } 1045 1046 // Sixth argument is always passed as a pointer to clk_event_t. 1047 if (!Arg5->isNullPointerConstant(S.Context, 1048 Expr::NPC_ValueDependentIsNotNull) && 1049 !(Arg5->getType()->isPointerType() && 1050 Arg5->getType()->getPointeeType()->isClkEventT())) { 1051 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1052 diag::err_opencl_builtin_expected_type) 1053 << TheCall->getDirectCallee() 1054 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1055 return true; 1056 } 1057 1058 if (NumArgs == 7) 1059 return false; 1060 1061 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1062 } 1063 1064 // None of the specific case has been detected, give generic error 1065 S.Diag(TheCall->getBeginLoc(), 1066 diag::err_opencl_enqueue_kernel_incorrect_args); 1067 return true; 1068 } 1069 1070 /// Returns OpenCL access qual. 1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1072 return D->getAttr<OpenCLAccessAttr>(); 1073 } 1074 1075 /// Returns true if pipe element type is different from the pointer. 1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1077 const Expr *Arg0 = Call->getArg(0); 1078 // First argument type should always be pipe. 1079 if (!Arg0->getType()->isPipeType()) { 1080 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1081 << Call->getDirectCallee() << Arg0->getSourceRange(); 1082 return true; 1083 } 1084 OpenCLAccessAttr *AccessQual = 1085 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1086 // Validates the access qualifier is compatible with the call. 1087 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1088 // read_only and write_only, and assumed to be read_only if no qualifier is 1089 // specified. 1090 switch (Call->getDirectCallee()->getBuiltinID()) { 1091 case Builtin::BIread_pipe: 1092 case Builtin::BIreserve_read_pipe: 1093 case Builtin::BIcommit_read_pipe: 1094 case Builtin::BIwork_group_reserve_read_pipe: 1095 case Builtin::BIsub_group_reserve_read_pipe: 1096 case Builtin::BIwork_group_commit_read_pipe: 1097 case Builtin::BIsub_group_commit_read_pipe: 1098 if (!(!AccessQual || AccessQual->isReadOnly())) { 1099 S.Diag(Arg0->getBeginLoc(), 1100 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1101 << "read_only" << Arg0->getSourceRange(); 1102 return true; 1103 } 1104 break; 1105 case Builtin::BIwrite_pipe: 1106 case Builtin::BIreserve_write_pipe: 1107 case Builtin::BIcommit_write_pipe: 1108 case Builtin::BIwork_group_reserve_write_pipe: 1109 case Builtin::BIsub_group_reserve_write_pipe: 1110 case Builtin::BIwork_group_commit_write_pipe: 1111 case Builtin::BIsub_group_commit_write_pipe: 1112 if (!(AccessQual && AccessQual->isWriteOnly())) { 1113 S.Diag(Arg0->getBeginLoc(), 1114 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1115 << "write_only" << Arg0->getSourceRange(); 1116 return true; 1117 } 1118 break; 1119 default: 1120 break; 1121 } 1122 return false; 1123 } 1124 1125 /// Returns true if pipe element type is different from the pointer. 1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1127 const Expr *Arg0 = Call->getArg(0); 1128 const Expr *ArgIdx = Call->getArg(Idx); 1129 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1130 const QualType EltTy = PipeTy->getElementType(); 1131 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1132 // The Idx argument should be a pointer and the type of the pointer and 1133 // the type of pipe element should also be the same. 1134 if (!ArgTy || 1135 !S.Context.hasSameType( 1136 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1137 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1138 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1139 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1140 return true; 1141 } 1142 return false; 1143 } 1144 1145 // Performs semantic analysis for the read/write_pipe call. 1146 // \param S Reference to the semantic analyzer. 1147 // \param Call A pointer to the builtin call. 1148 // \return True if a semantic error has been found, false otherwise. 1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1150 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1151 // functions have two forms. 1152 switch (Call->getNumArgs()) { 1153 case 2: 1154 if (checkOpenCLPipeArg(S, Call)) 1155 return true; 1156 // The call with 2 arguments should be 1157 // read/write_pipe(pipe T, T*). 1158 // Check packet type T. 1159 if (checkOpenCLPipePacketType(S, Call, 1)) 1160 return true; 1161 break; 1162 1163 case 4: { 1164 if (checkOpenCLPipeArg(S, Call)) 1165 return true; 1166 // The call with 4 arguments should be 1167 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1168 // Check reserve_id_t. 1169 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1170 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1171 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1172 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1173 return true; 1174 } 1175 1176 // Check the index. 1177 const Expr *Arg2 = Call->getArg(2); 1178 if (!Arg2->getType()->isIntegerType() && 1179 !Arg2->getType()->isUnsignedIntegerType()) { 1180 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1181 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1182 << Arg2->getType() << Arg2->getSourceRange(); 1183 return true; 1184 } 1185 1186 // Check packet type T. 1187 if (checkOpenCLPipePacketType(S, Call, 3)) 1188 return true; 1189 } break; 1190 default: 1191 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1192 << Call->getDirectCallee() << Call->getSourceRange(); 1193 return true; 1194 } 1195 1196 return false; 1197 } 1198 1199 // Performs a semantic analysis on the {work_group_/sub_group_ 1200 // /_}reserve_{read/write}_pipe 1201 // \param S Reference to the semantic analyzer. 1202 // \param Call The call to the builtin function to be analyzed. 1203 // \return True if a semantic error was found, false otherwise. 1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1205 if (checkArgCount(S, Call, 2)) 1206 return true; 1207 1208 if (checkOpenCLPipeArg(S, Call)) 1209 return true; 1210 1211 // Check the reserve size. 1212 if (!Call->getArg(1)->getType()->isIntegerType() && 1213 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1214 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1215 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1216 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1217 return true; 1218 } 1219 1220 // Since return type of reserve_read/write_pipe built-in function is 1221 // reserve_id_t, which is not defined in the builtin def file , we used int 1222 // as return type and need to override the return type of these functions. 1223 Call->setType(S.Context.OCLReserveIDTy); 1224 1225 return false; 1226 } 1227 1228 // Performs a semantic analysis on {work_group_/sub_group_ 1229 // /_}commit_{read/write}_pipe 1230 // \param S Reference to the semantic analyzer. 1231 // \param Call The call to the builtin function to be analyzed. 1232 // \return True if a semantic error was found, false otherwise. 1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1234 if (checkArgCount(S, Call, 2)) 1235 return true; 1236 1237 if (checkOpenCLPipeArg(S, Call)) 1238 return true; 1239 1240 // Check reserve_id_t. 1241 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1242 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1243 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1244 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1245 return true; 1246 } 1247 1248 return false; 1249 } 1250 1251 // Performs a semantic analysis on the call to built-in Pipe 1252 // Query Functions. 1253 // \param S Reference to the semantic analyzer. 1254 // \param Call The call to the builtin function to be analyzed. 1255 // \return True if a semantic error was found, false otherwise. 1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1257 if (checkArgCount(S, Call, 1)) 1258 return true; 1259 1260 if (!Call->getArg(0)->getType()->isPipeType()) { 1261 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1262 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1263 return true; 1264 } 1265 1266 return false; 1267 } 1268 1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1270 // Performs semantic analysis for the to_global/local/private call. 1271 // \param S Reference to the semantic analyzer. 1272 // \param BuiltinID ID of the builtin function. 1273 // \param Call A pointer to the builtin call. 1274 // \return True if a semantic error has been found, false otherwise. 1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1276 CallExpr *Call) { 1277 if (checkArgCount(S, Call, 1)) 1278 return true; 1279 1280 auto RT = Call->getArg(0)->getType(); 1281 if (!RT->isPointerType() || RT->getPointeeType() 1282 .getAddressSpace() == LangAS::opencl_constant) { 1283 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1284 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1285 return true; 1286 } 1287 1288 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1289 S.Diag(Call->getArg(0)->getBeginLoc(), 1290 diag::warn_opencl_generic_address_space_arg) 1291 << Call->getDirectCallee()->getNameInfo().getAsString() 1292 << Call->getArg(0)->getSourceRange(); 1293 } 1294 1295 RT = RT->getPointeeType(); 1296 auto Qual = RT.getQualifiers(); 1297 switch (BuiltinID) { 1298 case Builtin::BIto_global: 1299 Qual.setAddressSpace(LangAS::opencl_global); 1300 break; 1301 case Builtin::BIto_local: 1302 Qual.setAddressSpace(LangAS::opencl_local); 1303 break; 1304 case Builtin::BIto_private: 1305 Qual.setAddressSpace(LangAS::opencl_private); 1306 break; 1307 default: 1308 llvm_unreachable("Invalid builtin function"); 1309 } 1310 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1311 RT.getUnqualifiedType(), Qual))); 1312 1313 return false; 1314 } 1315 1316 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1317 if (checkArgCount(S, TheCall, 1)) 1318 return ExprError(); 1319 1320 // Compute __builtin_launder's parameter type from the argument. 1321 // The parameter type is: 1322 // * The type of the argument if it's not an array or function type, 1323 // Otherwise, 1324 // * The decayed argument type. 1325 QualType ParamTy = [&]() { 1326 QualType ArgTy = TheCall->getArg(0)->getType(); 1327 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1328 return S.Context.getPointerType(Ty->getElementType()); 1329 if (ArgTy->isFunctionType()) { 1330 return S.Context.getPointerType(ArgTy); 1331 } 1332 return ArgTy; 1333 }(); 1334 1335 TheCall->setType(ParamTy); 1336 1337 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1338 if (!ParamTy->isPointerType()) 1339 return 0; 1340 if (ParamTy->isFunctionPointerType()) 1341 return 1; 1342 if (ParamTy->isVoidPointerType()) 1343 return 2; 1344 return llvm::Optional<unsigned>{}; 1345 }(); 1346 if (DiagSelect.hasValue()) { 1347 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1348 << DiagSelect.getValue() << TheCall->getSourceRange(); 1349 return ExprError(); 1350 } 1351 1352 // We either have an incomplete class type, or we have a class template 1353 // whose instantiation has not been forced. Example: 1354 // 1355 // template <class T> struct Foo { T value; }; 1356 // Foo<int> *p = nullptr; 1357 // auto *d = __builtin_launder(p); 1358 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1359 diag::err_incomplete_type)) 1360 return ExprError(); 1361 1362 assert(ParamTy->getPointeeType()->isObjectType() && 1363 "Unhandled non-object pointer case"); 1364 1365 InitializedEntity Entity = 1366 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1367 ExprResult Arg = 1368 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1369 if (Arg.isInvalid()) 1370 return ExprError(); 1371 TheCall->setArg(0, Arg.get()); 1372 1373 return TheCall; 1374 } 1375 1376 // Emit an error and return true if the current architecture is not in the list 1377 // of supported architectures. 1378 static bool 1379 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1380 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1381 llvm::Triple::ArchType CurArch = 1382 S.getASTContext().getTargetInfo().getTriple().getArch(); 1383 if (llvm::is_contained(SupportedArchs, CurArch)) 1384 return false; 1385 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1386 << TheCall->getSourceRange(); 1387 return true; 1388 } 1389 1390 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1391 SourceLocation CallSiteLoc); 1392 1393 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1394 CallExpr *TheCall) { 1395 switch (TI.getTriple().getArch()) { 1396 default: 1397 // Some builtins don't require additional checking, so just consider these 1398 // acceptable. 1399 return false; 1400 case llvm::Triple::arm: 1401 case llvm::Triple::armeb: 1402 case llvm::Triple::thumb: 1403 case llvm::Triple::thumbeb: 1404 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1405 case llvm::Triple::aarch64: 1406 case llvm::Triple::aarch64_32: 1407 case llvm::Triple::aarch64_be: 1408 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1409 case llvm::Triple::bpfeb: 1410 case llvm::Triple::bpfel: 1411 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1412 case llvm::Triple::hexagon: 1413 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::mips: 1415 case llvm::Triple::mipsel: 1416 case llvm::Triple::mips64: 1417 case llvm::Triple::mips64el: 1418 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1419 case llvm::Triple::systemz: 1420 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1421 case llvm::Triple::x86: 1422 case llvm::Triple::x86_64: 1423 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1424 case llvm::Triple::ppc: 1425 case llvm::Triple::ppc64: 1426 case llvm::Triple::ppc64le: 1427 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1428 case llvm::Triple::amdgcn: 1429 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1430 } 1431 } 1432 1433 ExprResult 1434 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1435 CallExpr *TheCall) { 1436 ExprResult TheCallResult(TheCall); 1437 1438 // Find out if any arguments are required to be integer constant expressions. 1439 unsigned ICEArguments = 0; 1440 ASTContext::GetBuiltinTypeError Error; 1441 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1442 if (Error != ASTContext::GE_None) 1443 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1444 1445 // If any arguments are required to be ICE's, check and diagnose. 1446 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1447 // Skip arguments not required to be ICE's. 1448 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1449 1450 llvm::APSInt Result; 1451 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1452 return true; 1453 ICEArguments &= ~(1 << ArgNo); 1454 } 1455 1456 switch (BuiltinID) { 1457 case Builtin::BI__builtin___CFStringMakeConstantString: 1458 assert(TheCall->getNumArgs() == 1 && 1459 "Wrong # arguments to builtin CFStringMakeConstantString"); 1460 if (CheckObjCString(TheCall->getArg(0))) 1461 return ExprError(); 1462 break; 1463 case Builtin::BI__builtin_ms_va_start: 1464 case Builtin::BI__builtin_stdarg_start: 1465 case Builtin::BI__builtin_va_start: 1466 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__va_start: { 1470 switch (Context.getTargetInfo().getTriple().getArch()) { 1471 case llvm::Triple::aarch64: 1472 case llvm::Triple::arm: 1473 case llvm::Triple::thumb: 1474 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1475 return ExprError(); 1476 break; 1477 default: 1478 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1479 return ExprError(); 1480 break; 1481 } 1482 break; 1483 } 1484 1485 // The acquire, release, and no fence variants are ARM and AArch64 only. 1486 case Builtin::BI_interlockedbittestandset_acq: 1487 case Builtin::BI_interlockedbittestandset_rel: 1488 case Builtin::BI_interlockedbittestandset_nf: 1489 case Builtin::BI_interlockedbittestandreset_acq: 1490 case Builtin::BI_interlockedbittestandreset_rel: 1491 case Builtin::BI_interlockedbittestandreset_nf: 1492 if (CheckBuiltinTargetSupport( 1493 *this, BuiltinID, TheCall, 1494 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1495 return ExprError(); 1496 break; 1497 1498 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1499 case Builtin::BI_bittest64: 1500 case Builtin::BI_bittestandcomplement64: 1501 case Builtin::BI_bittestandreset64: 1502 case Builtin::BI_bittestandset64: 1503 case Builtin::BI_interlockedbittestandreset64: 1504 case Builtin::BI_interlockedbittestandset64: 1505 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1506 {llvm::Triple::x86_64, llvm::Triple::arm, 1507 llvm::Triple::thumb, llvm::Triple::aarch64})) 1508 return ExprError(); 1509 break; 1510 1511 case Builtin::BI__builtin_isgreater: 1512 case Builtin::BI__builtin_isgreaterequal: 1513 case Builtin::BI__builtin_isless: 1514 case Builtin::BI__builtin_islessequal: 1515 case Builtin::BI__builtin_islessgreater: 1516 case Builtin::BI__builtin_isunordered: 1517 if (SemaBuiltinUnorderedCompare(TheCall)) 1518 return ExprError(); 1519 break; 1520 case Builtin::BI__builtin_fpclassify: 1521 if (SemaBuiltinFPClassification(TheCall, 6)) 1522 return ExprError(); 1523 break; 1524 case Builtin::BI__builtin_isfinite: 1525 case Builtin::BI__builtin_isinf: 1526 case Builtin::BI__builtin_isinf_sign: 1527 case Builtin::BI__builtin_isnan: 1528 case Builtin::BI__builtin_isnormal: 1529 case Builtin::BI__builtin_signbit: 1530 case Builtin::BI__builtin_signbitf: 1531 case Builtin::BI__builtin_signbitl: 1532 if (SemaBuiltinFPClassification(TheCall, 1)) 1533 return ExprError(); 1534 break; 1535 case Builtin::BI__builtin_shufflevector: 1536 return SemaBuiltinShuffleVector(TheCall); 1537 // TheCall will be freed by the smart pointer here, but that's fine, since 1538 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1539 case Builtin::BI__builtin_prefetch: 1540 if (SemaBuiltinPrefetch(TheCall)) 1541 return ExprError(); 1542 break; 1543 case Builtin::BI__builtin_alloca_with_align: 1544 if (SemaBuiltinAllocaWithAlign(TheCall)) 1545 return ExprError(); 1546 LLVM_FALLTHROUGH; 1547 case Builtin::BI__builtin_alloca: 1548 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1549 << TheCall->getDirectCallee(); 1550 break; 1551 case Builtin::BI__assume: 1552 case Builtin::BI__builtin_assume: 1553 if (SemaBuiltinAssume(TheCall)) 1554 return ExprError(); 1555 break; 1556 case Builtin::BI__builtin_assume_aligned: 1557 if (SemaBuiltinAssumeAligned(TheCall)) 1558 return ExprError(); 1559 break; 1560 case Builtin::BI__builtin_dynamic_object_size: 1561 case Builtin::BI__builtin_object_size: 1562 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1563 return ExprError(); 1564 break; 1565 case Builtin::BI__builtin_longjmp: 1566 if (SemaBuiltinLongjmp(TheCall)) 1567 return ExprError(); 1568 break; 1569 case Builtin::BI__builtin_setjmp: 1570 if (SemaBuiltinSetjmp(TheCall)) 1571 return ExprError(); 1572 break; 1573 case Builtin::BI__builtin_classify_type: 1574 if (checkArgCount(*this, TheCall, 1)) return true; 1575 TheCall->setType(Context.IntTy); 1576 break; 1577 case Builtin::BI__builtin_complex: 1578 if (SemaBuiltinComplex(TheCall)) 1579 return ExprError(); 1580 break; 1581 case Builtin::BI__builtin_constant_p: { 1582 if (checkArgCount(*this, TheCall, 1)) return true; 1583 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1584 if (Arg.isInvalid()) return true; 1585 TheCall->setArg(0, Arg.get()); 1586 TheCall->setType(Context.IntTy); 1587 break; 1588 } 1589 case Builtin::BI__builtin_launder: 1590 return SemaBuiltinLaunder(*this, TheCall); 1591 case Builtin::BI__sync_fetch_and_add: 1592 case Builtin::BI__sync_fetch_and_add_1: 1593 case Builtin::BI__sync_fetch_and_add_2: 1594 case Builtin::BI__sync_fetch_and_add_4: 1595 case Builtin::BI__sync_fetch_and_add_8: 1596 case Builtin::BI__sync_fetch_and_add_16: 1597 case Builtin::BI__sync_fetch_and_sub: 1598 case Builtin::BI__sync_fetch_and_sub_1: 1599 case Builtin::BI__sync_fetch_and_sub_2: 1600 case Builtin::BI__sync_fetch_and_sub_4: 1601 case Builtin::BI__sync_fetch_and_sub_8: 1602 case Builtin::BI__sync_fetch_and_sub_16: 1603 case Builtin::BI__sync_fetch_and_or: 1604 case Builtin::BI__sync_fetch_and_or_1: 1605 case Builtin::BI__sync_fetch_and_or_2: 1606 case Builtin::BI__sync_fetch_and_or_4: 1607 case Builtin::BI__sync_fetch_and_or_8: 1608 case Builtin::BI__sync_fetch_and_or_16: 1609 case Builtin::BI__sync_fetch_and_and: 1610 case Builtin::BI__sync_fetch_and_and_1: 1611 case Builtin::BI__sync_fetch_and_and_2: 1612 case Builtin::BI__sync_fetch_and_and_4: 1613 case Builtin::BI__sync_fetch_and_and_8: 1614 case Builtin::BI__sync_fetch_and_and_16: 1615 case Builtin::BI__sync_fetch_and_xor: 1616 case Builtin::BI__sync_fetch_and_xor_1: 1617 case Builtin::BI__sync_fetch_and_xor_2: 1618 case Builtin::BI__sync_fetch_and_xor_4: 1619 case Builtin::BI__sync_fetch_and_xor_8: 1620 case Builtin::BI__sync_fetch_and_xor_16: 1621 case Builtin::BI__sync_fetch_and_nand: 1622 case Builtin::BI__sync_fetch_and_nand_1: 1623 case Builtin::BI__sync_fetch_and_nand_2: 1624 case Builtin::BI__sync_fetch_and_nand_4: 1625 case Builtin::BI__sync_fetch_and_nand_8: 1626 case Builtin::BI__sync_fetch_and_nand_16: 1627 case Builtin::BI__sync_add_and_fetch: 1628 case Builtin::BI__sync_add_and_fetch_1: 1629 case Builtin::BI__sync_add_and_fetch_2: 1630 case Builtin::BI__sync_add_and_fetch_4: 1631 case Builtin::BI__sync_add_and_fetch_8: 1632 case Builtin::BI__sync_add_and_fetch_16: 1633 case Builtin::BI__sync_sub_and_fetch: 1634 case Builtin::BI__sync_sub_and_fetch_1: 1635 case Builtin::BI__sync_sub_and_fetch_2: 1636 case Builtin::BI__sync_sub_and_fetch_4: 1637 case Builtin::BI__sync_sub_and_fetch_8: 1638 case Builtin::BI__sync_sub_and_fetch_16: 1639 case Builtin::BI__sync_and_and_fetch: 1640 case Builtin::BI__sync_and_and_fetch_1: 1641 case Builtin::BI__sync_and_and_fetch_2: 1642 case Builtin::BI__sync_and_and_fetch_4: 1643 case Builtin::BI__sync_and_and_fetch_8: 1644 case Builtin::BI__sync_and_and_fetch_16: 1645 case Builtin::BI__sync_or_and_fetch: 1646 case Builtin::BI__sync_or_and_fetch_1: 1647 case Builtin::BI__sync_or_and_fetch_2: 1648 case Builtin::BI__sync_or_and_fetch_4: 1649 case Builtin::BI__sync_or_and_fetch_8: 1650 case Builtin::BI__sync_or_and_fetch_16: 1651 case Builtin::BI__sync_xor_and_fetch: 1652 case Builtin::BI__sync_xor_and_fetch_1: 1653 case Builtin::BI__sync_xor_and_fetch_2: 1654 case Builtin::BI__sync_xor_and_fetch_4: 1655 case Builtin::BI__sync_xor_and_fetch_8: 1656 case Builtin::BI__sync_xor_and_fetch_16: 1657 case Builtin::BI__sync_nand_and_fetch: 1658 case Builtin::BI__sync_nand_and_fetch_1: 1659 case Builtin::BI__sync_nand_and_fetch_2: 1660 case Builtin::BI__sync_nand_and_fetch_4: 1661 case Builtin::BI__sync_nand_and_fetch_8: 1662 case Builtin::BI__sync_nand_and_fetch_16: 1663 case Builtin::BI__sync_val_compare_and_swap: 1664 case Builtin::BI__sync_val_compare_and_swap_1: 1665 case Builtin::BI__sync_val_compare_and_swap_2: 1666 case Builtin::BI__sync_val_compare_and_swap_4: 1667 case Builtin::BI__sync_val_compare_and_swap_8: 1668 case Builtin::BI__sync_val_compare_and_swap_16: 1669 case Builtin::BI__sync_bool_compare_and_swap: 1670 case Builtin::BI__sync_bool_compare_and_swap_1: 1671 case Builtin::BI__sync_bool_compare_and_swap_2: 1672 case Builtin::BI__sync_bool_compare_and_swap_4: 1673 case Builtin::BI__sync_bool_compare_and_swap_8: 1674 case Builtin::BI__sync_bool_compare_and_swap_16: 1675 case Builtin::BI__sync_lock_test_and_set: 1676 case Builtin::BI__sync_lock_test_and_set_1: 1677 case Builtin::BI__sync_lock_test_and_set_2: 1678 case Builtin::BI__sync_lock_test_and_set_4: 1679 case Builtin::BI__sync_lock_test_and_set_8: 1680 case Builtin::BI__sync_lock_test_and_set_16: 1681 case Builtin::BI__sync_lock_release: 1682 case Builtin::BI__sync_lock_release_1: 1683 case Builtin::BI__sync_lock_release_2: 1684 case Builtin::BI__sync_lock_release_4: 1685 case Builtin::BI__sync_lock_release_8: 1686 case Builtin::BI__sync_lock_release_16: 1687 case Builtin::BI__sync_swap: 1688 case Builtin::BI__sync_swap_1: 1689 case Builtin::BI__sync_swap_2: 1690 case Builtin::BI__sync_swap_4: 1691 case Builtin::BI__sync_swap_8: 1692 case Builtin::BI__sync_swap_16: 1693 return SemaBuiltinAtomicOverloaded(TheCallResult); 1694 case Builtin::BI__sync_synchronize: 1695 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1696 << TheCall->getCallee()->getSourceRange(); 1697 break; 1698 case Builtin::BI__builtin_nontemporal_load: 1699 case Builtin::BI__builtin_nontemporal_store: 1700 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1701 case Builtin::BI__builtin_memcpy_inline: { 1702 clang::Expr *SizeOp = TheCall->getArg(2); 1703 // We warn about copying to or from `nullptr` pointers when `size` is 1704 // greater than 0. When `size` is value dependent we cannot evaluate its 1705 // value so we bail out. 1706 if (SizeOp->isValueDependent()) 1707 break; 1708 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1709 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1710 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1711 } 1712 break; 1713 } 1714 #define BUILTIN(ID, TYPE, ATTRS) 1715 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1716 case Builtin::BI##ID: \ 1717 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1718 #include "clang/Basic/Builtins.def" 1719 case Builtin::BI__annotation: 1720 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1721 return ExprError(); 1722 break; 1723 case Builtin::BI__builtin_annotation: 1724 if (SemaBuiltinAnnotation(*this, TheCall)) 1725 return ExprError(); 1726 break; 1727 case Builtin::BI__builtin_addressof: 1728 if (SemaBuiltinAddressof(*this, TheCall)) 1729 return ExprError(); 1730 break; 1731 case Builtin::BI__builtin_is_aligned: 1732 case Builtin::BI__builtin_align_up: 1733 case Builtin::BI__builtin_align_down: 1734 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1735 return ExprError(); 1736 break; 1737 case Builtin::BI__builtin_add_overflow: 1738 case Builtin::BI__builtin_sub_overflow: 1739 case Builtin::BI__builtin_mul_overflow: 1740 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1741 return ExprError(); 1742 break; 1743 case Builtin::BI__builtin_operator_new: 1744 case Builtin::BI__builtin_operator_delete: { 1745 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1746 ExprResult Res = 1747 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1748 if (Res.isInvalid()) 1749 CorrectDelayedTyposInExpr(TheCallResult.get()); 1750 return Res; 1751 } 1752 case Builtin::BI__builtin_dump_struct: { 1753 // We first want to ensure we are called with 2 arguments 1754 if (checkArgCount(*this, TheCall, 2)) 1755 return ExprError(); 1756 // Ensure that the first argument is of type 'struct XX *' 1757 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1758 const QualType PtrArgType = PtrArg->getType(); 1759 if (!PtrArgType->isPointerType() || 1760 !PtrArgType->getPointeeType()->isRecordType()) { 1761 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1762 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1763 << "structure pointer"; 1764 return ExprError(); 1765 } 1766 1767 // Ensure that the second argument is of type 'FunctionType' 1768 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1769 const QualType FnPtrArgType = FnPtrArg->getType(); 1770 if (!FnPtrArgType->isPointerType()) { 1771 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1772 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1773 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1774 return ExprError(); 1775 } 1776 1777 const auto *FuncType = 1778 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1779 1780 if (!FuncType) { 1781 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1782 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1783 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1784 return ExprError(); 1785 } 1786 1787 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1788 if (!FT->getNumParams()) { 1789 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1790 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1791 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1792 return ExprError(); 1793 } 1794 QualType PT = FT->getParamType(0); 1795 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1796 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1797 !PT->getPointeeType().isConstQualified()) { 1798 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1799 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1800 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1801 return ExprError(); 1802 } 1803 } 1804 1805 TheCall->setType(Context.IntTy); 1806 break; 1807 } 1808 case Builtin::BI__builtin_expect_with_probability: { 1809 // We first want to ensure we are called with 3 arguments 1810 if (checkArgCount(*this, TheCall, 3)) 1811 return ExprError(); 1812 // then check probability is constant float in range [0.0, 1.0] 1813 const Expr *ProbArg = TheCall->getArg(2); 1814 SmallVector<PartialDiagnosticAt, 8> Notes; 1815 Expr::EvalResult Eval; 1816 Eval.Diag = &Notes; 1817 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1818 !Eval.Val.isFloat()) { 1819 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1820 << ProbArg->getSourceRange(); 1821 for (const PartialDiagnosticAt &PDiag : Notes) 1822 Diag(PDiag.first, PDiag.second); 1823 return ExprError(); 1824 } 1825 llvm::APFloat Probability = Eval.Val.getFloat(); 1826 bool LoseInfo = false; 1827 Probability.convert(llvm::APFloat::IEEEdouble(), 1828 llvm::RoundingMode::Dynamic, &LoseInfo); 1829 if (!(Probability >= llvm::APFloat(0.0) && 1830 Probability <= llvm::APFloat(1.0))) { 1831 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1832 << ProbArg->getSourceRange(); 1833 return ExprError(); 1834 } 1835 break; 1836 } 1837 case Builtin::BI__builtin_preserve_access_index: 1838 if (SemaBuiltinPreserveAI(*this, TheCall)) 1839 return ExprError(); 1840 break; 1841 case Builtin::BI__builtin_call_with_static_chain: 1842 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1843 return ExprError(); 1844 break; 1845 case Builtin::BI__exception_code: 1846 case Builtin::BI_exception_code: 1847 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1848 diag::err_seh___except_block)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__exception_info: 1852 case Builtin::BI_exception_info: 1853 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1854 diag::err_seh___except_filter)) 1855 return ExprError(); 1856 break; 1857 case Builtin::BI__GetExceptionInfo: 1858 if (checkArgCount(*this, TheCall, 1)) 1859 return ExprError(); 1860 1861 if (CheckCXXThrowOperand( 1862 TheCall->getBeginLoc(), 1863 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1864 TheCall)) 1865 return ExprError(); 1866 1867 TheCall->setType(Context.VoidPtrTy); 1868 break; 1869 // OpenCL v2.0, s6.13.16 - Pipe functions 1870 case Builtin::BIread_pipe: 1871 case Builtin::BIwrite_pipe: 1872 // Since those two functions are declared with var args, we need a semantic 1873 // check for the argument. 1874 if (SemaBuiltinRWPipe(*this, TheCall)) 1875 return ExprError(); 1876 break; 1877 case Builtin::BIreserve_read_pipe: 1878 case Builtin::BIreserve_write_pipe: 1879 case Builtin::BIwork_group_reserve_read_pipe: 1880 case Builtin::BIwork_group_reserve_write_pipe: 1881 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1882 return ExprError(); 1883 break; 1884 case Builtin::BIsub_group_reserve_read_pipe: 1885 case Builtin::BIsub_group_reserve_write_pipe: 1886 if (checkOpenCLSubgroupExt(*this, TheCall) || 1887 SemaBuiltinReserveRWPipe(*this, TheCall)) 1888 return ExprError(); 1889 break; 1890 case Builtin::BIcommit_read_pipe: 1891 case Builtin::BIcommit_write_pipe: 1892 case Builtin::BIwork_group_commit_read_pipe: 1893 case Builtin::BIwork_group_commit_write_pipe: 1894 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1895 return ExprError(); 1896 break; 1897 case Builtin::BIsub_group_commit_read_pipe: 1898 case Builtin::BIsub_group_commit_write_pipe: 1899 if (checkOpenCLSubgroupExt(*this, TheCall) || 1900 SemaBuiltinCommitRWPipe(*this, TheCall)) 1901 return ExprError(); 1902 break; 1903 case Builtin::BIget_pipe_num_packets: 1904 case Builtin::BIget_pipe_max_packets: 1905 if (SemaBuiltinPipePackets(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIto_global: 1909 case Builtin::BIto_local: 1910 case Builtin::BIto_private: 1911 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1912 return ExprError(); 1913 break; 1914 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1915 case Builtin::BIenqueue_kernel: 1916 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1917 return ExprError(); 1918 break; 1919 case Builtin::BIget_kernel_work_group_size: 1920 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1921 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1922 return ExprError(); 1923 break; 1924 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1925 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1926 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1927 return ExprError(); 1928 break; 1929 case Builtin::BI__builtin_os_log_format: 1930 Cleanup.setExprNeedsCleanups(true); 1931 LLVM_FALLTHROUGH; 1932 case Builtin::BI__builtin_os_log_format_buffer_size: 1933 if (SemaBuiltinOSLogFormat(TheCall)) 1934 return ExprError(); 1935 break; 1936 case Builtin::BI__builtin_frame_address: 1937 case Builtin::BI__builtin_return_address: { 1938 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1939 return ExprError(); 1940 1941 // -Wframe-address warning if non-zero passed to builtin 1942 // return/frame address. 1943 Expr::EvalResult Result; 1944 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1945 Result.Val.getInt() != 0) 1946 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1947 << ((BuiltinID == Builtin::BI__builtin_return_address) 1948 ? "__builtin_return_address" 1949 : "__builtin_frame_address") 1950 << TheCall->getSourceRange(); 1951 break; 1952 } 1953 1954 case Builtin::BI__builtin_matrix_transpose: 1955 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1956 1957 case Builtin::BI__builtin_matrix_column_major_load: 1958 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1959 1960 case Builtin::BI__builtin_matrix_column_major_store: 1961 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1962 } 1963 1964 // Since the target specific builtins for each arch overlap, only check those 1965 // of the arch we are compiling for. 1966 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1967 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1968 assert(Context.getAuxTargetInfo() && 1969 "Aux Target Builtin, but not an aux target?"); 1970 1971 if (CheckTSBuiltinFunctionCall( 1972 *Context.getAuxTargetInfo(), 1973 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1974 return ExprError(); 1975 } else { 1976 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1977 TheCall)) 1978 return ExprError(); 1979 } 1980 } 1981 1982 return TheCallResult; 1983 } 1984 1985 // Get the valid immediate range for the specified NEON type code. 1986 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1987 NeonTypeFlags Type(t); 1988 int IsQuad = ForceQuad ? true : Type.isQuad(); 1989 switch (Type.getEltType()) { 1990 case NeonTypeFlags::Int8: 1991 case NeonTypeFlags::Poly8: 1992 return shift ? 7 : (8 << IsQuad) - 1; 1993 case NeonTypeFlags::Int16: 1994 case NeonTypeFlags::Poly16: 1995 return shift ? 15 : (4 << IsQuad) - 1; 1996 case NeonTypeFlags::Int32: 1997 return shift ? 31 : (2 << IsQuad) - 1; 1998 case NeonTypeFlags::Int64: 1999 case NeonTypeFlags::Poly64: 2000 return shift ? 63 : (1 << IsQuad) - 1; 2001 case NeonTypeFlags::Poly128: 2002 return shift ? 127 : (1 << IsQuad) - 1; 2003 case NeonTypeFlags::Float16: 2004 assert(!shift && "cannot shift float types!"); 2005 return (4 << IsQuad) - 1; 2006 case NeonTypeFlags::Float32: 2007 assert(!shift && "cannot shift float types!"); 2008 return (2 << IsQuad) - 1; 2009 case NeonTypeFlags::Float64: 2010 assert(!shift && "cannot shift float types!"); 2011 return (1 << IsQuad) - 1; 2012 case NeonTypeFlags::BFloat16: 2013 assert(!shift && "cannot shift float types!"); 2014 return (4 << IsQuad) - 1; 2015 } 2016 llvm_unreachable("Invalid NeonTypeFlag!"); 2017 } 2018 2019 /// getNeonEltType - Return the QualType corresponding to the elements of 2020 /// the vector type specified by the NeonTypeFlags. This is used to check 2021 /// the pointer arguments for Neon load/store intrinsics. 2022 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2023 bool IsPolyUnsigned, bool IsInt64Long) { 2024 switch (Flags.getEltType()) { 2025 case NeonTypeFlags::Int8: 2026 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2027 case NeonTypeFlags::Int16: 2028 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2029 case NeonTypeFlags::Int32: 2030 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2031 case NeonTypeFlags::Int64: 2032 if (IsInt64Long) 2033 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2034 else 2035 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2036 : Context.LongLongTy; 2037 case NeonTypeFlags::Poly8: 2038 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2039 case NeonTypeFlags::Poly16: 2040 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2041 case NeonTypeFlags::Poly64: 2042 if (IsInt64Long) 2043 return Context.UnsignedLongTy; 2044 else 2045 return Context.UnsignedLongLongTy; 2046 case NeonTypeFlags::Poly128: 2047 break; 2048 case NeonTypeFlags::Float16: 2049 return Context.HalfTy; 2050 case NeonTypeFlags::Float32: 2051 return Context.FloatTy; 2052 case NeonTypeFlags::Float64: 2053 return Context.DoubleTy; 2054 case NeonTypeFlags::BFloat16: 2055 return Context.BFloat16Ty; 2056 } 2057 llvm_unreachable("Invalid NeonTypeFlag!"); 2058 } 2059 2060 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2061 // Range check SVE intrinsics that take immediate values. 2062 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2063 2064 switch (BuiltinID) { 2065 default: 2066 return false; 2067 #define GET_SVE_IMMEDIATE_CHECK 2068 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2069 #undef GET_SVE_IMMEDIATE_CHECK 2070 } 2071 2072 // Perform all the immediate checks for this builtin call. 2073 bool HasError = false; 2074 for (auto &I : ImmChecks) { 2075 int ArgNum, CheckTy, ElementSizeInBits; 2076 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2077 2078 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2079 2080 // Function that checks whether the operand (ArgNum) is an immediate 2081 // that is one of the predefined values. 2082 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2083 int ErrDiag) -> bool { 2084 // We can't check the value of a dependent argument. 2085 Expr *Arg = TheCall->getArg(ArgNum); 2086 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2087 return false; 2088 2089 // Check constant-ness first. 2090 llvm::APSInt Imm; 2091 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2092 return true; 2093 2094 if (!CheckImm(Imm.getSExtValue())) 2095 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2096 return false; 2097 }; 2098 2099 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2100 case SVETypeFlags::ImmCheck0_31: 2101 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2102 HasError = true; 2103 break; 2104 case SVETypeFlags::ImmCheck0_13: 2105 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2106 HasError = true; 2107 break; 2108 case SVETypeFlags::ImmCheck1_16: 2109 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2110 HasError = true; 2111 break; 2112 case SVETypeFlags::ImmCheck0_7: 2113 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2114 HasError = true; 2115 break; 2116 case SVETypeFlags::ImmCheckExtract: 2117 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2118 (2048 / ElementSizeInBits) - 1)) 2119 HasError = true; 2120 break; 2121 case SVETypeFlags::ImmCheckShiftRight: 2122 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2123 HasError = true; 2124 break; 2125 case SVETypeFlags::ImmCheckShiftRightNarrow: 2126 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2127 ElementSizeInBits / 2)) 2128 HasError = true; 2129 break; 2130 case SVETypeFlags::ImmCheckShiftLeft: 2131 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2132 ElementSizeInBits - 1)) 2133 HasError = true; 2134 break; 2135 case SVETypeFlags::ImmCheckLaneIndex: 2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2137 (128 / (1 * ElementSizeInBits)) - 1)) 2138 HasError = true; 2139 break; 2140 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2141 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2142 (128 / (2 * ElementSizeInBits)) - 1)) 2143 HasError = true; 2144 break; 2145 case SVETypeFlags::ImmCheckLaneIndexDot: 2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2147 (128 / (4 * ElementSizeInBits)) - 1)) 2148 HasError = true; 2149 break; 2150 case SVETypeFlags::ImmCheckComplexRot90_270: 2151 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2152 diag::err_rotation_argument_to_cadd)) 2153 HasError = true; 2154 break; 2155 case SVETypeFlags::ImmCheckComplexRotAll90: 2156 if (CheckImmediateInSet( 2157 [](int64_t V) { 2158 return V == 0 || V == 90 || V == 180 || V == 270; 2159 }, 2160 diag::err_rotation_argument_to_cmla)) 2161 HasError = true; 2162 break; 2163 case SVETypeFlags::ImmCheck0_1: 2164 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2165 HasError = true; 2166 break; 2167 case SVETypeFlags::ImmCheck0_2: 2168 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2169 HasError = true; 2170 break; 2171 case SVETypeFlags::ImmCheck0_3: 2172 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2173 HasError = true; 2174 break; 2175 } 2176 } 2177 2178 return HasError; 2179 } 2180 2181 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2182 unsigned BuiltinID, CallExpr *TheCall) { 2183 llvm::APSInt Result; 2184 uint64_t mask = 0; 2185 unsigned TV = 0; 2186 int PtrArgNum = -1; 2187 bool HasConstPtr = false; 2188 switch (BuiltinID) { 2189 #define GET_NEON_OVERLOAD_CHECK 2190 #include "clang/Basic/arm_neon.inc" 2191 #include "clang/Basic/arm_fp16.inc" 2192 #undef GET_NEON_OVERLOAD_CHECK 2193 } 2194 2195 // For NEON intrinsics which are overloaded on vector element type, validate 2196 // the immediate which specifies which variant to emit. 2197 unsigned ImmArg = TheCall->getNumArgs()-1; 2198 if (mask) { 2199 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2200 return true; 2201 2202 TV = Result.getLimitedValue(64); 2203 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2204 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2205 << TheCall->getArg(ImmArg)->getSourceRange(); 2206 } 2207 2208 if (PtrArgNum >= 0) { 2209 // Check that pointer arguments have the specified type. 2210 Expr *Arg = TheCall->getArg(PtrArgNum); 2211 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2212 Arg = ICE->getSubExpr(); 2213 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2214 QualType RHSTy = RHS.get()->getType(); 2215 2216 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2217 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2218 Arch == llvm::Triple::aarch64_32 || 2219 Arch == llvm::Triple::aarch64_be; 2220 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2221 QualType EltTy = 2222 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2223 if (HasConstPtr) 2224 EltTy = EltTy.withConst(); 2225 QualType LHSTy = Context.getPointerType(EltTy); 2226 AssignConvertType ConvTy; 2227 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2228 if (RHS.isInvalid()) 2229 return true; 2230 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2231 RHS.get(), AA_Assigning)) 2232 return true; 2233 } 2234 2235 // For NEON intrinsics which take an immediate value as part of the 2236 // instruction, range check them here. 2237 unsigned i = 0, l = 0, u = 0; 2238 switch (BuiltinID) { 2239 default: 2240 return false; 2241 #define GET_NEON_IMMEDIATE_CHECK 2242 #include "clang/Basic/arm_neon.inc" 2243 #include "clang/Basic/arm_fp16.inc" 2244 #undef GET_NEON_IMMEDIATE_CHECK 2245 } 2246 2247 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2248 } 2249 2250 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2251 switch (BuiltinID) { 2252 default: 2253 return false; 2254 #include "clang/Basic/arm_mve_builtin_sema.inc" 2255 } 2256 } 2257 2258 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2259 CallExpr *TheCall) { 2260 bool Err = false; 2261 switch (BuiltinID) { 2262 default: 2263 return false; 2264 #include "clang/Basic/arm_cde_builtin_sema.inc" 2265 } 2266 2267 if (Err) 2268 return true; 2269 2270 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2271 } 2272 2273 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2274 const Expr *CoprocArg, bool WantCDE) { 2275 if (isConstantEvaluated()) 2276 return false; 2277 2278 // We can't check the value of a dependent argument. 2279 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2280 return false; 2281 2282 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2283 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2284 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2285 2286 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2287 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2288 2289 if (IsCDECoproc != WantCDE) 2290 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2291 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2292 2293 return false; 2294 } 2295 2296 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2297 unsigned MaxWidth) { 2298 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2299 BuiltinID == ARM::BI__builtin_arm_ldaex || 2300 BuiltinID == ARM::BI__builtin_arm_strex || 2301 BuiltinID == ARM::BI__builtin_arm_stlex || 2302 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2303 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2304 BuiltinID == AArch64::BI__builtin_arm_strex || 2305 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2306 "unexpected ARM builtin"); 2307 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2308 BuiltinID == ARM::BI__builtin_arm_ldaex || 2309 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2310 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2311 2312 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2313 2314 // Ensure that we have the proper number of arguments. 2315 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2316 return true; 2317 2318 // Inspect the pointer argument of the atomic builtin. This should always be 2319 // a pointer type, whose element is an integral scalar or pointer type. 2320 // Because it is a pointer type, we don't have to worry about any implicit 2321 // casts here. 2322 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2323 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2324 if (PointerArgRes.isInvalid()) 2325 return true; 2326 PointerArg = PointerArgRes.get(); 2327 2328 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2329 if (!pointerType) { 2330 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2331 << PointerArg->getType() << PointerArg->getSourceRange(); 2332 return true; 2333 } 2334 2335 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2336 // task is to insert the appropriate casts into the AST. First work out just 2337 // what the appropriate type is. 2338 QualType ValType = pointerType->getPointeeType(); 2339 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2340 if (IsLdrex) 2341 AddrType.addConst(); 2342 2343 // Issue a warning if the cast is dodgy. 2344 CastKind CastNeeded = CK_NoOp; 2345 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2346 CastNeeded = CK_BitCast; 2347 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2348 << PointerArg->getType() << Context.getPointerType(AddrType) 2349 << AA_Passing << PointerArg->getSourceRange(); 2350 } 2351 2352 // Finally, do the cast and replace the argument with the corrected version. 2353 AddrType = Context.getPointerType(AddrType); 2354 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2355 if (PointerArgRes.isInvalid()) 2356 return true; 2357 PointerArg = PointerArgRes.get(); 2358 2359 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2360 2361 // In general, we allow ints, floats and pointers to be loaded and stored. 2362 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2363 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2364 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2365 << PointerArg->getType() << PointerArg->getSourceRange(); 2366 return true; 2367 } 2368 2369 // But ARM doesn't have instructions to deal with 128-bit versions. 2370 if (Context.getTypeSize(ValType) > MaxWidth) { 2371 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2372 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2373 << PointerArg->getType() << PointerArg->getSourceRange(); 2374 return true; 2375 } 2376 2377 switch (ValType.getObjCLifetime()) { 2378 case Qualifiers::OCL_None: 2379 case Qualifiers::OCL_ExplicitNone: 2380 // okay 2381 break; 2382 2383 case Qualifiers::OCL_Weak: 2384 case Qualifiers::OCL_Strong: 2385 case Qualifiers::OCL_Autoreleasing: 2386 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2387 << ValType << PointerArg->getSourceRange(); 2388 return true; 2389 } 2390 2391 if (IsLdrex) { 2392 TheCall->setType(ValType); 2393 return false; 2394 } 2395 2396 // Initialize the argument to be stored. 2397 ExprResult ValArg = TheCall->getArg(0); 2398 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2399 Context, ValType, /*consume*/ false); 2400 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2401 if (ValArg.isInvalid()) 2402 return true; 2403 TheCall->setArg(0, ValArg.get()); 2404 2405 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2406 // but the custom checker bypasses all default analysis. 2407 TheCall->setType(Context.IntTy); 2408 return false; 2409 } 2410 2411 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2412 CallExpr *TheCall) { 2413 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2414 BuiltinID == ARM::BI__builtin_arm_ldaex || 2415 BuiltinID == ARM::BI__builtin_arm_strex || 2416 BuiltinID == ARM::BI__builtin_arm_stlex) { 2417 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2418 } 2419 2420 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2421 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2422 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2423 } 2424 2425 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2426 BuiltinID == ARM::BI__builtin_arm_wsr64) 2427 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2428 2429 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2430 BuiltinID == ARM::BI__builtin_arm_rsrp || 2431 BuiltinID == ARM::BI__builtin_arm_wsr || 2432 BuiltinID == ARM::BI__builtin_arm_wsrp) 2433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2434 2435 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2436 return true; 2437 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2438 return true; 2439 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2440 return true; 2441 2442 // For intrinsics which take an immediate value as part of the instruction, 2443 // range check them here. 2444 // FIXME: VFP Intrinsics should error if VFP not present. 2445 switch (BuiltinID) { 2446 default: return false; 2447 case ARM::BI__builtin_arm_ssat: 2448 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2449 case ARM::BI__builtin_arm_usat: 2450 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2451 case ARM::BI__builtin_arm_ssat16: 2452 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2453 case ARM::BI__builtin_arm_usat16: 2454 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2455 case ARM::BI__builtin_arm_vcvtr_f: 2456 case ARM::BI__builtin_arm_vcvtr_d: 2457 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2458 case ARM::BI__builtin_arm_dmb: 2459 case ARM::BI__builtin_arm_dsb: 2460 case ARM::BI__builtin_arm_isb: 2461 case ARM::BI__builtin_arm_dbg: 2462 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2463 case ARM::BI__builtin_arm_cdp: 2464 case ARM::BI__builtin_arm_cdp2: 2465 case ARM::BI__builtin_arm_mcr: 2466 case ARM::BI__builtin_arm_mcr2: 2467 case ARM::BI__builtin_arm_mrc: 2468 case ARM::BI__builtin_arm_mrc2: 2469 case ARM::BI__builtin_arm_mcrr: 2470 case ARM::BI__builtin_arm_mcrr2: 2471 case ARM::BI__builtin_arm_mrrc: 2472 case ARM::BI__builtin_arm_mrrc2: 2473 case ARM::BI__builtin_arm_ldc: 2474 case ARM::BI__builtin_arm_ldcl: 2475 case ARM::BI__builtin_arm_ldc2: 2476 case ARM::BI__builtin_arm_ldc2l: 2477 case ARM::BI__builtin_arm_stc: 2478 case ARM::BI__builtin_arm_stcl: 2479 case ARM::BI__builtin_arm_stc2: 2480 case ARM::BI__builtin_arm_stc2l: 2481 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2482 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2483 /*WantCDE*/ false); 2484 } 2485 } 2486 2487 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2488 unsigned BuiltinID, 2489 CallExpr *TheCall) { 2490 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2491 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2492 BuiltinID == AArch64::BI__builtin_arm_strex || 2493 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2494 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2495 } 2496 2497 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2498 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2499 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2500 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2501 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2502 } 2503 2504 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2505 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2506 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2507 2508 // Memory Tagging Extensions (MTE) Intrinsics 2509 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2510 BuiltinID == AArch64::BI__builtin_arm_addg || 2511 BuiltinID == AArch64::BI__builtin_arm_gmi || 2512 BuiltinID == AArch64::BI__builtin_arm_ldg || 2513 BuiltinID == AArch64::BI__builtin_arm_stg || 2514 BuiltinID == AArch64::BI__builtin_arm_subp) { 2515 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2516 } 2517 2518 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2519 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2520 BuiltinID == AArch64::BI__builtin_arm_wsr || 2521 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2522 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2523 2524 // Only check the valid encoding range. Any constant in this range would be 2525 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2526 // an exception for incorrect registers. This matches MSVC behavior. 2527 if (BuiltinID == AArch64::BI_ReadStatusReg || 2528 BuiltinID == AArch64::BI_WriteStatusReg) 2529 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2530 2531 if (BuiltinID == AArch64::BI__getReg) 2532 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2533 2534 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2535 return true; 2536 2537 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2538 return true; 2539 2540 // For intrinsics which take an immediate value as part of the instruction, 2541 // range check them here. 2542 unsigned i = 0, l = 0, u = 0; 2543 switch (BuiltinID) { 2544 default: return false; 2545 case AArch64::BI__builtin_arm_dmb: 2546 case AArch64::BI__builtin_arm_dsb: 2547 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2548 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2549 } 2550 2551 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2552 } 2553 2554 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2555 if (Arg->getType()->getAsPlaceholderType()) 2556 return false; 2557 2558 // The first argument needs to be a record field access. 2559 // If it is an array element access, we delay decision 2560 // to BPF backend to check whether the access is a 2561 // field access or not. 2562 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2563 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2564 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2565 } 2566 2567 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2568 QualType VectorTy, QualType EltTy) { 2569 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2570 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2571 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2572 << Call->getSourceRange() << VectorEltTy << EltTy; 2573 return false; 2574 } 2575 return true; 2576 } 2577 2578 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2579 QualType ArgType = Arg->getType(); 2580 if (ArgType->getAsPlaceholderType()) 2581 return false; 2582 2583 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2584 // format: 2585 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2586 // 2. <type> var; 2587 // __builtin_preserve_type_info(var, flag); 2588 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2589 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2590 return false; 2591 2592 // Typedef type. 2593 if (ArgType->getAs<TypedefType>()) 2594 return true; 2595 2596 // Record type or Enum type. 2597 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2598 if (const auto *RT = Ty->getAs<RecordType>()) { 2599 if (!RT->getDecl()->getDeclName().isEmpty()) 2600 return true; 2601 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2602 if (!ET->getDecl()->getDeclName().isEmpty()) 2603 return true; 2604 } 2605 2606 return false; 2607 } 2608 2609 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2610 QualType ArgType = Arg->getType(); 2611 if (ArgType->getAsPlaceholderType()) 2612 return false; 2613 2614 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2615 // format: 2616 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2617 // flag); 2618 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2619 if (!UO) 2620 return false; 2621 2622 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2623 if (!CE || CE->getCastKind() != CK_IntegralToPointer) 2624 return false; 2625 2626 // The integer must be from an EnumConstantDecl. 2627 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2628 if (!DR) 2629 return false; 2630 2631 const EnumConstantDecl *Enumerator = 2632 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2633 if (!Enumerator) 2634 return false; 2635 2636 // The type must be EnumType. 2637 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2638 const auto *ET = Ty->getAs<EnumType>(); 2639 if (!ET) 2640 return false; 2641 2642 // The enum value must be supported. 2643 for (auto *EDI : ET->getDecl()->enumerators()) { 2644 if (EDI == Enumerator) 2645 return true; 2646 } 2647 2648 return false; 2649 } 2650 2651 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2652 CallExpr *TheCall) { 2653 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2654 BuiltinID == BPF::BI__builtin_btf_type_id || 2655 BuiltinID == BPF::BI__builtin_preserve_type_info || 2656 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2657 "unexpected BPF builtin"); 2658 2659 if (checkArgCount(*this, TheCall, 2)) 2660 return true; 2661 2662 // The second argument needs to be a constant int 2663 Expr *Arg = TheCall->getArg(1); 2664 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2665 diag::kind kind; 2666 if (!Value) { 2667 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2668 kind = diag::err_preserve_field_info_not_const; 2669 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2670 kind = diag::err_btf_type_id_not_const; 2671 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2672 kind = diag::err_preserve_type_info_not_const; 2673 else 2674 kind = diag::err_preserve_enum_value_not_const; 2675 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2676 return true; 2677 } 2678 2679 // The first argument 2680 Arg = TheCall->getArg(0); 2681 bool InvalidArg = false; 2682 bool ReturnUnsignedInt = true; 2683 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2684 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2685 InvalidArg = true; 2686 kind = diag::err_preserve_field_info_not_field; 2687 } 2688 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2689 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2690 InvalidArg = true; 2691 kind = diag::err_preserve_type_info_invalid; 2692 } 2693 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2694 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2695 InvalidArg = true; 2696 kind = diag::err_preserve_enum_value_invalid; 2697 } 2698 ReturnUnsignedInt = false; 2699 } 2700 2701 if (InvalidArg) { 2702 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2703 return true; 2704 } 2705 2706 if (ReturnUnsignedInt) 2707 TheCall->setType(Context.UnsignedIntTy); 2708 else 2709 TheCall->setType(Context.UnsignedLongTy); 2710 return false; 2711 } 2712 2713 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2714 struct ArgInfo { 2715 uint8_t OpNum; 2716 bool IsSigned; 2717 uint8_t BitWidth; 2718 uint8_t Align; 2719 }; 2720 struct BuiltinInfo { 2721 unsigned BuiltinID; 2722 ArgInfo Infos[2]; 2723 }; 2724 2725 static BuiltinInfo Infos[] = { 2726 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2727 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2728 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2729 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2730 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2731 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2732 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2733 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2734 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2735 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2736 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2737 2738 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2749 2750 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2802 {{ 1, false, 6, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2810 {{ 1, false, 5, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2817 { 2, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2819 { 2, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2821 { 3, false, 5, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2823 { 3, false, 6, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2840 {{ 2, false, 4, 0 }, 2841 { 3, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2843 {{ 2, false, 4, 0 }, 2844 { 3, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2846 {{ 2, false, 4, 0 }, 2847 { 3, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2849 {{ 2, false, 4, 0 }, 2850 { 3, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2862 { 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2864 { 2, false, 6, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2874 {{ 1, false, 4, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2877 {{ 1, false, 4, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2898 {{ 3, false, 1, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2903 {{ 3, false, 1, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2908 {{ 3, false, 1, 0 }} }, 2909 }; 2910 2911 // Use a dynamically initialized static to sort the table exactly once on 2912 // first run. 2913 static const bool SortOnce = 2914 (llvm::sort(Infos, 2915 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2916 return LHS.BuiltinID < RHS.BuiltinID; 2917 }), 2918 true); 2919 (void)SortOnce; 2920 2921 const BuiltinInfo *F = llvm::partition_point( 2922 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2923 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2924 return false; 2925 2926 bool Error = false; 2927 2928 for (const ArgInfo &A : F->Infos) { 2929 // Ignore empty ArgInfo elements. 2930 if (A.BitWidth == 0) 2931 continue; 2932 2933 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2934 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2935 if (!A.Align) { 2936 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2937 } else { 2938 unsigned M = 1 << A.Align; 2939 Min *= M; 2940 Max *= M; 2941 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2942 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2943 } 2944 } 2945 return Error; 2946 } 2947 2948 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2949 CallExpr *TheCall) { 2950 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2951 } 2952 2953 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2954 unsigned BuiltinID, CallExpr *TheCall) { 2955 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2956 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2957 } 2958 2959 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2960 CallExpr *TheCall) { 2961 2962 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2963 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2964 if (!TI.hasFeature("dsp")) 2965 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2966 } 2967 2968 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2969 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2970 if (!TI.hasFeature("dspr2")) 2971 return Diag(TheCall->getBeginLoc(), 2972 diag::err_mips_builtin_requires_dspr2); 2973 } 2974 2975 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2976 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2977 if (!TI.hasFeature("msa")) 2978 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2979 } 2980 2981 return false; 2982 } 2983 2984 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2985 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2986 // ordering for DSP is unspecified. MSA is ordered by the data format used 2987 // by the underlying instruction i.e., df/m, df/n and then by size. 2988 // 2989 // FIXME: The size tests here should instead be tablegen'd along with the 2990 // definitions from include/clang/Basic/BuiltinsMips.def. 2991 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2992 // be too. 2993 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2994 unsigned i = 0, l = 0, u = 0, m = 0; 2995 switch (BuiltinID) { 2996 default: return false; 2997 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2998 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2999 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3000 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3001 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3002 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3003 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3004 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3005 // df/m field. 3006 // These intrinsics take an unsigned 3 bit immediate. 3007 case Mips::BI__builtin_msa_bclri_b: 3008 case Mips::BI__builtin_msa_bnegi_b: 3009 case Mips::BI__builtin_msa_bseti_b: 3010 case Mips::BI__builtin_msa_sat_s_b: 3011 case Mips::BI__builtin_msa_sat_u_b: 3012 case Mips::BI__builtin_msa_slli_b: 3013 case Mips::BI__builtin_msa_srai_b: 3014 case Mips::BI__builtin_msa_srari_b: 3015 case Mips::BI__builtin_msa_srli_b: 3016 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3017 case Mips::BI__builtin_msa_binsli_b: 3018 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3019 // These intrinsics take an unsigned 4 bit immediate. 3020 case Mips::BI__builtin_msa_bclri_h: 3021 case Mips::BI__builtin_msa_bnegi_h: 3022 case Mips::BI__builtin_msa_bseti_h: 3023 case Mips::BI__builtin_msa_sat_s_h: 3024 case Mips::BI__builtin_msa_sat_u_h: 3025 case Mips::BI__builtin_msa_slli_h: 3026 case Mips::BI__builtin_msa_srai_h: 3027 case Mips::BI__builtin_msa_srari_h: 3028 case Mips::BI__builtin_msa_srli_h: 3029 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3030 case Mips::BI__builtin_msa_binsli_h: 3031 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3032 // These intrinsics take an unsigned 5 bit immediate. 3033 // The first block of intrinsics actually have an unsigned 5 bit field, 3034 // not a df/n field. 3035 case Mips::BI__builtin_msa_cfcmsa: 3036 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3037 case Mips::BI__builtin_msa_clei_u_b: 3038 case Mips::BI__builtin_msa_clei_u_h: 3039 case Mips::BI__builtin_msa_clei_u_w: 3040 case Mips::BI__builtin_msa_clei_u_d: 3041 case Mips::BI__builtin_msa_clti_u_b: 3042 case Mips::BI__builtin_msa_clti_u_h: 3043 case Mips::BI__builtin_msa_clti_u_w: 3044 case Mips::BI__builtin_msa_clti_u_d: 3045 case Mips::BI__builtin_msa_maxi_u_b: 3046 case Mips::BI__builtin_msa_maxi_u_h: 3047 case Mips::BI__builtin_msa_maxi_u_w: 3048 case Mips::BI__builtin_msa_maxi_u_d: 3049 case Mips::BI__builtin_msa_mini_u_b: 3050 case Mips::BI__builtin_msa_mini_u_h: 3051 case Mips::BI__builtin_msa_mini_u_w: 3052 case Mips::BI__builtin_msa_mini_u_d: 3053 case Mips::BI__builtin_msa_addvi_b: 3054 case Mips::BI__builtin_msa_addvi_h: 3055 case Mips::BI__builtin_msa_addvi_w: 3056 case Mips::BI__builtin_msa_addvi_d: 3057 case Mips::BI__builtin_msa_bclri_w: 3058 case Mips::BI__builtin_msa_bnegi_w: 3059 case Mips::BI__builtin_msa_bseti_w: 3060 case Mips::BI__builtin_msa_sat_s_w: 3061 case Mips::BI__builtin_msa_sat_u_w: 3062 case Mips::BI__builtin_msa_slli_w: 3063 case Mips::BI__builtin_msa_srai_w: 3064 case Mips::BI__builtin_msa_srari_w: 3065 case Mips::BI__builtin_msa_srli_w: 3066 case Mips::BI__builtin_msa_srlri_w: 3067 case Mips::BI__builtin_msa_subvi_b: 3068 case Mips::BI__builtin_msa_subvi_h: 3069 case Mips::BI__builtin_msa_subvi_w: 3070 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3071 case Mips::BI__builtin_msa_binsli_w: 3072 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3073 // These intrinsics take an unsigned 6 bit immediate. 3074 case Mips::BI__builtin_msa_bclri_d: 3075 case Mips::BI__builtin_msa_bnegi_d: 3076 case Mips::BI__builtin_msa_bseti_d: 3077 case Mips::BI__builtin_msa_sat_s_d: 3078 case Mips::BI__builtin_msa_sat_u_d: 3079 case Mips::BI__builtin_msa_slli_d: 3080 case Mips::BI__builtin_msa_srai_d: 3081 case Mips::BI__builtin_msa_srari_d: 3082 case Mips::BI__builtin_msa_srli_d: 3083 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3084 case Mips::BI__builtin_msa_binsli_d: 3085 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3086 // These intrinsics take a signed 5 bit immediate. 3087 case Mips::BI__builtin_msa_ceqi_b: 3088 case Mips::BI__builtin_msa_ceqi_h: 3089 case Mips::BI__builtin_msa_ceqi_w: 3090 case Mips::BI__builtin_msa_ceqi_d: 3091 case Mips::BI__builtin_msa_clti_s_b: 3092 case Mips::BI__builtin_msa_clti_s_h: 3093 case Mips::BI__builtin_msa_clti_s_w: 3094 case Mips::BI__builtin_msa_clti_s_d: 3095 case Mips::BI__builtin_msa_clei_s_b: 3096 case Mips::BI__builtin_msa_clei_s_h: 3097 case Mips::BI__builtin_msa_clei_s_w: 3098 case Mips::BI__builtin_msa_clei_s_d: 3099 case Mips::BI__builtin_msa_maxi_s_b: 3100 case Mips::BI__builtin_msa_maxi_s_h: 3101 case Mips::BI__builtin_msa_maxi_s_w: 3102 case Mips::BI__builtin_msa_maxi_s_d: 3103 case Mips::BI__builtin_msa_mini_s_b: 3104 case Mips::BI__builtin_msa_mini_s_h: 3105 case Mips::BI__builtin_msa_mini_s_w: 3106 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3107 // These intrinsics take an unsigned 8 bit immediate. 3108 case Mips::BI__builtin_msa_andi_b: 3109 case Mips::BI__builtin_msa_nori_b: 3110 case Mips::BI__builtin_msa_ori_b: 3111 case Mips::BI__builtin_msa_shf_b: 3112 case Mips::BI__builtin_msa_shf_h: 3113 case Mips::BI__builtin_msa_shf_w: 3114 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3115 case Mips::BI__builtin_msa_bseli_b: 3116 case Mips::BI__builtin_msa_bmnzi_b: 3117 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3118 // df/n format 3119 // These intrinsics take an unsigned 4 bit immediate. 3120 case Mips::BI__builtin_msa_copy_s_b: 3121 case Mips::BI__builtin_msa_copy_u_b: 3122 case Mips::BI__builtin_msa_insve_b: 3123 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3124 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3125 // These intrinsics take an unsigned 3 bit immediate. 3126 case Mips::BI__builtin_msa_copy_s_h: 3127 case Mips::BI__builtin_msa_copy_u_h: 3128 case Mips::BI__builtin_msa_insve_h: 3129 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3130 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3131 // These intrinsics take an unsigned 2 bit immediate. 3132 case Mips::BI__builtin_msa_copy_s_w: 3133 case Mips::BI__builtin_msa_copy_u_w: 3134 case Mips::BI__builtin_msa_insve_w: 3135 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3136 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3137 // These intrinsics take an unsigned 1 bit immediate. 3138 case Mips::BI__builtin_msa_copy_s_d: 3139 case Mips::BI__builtin_msa_copy_u_d: 3140 case Mips::BI__builtin_msa_insve_d: 3141 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3142 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3143 // Memory offsets and immediate loads. 3144 // These intrinsics take a signed 10 bit immediate. 3145 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3146 case Mips::BI__builtin_msa_ldi_h: 3147 case Mips::BI__builtin_msa_ldi_w: 3148 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3149 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3150 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3151 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3152 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3153 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3154 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3155 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3156 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3157 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3158 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3159 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3160 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3161 } 3162 3163 if (!m) 3164 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3165 3166 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3167 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3168 } 3169 3170 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3171 /// advancing the pointer over the consumed characters. The decoded type is 3172 /// returned. If the decoded type represents a constant integer with a 3173 /// constraint on its value then Mask is set to that value. The type descriptors 3174 /// used in Str are specific to PPC MMA builtins and are documented in the file 3175 /// defining the PPC builtins. 3176 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3177 unsigned &Mask) { 3178 bool RequireICE = false; 3179 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3180 switch (*Str++) { 3181 case 'V': 3182 return Context.getVectorType(Context.UnsignedCharTy, 16, 3183 VectorType::VectorKind::AltiVecVector); 3184 case 'i': { 3185 char *End; 3186 unsigned size = strtoul(Str, &End, 10); 3187 assert(End != Str && "Missing constant parameter constraint"); 3188 Str = End; 3189 Mask = size; 3190 return Context.IntTy; 3191 } 3192 case 'W': { 3193 char *End; 3194 unsigned size = strtoul(Str, &End, 10); 3195 assert(End != Str && "Missing PowerPC MMA type size"); 3196 Str = End; 3197 QualType Type; 3198 switch (size) { 3199 #define PPC_MMA_VECTOR_TYPE(typeName, Id, size) \ 3200 case size: Type = Context.Id##Ty; break; 3201 #include "clang/Basic/PPCTypes.def" 3202 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3203 } 3204 bool CheckVectorArgs = false; 3205 while (!CheckVectorArgs) { 3206 switch (*Str++) { 3207 case '*': 3208 Type = Context.getPointerType(Type); 3209 break; 3210 case 'C': 3211 Type = Type.withConst(); 3212 break; 3213 default: 3214 CheckVectorArgs = true; 3215 --Str; 3216 break; 3217 } 3218 } 3219 return Type; 3220 } 3221 default: 3222 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3223 } 3224 } 3225 3226 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3227 CallExpr *TheCall) { 3228 unsigned i = 0, l = 0, u = 0; 3229 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3230 BuiltinID == PPC::BI__builtin_divdeu || 3231 BuiltinID == PPC::BI__builtin_bpermd; 3232 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3233 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3234 BuiltinID == PPC::BI__builtin_divweu || 3235 BuiltinID == PPC::BI__builtin_divde || 3236 BuiltinID == PPC::BI__builtin_divdeu; 3237 3238 if (Is64BitBltin && !IsTarget64Bit) 3239 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3240 << TheCall->getSourceRange(); 3241 3242 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3243 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3244 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3245 << TheCall->getSourceRange(); 3246 3247 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3248 if (!TI.hasFeature("vsx")) 3249 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3250 << TheCall->getSourceRange(); 3251 return false; 3252 }; 3253 3254 switch (BuiltinID) { 3255 default: return false; 3256 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3257 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3258 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3259 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3260 case PPC::BI__builtin_altivec_dss: 3261 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3262 case PPC::BI__builtin_tbegin: 3263 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3264 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3265 case PPC::BI__builtin_tabortwc: 3266 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3267 case PPC::BI__builtin_tabortwci: 3268 case PPC::BI__builtin_tabortdci: 3269 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3270 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3271 case PPC::BI__builtin_altivec_dst: 3272 case PPC::BI__builtin_altivec_dstt: 3273 case PPC::BI__builtin_altivec_dstst: 3274 case PPC::BI__builtin_altivec_dststt: 3275 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3276 case PPC::BI__builtin_vsx_xxpermdi: 3277 case PPC::BI__builtin_vsx_xxsldwi: 3278 return SemaBuiltinVSX(TheCall); 3279 case PPC::BI__builtin_unpack_vector_int128: 3280 return SemaVSXCheck(TheCall) || 3281 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3282 case PPC::BI__builtin_pack_vector_int128: 3283 return SemaVSXCheck(TheCall); 3284 case PPC::BI__builtin_altivec_vgnb: 3285 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3286 case PPC::BI__builtin_altivec_vec_replace_elt: 3287 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3288 QualType VecTy = TheCall->getArg(0)->getType(); 3289 QualType EltTy = TheCall->getArg(1)->getType(); 3290 unsigned Width = Context.getIntWidth(EltTy); 3291 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3292 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3293 } 3294 case PPC::BI__builtin_vsx_xxeval: 3295 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3296 case PPC::BI__builtin_altivec_vsldbi: 3297 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3298 case PPC::BI__builtin_altivec_vsrdbi: 3299 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3300 case PPC::BI__builtin_vsx_xxpermx: 3301 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3302 #define MMA_BUILTIN(Name, Types, Acc) \ 3303 case PPC::BI__builtin_mma_##Name: \ 3304 return SemaBuiltinPPCMMACall(TheCall, Types); 3305 #include "clang/Basic/BuiltinsPPC.def" 3306 } 3307 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3308 } 3309 3310 // Check if the given type is a non-pointer PPC MMA type. This function is used 3311 // in Sema to prevent invalid uses of restricted PPC MMA types. 3312 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3313 if (Type->isPointerType() || Type->isArrayType()) 3314 return false; 3315 3316 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3317 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3318 if (false 3319 #include "clang/Basic/PPCTypes.def" 3320 ) { 3321 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3322 return true; 3323 } 3324 return false; 3325 } 3326 3327 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3328 CallExpr *TheCall) { 3329 // position of memory order and scope arguments in the builtin 3330 unsigned OrderIndex, ScopeIndex; 3331 switch (BuiltinID) { 3332 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3333 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3334 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3335 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3336 OrderIndex = 2; 3337 ScopeIndex = 3; 3338 break; 3339 case AMDGPU::BI__builtin_amdgcn_fence: 3340 OrderIndex = 0; 3341 ScopeIndex = 1; 3342 break; 3343 default: 3344 return false; 3345 } 3346 3347 ExprResult Arg = TheCall->getArg(OrderIndex); 3348 auto ArgExpr = Arg.get(); 3349 Expr::EvalResult ArgResult; 3350 3351 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3352 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3353 << ArgExpr->getType(); 3354 int ord = ArgResult.Val.getInt().getZExtValue(); 3355 3356 // Check valididty of memory ordering as per C11 / C++11's memody model. 3357 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3358 case llvm::AtomicOrderingCABI::acquire: 3359 case llvm::AtomicOrderingCABI::release: 3360 case llvm::AtomicOrderingCABI::acq_rel: 3361 case llvm::AtomicOrderingCABI::seq_cst: 3362 break; 3363 default: { 3364 return Diag(ArgExpr->getBeginLoc(), 3365 diag::warn_atomic_op_has_invalid_memory_order) 3366 << ArgExpr->getSourceRange(); 3367 } 3368 } 3369 3370 Arg = TheCall->getArg(ScopeIndex); 3371 ArgExpr = Arg.get(); 3372 Expr::EvalResult ArgResult1; 3373 // Check that sync scope is a constant literal 3374 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3375 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3376 << ArgExpr->getType(); 3377 3378 return false; 3379 } 3380 3381 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3382 CallExpr *TheCall) { 3383 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3384 Expr *Arg = TheCall->getArg(0); 3385 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3386 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3387 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3388 << Arg->getSourceRange(); 3389 } 3390 3391 // For intrinsics which take an immediate value as part of the instruction, 3392 // range check them here. 3393 unsigned i = 0, l = 0, u = 0; 3394 switch (BuiltinID) { 3395 default: return false; 3396 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3397 case SystemZ::BI__builtin_s390_verimb: 3398 case SystemZ::BI__builtin_s390_verimh: 3399 case SystemZ::BI__builtin_s390_verimf: 3400 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3401 case SystemZ::BI__builtin_s390_vfaeb: 3402 case SystemZ::BI__builtin_s390_vfaeh: 3403 case SystemZ::BI__builtin_s390_vfaef: 3404 case SystemZ::BI__builtin_s390_vfaebs: 3405 case SystemZ::BI__builtin_s390_vfaehs: 3406 case SystemZ::BI__builtin_s390_vfaefs: 3407 case SystemZ::BI__builtin_s390_vfaezb: 3408 case SystemZ::BI__builtin_s390_vfaezh: 3409 case SystemZ::BI__builtin_s390_vfaezf: 3410 case SystemZ::BI__builtin_s390_vfaezbs: 3411 case SystemZ::BI__builtin_s390_vfaezhs: 3412 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3413 case SystemZ::BI__builtin_s390_vfisb: 3414 case SystemZ::BI__builtin_s390_vfidb: 3415 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3416 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3417 case SystemZ::BI__builtin_s390_vftcisb: 3418 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3419 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3420 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3421 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3422 case SystemZ::BI__builtin_s390_vstrcb: 3423 case SystemZ::BI__builtin_s390_vstrch: 3424 case SystemZ::BI__builtin_s390_vstrcf: 3425 case SystemZ::BI__builtin_s390_vstrczb: 3426 case SystemZ::BI__builtin_s390_vstrczh: 3427 case SystemZ::BI__builtin_s390_vstrczf: 3428 case SystemZ::BI__builtin_s390_vstrcbs: 3429 case SystemZ::BI__builtin_s390_vstrchs: 3430 case SystemZ::BI__builtin_s390_vstrcfs: 3431 case SystemZ::BI__builtin_s390_vstrczbs: 3432 case SystemZ::BI__builtin_s390_vstrczhs: 3433 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3434 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3435 case SystemZ::BI__builtin_s390_vfminsb: 3436 case SystemZ::BI__builtin_s390_vfmaxsb: 3437 case SystemZ::BI__builtin_s390_vfmindb: 3438 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3439 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3440 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3441 } 3442 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3443 } 3444 3445 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3446 /// This checks that the target supports __builtin_cpu_supports and 3447 /// that the string argument is constant and valid. 3448 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3449 CallExpr *TheCall) { 3450 Expr *Arg = TheCall->getArg(0); 3451 3452 // Check if the argument is a string literal. 3453 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3454 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3455 << Arg->getSourceRange(); 3456 3457 // Check the contents of the string. 3458 StringRef Feature = 3459 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3460 if (!TI.validateCpuSupports(Feature)) 3461 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3462 << Arg->getSourceRange(); 3463 return false; 3464 } 3465 3466 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3467 /// This checks that the target supports __builtin_cpu_is and 3468 /// that the string argument is constant and valid. 3469 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3470 Expr *Arg = TheCall->getArg(0); 3471 3472 // Check if the argument is a string literal. 3473 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3474 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3475 << Arg->getSourceRange(); 3476 3477 // Check the contents of the string. 3478 StringRef Feature = 3479 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3480 if (!TI.validateCpuIs(Feature)) 3481 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3482 << Arg->getSourceRange(); 3483 return false; 3484 } 3485 3486 // Check if the rounding mode is legal. 3487 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3488 // Indicates if this instruction has rounding control or just SAE. 3489 bool HasRC = false; 3490 3491 unsigned ArgNum = 0; 3492 switch (BuiltinID) { 3493 default: 3494 return false; 3495 case X86::BI__builtin_ia32_vcvttsd2si32: 3496 case X86::BI__builtin_ia32_vcvttsd2si64: 3497 case X86::BI__builtin_ia32_vcvttsd2usi32: 3498 case X86::BI__builtin_ia32_vcvttsd2usi64: 3499 case X86::BI__builtin_ia32_vcvttss2si32: 3500 case X86::BI__builtin_ia32_vcvttss2si64: 3501 case X86::BI__builtin_ia32_vcvttss2usi32: 3502 case X86::BI__builtin_ia32_vcvttss2usi64: 3503 ArgNum = 1; 3504 break; 3505 case X86::BI__builtin_ia32_maxpd512: 3506 case X86::BI__builtin_ia32_maxps512: 3507 case X86::BI__builtin_ia32_minpd512: 3508 case X86::BI__builtin_ia32_minps512: 3509 ArgNum = 2; 3510 break; 3511 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3512 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3513 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3514 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3515 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3516 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3517 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3518 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3519 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3520 case X86::BI__builtin_ia32_exp2pd_mask: 3521 case X86::BI__builtin_ia32_exp2ps_mask: 3522 case X86::BI__builtin_ia32_getexppd512_mask: 3523 case X86::BI__builtin_ia32_getexpps512_mask: 3524 case X86::BI__builtin_ia32_rcp28pd_mask: 3525 case X86::BI__builtin_ia32_rcp28ps_mask: 3526 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3527 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3528 case X86::BI__builtin_ia32_vcomisd: 3529 case X86::BI__builtin_ia32_vcomiss: 3530 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3531 ArgNum = 3; 3532 break; 3533 case X86::BI__builtin_ia32_cmppd512_mask: 3534 case X86::BI__builtin_ia32_cmpps512_mask: 3535 case X86::BI__builtin_ia32_cmpsd_mask: 3536 case X86::BI__builtin_ia32_cmpss_mask: 3537 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3538 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3539 case X86::BI__builtin_ia32_getexpss128_round_mask: 3540 case X86::BI__builtin_ia32_getmantpd512_mask: 3541 case X86::BI__builtin_ia32_getmantps512_mask: 3542 case X86::BI__builtin_ia32_maxsd_round_mask: 3543 case X86::BI__builtin_ia32_maxss_round_mask: 3544 case X86::BI__builtin_ia32_minsd_round_mask: 3545 case X86::BI__builtin_ia32_minss_round_mask: 3546 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3547 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3548 case X86::BI__builtin_ia32_reducepd512_mask: 3549 case X86::BI__builtin_ia32_reduceps512_mask: 3550 case X86::BI__builtin_ia32_rndscalepd_mask: 3551 case X86::BI__builtin_ia32_rndscaleps_mask: 3552 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3553 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3554 ArgNum = 4; 3555 break; 3556 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3557 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3558 case X86::BI__builtin_ia32_fixupimmps512_mask: 3559 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3560 case X86::BI__builtin_ia32_fixupimmsd_mask: 3561 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3562 case X86::BI__builtin_ia32_fixupimmss_mask: 3563 case X86::BI__builtin_ia32_fixupimmss_maskz: 3564 case X86::BI__builtin_ia32_getmantsd_round_mask: 3565 case X86::BI__builtin_ia32_getmantss_round_mask: 3566 case X86::BI__builtin_ia32_rangepd512_mask: 3567 case X86::BI__builtin_ia32_rangeps512_mask: 3568 case X86::BI__builtin_ia32_rangesd128_round_mask: 3569 case X86::BI__builtin_ia32_rangess128_round_mask: 3570 case X86::BI__builtin_ia32_reducesd_mask: 3571 case X86::BI__builtin_ia32_reducess_mask: 3572 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3573 case X86::BI__builtin_ia32_rndscaless_round_mask: 3574 ArgNum = 5; 3575 break; 3576 case X86::BI__builtin_ia32_vcvtsd2si64: 3577 case X86::BI__builtin_ia32_vcvtsd2si32: 3578 case X86::BI__builtin_ia32_vcvtsd2usi32: 3579 case X86::BI__builtin_ia32_vcvtsd2usi64: 3580 case X86::BI__builtin_ia32_vcvtss2si32: 3581 case X86::BI__builtin_ia32_vcvtss2si64: 3582 case X86::BI__builtin_ia32_vcvtss2usi32: 3583 case X86::BI__builtin_ia32_vcvtss2usi64: 3584 case X86::BI__builtin_ia32_sqrtpd512: 3585 case X86::BI__builtin_ia32_sqrtps512: 3586 ArgNum = 1; 3587 HasRC = true; 3588 break; 3589 case X86::BI__builtin_ia32_addpd512: 3590 case X86::BI__builtin_ia32_addps512: 3591 case X86::BI__builtin_ia32_divpd512: 3592 case X86::BI__builtin_ia32_divps512: 3593 case X86::BI__builtin_ia32_mulpd512: 3594 case X86::BI__builtin_ia32_mulps512: 3595 case X86::BI__builtin_ia32_subpd512: 3596 case X86::BI__builtin_ia32_subps512: 3597 case X86::BI__builtin_ia32_cvtsi2sd64: 3598 case X86::BI__builtin_ia32_cvtsi2ss32: 3599 case X86::BI__builtin_ia32_cvtsi2ss64: 3600 case X86::BI__builtin_ia32_cvtusi2sd64: 3601 case X86::BI__builtin_ia32_cvtusi2ss32: 3602 case X86::BI__builtin_ia32_cvtusi2ss64: 3603 ArgNum = 2; 3604 HasRC = true; 3605 break; 3606 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3607 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3608 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3609 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3610 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3611 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3612 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3613 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3614 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3615 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3616 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3617 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3618 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3619 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3620 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3621 ArgNum = 3; 3622 HasRC = true; 3623 break; 3624 case X86::BI__builtin_ia32_addss_round_mask: 3625 case X86::BI__builtin_ia32_addsd_round_mask: 3626 case X86::BI__builtin_ia32_divss_round_mask: 3627 case X86::BI__builtin_ia32_divsd_round_mask: 3628 case X86::BI__builtin_ia32_mulss_round_mask: 3629 case X86::BI__builtin_ia32_mulsd_round_mask: 3630 case X86::BI__builtin_ia32_subss_round_mask: 3631 case X86::BI__builtin_ia32_subsd_round_mask: 3632 case X86::BI__builtin_ia32_scalefpd512_mask: 3633 case X86::BI__builtin_ia32_scalefps512_mask: 3634 case X86::BI__builtin_ia32_scalefsd_round_mask: 3635 case X86::BI__builtin_ia32_scalefss_round_mask: 3636 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3637 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3638 case X86::BI__builtin_ia32_sqrtss_round_mask: 3639 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3640 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3641 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3642 case X86::BI__builtin_ia32_vfmaddss3_mask: 3643 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3644 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3645 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3646 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3647 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3648 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3649 case X86::BI__builtin_ia32_vfmaddps512_mask: 3650 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3651 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3652 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3653 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3654 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3655 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3656 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3657 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3658 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3659 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3660 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3661 ArgNum = 4; 3662 HasRC = true; 3663 break; 3664 } 3665 3666 llvm::APSInt Result; 3667 3668 // We can't check the value of a dependent argument. 3669 Expr *Arg = TheCall->getArg(ArgNum); 3670 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3671 return false; 3672 3673 // Check constant-ness first. 3674 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3675 return true; 3676 3677 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3678 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3679 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3680 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3681 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3682 Result == 8/*ROUND_NO_EXC*/ || 3683 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3684 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3685 return false; 3686 3687 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3688 << Arg->getSourceRange(); 3689 } 3690 3691 // Check if the gather/scatter scale is legal. 3692 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3693 CallExpr *TheCall) { 3694 unsigned ArgNum = 0; 3695 switch (BuiltinID) { 3696 default: 3697 return false; 3698 case X86::BI__builtin_ia32_gatherpfdpd: 3699 case X86::BI__builtin_ia32_gatherpfdps: 3700 case X86::BI__builtin_ia32_gatherpfqpd: 3701 case X86::BI__builtin_ia32_gatherpfqps: 3702 case X86::BI__builtin_ia32_scatterpfdpd: 3703 case X86::BI__builtin_ia32_scatterpfdps: 3704 case X86::BI__builtin_ia32_scatterpfqpd: 3705 case X86::BI__builtin_ia32_scatterpfqps: 3706 ArgNum = 3; 3707 break; 3708 case X86::BI__builtin_ia32_gatherd_pd: 3709 case X86::BI__builtin_ia32_gatherd_pd256: 3710 case X86::BI__builtin_ia32_gatherq_pd: 3711 case X86::BI__builtin_ia32_gatherq_pd256: 3712 case X86::BI__builtin_ia32_gatherd_ps: 3713 case X86::BI__builtin_ia32_gatherd_ps256: 3714 case X86::BI__builtin_ia32_gatherq_ps: 3715 case X86::BI__builtin_ia32_gatherq_ps256: 3716 case X86::BI__builtin_ia32_gatherd_q: 3717 case X86::BI__builtin_ia32_gatherd_q256: 3718 case X86::BI__builtin_ia32_gatherq_q: 3719 case X86::BI__builtin_ia32_gatherq_q256: 3720 case X86::BI__builtin_ia32_gatherd_d: 3721 case X86::BI__builtin_ia32_gatherd_d256: 3722 case X86::BI__builtin_ia32_gatherq_d: 3723 case X86::BI__builtin_ia32_gatherq_d256: 3724 case X86::BI__builtin_ia32_gather3div2df: 3725 case X86::BI__builtin_ia32_gather3div2di: 3726 case X86::BI__builtin_ia32_gather3div4df: 3727 case X86::BI__builtin_ia32_gather3div4di: 3728 case X86::BI__builtin_ia32_gather3div4sf: 3729 case X86::BI__builtin_ia32_gather3div4si: 3730 case X86::BI__builtin_ia32_gather3div8sf: 3731 case X86::BI__builtin_ia32_gather3div8si: 3732 case X86::BI__builtin_ia32_gather3siv2df: 3733 case X86::BI__builtin_ia32_gather3siv2di: 3734 case X86::BI__builtin_ia32_gather3siv4df: 3735 case X86::BI__builtin_ia32_gather3siv4di: 3736 case X86::BI__builtin_ia32_gather3siv4sf: 3737 case X86::BI__builtin_ia32_gather3siv4si: 3738 case X86::BI__builtin_ia32_gather3siv8sf: 3739 case X86::BI__builtin_ia32_gather3siv8si: 3740 case X86::BI__builtin_ia32_gathersiv8df: 3741 case X86::BI__builtin_ia32_gathersiv16sf: 3742 case X86::BI__builtin_ia32_gatherdiv8df: 3743 case X86::BI__builtin_ia32_gatherdiv16sf: 3744 case X86::BI__builtin_ia32_gathersiv8di: 3745 case X86::BI__builtin_ia32_gathersiv16si: 3746 case X86::BI__builtin_ia32_gatherdiv8di: 3747 case X86::BI__builtin_ia32_gatherdiv16si: 3748 case X86::BI__builtin_ia32_scatterdiv2df: 3749 case X86::BI__builtin_ia32_scatterdiv2di: 3750 case X86::BI__builtin_ia32_scatterdiv4df: 3751 case X86::BI__builtin_ia32_scatterdiv4di: 3752 case X86::BI__builtin_ia32_scatterdiv4sf: 3753 case X86::BI__builtin_ia32_scatterdiv4si: 3754 case X86::BI__builtin_ia32_scatterdiv8sf: 3755 case X86::BI__builtin_ia32_scatterdiv8si: 3756 case X86::BI__builtin_ia32_scattersiv2df: 3757 case X86::BI__builtin_ia32_scattersiv2di: 3758 case X86::BI__builtin_ia32_scattersiv4df: 3759 case X86::BI__builtin_ia32_scattersiv4di: 3760 case X86::BI__builtin_ia32_scattersiv4sf: 3761 case X86::BI__builtin_ia32_scattersiv4si: 3762 case X86::BI__builtin_ia32_scattersiv8sf: 3763 case X86::BI__builtin_ia32_scattersiv8si: 3764 case X86::BI__builtin_ia32_scattersiv8df: 3765 case X86::BI__builtin_ia32_scattersiv16sf: 3766 case X86::BI__builtin_ia32_scatterdiv8df: 3767 case X86::BI__builtin_ia32_scatterdiv16sf: 3768 case X86::BI__builtin_ia32_scattersiv8di: 3769 case X86::BI__builtin_ia32_scattersiv16si: 3770 case X86::BI__builtin_ia32_scatterdiv8di: 3771 case X86::BI__builtin_ia32_scatterdiv16si: 3772 ArgNum = 4; 3773 break; 3774 } 3775 3776 llvm::APSInt Result; 3777 3778 // We can't check the value of a dependent argument. 3779 Expr *Arg = TheCall->getArg(ArgNum); 3780 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3781 return false; 3782 3783 // Check constant-ness first. 3784 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3785 return true; 3786 3787 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3788 return false; 3789 3790 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3791 << Arg->getSourceRange(); 3792 } 3793 3794 enum { TileRegLow = 0, TileRegHigh = 7 }; 3795 3796 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3797 ArrayRef<int> ArgNums) { 3798 for (int ArgNum : ArgNums) { 3799 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3800 return true; 3801 } 3802 return false; 3803 } 3804 3805 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3806 ArrayRef<int> ArgNums) { 3807 // Because the max number of tile register is TileRegHigh + 1, so here we use 3808 // each bit to represent the usage of them in bitset. 3809 std::bitset<TileRegHigh + 1> ArgValues; 3810 for (int ArgNum : ArgNums) { 3811 Expr *Arg = TheCall->getArg(ArgNum); 3812 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3813 continue; 3814 3815 llvm::APSInt Result; 3816 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3817 return true; 3818 int ArgExtValue = Result.getExtValue(); 3819 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3820 "Incorrect tile register num."); 3821 if (ArgValues.test(ArgExtValue)) 3822 return Diag(TheCall->getBeginLoc(), 3823 diag::err_x86_builtin_tile_arg_duplicate) 3824 << TheCall->getArg(ArgNum)->getSourceRange(); 3825 ArgValues.set(ArgExtValue); 3826 } 3827 return false; 3828 } 3829 3830 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3831 ArrayRef<int> ArgNums) { 3832 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3833 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3834 } 3835 3836 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3837 switch (BuiltinID) { 3838 default: 3839 return false; 3840 case X86::BI__builtin_ia32_tileloadd64: 3841 case X86::BI__builtin_ia32_tileloaddt164: 3842 case X86::BI__builtin_ia32_tilestored64: 3843 case X86::BI__builtin_ia32_tilezero: 3844 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3845 case X86::BI__builtin_ia32_tdpbssd: 3846 case X86::BI__builtin_ia32_tdpbsud: 3847 case X86::BI__builtin_ia32_tdpbusd: 3848 case X86::BI__builtin_ia32_tdpbuud: 3849 case X86::BI__builtin_ia32_tdpbf16ps: 3850 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3851 } 3852 } 3853 static bool isX86_32Builtin(unsigned BuiltinID) { 3854 // These builtins only work on x86-32 targets. 3855 switch (BuiltinID) { 3856 case X86::BI__builtin_ia32_readeflags_u32: 3857 case X86::BI__builtin_ia32_writeeflags_u32: 3858 return true; 3859 } 3860 3861 return false; 3862 } 3863 3864 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3865 CallExpr *TheCall) { 3866 if (BuiltinID == X86::BI__builtin_cpu_supports) 3867 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3868 3869 if (BuiltinID == X86::BI__builtin_cpu_is) 3870 return SemaBuiltinCpuIs(*this, TI, TheCall); 3871 3872 // Check for 32-bit only builtins on a 64-bit target. 3873 const llvm::Triple &TT = TI.getTriple(); 3874 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3875 return Diag(TheCall->getCallee()->getBeginLoc(), 3876 diag::err_32_bit_builtin_64_bit_tgt); 3877 3878 // If the intrinsic has rounding or SAE make sure its valid. 3879 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3880 return true; 3881 3882 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3883 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3884 return true; 3885 3886 // If the intrinsic has a tile arguments, make sure they are valid. 3887 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3888 return true; 3889 3890 // For intrinsics which take an immediate value as part of the instruction, 3891 // range check them here. 3892 int i = 0, l = 0, u = 0; 3893 switch (BuiltinID) { 3894 default: 3895 return false; 3896 case X86::BI__builtin_ia32_vec_ext_v2si: 3897 case X86::BI__builtin_ia32_vec_ext_v2di: 3898 case X86::BI__builtin_ia32_vextractf128_pd256: 3899 case X86::BI__builtin_ia32_vextractf128_ps256: 3900 case X86::BI__builtin_ia32_vextractf128_si256: 3901 case X86::BI__builtin_ia32_extract128i256: 3902 case X86::BI__builtin_ia32_extractf64x4_mask: 3903 case X86::BI__builtin_ia32_extracti64x4_mask: 3904 case X86::BI__builtin_ia32_extractf32x8_mask: 3905 case X86::BI__builtin_ia32_extracti32x8_mask: 3906 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3907 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3908 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3909 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3910 i = 1; l = 0; u = 1; 3911 break; 3912 case X86::BI__builtin_ia32_vec_set_v2di: 3913 case X86::BI__builtin_ia32_vinsertf128_pd256: 3914 case X86::BI__builtin_ia32_vinsertf128_ps256: 3915 case X86::BI__builtin_ia32_vinsertf128_si256: 3916 case X86::BI__builtin_ia32_insert128i256: 3917 case X86::BI__builtin_ia32_insertf32x8: 3918 case X86::BI__builtin_ia32_inserti32x8: 3919 case X86::BI__builtin_ia32_insertf64x4: 3920 case X86::BI__builtin_ia32_inserti64x4: 3921 case X86::BI__builtin_ia32_insertf64x2_256: 3922 case X86::BI__builtin_ia32_inserti64x2_256: 3923 case X86::BI__builtin_ia32_insertf32x4_256: 3924 case X86::BI__builtin_ia32_inserti32x4_256: 3925 i = 2; l = 0; u = 1; 3926 break; 3927 case X86::BI__builtin_ia32_vpermilpd: 3928 case X86::BI__builtin_ia32_vec_ext_v4hi: 3929 case X86::BI__builtin_ia32_vec_ext_v4si: 3930 case X86::BI__builtin_ia32_vec_ext_v4sf: 3931 case X86::BI__builtin_ia32_vec_ext_v4di: 3932 case X86::BI__builtin_ia32_extractf32x4_mask: 3933 case X86::BI__builtin_ia32_extracti32x4_mask: 3934 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3935 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3936 i = 1; l = 0; u = 3; 3937 break; 3938 case X86::BI_mm_prefetch: 3939 case X86::BI__builtin_ia32_vec_ext_v8hi: 3940 case X86::BI__builtin_ia32_vec_ext_v8si: 3941 i = 1; l = 0; u = 7; 3942 break; 3943 case X86::BI__builtin_ia32_sha1rnds4: 3944 case X86::BI__builtin_ia32_blendpd: 3945 case X86::BI__builtin_ia32_shufpd: 3946 case X86::BI__builtin_ia32_vec_set_v4hi: 3947 case X86::BI__builtin_ia32_vec_set_v4si: 3948 case X86::BI__builtin_ia32_vec_set_v4di: 3949 case X86::BI__builtin_ia32_shuf_f32x4_256: 3950 case X86::BI__builtin_ia32_shuf_f64x2_256: 3951 case X86::BI__builtin_ia32_shuf_i32x4_256: 3952 case X86::BI__builtin_ia32_shuf_i64x2_256: 3953 case X86::BI__builtin_ia32_insertf64x2_512: 3954 case X86::BI__builtin_ia32_inserti64x2_512: 3955 case X86::BI__builtin_ia32_insertf32x4: 3956 case X86::BI__builtin_ia32_inserti32x4: 3957 i = 2; l = 0; u = 3; 3958 break; 3959 case X86::BI__builtin_ia32_vpermil2pd: 3960 case X86::BI__builtin_ia32_vpermil2pd256: 3961 case X86::BI__builtin_ia32_vpermil2ps: 3962 case X86::BI__builtin_ia32_vpermil2ps256: 3963 i = 3; l = 0; u = 3; 3964 break; 3965 case X86::BI__builtin_ia32_cmpb128_mask: 3966 case X86::BI__builtin_ia32_cmpw128_mask: 3967 case X86::BI__builtin_ia32_cmpd128_mask: 3968 case X86::BI__builtin_ia32_cmpq128_mask: 3969 case X86::BI__builtin_ia32_cmpb256_mask: 3970 case X86::BI__builtin_ia32_cmpw256_mask: 3971 case X86::BI__builtin_ia32_cmpd256_mask: 3972 case X86::BI__builtin_ia32_cmpq256_mask: 3973 case X86::BI__builtin_ia32_cmpb512_mask: 3974 case X86::BI__builtin_ia32_cmpw512_mask: 3975 case X86::BI__builtin_ia32_cmpd512_mask: 3976 case X86::BI__builtin_ia32_cmpq512_mask: 3977 case X86::BI__builtin_ia32_ucmpb128_mask: 3978 case X86::BI__builtin_ia32_ucmpw128_mask: 3979 case X86::BI__builtin_ia32_ucmpd128_mask: 3980 case X86::BI__builtin_ia32_ucmpq128_mask: 3981 case X86::BI__builtin_ia32_ucmpb256_mask: 3982 case X86::BI__builtin_ia32_ucmpw256_mask: 3983 case X86::BI__builtin_ia32_ucmpd256_mask: 3984 case X86::BI__builtin_ia32_ucmpq256_mask: 3985 case X86::BI__builtin_ia32_ucmpb512_mask: 3986 case X86::BI__builtin_ia32_ucmpw512_mask: 3987 case X86::BI__builtin_ia32_ucmpd512_mask: 3988 case X86::BI__builtin_ia32_ucmpq512_mask: 3989 case X86::BI__builtin_ia32_vpcomub: 3990 case X86::BI__builtin_ia32_vpcomuw: 3991 case X86::BI__builtin_ia32_vpcomud: 3992 case X86::BI__builtin_ia32_vpcomuq: 3993 case X86::BI__builtin_ia32_vpcomb: 3994 case X86::BI__builtin_ia32_vpcomw: 3995 case X86::BI__builtin_ia32_vpcomd: 3996 case X86::BI__builtin_ia32_vpcomq: 3997 case X86::BI__builtin_ia32_vec_set_v8hi: 3998 case X86::BI__builtin_ia32_vec_set_v8si: 3999 i = 2; l = 0; u = 7; 4000 break; 4001 case X86::BI__builtin_ia32_vpermilpd256: 4002 case X86::BI__builtin_ia32_roundps: 4003 case X86::BI__builtin_ia32_roundpd: 4004 case X86::BI__builtin_ia32_roundps256: 4005 case X86::BI__builtin_ia32_roundpd256: 4006 case X86::BI__builtin_ia32_getmantpd128_mask: 4007 case X86::BI__builtin_ia32_getmantpd256_mask: 4008 case X86::BI__builtin_ia32_getmantps128_mask: 4009 case X86::BI__builtin_ia32_getmantps256_mask: 4010 case X86::BI__builtin_ia32_getmantpd512_mask: 4011 case X86::BI__builtin_ia32_getmantps512_mask: 4012 case X86::BI__builtin_ia32_vec_ext_v16qi: 4013 case X86::BI__builtin_ia32_vec_ext_v16hi: 4014 i = 1; l = 0; u = 15; 4015 break; 4016 case X86::BI__builtin_ia32_pblendd128: 4017 case X86::BI__builtin_ia32_blendps: 4018 case X86::BI__builtin_ia32_blendpd256: 4019 case X86::BI__builtin_ia32_shufpd256: 4020 case X86::BI__builtin_ia32_roundss: 4021 case X86::BI__builtin_ia32_roundsd: 4022 case X86::BI__builtin_ia32_rangepd128_mask: 4023 case X86::BI__builtin_ia32_rangepd256_mask: 4024 case X86::BI__builtin_ia32_rangepd512_mask: 4025 case X86::BI__builtin_ia32_rangeps128_mask: 4026 case X86::BI__builtin_ia32_rangeps256_mask: 4027 case X86::BI__builtin_ia32_rangeps512_mask: 4028 case X86::BI__builtin_ia32_getmantsd_round_mask: 4029 case X86::BI__builtin_ia32_getmantss_round_mask: 4030 case X86::BI__builtin_ia32_vec_set_v16qi: 4031 case X86::BI__builtin_ia32_vec_set_v16hi: 4032 i = 2; l = 0; u = 15; 4033 break; 4034 case X86::BI__builtin_ia32_vec_ext_v32qi: 4035 i = 1; l = 0; u = 31; 4036 break; 4037 case X86::BI__builtin_ia32_cmpps: 4038 case X86::BI__builtin_ia32_cmpss: 4039 case X86::BI__builtin_ia32_cmppd: 4040 case X86::BI__builtin_ia32_cmpsd: 4041 case X86::BI__builtin_ia32_cmpps256: 4042 case X86::BI__builtin_ia32_cmppd256: 4043 case X86::BI__builtin_ia32_cmpps128_mask: 4044 case X86::BI__builtin_ia32_cmppd128_mask: 4045 case X86::BI__builtin_ia32_cmpps256_mask: 4046 case X86::BI__builtin_ia32_cmppd256_mask: 4047 case X86::BI__builtin_ia32_cmpps512_mask: 4048 case X86::BI__builtin_ia32_cmppd512_mask: 4049 case X86::BI__builtin_ia32_cmpsd_mask: 4050 case X86::BI__builtin_ia32_cmpss_mask: 4051 case X86::BI__builtin_ia32_vec_set_v32qi: 4052 i = 2; l = 0; u = 31; 4053 break; 4054 case X86::BI__builtin_ia32_permdf256: 4055 case X86::BI__builtin_ia32_permdi256: 4056 case X86::BI__builtin_ia32_permdf512: 4057 case X86::BI__builtin_ia32_permdi512: 4058 case X86::BI__builtin_ia32_vpermilps: 4059 case X86::BI__builtin_ia32_vpermilps256: 4060 case X86::BI__builtin_ia32_vpermilpd512: 4061 case X86::BI__builtin_ia32_vpermilps512: 4062 case X86::BI__builtin_ia32_pshufd: 4063 case X86::BI__builtin_ia32_pshufd256: 4064 case X86::BI__builtin_ia32_pshufd512: 4065 case X86::BI__builtin_ia32_pshufhw: 4066 case X86::BI__builtin_ia32_pshufhw256: 4067 case X86::BI__builtin_ia32_pshufhw512: 4068 case X86::BI__builtin_ia32_pshuflw: 4069 case X86::BI__builtin_ia32_pshuflw256: 4070 case X86::BI__builtin_ia32_pshuflw512: 4071 case X86::BI__builtin_ia32_vcvtps2ph: 4072 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4073 case X86::BI__builtin_ia32_vcvtps2ph256: 4074 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4075 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4076 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4077 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4078 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4079 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4080 case X86::BI__builtin_ia32_rndscaleps_mask: 4081 case X86::BI__builtin_ia32_rndscalepd_mask: 4082 case X86::BI__builtin_ia32_reducepd128_mask: 4083 case X86::BI__builtin_ia32_reducepd256_mask: 4084 case X86::BI__builtin_ia32_reducepd512_mask: 4085 case X86::BI__builtin_ia32_reduceps128_mask: 4086 case X86::BI__builtin_ia32_reduceps256_mask: 4087 case X86::BI__builtin_ia32_reduceps512_mask: 4088 case X86::BI__builtin_ia32_prold512: 4089 case X86::BI__builtin_ia32_prolq512: 4090 case X86::BI__builtin_ia32_prold128: 4091 case X86::BI__builtin_ia32_prold256: 4092 case X86::BI__builtin_ia32_prolq128: 4093 case X86::BI__builtin_ia32_prolq256: 4094 case X86::BI__builtin_ia32_prord512: 4095 case X86::BI__builtin_ia32_prorq512: 4096 case X86::BI__builtin_ia32_prord128: 4097 case X86::BI__builtin_ia32_prord256: 4098 case X86::BI__builtin_ia32_prorq128: 4099 case X86::BI__builtin_ia32_prorq256: 4100 case X86::BI__builtin_ia32_fpclasspd128_mask: 4101 case X86::BI__builtin_ia32_fpclasspd256_mask: 4102 case X86::BI__builtin_ia32_fpclassps128_mask: 4103 case X86::BI__builtin_ia32_fpclassps256_mask: 4104 case X86::BI__builtin_ia32_fpclassps512_mask: 4105 case X86::BI__builtin_ia32_fpclasspd512_mask: 4106 case X86::BI__builtin_ia32_fpclasssd_mask: 4107 case X86::BI__builtin_ia32_fpclassss_mask: 4108 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4109 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4110 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4111 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4112 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4113 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4114 case X86::BI__builtin_ia32_kshiftliqi: 4115 case X86::BI__builtin_ia32_kshiftlihi: 4116 case X86::BI__builtin_ia32_kshiftlisi: 4117 case X86::BI__builtin_ia32_kshiftlidi: 4118 case X86::BI__builtin_ia32_kshiftriqi: 4119 case X86::BI__builtin_ia32_kshiftrihi: 4120 case X86::BI__builtin_ia32_kshiftrisi: 4121 case X86::BI__builtin_ia32_kshiftridi: 4122 i = 1; l = 0; u = 255; 4123 break; 4124 case X86::BI__builtin_ia32_vperm2f128_pd256: 4125 case X86::BI__builtin_ia32_vperm2f128_ps256: 4126 case X86::BI__builtin_ia32_vperm2f128_si256: 4127 case X86::BI__builtin_ia32_permti256: 4128 case X86::BI__builtin_ia32_pblendw128: 4129 case X86::BI__builtin_ia32_pblendw256: 4130 case X86::BI__builtin_ia32_blendps256: 4131 case X86::BI__builtin_ia32_pblendd256: 4132 case X86::BI__builtin_ia32_palignr128: 4133 case X86::BI__builtin_ia32_palignr256: 4134 case X86::BI__builtin_ia32_palignr512: 4135 case X86::BI__builtin_ia32_alignq512: 4136 case X86::BI__builtin_ia32_alignd512: 4137 case X86::BI__builtin_ia32_alignd128: 4138 case X86::BI__builtin_ia32_alignd256: 4139 case X86::BI__builtin_ia32_alignq128: 4140 case X86::BI__builtin_ia32_alignq256: 4141 case X86::BI__builtin_ia32_vcomisd: 4142 case X86::BI__builtin_ia32_vcomiss: 4143 case X86::BI__builtin_ia32_shuf_f32x4: 4144 case X86::BI__builtin_ia32_shuf_f64x2: 4145 case X86::BI__builtin_ia32_shuf_i32x4: 4146 case X86::BI__builtin_ia32_shuf_i64x2: 4147 case X86::BI__builtin_ia32_shufpd512: 4148 case X86::BI__builtin_ia32_shufps: 4149 case X86::BI__builtin_ia32_shufps256: 4150 case X86::BI__builtin_ia32_shufps512: 4151 case X86::BI__builtin_ia32_dbpsadbw128: 4152 case X86::BI__builtin_ia32_dbpsadbw256: 4153 case X86::BI__builtin_ia32_dbpsadbw512: 4154 case X86::BI__builtin_ia32_vpshldd128: 4155 case X86::BI__builtin_ia32_vpshldd256: 4156 case X86::BI__builtin_ia32_vpshldd512: 4157 case X86::BI__builtin_ia32_vpshldq128: 4158 case X86::BI__builtin_ia32_vpshldq256: 4159 case X86::BI__builtin_ia32_vpshldq512: 4160 case X86::BI__builtin_ia32_vpshldw128: 4161 case X86::BI__builtin_ia32_vpshldw256: 4162 case X86::BI__builtin_ia32_vpshldw512: 4163 case X86::BI__builtin_ia32_vpshrdd128: 4164 case X86::BI__builtin_ia32_vpshrdd256: 4165 case X86::BI__builtin_ia32_vpshrdd512: 4166 case X86::BI__builtin_ia32_vpshrdq128: 4167 case X86::BI__builtin_ia32_vpshrdq256: 4168 case X86::BI__builtin_ia32_vpshrdq512: 4169 case X86::BI__builtin_ia32_vpshrdw128: 4170 case X86::BI__builtin_ia32_vpshrdw256: 4171 case X86::BI__builtin_ia32_vpshrdw512: 4172 i = 2; l = 0; u = 255; 4173 break; 4174 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4175 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4176 case X86::BI__builtin_ia32_fixupimmps512_mask: 4177 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4178 case X86::BI__builtin_ia32_fixupimmsd_mask: 4179 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4180 case X86::BI__builtin_ia32_fixupimmss_mask: 4181 case X86::BI__builtin_ia32_fixupimmss_maskz: 4182 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4183 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4184 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4185 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4186 case X86::BI__builtin_ia32_fixupimmps128_mask: 4187 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4188 case X86::BI__builtin_ia32_fixupimmps256_mask: 4189 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4190 case X86::BI__builtin_ia32_pternlogd512_mask: 4191 case X86::BI__builtin_ia32_pternlogd512_maskz: 4192 case X86::BI__builtin_ia32_pternlogq512_mask: 4193 case X86::BI__builtin_ia32_pternlogq512_maskz: 4194 case X86::BI__builtin_ia32_pternlogd128_mask: 4195 case X86::BI__builtin_ia32_pternlogd128_maskz: 4196 case X86::BI__builtin_ia32_pternlogd256_mask: 4197 case X86::BI__builtin_ia32_pternlogd256_maskz: 4198 case X86::BI__builtin_ia32_pternlogq128_mask: 4199 case X86::BI__builtin_ia32_pternlogq128_maskz: 4200 case X86::BI__builtin_ia32_pternlogq256_mask: 4201 case X86::BI__builtin_ia32_pternlogq256_maskz: 4202 i = 3; l = 0; u = 255; 4203 break; 4204 case X86::BI__builtin_ia32_gatherpfdpd: 4205 case X86::BI__builtin_ia32_gatherpfdps: 4206 case X86::BI__builtin_ia32_gatherpfqpd: 4207 case X86::BI__builtin_ia32_gatherpfqps: 4208 case X86::BI__builtin_ia32_scatterpfdpd: 4209 case X86::BI__builtin_ia32_scatterpfdps: 4210 case X86::BI__builtin_ia32_scatterpfqpd: 4211 case X86::BI__builtin_ia32_scatterpfqps: 4212 i = 4; l = 2; u = 3; 4213 break; 4214 case X86::BI__builtin_ia32_reducesd_mask: 4215 case X86::BI__builtin_ia32_reducess_mask: 4216 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4217 case X86::BI__builtin_ia32_rndscaless_round_mask: 4218 i = 4; l = 0; u = 255; 4219 break; 4220 } 4221 4222 // Note that we don't force a hard error on the range check here, allowing 4223 // template-generated or macro-generated dead code to potentially have out-of- 4224 // range values. These need to code generate, but don't need to necessarily 4225 // make any sense. We use a warning that defaults to an error. 4226 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4227 } 4228 4229 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4230 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4231 /// Returns true when the format fits the function and the FormatStringInfo has 4232 /// been populated. 4233 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4234 FormatStringInfo *FSI) { 4235 FSI->HasVAListArg = Format->getFirstArg() == 0; 4236 FSI->FormatIdx = Format->getFormatIdx() - 1; 4237 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4238 4239 // The way the format attribute works in GCC, the implicit this argument 4240 // of member functions is counted. However, it doesn't appear in our own 4241 // lists, so decrement format_idx in that case. 4242 if (IsCXXMember) { 4243 if(FSI->FormatIdx == 0) 4244 return false; 4245 --FSI->FormatIdx; 4246 if (FSI->FirstDataArg != 0) 4247 --FSI->FirstDataArg; 4248 } 4249 return true; 4250 } 4251 4252 /// Checks if a the given expression evaluates to null. 4253 /// 4254 /// Returns true if the value evaluates to null. 4255 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4256 // If the expression has non-null type, it doesn't evaluate to null. 4257 if (auto nullability 4258 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4259 if (*nullability == NullabilityKind::NonNull) 4260 return false; 4261 } 4262 4263 // As a special case, transparent unions initialized with zero are 4264 // considered null for the purposes of the nonnull attribute. 4265 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4266 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4267 if (const CompoundLiteralExpr *CLE = 4268 dyn_cast<CompoundLiteralExpr>(Expr)) 4269 if (const InitListExpr *ILE = 4270 dyn_cast<InitListExpr>(CLE->getInitializer())) 4271 Expr = ILE->getInit(0); 4272 } 4273 4274 bool Result; 4275 return (!Expr->isValueDependent() && 4276 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4277 !Result); 4278 } 4279 4280 static void CheckNonNullArgument(Sema &S, 4281 const Expr *ArgExpr, 4282 SourceLocation CallSiteLoc) { 4283 if (CheckNonNullExpr(S, ArgExpr)) 4284 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4285 S.PDiag(diag::warn_null_arg) 4286 << ArgExpr->getSourceRange()); 4287 } 4288 4289 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4290 FormatStringInfo FSI; 4291 if ((GetFormatStringType(Format) == FST_NSString) && 4292 getFormatStringInfo(Format, false, &FSI)) { 4293 Idx = FSI.FormatIdx; 4294 return true; 4295 } 4296 return false; 4297 } 4298 4299 /// Diagnose use of %s directive in an NSString which is being passed 4300 /// as formatting string to formatting method. 4301 static void 4302 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4303 const NamedDecl *FDecl, 4304 Expr **Args, 4305 unsigned NumArgs) { 4306 unsigned Idx = 0; 4307 bool Format = false; 4308 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4309 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4310 Idx = 2; 4311 Format = true; 4312 } 4313 else 4314 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4315 if (S.GetFormatNSStringIdx(I, Idx)) { 4316 Format = true; 4317 break; 4318 } 4319 } 4320 if (!Format || NumArgs <= Idx) 4321 return; 4322 const Expr *FormatExpr = Args[Idx]; 4323 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4324 FormatExpr = CSCE->getSubExpr(); 4325 const StringLiteral *FormatString; 4326 if (const ObjCStringLiteral *OSL = 4327 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4328 FormatString = OSL->getString(); 4329 else 4330 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4331 if (!FormatString) 4332 return; 4333 if (S.FormatStringHasSArg(FormatString)) { 4334 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4335 << "%s" << 1 << 1; 4336 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4337 << FDecl->getDeclName(); 4338 } 4339 } 4340 4341 /// Determine whether the given type has a non-null nullability annotation. 4342 static bool isNonNullType(ASTContext &ctx, QualType type) { 4343 if (auto nullability = type->getNullability(ctx)) 4344 return *nullability == NullabilityKind::NonNull; 4345 4346 return false; 4347 } 4348 4349 static void CheckNonNullArguments(Sema &S, 4350 const NamedDecl *FDecl, 4351 const FunctionProtoType *Proto, 4352 ArrayRef<const Expr *> Args, 4353 SourceLocation CallSiteLoc) { 4354 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4355 4356 // Already checked by by constant evaluator. 4357 if (S.isConstantEvaluated()) 4358 return; 4359 // Check the attributes attached to the method/function itself. 4360 llvm::SmallBitVector NonNullArgs; 4361 if (FDecl) { 4362 // Handle the nonnull attribute on the function/method declaration itself. 4363 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4364 if (!NonNull->args_size()) { 4365 // Easy case: all pointer arguments are nonnull. 4366 for (const auto *Arg : Args) 4367 if (S.isValidPointerAttrType(Arg->getType())) 4368 CheckNonNullArgument(S, Arg, CallSiteLoc); 4369 return; 4370 } 4371 4372 for (const ParamIdx &Idx : NonNull->args()) { 4373 unsigned IdxAST = Idx.getASTIndex(); 4374 if (IdxAST >= Args.size()) 4375 continue; 4376 if (NonNullArgs.empty()) 4377 NonNullArgs.resize(Args.size()); 4378 NonNullArgs.set(IdxAST); 4379 } 4380 } 4381 } 4382 4383 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4384 // Handle the nonnull attribute on the parameters of the 4385 // function/method. 4386 ArrayRef<ParmVarDecl*> parms; 4387 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4388 parms = FD->parameters(); 4389 else 4390 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4391 4392 unsigned ParamIndex = 0; 4393 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4394 I != E; ++I, ++ParamIndex) { 4395 const ParmVarDecl *PVD = *I; 4396 if (PVD->hasAttr<NonNullAttr>() || 4397 isNonNullType(S.Context, PVD->getType())) { 4398 if (NonNullArgs.empty()) 4399 NonNullArgs.resize(Args.size()); 4400 4401 NonNullArgs.set(ParamIndex); 4402 } 4403 } 4404 } else { 4405 // If we have a non-function, non-method declaration but no 4406 // function prototype, try to dig out the function prototype. 4407 if (!Proto) { 4408 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4409 QualType type = VD->getType().getNonReferenceType(); 4410 if (auto pointerType = type->getAs<PointerType>()) 4411 type = pointerType->getPointeeType(); 4412 else if (auto blockType = type->getAs<BlockPointerType>()) 4413 type = blockType->getPointeeType(); 4414 // FIXME: data member pointers? 4415 4416 // Dig out the function prototype, if there is one. 4417 Proto = type->getAs<FunctionProtoType>(); 4418 } 4419 } 4420 4421 // Fill in non-null argument information from the nullability 4422 // information on the parameter types (if we have them). 4423 if (Proto) { 4424 unsigned Index = 0; 4425 for (auto paramType : Proto->getParamTypes()) { 4426 if (isNonNullType(S.Context, paramType)) { 4427 if (NonNullArgs.empty()) 4428 NonNullArgs.resize(Args.size()); 4429 4430 NonNullArgs.set(Index); 4431 } 4432 4433 ++Index; 4434 } 4435 } 4436 } 4437 4438 // Check for non-null arguments. 4439 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4440 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4441 if (NonNullArgs[ArgIndex]) 4442 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4443 } 4444 } 4445 4446 /// Handles the checks for format strings, non-POD arguments to vararg 4447 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4448 /// attributes. 4449 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4450 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4451 bool IsMemberFunction, SourceLocation Loc, 4452 SourceRange Range, VariadicCallType CallType) { 4453 // FIXME: We should check as much as we can in the template definition. 4454 if (CurContext->isDependentContext()) 4455 return; 4456 4457 // Printf and scanf checking. 4458 llvm::SmallBitVector CheckedVarArgs; 4459 if (FDecl) { 4460 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4461 // Only create vector if there are format attributes. 4462 CheckedVarArgs.resize(Args.size()); 4463 4464 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4465 CheckedVarArgs); 4466 } 4467 } 4468 4469 // Refuse POD arguments that weren't caught by the format string 4470 // checks above. 4471 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4472 if (CallType != VariadicDoesNotApply && 4473 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4474 unsigned NumParams = Proto ? Proto->getNumParams() 4475 : FDecl && isa<FunctionDecl>(FDecl) 4476 ? cast<FunctionDecl>(FDecl)->getNumParams() 4477 : FDecl && isa<ObjCMethodDecl>(FDecl) 4478 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4479 : 0; 4480 4481 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4482 // Args[ArgIdx] can be null in malformed code. 4483 if (const Expr *Arg = Args[ArgIdx]) { 4484 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4485 checkVariadicArgument(Arg, CallType); 4486 } 4487 } 4488 } 4489 4490 if (FDecl || Proto) { 4491 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4492 4493 // Type safety checking. 4494 if (FDecl) { 4495 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4496 CheckArgumentWithTypeTag(I, Args, Loc); 4497 } 4498 } 4499 4500 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4501 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4502 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4503 if (!Arg->isValueDependent()) { 4504 Expr::EvalResult Align; 4505 if (Arg->EvaluateAsInt(Align, Context)) { 4506 const llvm::APSInt &I = Align.Val.getInt(); 4507 if (!I.isPowerOf2()) 4508 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4509 << Arg->getSourceRange(); 4510 4511 if (I > Sema::MaximumAlignment) 4512 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4513 << Arg->getSourceRange() << Sema::MaximumAlignment; 4514 } 4515 } 4516 } 4517 4518 if (FD) 4519 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4520 } 4521 4522 /// CheckConstructorCall - Check a constructor call for correctness and safety 4523 /// properties not enforced by the C type system. 4524 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4525 ArrayRef<const Expr *> Args, 4526 const FunctionProtoType *Proto, 4527 SourceLocation Loc) { 4528 VariadicCallType CallType = 4529 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4530 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4531 Loc, SourceRange(), CallType); 4532 } 4533 4534 /// CheckFunctionCall - Check a direct function call for various correctness 4535 /// and safety properties not strictly enforced by the C type system. 4536 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4537 const FunctionProtoType *Proto) { 4538 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4539 isa<CXXMethodDecl>(FDecl); 4540 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4541 IsMemberOperatorCall; 4542 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4543 TheCall->getCallee()); 4544 Expr** Args = TheCall->getArgs(); 4545 unsigned NumArgs = TheCall->getNumArgs(); 4546 4547 Expr *ImplicitThis = nullptr; 4548 if (IsMemberOperatorCall) { 4549 // If this is a call to a member operator, hide the first argument 4550 // from checkCall. 4551 // FIXME: Our choice of AST representation here is less than ideal. 4552 ImplicitThis = Args[0]; 4553 ++Args; 4554 --NumArgs; 4555 } else if (IsMemberFunction) 4556 ImplicitThis = 4557 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4558 4559 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4560 IsMemberFunction, TheCall->getRParenLoc(), 4561 TheCall->getCallee()->getSourceRange(), CallType); 4562 4563 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4564 // None of the checks below are needed for functions that don't have 4565 // simple names (e.g., C++ conversion functions). 4566 if (!FnInfo) 4567 return false; 4568 4569 CheckAbsoluteValueFunction(TheCall, FDecl); 4570 CheckMaxUnsignedZero(TheCall, FDecl); 4571 4572 if (getLangOpts().ObjC) 4573 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4574 4575 unsigned CMId = FDecl->getMemoryFunctionKind(); 4576 4577 // Handle memory setting and copying functions. 4578 switch (CMId) { 4579 case 0: 4580 return false; 4581 case Builtin::BIstrlcpy: // fallthrough 4582 case Builtin::BIstrlcat: 4583 CheckStrlcpycatArguments(TheCall, FnInfo); 4584 break; 4585 case Builtin::BIstrncat: 4586 CheckStrncatArguments(TheCall, FnInfo); 4587 break; 4588 case Builtin::BIfree: 4589 CheckFreeArguments(TheCall); 4590 break; 4591 default: 4592 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4593 } 4594 4595 return false; 4596 } 4597 4598 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4599 ArrayRef<const Expr *> Args) { 4600 VariadicCallType CallType = 4601 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4602 4603 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4604 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4605 CallType); 4606 4607 return false; 4608 } 4609 4610 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4611 const FunctionProtoType *Proto) { 4612 QualType Ty; 4613 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4614 Ty = V->getType().getNonReferenceType(); 4615 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4616 Ty = F->getType().getNonReferenceType(); 4617 else 4618 return false; 4619 4620 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4621 !Ty->isFunctionProtoType()) 4622 return false; 4623 4624 VariadicCallType CallType; 4625 if (!Proto || !Proto->isVariadic()) { 4626 CallType = VariadicDoesNotApply; 4627 } else if (Ty->isBlockPointerType()) { 4628 CallType = VariadicBlock; 4629 } else { // Ty->isFunctionPointerType() 4630 CallType = VariadicFunction; 4631 } 4632 4633 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4634 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4635 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4636 TheCall->getCallee()->getSourceRange(), CallType); 4637 4638 return false; 4639 } 4640 4641 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4642 /// such as function pointers returned from functions. 4643 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4644 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4645 TheCall->getCallee()); 4646 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4647 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4648 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4649 TheCall->getCallee()->getSourceRange(), CallType); 4650 4651 return false; 4652 } 4653 4654 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4655 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4656 return false; 4657 4658 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4659 switch (Op) { 4660 case AtomicExpr::AO__c11_atomic_init: 4661 case AtomicExpr::AO__opencl_atomic_init: 4662 llvm_unreachable("There is no ordering argument for an init"); 4663 4664 case AtomicExpr::AO__c11_atomic_load: 4665 case AtomicExpr::AO__opencl_atomic_load: 4666 case AtomicExpr::AO__atomic_load_n: 4667 case AtomicExpr::AO__atomic_load: 4668 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4669 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4670 4671 case AtomicExpr::AO__c11_atomic_store: 4672 case AtomicExpr::AO__opencl_atomic_store: 4673 case AtomicExpr::AO__atomic_store: 4674 case AtomicExpr::AO__atomic_store_n: 4675 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4676 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4677 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4678 4679 default: 4680 return true; 4681 } 4682 } 4683 4684 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4685 AtomicExpr::AtomicOp Op) { 4686 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4687 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4688 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4689 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4690 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4691 Op); 4692 } 4693 4694 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4695 SourceLocation RParenLoc, MultiExprArg Args, 4696 AtomicExpr::AtomicOp Op, 4697 AtomicArgumentOrder ArgOrder) { 4698 // All the non-OpenCL operations take one of the following forms. 4699 // The OpenCL operations take the __c11 forms with one extra argument for 4700 // synchronization scope. 4701 enum { 4702 // C __c11_atomic_init(A *, C) 4703 Init, 4704 4705 // C __c11_atomic_load(A *, int) 4706 Load, 4707 4708 // void __atomic_load(A *, CP, int) 4709 LoadCopy, 4710 4711 // void __atomic_store(A *, CP, int) 4712 Copy, 4713 4714 // C __c11_atomic_add(A *, M, int) 4715 Arithmetic, 4716 4717 // C __atomic_exchange_n(A *, CP, int) 4718 Xchg, 4719 4720 // void __atomic_exchange(A *, C *, CP, int) 4721 GNUXchg, 4722 4723 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4724 C11CmpXchg, 4725 4726 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4727 GNUCmpXchg 4728 } Form = Init; 4729 4730 const unsigned NumForm = GNUCmpXchg + 1; 4731 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4732 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4733 // where: 4734 // C is an appropriate type, 4735 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4736 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4737 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4738 // the int parameters are for orderings. 4739 4740 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4741 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4742 "need to update code for modified forms"); 4743 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4744 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4745 AtomicExpr::AO__atomic_load, 4746 "need to update code for modified C11 atomics"); 4747 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4748 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4749 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4750 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4751 IsOpenCL; 4752 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4753 Op == AtomicExpr::AO__atomic_store_n || 4754 Op == AtomicExpr::AO__atomic_exchange_n || 4755 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4756 bool IsAddSub = false; 4757 4758 switch (Op) { 4759 case AtomicExpr::AO__c11_atomic_init: 4760 case AtomicExpr::AO__opencl_atomic_init: 4761 Form = Init; 4762 break; 4763 4764 case AtomicExpr::AO__c11_atomic_load: 4765 case AtomicExpr::AO__opencl_atomic_load: 4766 case AtomicExpr::AO__atomic_load_n: 4767 Form = Load; 4768 break; 4769 4770 case AtomicExpr::AO__atomic_load: 4771 Form = LoadCopy; 4772 break; 4773 4774 case AtomicExpr::AO__c11_atomic_store: 4775 case AtomicExpr::AO__opencl_atomic_store: 4776 case AtomicExpr::AO__atomic_store: 4777 case AtomicExpr::AO__atomic_store_n: 4778 Form = Copy; 4779 break; 4780 4781 case AtomicExpr::AO__c11_atomic_fetch_add: 4782 case AtomicExpr::AO__c11_atomic_fetch_sub: 4783 case AtomicExpr::AO__opencl_atomic_fetch_add: 4784 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4785 case AtomicExpr::AO__atomic_fetch_add: 4786 case AtomicExpr::AO__atomic_fetch_sub: 4787 case AtomicExpr::AO__atomic_add_fetch: 4788 case AtomicExpr::AO__atomic_sub_fetch: 4789 IsAddSub = true; 4790 LLVM_FALLTHROUGH; 4791 case AtomicExpr::AO__c11_atomic_fetch_and: 4792 case AtomicExpr::AO__c11_atomic_fetch_or: 4793 case AtomicExpr::AO__c11_atomic_fetch_xor: 4794 case AtomicExpr::AO__opencl_atomic_fetch_and: 4795 case AtomicExpr::AO__opencl_atomic_fetch_or: 4796 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4797 case AtomicExpr::AO__atomic_fetch_and: 4798 case AtomicExpr::AO__atomic_fetch_or: 4799 case AtomicExpr::AO__atomic_fetch_xor: 4800 case AtomicExpr::AO__atomic_fetch_nand: 4801 case AtomicExpr::AO__atomic_and_fetch: 4802 case AtomicExpr::AO__atomic_or_fetch: 4803 case AtomicExpr::AO__atomic_xor_fetch: 4804 case AtomicExpr::AO__atomic_nand_fetch: 4805 case AtomicExpr::AO__c11_atomic_fetch_min: 4806 case AtomicExpr::AO__c11_atomic_fetch_max: 4807 case AtomicExpr::AO__opencl_atomic_fetch_min: 4808 case AtomicExpr::AO__opencl_atomic_fetch_max: 4809 case AtomicExpr::AO__atomic_min_fetch: 4810 case AtomicExpr::AO__atomic_max_fetch: 4811 case AtomicExpr::AO__atomic_fetch_min: 4812 case AtomicExpr::AO__atomic_fetch_max: 4813 Form = Arithmetic; 4814 break; 4815 4816 case AtomicExpr::AO__c11_atomic_exchange: 4817 case AtomicExpr::AO__opencl_atomic_exchange: 4818 case AtomicExpr::AO__atomic_exchange_n: 4819 Form = Xchg; 4820 break; 4821 4822 case AtomicExpr::AO__atomic_exchange: 4823 Form = GNUXchg; 4824 break; 4825 4826 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4827 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4828 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4829 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4830 Form = C11CmpXchg; 4831 break; 4832 4833 case AtomicExpr::AO__atomic_compare_exchange: 4834 case AtomicExpr::AO__atomic_compare_exchange_n: 4835 Form = GNUCmpXchg; 4836 break; 4837 } 4838 4839 unsigned AdjustedNumArgs = NumArgs[Form]; 4840 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4841 ++AdjustedNumArgs; 4842 // Check we have the right number of arguments. 4843 if (Args.size() < AdjustedNumArgs) { 4844 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4845 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4846 << ExprRange; 4847 return ExprError(); 4848 } else if (Args.size() > AdjustedNumArgs) { 4849 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4850 diag::err_typecheck_call_too_many_args) 4851 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4852 << ExprRange; 4853 return ExprError(); 4854 } 4855 4856 // Inspect the first argument of the atomic operation. 4857 Expr *Ptr = Args[0]; 4858 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4859 if (ConvertedPtr.isInvalid()) 4860 return ExprError(); 4861 4862 Ptr = ConvertedPtr.get(); 4863 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4864 if (!pointerType) { 4865 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4866 << Ptr->getType() << Ptr->getSourceRange(); 4867 return ExprError(); 4868 } 4869 4870 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4871 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4872 QualType ValType = AtomTy; // 'C' 4873 if (IsC11) { 4874 if (!AtomTy->isAtomicType()) { 4875 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4876 << Ptr->getType() << Ptr->getSourceRange(); 4877 return ExprError(); 4878 } 4879 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4880 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4881 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4882 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4883 << Ptr->getSourceRange(); 4884 return ExprError(); 4885 } 4886 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4887 } else if (Form != Load && Form != LoadCopy) { 4888 if (ValType.isConstQualified()) { 4889 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4890 << Ptr->getType() << Ptr->getSourceRange(); 4891 return ExprError(); 4892 } 4893 } 4894 4895 // For an arithmetic operation, the implied arithmetic must be well-formed. 4896 if (Form == Arithmetic) { 4897 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4898 if (IsAddSub && !ValType->isIntegerType() 4899 && !ValType->isPointerType()) { 4900 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4901 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4902 return ExprError(); 4903 } 4904 if (!IsAddSub && !ValType->isIntegerType()) { 4905 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4906 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4907 return ExprError(); 4908 } 4909 if (IsC11 && ValType->isPointerType() && 4910 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4911 diag::err_incomplete_type)) { 4912 return ExprError(); 4913 } 4914 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4915 // For __atomic_*_n operations, the value type must be a scalar integral or 4916 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4917 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4918 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4919 return ExprError(); 4920 } 4921 4922 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4923 !AtomTy->isScalarType()) { 4924 // For GNU atomics, require a trivially-copyable type. This is not part of 4925 // the GNU atomics specification, but we enforce it for sanity. 4926 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4927 << Ptr->getType() << Ptr->getSourceRange(); 4928 return ExprError(); 4929 } 4930 4931 switch (ValType.getObjCLifetime()) { 4932 case Qualifiers::OCL_None: 4933 case Qualifiers::OCL_ExplicitNone: 4934 // okay 4935 break; 4936 4937 case Qualifiers::OCL_Weak: 4938 case Qualifiers::OCL_Strong: 4939 case Qualifiers::OCL_Autoreleasing: 4940 // FIXME: Can this happen? By this point, ValType should be known 4941 // to be trivially copyable. 4942 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4943 << ValType << Ptr->getSourceRange(); 4944 return ExprError(); 4945 } 4946 4947 // All atomic operations have an overload which takes a pointer to a volatile 4948 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4949 // into the result or the other operands. Similarly atomic_load takes a 4950 // pointer to a const 'A'. 4951 ValType.removeLocalVolatile(); 4952 ValType.removeLocalConst(); 4953 QualType ResultType = ValType; 4954 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4955 Form == Init) 4956 ResultType = Context.VoidTy; 4957 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4958 ResultType = Context.BoolTy; 4959 4960 // The type of a parameter passed 'by value'. In the GNU atomics, such 4961 // arguments are actually passed as pointers. 4962 QualType ByValType = ValType; // 'CP' 4963 bool IsPassedByAddress = false; 4964 if (!IsC11 && !IsN) { 4965 ByValType = Ptr->getType(); 4966 IsPassedByAddress = true; 4967 } 4968 4969 SmallVector<Expr *, 5> APIOrderedArgs; 4970 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4971 APIOrderedArgs.push_back(Args[0]); 4972 switch (Form) { 4973 case Init: 4974 case Load: 4975 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4976 break; 4977 case LoadCopy: 4978 case Copy: 4979 case Arithmetic: 4980 case Xchg: 4981 APIOrderedArgs.push_back(Args[2]); // Val1 4982 APIOrderedArgs.push_back(Args[1]); // Order 4983 break; 4984 case GNUXchg: 4985 APIOrderedArgs.push_back(Args[2]); // Val1 4986 APIOrderedArgs.push_back(Args[3]); // Val2 4987 APIOrderedArgs.push_back(Args[1]); // Order 4988 break; 4989 case C11CmpXchg: 4990 APIOrderedArgs.push_back(Args[2]); // Val1 4991 APIOrderedArgs.push_back(Args[4]); // Val2 4992 APIOrderedArgs.push_back(Args[1]); // Order 4993 APIOrderedArgs.push_back(Args[3]); // OrderFail 4994 break; 4995 case GNUCmpXchg: 4996 APIOrderedArgs.push_back(Args[2]); // Val1 4997 APIOrderedArgs.push_back(Args[4]); // Val2 4998 APIOrderedArgs.push_back(Args[5]); // Weak 4999 APIOrderedArgs.push_back(Args[1]); // Order 5000 APIOrderedArgs.push_back(Args[3]); // OrderFail 5001 break; 5002 } 5003 } else 5004 APIOrderedArgs.append(Args.begin(), Args.end()); 5005 5006 // The first argument's non-CV pointer type is used to deduce the type of 5007 // subsequent arguments, except for: 5008 // - weak flag (always converted to bool) 5009 // - memory order (always converted to int) 5010 // - scope (always converted to int) 5011 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5012 QualType Ty; 5013 if (i < NumVals[Form] + 1) { 5014 switch (i) { 5015 case 0: 5016 // The first argument is always a pointer. It has a fixed type. 5017 // It is always dereferenced, a nullptr is undefined. 5018 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5019 // Nothing else to do: we already know all we want about this pointer. 5020 continue; 5021 case 1: 5022 // The second argument is the non-atomic operand. For arithmetic, this 5023 // is always passed by value, and for a compare_exchange it is always 5024 // passed by address. For the rest, GNU uses by-address and C11 uses 5025 // by-value. 5026 assert(Form != Load); 5027 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 5028 Ty = ValType; 5029 else if (Form == Copy || Form == Xchg) { 5030 if (IsPassedByAddress) { 5031 // The value pointer is always dereferenced, a nullptr is undefined. 5032 CheckNonNullArgument(*this, APIOrderedArgs[i], 5033 ExprRange.getBegin()); 5034 } 5035 Ty = ByValType; 5036 } else if (Form == Arithmetic) 5037 Ty = Context.getPointerDiffType(); 5038 else { 5039 Expr *ValArg = APIOrderedArgs[i]; 5040 // The value pointer is always dereferenced, a nullptr is undefined. 5041 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5042 LangAS AS = LangAS::Default; 5043 // Keep address space of non-atomic pointer type. 5044 if (const PointerType *PtrTy = 5045 ValArg->getType()->getAs<PointerType>()) { 5046 AS = PtrTy->getPointeeType().getAddressSpace(); 5047 } 5048 Ty = Context.getPointerType( 5049 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5050 } 5051 break; 5052 case 2: 5053 // The third argument to compare_exchange / GNU exchange is the desired 5054 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5055 if (IsPassedByAddress) 5056 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5057 Ty = ByValType; 5058 break; 5059 case 3: 5060 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5061 Ty = Context.BoolTy; 5062 break; 5063 } 5064 } else { 5065 // The order(s) and scope are always converted to int. 5066 Ty = Context.IntTy; 5067 } 5068 5069 InitializedEntity Entity = 5070 InitializedEntity::InitializeParameter(Context, Ty, false); 5071 ExprResult Arg = APIOrderedArgs[i]; 5072 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5073 if (Arg.isInvalid()) 5074 return true; 5075 APIOrderedArgs[i] = Arg.get(); 5076 } 5077 5078 // Permute the arguments into a 'consistent' order. 5079 SmallVector<Expr*, 5> SubExprs; 5080 SubExprs.push_back(Ptr); 5081 switch (Form) { 5082 case Init: 5083 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5084 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5085 break; 5086 case Load: 5087 SubExprs.push_back(APIOrderedArgs[1]); // Order 5088 break; 5089 case LoadCopy: 5090 case Copy: 5091 case Arithmetic: 5092 case Xchg: 5093 SubExprs.push_back(APIOrderedArgs[2]); // Order 5094 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5095 break; 5096 case GNUXchg: 5097 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5098 SubExprs.push_back(APIOrderedArgs[3]); // Order 5099 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5100 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5101 break; 5102 case C11CmpXchg: 5103 SubExprs.push_back(APIOrderedArgs[3]); // Order 5104 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5105 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5106 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5107 break; 5108 case GNUCmpXchg: 5109 SubExprs.push_back(APIOrderedArgs[4]); // Order 5110 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5111 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5112 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5113 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5114 break; 5115 } 5116 5117 if (SubExprs.size() >= 2 && Form != Init) { 5118 if (Optional<llvm::APSInt> Result = 5119 SubExprs[1]->getIntegerConstantExpr(Context)) 5120 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5121 Diag(SubExprs[1]->getBeginLoc(), 5122 diag::warn_atomic_op_has_invalid_memory_order) 5123 << SubExprs[1]->getSourceRange(); 5124 } 5125 5126 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5127 auto *Scope = Args[Args.size() - 1]; 5128 if (Optional<llvm::APSInt> Result = 5129 Scope->getIntegerConstantExpr(Context)) { 5130 if (!ScopeModel->isValid(Result->getZExtValue())) 5131 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5132 << Scope->getSourceRange(); 5133 } 5134 SubExprs.push_back(Scope); 5135 } 5136 5137 AtomicExpr *AE = new (Context) 5138 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5139 5140 if ((Op == AtomicExpr::AO__c11_atomic_load || 5141 Op == AtomicExpr::AO__c11_atomic_store || 5142 Op == AtomicExpr::AO__opencl_atomic_load || 5143 Op == AtomicExpr::AO__opencl_atomic_store ) && 5144 Context.AtomicUsesUnsupportedLibcall(AE)) 5145 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5146 << ((Op == AtomicExpr::AO__c11_atomic_load || 5147 Op == AtomicExpr::AO__opencl_atomic_load) 5148 ? 0 5149 : 1); 5150 5151 if (ValType->isExtIntType()) { 5152 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5153 return ExprError(); 5154 } 5155 5156 return AE; 5157 } 5158 5159 /// checkBuiltinArgument - Given a call to a builtin function, perform 5160 /// normal type-checking on the given argument, updating the call in 5161 /// place. This is useful when a builtin function requires custom 5162 /// type-checking for some of its arguments but not necessarily all of 5163 /// them. 5164 /// 5165 /// Returns true on error. 5166 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5167 FunctionDecl *Fn = E->getDirectCallee(); 5168 assert(Fn && "builtin call without direct callee!"); 5169 5170 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5171 InitializedEntity Entity = 5172 InitializedEntity::InitializeParameter(S.Context, Param); 5173 5174 ExprResult Arg = E->getArg(0); 5175 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5176 if (Arg.isInvalid()) 5177 return true; 5178 5179 E->setArg(ArgIndex, Arg.get()); 5180 return false; 5181 } 5182 5183 /// We have a call to a function like __sync_fetch_and_add, which is an 5184 /// overloaded function based on the pointer type of its first argument. 5185 /// The main BuildCallExpr routines have already promoted the types of 5186 /// arguments because all of these calls are prototyped as void(...). 5187 /// 5188 /// This function goes through and does final semantic checking for these 5189 /// builtins, as well as generating any warnings. 5190 ExprResult 5191 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5192 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5193 Expr *Callee = TheCall->getCallee(); 5194 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5195 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5196 5197 // Ensure that we have at least one argument to do type inference from. 5198 if (TheCall->getNumArgs() < 1) { 5199 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5200 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5201 return ExprError(); 5202 } 5203 5204 // Inspect the first argument of the atomic builtin. This should always be 5205 // a pointer type, whose element is an integral scalar or pointer type. 5206 // Because it is a pointer type, we don't have to worry about any implicit 5207 // casts here. 5208 // FIXME: We don't allow floating point scalars as input. 5209 Expr *FirstArg = TheCall->getArg(0); 5210 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5211 if (FirstArgResult.isInvalid()) 5212 return ExprError(); 5213 FirstArg = FirstArgResult.get(); 5214 TheCall->setArg(0, FirstArg); 5215 5216 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5217 if (!pointerType) { 5218 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5219 << FirstArg->getType() << FirstArg->getSourceRange(); 5220 return ExprError(); 5221 } 5222 5223 QualType ValType = pointerType->getPointeeType(); 5224 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5225 !ValType->isBlockPointerType()) { 5226 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5227 << FirstArg->getType() << FirstArg->getSourceRange(); 5228 return ExprError(); 5229 } 5230 5231 if (ValType.isConstQualified()) { 5232 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5233 << FirstArg->getType() << FirstArg->getSourceRange(); 5234 return ExprError(); 5235 } 5236 5237 switch (ValType.getObjCLifetime()) { 5238 case Qualifiers::OCL_None: 5239 case Qualifiers::OCL_ExplicitNone: 5240 // okay 5241 break; 5242 5243 case Qualifiers::OCL_Weak: 5244 case Qualifiers::OCL_Strong: 5245 case Qualifiers::OCL_Autoreleasing: 5246 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5247 << ValType << FirstArg->getSourceRange(); 5248 return ExprError(); 5249 } 5250 5251 // Strip any qualifiers off ValType. 5252 ValType = ValType.getUnqualifiedType(); 5253 5254 // The majority of builtins return a value, but a few have special return 5255 // types, so allow them to override appropriately below. 5256 QualType ResultType = ValType; 5257 5258 // We need to figure out which concrete builtin this maps onto. For example, 5259 // __sync_fetch_and_add with a 2 byte object turns into 5260 // __sync_fetch_and_add_2. 5261 #define BUILTIN_ROW(x) \ 5262 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5263 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5264 5265 static const unsigned BuiltinIndices[][5] = { 5266 BUILTIN_ROW(__sync_fetch_and_add), 5267 BUILTIN_ROW(__sync_fetch_and_sub), 5268 BUILTIN_ROW(__sync_fetch_and_or), 5269 BUILTIN_ROW(__sync_fetch_and_and), 5270 BUILTIN_ROW(__sync_fetch_and_xor), 5271 BUILTIN_ROW(__sync_fetch_and_nand), 5272 5273 BUILTIN_ROW(__sync_add_and_fetch), 5274 BUILTIN_ROW(__sync_sub_and_fetch), 5275 BUILTIN_ROW(__sync_and_and_fetch), 5276 BUILTIN_ROW(__sync_or_and_fetch), 5277 BUILTIN_ROW(__sync_xor_and_fetch), 5278 BUILTIN_ROW(__sync_nand_and_fetch), 5279 5280 BUILTIN_ROW(__sync_val_compare_and_swap), 5281 BUILTIN_ROW(__sync_bool_compare_and_swap), 5282 BUILTIN_ROW(__sync_lock_test_and_set), 5283 BUILTIN_ROW(__sync_lock_release), 5284 BUILTIN_ROW(__sync_swap) 5285 }; 5286 #undef BUILTIN_ROW 5287 5288 // Determine the index of the size. 5289 unsigned SizeIndex; 5290 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5291 case 1: SizeIndex = 0; break; 5292 case 2: SizeIndex = 1; break; 5293 case 4: SizeIndex = 2; break; 5294 case 8: SizeIndex = 3; break; 5295 case 16: SizeIndex = 4; break; 5296 default: 5297 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5298 << FirstArg->getType() << FirstArg->getSourceRange(); 5299 return ExprError(); 5300 } 5301 5302 // Each of these builtins has one pointer argument, followed by some number of 5303 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5304 // that we ignore. Find out which row of BuiltinIndices to read from as well 5305 // as the number of fixed args. 5306 unsigned BuiltinID = FDecl->getBuiltinID(); 5307 unsigned BuiltinIndex, NumFixed = 1; 5308 bool WarnAboutSemanticsChange = false; 5309 switch (BuiltinID) { 5310 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5311 case Builtin::BI__sync_fetch_and_add: 5312 case Builtin::BI__sync_fetch_and_add_1: 5313 case Builtin::BI__sync_fetch_and_add_2: 5314 case Builtin::BI__sync_fetch_and_add_4: 5315 case Builtin::BI__sync_fetch_and_add_8: 5316 case Builtin::BI__sync_fetch_and_add_16: 5317 BuiltinIndex = 0; 5318 break; 5319 5320 case Builtin::BI__sync_fetch_and_sub: 5321 case Builtin::BI__sync_fetch_and_sub_1: 5322 case Builtin::BI__sync_fetch_and_sub_2: 5323 case Builtin::BI__sync_fetch_and_sub_4: 5324 case Builtin::BI__sync_fetch_and_sub_8: 5325 case Builtin::BI__sync_fetch_and_sub_16: 5326 BuiltinIndex = 1; 5327 break; 5328 5329 case Builtin::BI__sync_fetch_and_or: 5330 case Builtin::BI__sync_fetch_and_or_1: 5331 case Builtin::BI__sync_fetch_and_or_2: 5332 case Builtin::BI__sync_fetch_and_or_4: 5333 case Builtin::BI__sync_fetch_and_or_8: 5334 case Builtin::BI__sync_fetch_and_or_16: 5335 BuiltinIndex = 2; 5336 break; 5337 5338 case Builtin::BI__sync_fetch_and_and: 5339 case Builtin::BI__sync_fetch_and_and_1: 5340 case Builtin::BI__sync_fetch_and_and_2: 5341 case Builtin::BI__sync_fetch_and_and_4: 5342 case Builtin::BI__sync_fetch_and_and_8: 5343 case Builtin::BI__sync_fetch_and_and_16: 5344 BuiltinIndex = 3; 5345 break; 5346 5347 case Builtin::BI__sync_fetch_and_xor: 5348 case Builtin::BI__sync_fetch_and_xor_1: 5349 case Builtin::BI__sync_fetch_and_xor_2: 5350 case Builtin::BI__sync_fetch_and_xor_4: 5351 case Builtin::BI__sync_fetch_and_xor_8: 5352 case Builtin::BI__sync_fetch_and_xor_16: 5353 BuiltinIndex = 4; 5354 break; 5355 5356 case Builtin::BI__sync_fetch_and_nand: 5357 case Builtin::BI__sync_fetch_and_nand_1: 5358 case Builtin::BI__sync_fetch_and_nand_2: 5359 case Builtin::BI__sync_fetch_and_nand_4: 5360 case Builtin::BI__sync_fetch_and_nand_8: 5361 case Builtin::BI__sync_fetch_and_nand_16: 5362 BuiltinIndex = 5; 5363 WarnAboutSemanticsChange = true; 5364 break; 5365 5366 case Builtin::BI__sync_add_and_fetch: 5367 case Builtin::BI__sync_add_and_fetch_1: 5368 case Builtin::BI__sync_add_and_fetch_2: 5369 case Builtin::BI__sync_add_and_fetch_4: 5370 case Builtin::BI__sync_add_and_fetch_8: 5371 case Builtin::BI__sync_add_and_fetch_16: 5372 BuiltinIndex = 6; 5373 break; 5374 5375 case Builtin::BI__sync_sub_and_fetch: 5376 case Builtin::BI__sync_sub_and_fetch_1: 5377 case Builtin::BI__sync_sub_and_fetch_2: 5378 case Builtin::BI__sync_sub_and_fetch_4: 5379 case Builtin::BI__sync_sub_and_fetch_8: 5380 case Builtin::BI__sync_sub_and_fetch_16: 5381 BuiltinIndex = 7; 5382 break; 5383 5384 case Builtin::BI__sync_and_and_fetch: 5385 case Builtin::BI__sync_and_and_fetch_1: 5386 case Builtin::BI__sync_and_and_fetch_2: 5387 case Builtin::BI__sync_and_and_fetch_4: 5388 case Builtin::BI__sync_and_and_fetch_8: 5389 case Builtin::BI__sync_and_and_fetch_16: 5390 BuiltinIndex = 8; 5391 break; 5392 5393 case Builtin::BI__sync_or_and_fetch: 5394 case Builtin::BI__sync_or_and_fetch_1: 5395 case Builtin::BI__sync_or_and_fetch_2: 5396 case Builtin::BI__sync_or_and_fetch_4: 5397 case Builtin::BI__sync_or_and_fetch_8: 5398 case Builtin::BI__sync_or_and_fetch_16: 5399 BuiltinIndex = 9; 5400 break; 5401 5402 case Builtin::BI__sync_xor_and_fetch: 5403 case Builtin::BI__sync_xor_and_fetch_1: 5404 case Builtin::BI__sync_xor_and_fetch_2: 5405 case Builtin::BI__sync_xor_and_fetch_4: 5406 case Builtin::BI__sync_xor_and_fetch_8: 5407 case Builtin::BI__sync_xor_and_fetch_16: 5408 BuiltinIndex = 10; 5409 break; 5410 5411 case Builtin::BI__sync_nand_and_fetch: 5412 case Builtin::BI__sync_nand_and_fetch_1: 5413 case Builtin::BI__sync_nand_and_fetch_2: 5414 case Builtin::BI__sync_nand_and_fetch_4: 5415 case Builtin::BI__sync_nand_and_fetch_8: 5416 case Builtin::BI__sync_nand_and_fetch_16: 5417 BuiltinIndex = 11; 5418 WarnAboutSemanticsChange = true; 5419 break; 5420 5421 case Builtin::BI__sync_val_compare_and_swap: 5422 case Builtin::BI__sync_val_compare_and_swap_1: 5423 case Builtin::BI__sync_val_compare_and_swap_2: 5424 case Builtin::BI__sync_val_compare_and_swap_4: 5425 case Builtin::BI__sync_val_compare_and_swap_8: 5426 case Builtin::BI__sync_val_compare_and_swap_16: 5427 BuiltinIndex = 12; 5428 NumFixed = 2; 5429 break; 5430 5431 case Builtin::BI__sync_bool_compare_and_swap: 5432 case Builtin::BI__sync_bool_compare_and_swap_1: 5433 case Builtin::BI__sync_bool_compare_and_swap_2: 5434 case Builtin::BI__sync_bool_compare_and_swap_4: 5435 case Builtin::BI__sync_bool_compare_and_swap_8: 5436 case Builtin::BI__sync_bool_compare_and_swap_16: 5437 BuiltinIndex = 13; 5438 NumFixed = 2; 5439 ResultType = Context.BoolTy; 5440 break; 5441 5442 case Builtin::BI__sync_lock_test_and_set: 5443 case Builtin::BI__sync_lock_test_and_set_1: 5444 case Builtin::BI__sync_lock_test_and_set_2: 5445 case Builtin::BI__sync_lock_test_and_set_4: 5446 case Builtin::BI__sync_lock_test_and_set_8: 5447 case Builtin::BI__sync_lock_test_and_set_16: 5448 BuiltinIndex = 14; 5449 break; 5450 5451 case Builtin::BI__sync_lock_release: 5452 case Builtin::BI__sync_lock_release_1: 5453 case Builtin::BI__sync_lock_release_2: 5454 case Builtin::BI__sync_lock_release_4: 5455 case Builtin::BI__sync_lock_release_8: 5456 case Builtin::BI__sync_lock_release_16: 5457 BuiltinIndex = 15; 5458 NumFixed = 0; 5459 ResultType = Context.VoidTy; 5460 break; 5461 5462 case Builtin::BI__sync_swap: 5463 case Builtin::BI__sync_swap_1: 5464 case Builtin::BI__sync_swap_2: 5465 case Builtin::BI__sync_swap_4: 5466 case Builtin::BI__sync_swap_8: 5467 case Builtin::BI__sync_swap_16: 5468 BuiltinIndex = 16; 5469 break; 5470 } 5471 5472 // Now that we know how many fixed arguments we expect, first check that we 5473 // have at least that many. 5474 if (TheCall->getNumArgs() < 1+NumFixed) { 5475 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5476 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5477 << Callee->getSourceRange(); 5478 return ExprError(); 5479 } 5480 5481 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5482 << Callee->getSourceRange(); 5483 5484 if (WarnAboutSemanticsChange) { 5485 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5486 << Callee->getSourceRange(); 5487 } 5488 5489 // Get the decl for the concrete builtin from this, we can tell what the 5490 // concrete integer type we should convert to is. 5491 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5492 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5493 FunctionDecl *NewBuiltinDecl; 5494 if (NewBuiltinID == BuiltinID) 5495 NewBuiltinDecl = FDecl; 5496 else { 5497 // Perform builtin lookup to avoid redeclaring it. 5498 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5499 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5500 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5501 assert(Res.getFoundDecl()); 5502 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5503 if (!NewBuiltinDecl) 5504 return ExprError(); 5505 } 5506 5507 // The first argument --- the pointer --- has a fixed type; we 5508 // deduce the types of the rest of the arguments accordingly. Walk 5509 // the remaining arguments, converting them to the deduced value type. 5510 for (unsigned i = 0; i != NumFixed; ++i) { 5511 ExprResult Arg = TheCall->getArg(i+1); 5512 5513 // GCC does an implicit conversion to the pointer or integer ValType. This 5514 // can fail in some cases (1i -> int**), check for this error case now. 5515 // Initialize the argument. 5516 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5517 ValType, /*consume*/ false); 5518 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5519 if (Arg.isInvalid()) 5520 return ExprError(); 5521 5522 // Okay, we have something that *can* be converted to the right type. Check 5523 // to see if there is a potentially weird extension going on here. This can 5524 // happen when you do an atomic operation on something like an char* and 5525 // pass in 42. The 42 gets converted to char. This is even more strange 5526 // for things like 45.123 -> char, etc. 5527 // FIXME: Do this check. 5528 TheCall->setArg(i+1, Arg.get()); 5529 } 5530 5531 // Create a new DeclRefExpr to refer to the new decl. 5532 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5533 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5534 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5535 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5536 5537 // Set the callee in the CallExpr. 5538 // FIXME: This loses syntactic information. 5539 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5540 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5541 CK_BuiltinFnToFnPtr); 5542 TheCall->setCallee(PromotedCall.get()); 5543 5544 // Change the result type of the call to match the original value type. This 5545 // is arbitrary, but the codegen for these builtins ins design to handle it 5546 // gracefully. 5547 TheCall->setType(ResultType); 5548 5549 // Prohibit use of _ExtInt with atomic builtins. 5550 // The arguments would have already been converted to the first argument's 5551 // type, so only need to check the first argument. 5552 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5553 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5554 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5555 return ExprError(); 5556 } 5557 5558 return TheCallResult; 5559 } 5560 5561 /// SemaBuiltinNontemporalOverloaded - We have a call to 5562 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5563 /// overloaded function based on the pointer type of its last argument. 5564 /// 5565 /// This function goes through and does final semantic checking for these 5566 /// builtins. 5567 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5568 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5569 DeclRefExpr *DRE = 5570 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5571 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5572 unsigned BuiltinID = FDecl->getBuiltinID(); 5573 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5574 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5575 "Unexpected nontemporal load/store builtin!"); 5576 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5577 unsigned numArgs = isStore ? 2 : 1; 5578 5579 // Ensure that we have the proper number of arguments. 5580 if (checkArgCount(*this, TheCall, numArgs)) 5581 return ExprError(); 5582 5583 // Inspect the last argument of the nontemporal builtin. This should always 5584 // be a pointer type, from which we imply the type of the memory access. 5585 // Because it is a pointer type, we don't have to worry about any implicit 5586 // casts here. 5587 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5588 ExprResult PointerArgResult = 5589 DefaultFunctionArrayLvalueConversion(PointerArg); 5590 5591 if (PointerArgResult.isInvalid()) 5592 return ExprError(); 5593 PointerArg = PointerArgResult.get(); 5594 TheCall->setArg(numArgs - 1, PointerArg); 5595 5596 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5597 if (!pointerType) { 5598 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5599 << PointerArg->getType() << PointerArg->getSourceRange(); 5600 return ExprError(); 5601 } 5602 5603 QualType ValType = pointerType->getPointeeType(); 5604 5605 // Strip any qualifiers off ValType. 5606 ValType = ValType.getUnqualifiedType(); 5607 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5608 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5609 !ValType->isVectorType()) { 5610 Diag(DRE->getBeginLoc(), 5611 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5612 << PointerArg->getType() << PointerArg->getSourceRange(); 5613 return ExprError(); 5614 } 5615 5616 if (!isStore) { 5617 TheCall->setType(ValType); 5618 return TheCallResult; 5619 } 5620 5621 ExprResult ValArg = TheCall->getArg(0); 5622 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5623 Context, ValType, /*consume*/ false); 5624 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5625 if (ValArg.isInvalid()) 5626 return ExprError(); 5627 5628 TheCall->setArg(0, ValArg.get()); 5629 TheCall->setType(Context.VoidTy); 5630 return TheCallResult; 5631 } 5632 5633 /// CheckObjCString - Checks that the argument to the builtin 5634 /// CFString constructor is correct 5635 /// Note: It might also make sense to do the UTF-16 conversion here (would 5636 /// simplify the backend). 5637 bool Sema::CheckObjCString(Expr *Arg) { 5638 Arg = Arg->IgnoreParenCasts(); 5639 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5640 5641 if (!Literal || !Literal->isAscii()) { 5642 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5643 << Arg->getSourceRange(); 5644 return true; 5645 } 5646 5647 if (Literal->containsNonAsciiOrNull()) { 5648 StringRef String = Literal->getString(); 5649 unsigned NumBytes = String.size(); 5650 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5651 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5652 llvm::UTF16 *ToPtr = &ToBuf[0]; 5653 5654 llvm::ConversionResult Result = 5655 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5656 ToPtr + NumBytes, llvm::strictConversion); 5657 // Check for conversion failure. 5658 if (Result != llvm::conversionOK) 5659 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5660 << Arg->getSourceRange(); 5661 } 5662 return false; 5663 } 5664 5665 /// CheckObjCString - Checks that the format string argument to the os_log() 5666 /// and os_trace() functions is correct, and converts it to const char *. 5667 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5668 Arg = Arg->IgnoreParenCasts(); 5669 auto *Literal = dyn_cast<StringLiteral>(Arg); 5670 if (!Literal) { 5671 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5672 Literal = ObjcLiteral->getString(); 5673 } 5674 } 5675 5676 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5677 return ExprError( 5678 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5679 << Arg->getSourceRange()); 5680 } 5681 5682 ExprResult Result(Literal); 5683 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5684 InitializedEntity Entity = 5685 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5686 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5687 return Result; 5688 } 5689 5690 /// Check that the user is calling the appropriate va_start builtin for the 5691 /// target and calling convention. 5692 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5693 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5694 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5695 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5696 TT.getArch() == llvm::Triple::aarch64_32); 5697 bool IsWindows = TT.isOSWindows(); 5698 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5699 if (IsX64 || IsAArch64) { 5700 CallingConv CC = CC_C; 5701 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5702 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5703 if (IsMSVAStart) { 5704 // Don't allow this in System V ABI functions. 5705 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5706 return S.Diag(Fn->getBeginLoc(), 5707 diag::err_ms_va_start_used_in_sysv_function); 5708 } else { 5709 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5710 // On x64 Windows, don't allow this in System V ABI functions. 5711 // (Yes, that means there's no corresponding way to support variadic 5712 // System V ABI functions on Windows.) 5713 if ((IsWindows && CC == CC_X86_64SysV) || 5714 (!IsWindows && CC == CC_Win64)) 5715 return S.Diag(Fn->getBeginLoc(), 5716 diag::err_va_start_used_in_wrong_abi_function) 5717 << !IsWindows; 5718 } 5719 return false; 5720 } 5721 5722 if (IsMSVAStart) 5723 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5724 return false; 5725 } 5726 5727 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5728 ParmVarDecl **LastParam = nullptr) { 5729 // Determine whether the current function, block, or obj-c method is variadic 5730 // and get its parameter list. 5731 bool IsVariadic = false; 5732 ArrayRef<ParmVarDecl *> Params; 5733 DeclContext *Caller = S.CurContext; 5734 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5735 IsVariadic = Block->isVariadic(); 5736 Params = Block->parameters(); 5737 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5738 IsVariadic = FD->isVariadic(); 5739 Params = FD->parameters(); 5740 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5741 IsVariadic = MD->isVariadic(); 5742 // FIXME: This isn't correct for methods (results in bogus warning). 5743 Params = MD->parameters(); 5744 } else if (isa<CapturedDecl>(Caller)) { 5745 // We don't support va_start in a CapturedDecl. 5746 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5747 return true; 5748 } else { 5749 // This must be some other declcontext that parses exprs. 5750 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5751 return true; 5752 } 5753 5754 if (!IsVariadic) { 5755 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5756 return true; 5757 } 5758 5759 if (LastParam) 5760 *LastParam = Params.empty() ? nullptr : Params.back(); 5761 5762 return false; 5763 } 5764 5765 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5766 /// for validity. Emit an error and return true on failure; return false 5767 /// on success. 5768 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5769 Expr *Fn = TheCall->getCallee(); 5770 5771 if (checkVAStartABI(*this, BuiltinID, Fn)) 5772 return true; 5773 5774 if (checkArgCount(*this, TheCall, 2)) 5775 return true; 5776 5777 // Type-check the first argument normally. 5778 if (checkBuiltinArgument(*this, TheCall, 0)) 5779 return true; 5780 5781 // Check that the current function is variadic, and get its last parameter. 5782 ParmVarDecl *LastParam; 5783 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5784 return true; 5785 5786 // Verify that the second argument to the builtin is the last argument of the 5787 // current function or method. 5788 bool SecondArgIsLastNamedArgument = false; 5789 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5790 5791 // These are valid if SecondArgIsLastNamedArgument is false after the next 5792 // block. 5793 QualType Type; 5794 SourceLocation ParamLoc; 5795 bool IsCRegister = false; 5796 5797 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5798 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5799 SecondArgIsLastNamedArgument = PV == LastParam; 5800 5801 Type = PV->getType(); 5802 ParamLoc = PV->getLocation(); 5803 IsCRegister = 5804 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5805 } 5806 } 5807 5808 if (!SecondArgIsLastNamedArgument) 5809 Diag(TheCall->getArg(1)->getBeginLoc(), 5810 diag::warn_second_arg_of_va_start_not_last_named_param); 5811 else if (IsCRegister || Type->isReferenceType() || 5812 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5813 // Promotable integers are UB, but enumerations need a bit of 5814 // extra checking to see what their promotable type actually is. 5815 if (!Type->isPromotableIntegerType()) 5816 return false; 5817 if (!Type->isEnumeralType()) 5818 return true; 5819 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5820 return !(ED && 5821 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5822 }()) { 5823 unsigned Reason = 0; 5824 if (Type->isReferenceType()) Reason = 1; 5825 else if (IsCRegister) Reason = 2; 5826 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5827 Diag(ParamLoc, diag::note_parameter_type) << Type; 5828 } 5829 5830 TheCall->setType(Context.VoidTy); 5831 return false; 5832 } 5833 5834 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5835 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5836 // const char *named_addr); 5837 5838 Expr *Func = Call->getCallee(); 5839 5840 if (Call->getNumArgs() < 3) 5841 return Diag(Call->getEndLoc(), 5842 diag::err_typecheck_call_too_few_args_at_least) 5843 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5844 5845 // Type-check the first argument normally. 5846 if (checkBuiltinArgument(*this, Call, 0)) 5847 return true; 5848 5849 // Check that the current function is variadic. 5850 if (checkVAStartIsInVariadicFunction(*this, Func)) 5851 return true; 5852 5853 // __va_start on Windows does not validate the parameter qualifiers 5854 5855 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5856 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5857 5858 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5859 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5860 5861 const QualType &ConstCharPtrTy = 5862 Context.getPointerType(Context.CharTy.withConst()); 5863 if (!Arg1Ty->isPointerType() || 5864 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5865 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5866 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5867 << 0 /* qualifier difference */ 5868 << 3 /* parameter mismatch */ 5869 << 2 << Arg1->getType() << ConstCharPtrTy; 5870 5871 const QualType SizeTy = Context.getSizeType(); 5872 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5873 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5874 << Arg2->getType() << SizeTy << 1 /* different class */ 5875 << 0 /* qualifier difference */ 5876 << 3 /* parameter mismatch */ 5877 << 3 << Arg2->getType() << SizeTy; 5878 5879 return false; 5880 } 5881 5882 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5883 /// friends. This is declared to take (...), so we have to check everything. 5884 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5885 if (checkArgCount(*this, TheCall, 2)) 5886 return true; 5887 5888 ExprResult OrigArg0 = TheCall->getArg(0); 5889 ExprResult OrigArg1 = TheCall->getArg(1); 5890 5891 // Do standard promotions between the two arguments, returning their common 5892 // type. 5893 QualType Res = UsualArithmeticConversions( 5894 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5895 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5896 return true; 5897 5898 // Make sure any conversions are pushed back into the call; this is 5899 // type safe since unordered compare builtins are declared as "_Bool 5900 // foo(...)". 5901 TheCall->setArg(0, OrigArg0.get()); 5902 TheCall->setArg(1, OrigArg1.get()); 5903 5904 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5905 return false; 5906 5907 // If the common type isn't a real floating type, then the arguments were 5908 // invalid for this operation. 5909 if (Res.isNull() || !Res->isRealFloatingType()) 5910 return Diag(OrigArg0.get()->getBeginLoc(), 5911 diag::err_typecheck_call_invalid_ordered_compare) 5912 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5913 << SourceRange(OrigArg0.get()->getBeginLoc(), 5914 OrigArg1.get()->getEndLoc()); 5915 5916 return false; 5917 } 5918 5919 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5920 /// __builtin_isnan and friends. This is declared to take (...), so we have 5921 /// to check everything. We expect the last argument to be a floating point 5922 /// value. 5923 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5924 if (checkArgCount(*this, TheCall, NumArgs)) 5925 return true; 5926 5927 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5928 // on all preceding parameters just being int. Try all of those. 5929 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5930 Expr *Arg = TheCall->getArg(i); 5931 5932 if (Arg->isTypeDependent()) 5933 return false; 5934 5935 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5936 5937 if (Res.isInvalid()) 5938 return true; 5939 TheCall->setArg(i, Res.get()); 5940 } 5941 5942 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5943 5944 if (OrigArg->isTypeDependent()) 5945 return false; 5946 5947 // Usual Unary Conversions will convert half to float, which we want for 5948 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5949 // type how it is, but do normal L->Rvalue conversions. 5950 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5951 OrigArg = UsualUnaryConversions(OrigArg).get(); 5952 else 5953 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5954 TheCall->setArg(NumArgs - 1, OrigArg); 5955 5956 // This operation requires a non-_Complex floating-point number. 5957 if (!OrigArg->getType()->isRealFloatingType()) 5958 return Diag(OrigArg->getBeginLoc(), 5959 diag::err_typecheck_call_invalid_unary_fp) 5960 << OrigArg->getType() << OrigArg->getSourceRange(); 5961 5962 return false; 5963 } 5964 5965 /// Perform semantic analysis for a call to __builtin_complex. 5966 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5967 if (checkArgCount(*this, TheCall, 2)) 5968 return true; 5969 5970 bool Dependent = false; 5971 for (unsigned I = 0; I != 2; ++I) { 5972 Expr *Arg = TheCall->getArg(I); 5973 QualType T = Arg->getType(); 5974 if (T->isDependentType()) { 5975 Dependent = true; 5976 continue; 5977 } 5978 5979 // Despite supporting _Complex int, GCC requires a real floating point type 5980 // for the operands of __builtin_complex. 5981 if (!T->isRealFloatingType()) { 5982 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5983 << Arg->getType() << Arg->getSourceRange(); 5984 } 5985 5986 ExprResult Converted = DefaultLvalueConversion(Arg); 5987 if (Converted.isInvalid()) 5988 return true; 5989 TheCall->setArg(I, Converted.get()); 5990 } 5991 5992 if (Dependent) { 5993 TheCall->setType(Context.DependentTy); 5994 return false; 5995 } 5996 5997 Expr *Real = TheCall->getArg(0); 5998 Expr *Imag = TheCall->getArg(1); 5999 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6000 return Diag(Real->getBeginLoc(), 6001 diag::err_typecheck_call_different_arg_types) 6002 << Real->getType() << Imag->getType() 6003 << Real->getSourceRange() << Imag->getSourceRange(); 6004 } 6005 6006 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6007 // don't allow this builtin to form those types either. 6008 // FIXME: Should we allow these types? 6009 if (Real->getType()->isFloat16Type()) 6010 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6011 << "_Float16"; 6012 if (Real->getType()->isHalfType()) 6013 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6014 << "half"; 6015 6016 TheCall->setType(Context.getComplexType(Real->getType())); 6017 return false; 6018 } 6019 6020 // Customized Sema Checking for VSX builtins that have the following signature: 6021 // vector [...] builtinName(vector [...], vector [...], const int); 6022 // Which takes the same type of vectors (any legal vector type) for the first 6023 // two arguments and takes compile time constant for the third argument. 6024 // Example builtins are : 6025 // vector double vec_xxpermdi(vector double, vector double, int); 6026 // vector short vec_xxsldwi(vector short, vector short, int); 6027 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6028 unsigned ExpectedNumArgs = 3; 6029 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6030 return true; 6031 6032 // Check the third argument is a compile time constant 6033 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6034 return Diag(TheCall->getBeginLoc(), 6035 diag::err_vsx_builtin_nonconstant_argument) 6036 << 3 /* argument index */ << TheCall->getDirectCallee() 6037 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6038 TheCall->getArg(2)->getEndLoc()); 6039 6040 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6041 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6042 6043 // Check the type of argument 1 and argument 2 are vectors. 6044 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6045 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6046 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6047 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6048 << TheCall->getDirectCallee() 6049 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6050 TheCall->getArg(1)->getEndLoc()); 6051 } 6052 6053 // Check the first two arguments are the same type. 6054 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6055 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6056 << TheCall->getDirectCallee() 6057 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6058 TheCall->getArg(1)->getEndLoc()); 6059 } 6060 6061 // When default clang type checking is turned off and the customized type 6062 // checking is used, the returning type of the function must be explicitly 6063 // set. Otherwise it is _Bool by default. 6064 TheCall->setType(Arg1Ty); 6065 6066 return false; 6067 } 6068 6069 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6070 // This is declared to take (...), so we have to check everything. 6071 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6072 if (TheCall->getNumArgs() < 2) 6073 return ExprError(Diag(TheCall->getEndLoc(), 6074 diag::err_typecheck_call_too_few_args_at_least) 6075 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6076 << TheCall->getSourceRange()); 6077 6078 // Determine which of the following types of shufflevector we're checking: 6079 // 1) unary, vector mask: (lhs, mask) 6080 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6081 QualType resType = TheCall->getArg(0)->getType(); 6082 unsigned numElements = 0; 6083 6084 if (!TheCall->getArg(0)->isTypeDependent() && 6085 !TheCall->getArg(1)->isTypeDependent()) { 6086 QualType LHSType = TheCall->getArg(0)->getType(); 6087 QualType RHSType = TheCall->getArg(1)->getType(); 6088 6089 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6090 return ExprError( 6091 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6092 << TheCall->getDirectCallee() 6093 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6094 TheCall->getArg(1)->getEndLoc())); 6095 6096 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6097 unsigned numResElements = TheCall->getNumArgs() - 2; 6098 6099 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6100 // with mask. If so, verify that RHS is an integer vector type with the 6101 // same number of elts as lhs. 6102 if (TheCall->getNumArgs() == 2) { 6103 if (!RHSType->hasIntegerRepresentation() || 6104 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6105 return ExprError(Diag(TheCall->getBeginLoc(), 6106 diag::err_vec_builtin_incompatible_vector) 6107 << TheCall->getDirectCallee() 6108 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6109 TheCall->getArg(1)->getEndLoc())); 6110 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6111 return ExprError(Diag(TheCall->getBeginLoc(), 6112 diag::err_vec_builtin_incompatible_vector) 6113 << TheCall->getDirectCallee() 6114 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6115 TheCall->getArg(1)->getEndLoc())); 6116 } else if (numElements != numResElements) { 6117 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6118 resType = Context.getVectorType(eltType, numResElements, 6119 VectorType::GenericVector); 6120 } 6121 } 6122 6123 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6124 if (TheCall->getArg(i)->isTypeDependent() || 6125 TheCall->getArg(i)->isValueDependent()) 6126 continue; 6127 6128 Optional<llvm::APSInt> Result; 6129 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6130 return ExprError(Diag(TheCall->getBeginLoc(), 6131 diag::err_shufflevector_nonconstant_argument) 6132 << TheCall->getArg(i)->getSourceRange()); 6133 6134 // Allow -1 which will be translated to undef in the IR. 6135 if (Result->isSigned() && Result->isAllOnesValue()) 6136 continue; 6137 6138 if (Result->getActiveBits() > 64 || 6139 Result->getZExtValue() >= numElements * 2) 6140 return ExprError(Diag(TheCall->getBeginLoc(), 6141 diag::err_shufflevector_argument_too_large) 6142 << TheCall->getArg(i)->getSourceRange()); 6143 } 6144 6145 SmallVector<Expr*, 32> exprs; 6146 6147 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6148 exprs.push_back(TheCall->getArg(i)); 6149 TheCall->setArg(i, nullptr); 6150 } 6151 6152 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6153 TheCall->getCallee()->getBeginLoc(), 6154 TheCall->getRParenLoc()); 6155 } 6156 6157 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6158 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6159 SourceLocation BuiltinLoc, 6160 SourceLocation RParenLoc) { 6161 ExprValueKind VK = VK_RValue; 6162 ExprObjectKind OK = OK_Ordinary; 6163 QualType DstTy = TInfo->getType(); 6164 QualType SrcTy = E->getType(); 6165 6166 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6167 return ExprError(Diag(BuiltinLoc, 6168 diag::err_convertvector_non_vector) 6169 << E->getSourceRange()); 6170 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6171 return ExprError(Diag(BuiltinLoc, 6172 diag::err_convertvector_non_vector_type)); 6173 6174 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6175 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6176 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6177 if (SrcElts != DstElts) 6178 return ExprError(Diag(BuiltinLoc, 6179 diag::err_convertvector_incompatible_vector) 6180 << E->getSourceRange()); 6181 } 6182 6183 return new (Context) 6184 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6185 } 6186 6187 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6188 // This is declared to take (const void*, ...) and can take two 6189 // optional constant int args. 6190 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6191 unsigned NumArgs = TheCall->getNumArgs(); 6192 6193 if (NumArgs > 3) 6194 return Diag(TheCall->getEndLoc(), 6195 diag::err_typecheck_call_too_many_args_at_most) 6196 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6197 6198 // Argument 0 is checked for us and the remaining arguments must be 6199 // constant integers. 6200 for (unsigned i = 1; i != NumArgs; ++i) 6201 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6202 return true; 6203 6204 return false; 6205 } 6206 6207 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6208 // __assume does not evaluate its arguments, and should warn if its argument 6209 // has side effects. 6210 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6211 Expr *Arg = TheCall->getArg(0); 6212 if (Arg->isInstantiationDependent()) return false; 6213 6214 if (Arg->HasSideEffects(Context)) 6215 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6216 << Arg->getSourceRange() 6217 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6218 6219 return false; 6220 } 6221 6222 /// Handle __builtin_alloca_with_align. This is declared 6223 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6224 /// than 8. 6225 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6226 // The alignment must be a constant integer. 6227 Expr *Arg = TheCall->getArg(1); 6228 6229 // We can't check the value of a dependent argument. 6230 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6231 if (const auto *UE = 6232 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6233 if (UE->getKind() == UETT_AlignOf || 6234 UE->getKind() == UETT_PreferredAlignOf) 6235 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6236 << Arg->getSourceRange(); 6237 6238 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6239 6240 if (!Result.isPowerOf2()) 6241 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6242 << Arg->getSourceRange(); 6243 6244 if (Result < Context.getCharWidth()) 6245 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6246 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6247 6248 if (Result > std::numeric_limits<int32_t>::max()) 6249 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6250 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6251 } 6252 6253 return false; 6254 } 6255 6256 /// Handle __builtin_assume_aligned. This is declared 6257 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6258 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6259 unsigned NumArgs = TheCall->getNumArgs(); 6260 6261 if (NumArgs > 3) 6262 return Diag(TheCall->getEndLoc(), 6263 diag::err_typecheck_call_too_many_args_at_most) 6264 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6265 6266 // The alignment must be a constant integer. 6267 Expr *Arg = TheCall->getArg(1); 6268 6269 // We can't check the value of a dependent argument. 6270 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6271 llvm::APSInt Result; 6272 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6273 return true; 6274 6275 if (!Result.isPowerOf2()) 6276 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6277 << Arg->getSourceRange(); 6278 6279 if (Result > Sema::MaximumAlignment) 6280 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6281 << Arg->getSourceRange() << Sema::MaximumAlignment; 6282 } 6283 6284 if (NumArgs > 2) { 6285 ExprResult Arg(TheCall->getArg(2)); 6286 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6287 Context.getSizeType(), false); 6288 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6289 if (Arg.isInvalid()) return true; 6290 TheCall->setArg(2, Arg.get()); 6291 } 6292 6293 return false; 6294 } 6295 6296 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6297 unsigned BuiltinID = 6298 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6299 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6300 6301 unsigned NumArgs = TheCall->getNumArgs(); 6302 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6303 if (NumArgs < NumRequiredArgs) { 6304 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6305 << 0 /* function call */ << NumRequiredArgs << NumArgs 6306 << TheCall->getSourceRange(); 6307 } 6308 if (NumArgs >= NumRequiredArgs + 0x100) { 6309 return Diag(TheCall->getEndLoc(), 6310 diag::err_typecheck_call_too_many_args_at_most) 6311 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6312 << TheCall->getSourceRange(); 6313 } 6314 unsigned i = 0; 6315 6316 // For formatting call, check buffer arg. 6317 if (!IsSizeCall) { 6318 ExprResult Arg(TheCall->getArg(i)); 6319 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6320 Context, Context.VoidPtrTy, false); 6321 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6322 if (Arg.isInvalid()) 6323 return true; 6324 TheCall->setArg(i, Arg.get()); 6325 i++; 6326 } 6327 6328 // Check string literal arg. 6329 unsigned FormatIdx = i; 6330 { 6331 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6332 if (Arg.isInvalid()) 6333 return true; 6334 TheCall->setArg(i, Arg.get()); 6335 i++; 6336 } 6337 6338 // Make sure variadic args are scalar. 6339 unsigned FirstDataArg = i; 6340 while (i < NumArgs) { 6341 ExprResult Arg = DefaultVariadicArgumentPromotion( 6342 TheCall->getArg(i), VariadicFunction, nullptr); 6343 if (Arg.isInvalid()) 6344 return true; 6345 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6346 if (ArgSize.getQuantity() >= 0x100) { 6347 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6348 << i << (int)ArgSize.getQuantity() << 0xff 6349 << TheCall->getSourceRange(); 6350 } 6351 TheCall->setArg(i, Arg.get()); 6352 i++; 6353 } 6354 6355 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6356 // call to avoid duplicate diagnostics. 6357 if (!IsSizeCall) { 6358 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6359 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6360 bool Success = CheckFormatArguments( 6361 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6362 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6363 CheckedVarArgs); 6364 if (!Success) 6365 return true; 6366 } 6367 6368 if (IsSizeCall) { 6369 TheCall->setType(Context.getSizeType()); 6370 } else { 6371 TheCall->setType(Context.VoidPtrTy); 6372 } 6373 return false; 6374 } 6375 6376 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6377 /// TheCall is a constant expression. 6378 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6379 llvm::APSInt &Result) { 6380 Expr *Arg = TheCall->getArg(ArgNum); 6381 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6382 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6383 6384 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6385 6386 Optional<llvm::APSInt> R; 6387 if (!(R = Arg->getIntegerConstantExpr(Context))) 6388 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6389 << FDecl->getDeclName() << Arg->getSourceRange(); 6390 Result = *R; 6391 return false; 6392 } 6393 6394 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6395 /// TheCall is a constant expression in the range [Low, High]. 6396 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6397 int Low, int High, bool RangeIsError) { 6398 if (isConstantEvaluated()) 6399 return false; 6400 llvm::APSInt Result; 6401 6402 // We can't check the value of a dependent argument. 6403 Expr *Arg = TheCall->getArg(ArgNum); 6404 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6405 return false; 6406 6407 // Check constant-ness first. 6408 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6409 return true; 6410 6411 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6412 if (RangeIsError) 6413 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6414 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6415 else 6416 // Defer the warning until we know if the code will be emitted so that 6417 // dead code can ignore this. 6418 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6419 PDiag(diag::warn_argument_invalid_range) 6420 << Result.toString(10) << Low << High 6421 << Arg->getSourceRange()); 6422 } 6423 6424 return false; 6425 } 6426 6427 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6428 /// TheCall is a constant expression is a multiple of Num.. 6429 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6430 unsigned Num) { 6431 llvm::APSInt Result; 6432 6433 // We can't check the value of a dependent argument. 6434 Expr *Arg = TheCall->getArg(ArgNum); 6435 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6436 return false; 6437 6438 // Check constant-ness first. 6439 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6440 return true; 6441 6442 if (Result.getSExtValue() % Num != 0) 6443 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6444 << Num << Arg->getSourceRange(); 6445 6446 return false; 6447 } 6448 6449 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6450 /// constant expression representing a power of 2. 6451 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6452 llvm::APSInt Result; 6453 6454 // We can't check the value of a dependent argument. 6455 Expr *Arg = TheCall->getArg(ArgNum); 6456 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6457 return false; 6458 6459 // Check constant-ness first. 6460 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6461 return true; 6462 6463 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6464 // and only if x is a power of 2. 6465 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6466 return false; 6467 6468 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6469 << Arg->getSourceRange(); 6470 } 6471 6472 static bool IsShiftedByte(llvm::APSInt Value) { 6473 if (Value.isNegative()) 6474 return false; 6475 6476 // Check if it's a shifted byte, by shifting it down 6477 while (true) { 6478 // If the value fits in the bottom byte, the check passes. 6479 if (Value < 0x100) 6480 return true; 6481 6482 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6483 // fails. 6484 if ((Value & 0xFF) != 0) 6485 return false; 6486 6487 // If the bottom 8 bits are all 0, but something above that is nonzero, 6488 // then shifting the value right by 8 bits won't affect whether it's a 6489 // shifted byte or not. So do that, and go round again. 6490 Value >>= 8; 6491 } 6492 } 6493 6494 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6495 /// a constant expression representing an arbitrary byte value shifted left by 6496 /// a multiple of 8 bits. 6497 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6498 unsigned ArgBits) { 6499 llvm::APSInt Result; 6500 6501 // We can't check the value of a dependent argument. 6502 Expr *Arg = TheCall->getArg(ArgNum); 6503 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6504 return false; 6505 6506 // Check constant-ness first. 6507 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6508 return true; 6509 6510 // Truncate to the given size. 6511 Result = Result.getLoBits(ArgBits); 6512 Result.setIsUnsigned(true); 6513 6514 if (IsShiftedByte(Result)) 6515 return false; 6516 6517 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6518 << Arg->getSourceRange(); 6519 } 6520 6521 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6522 /// TheCall is a constant expression representing either a shifted byte value, 6523 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6524 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6525 /// Arm MVE intrinsics. 6526 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6527 int ArgNum, 6528 unsigned ArgBits) { 6529 llvm::APSInt Result; 6530 6531 // We can't check the value of a dependent argument. 6532 Expr *Arg = TheCall->getArg(ArgNum); 6533 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6534 return false; 6535 6536 // Check constant-ness first. 6537 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6538 return true; 6539 6540 // Truncate to the given size. 6541 Result = Result.getLoBits(ArgBits); 6542 Result.setIsUnsigned(true); 6543 6544 // Check to see if it's in either of the required forms. 6545 if (IsShiftedByte(Result) || 6546 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6547 return false; 6548 6549 return Diag(TheCall->getBeginLoc(), 6550 diag::err_argument_not_shifted_byte_or_xxff) 6551 << Arg->getSourceRange(); 6552 } 6553 6554 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6555 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6556 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6557 if (checkArgCount(*this, TheCall, 2)) 6558 return true; 6559 Expr *Arg0 = TheCall->getArg(0); 6560 Expr *Arg1 = TheCall->getArg(1); 6561 6562 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6563 if (FirstArg.isInvalid()) 6564 return true; 6565 QualType FirstArgType = FirstArg.get()->getType(); 6566 if (!FirstArgType->isAnyPointerType()) 6567 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6568 << "first" << FirstArgType << Arg0->getSourceRange(); 6569 TheCall->setArg(0, FirstArg.get()); 6570 6571 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6572 if (SecArg.isInvalid()) 6573 return true; 6574 QualType SecArgType = SecArg.get()->getType(); 6575 if (!SecArgType->isIntegerType()) 6576 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6577 << "second" << SecArgType << Arg1->getSourceRange(); 6578 6579 // Derive the return type from the pointer argument. 6580 TheCall->setType(FirstArgType); 6581 return false; 6582 } 6583 6584 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6585 if (checkArgCount(*this, TheCall, 2)) 6586 return true; 6587 6588 Expr *Arg0 = TheCall->getArg(0); 6589 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6590 if (FirstArg.isInvalid()) 6591 return true; 6592 QualType FirstArgType = FirstArg.get()->getType(); 6593 if (!FirstArgType->isAnyPointerType()) 6594 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6595 << "first" << FirstArgType << Arg0->getSourceRange(); 6596 TheCall->setArg(0, FirstArg.get()); 6597 6598 // Derive the return type from the pointer argument. 6599 TheCall->setType(FirstArgType); 6600 6601 // Second arg must be an constant in range [0,15] 6602 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6603 } 6604 6605 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6606 if (checkArgCount(*this, TheCall, 2)) 6607 return true; 6608 Expr *Arg0 = TheCall->getArg(0); 6609 Expr *Arg1 = TheCall->getArg(1); 6610 6611 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6612 if (FirstArg.isInvalid()) 6613 return true; 6614 QualType FirstArgType = FirstArg.get()->getType(); 6615 if (!FirstArgType->isAnyPointerType()) 6616 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6617 << "first" << FirstArgType << Arg0->getSourceRange(); 6618 6619 QualType SecArgType = Arg1->getType(); 6620 if (!SecArgType->isIntegerType()) 6621 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6622 << "second" << SecArgType << Arg1->getSourceRange(); 6623 TheCall->setType(Context.IntTy); 6624 return false; 6625 } 6626 6627 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6628 BuiltinID == AArch64::BI__builtin_arm_stg) { 6629 if (checkArgCount(*this, TheCall, 1)) 6630 return true; 6631 Expr *Arg0 = TheCall->getArg(0); 6632 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6633 if (FirstArg.isInvalid()) 6634 return true; 6635 6636 QualType FirstArgType = FirstArg.get()->getType(); 6637 if (!FirstArgType->isAnyPointerType()) 6638 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6639 << "first" << FirstArgType << Arg0->getSourceRange(); 6640 TheCall->setArg(0, FirstArg.get()); 6641 6642 // Derive the return type from the pointer argument. 6643 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6644 TheCall->setType(FirstArgType); 6645 return false; 6646 } 6647 6648 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6649 Expr *ArgA = TheCall->getArg(0); 6650 Expr *ArgB = TheCall->getArg(1); 6651 6652 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6653 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6654 6655 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6656 return true; 6657 6658 QualType ArgTypeA = ArgExprA.get()->getType(); 6659 QualType ArgTypeB = ArgExprB.get()->getType(); 6660 6661 auto isNull = [&] (Expr *E) -> bool { 6662 return E->isNullPointerConstant( 6663 Context, Expr::NPC_ValueDependentIsNotNull); }; 6664 6665 // argument should be either a pointer or null 6666 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6667 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6668 << "first" << ArgTypeA << ArgA->getSourceRange(); 6669 6670 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6671 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6672 << "second" << ArgTypeB << ArgB->getSourceRange(); 6673 6674 // Ensure Pointee types are compatible 6675 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6676 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6677 QualType pointeeA = ArgTypeA->getPointeeType(); 6678 QualType pointeeB = ArgTypeB->getPointeeType(); 6679 if (!Context.typesAreCompatible( 6680 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6681 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6682 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6683 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6684 << ArgB->getSourceRange(); 6685 } 6686 } 6687 6688 // at least one argument should be pointer type 6689 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6690 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6691 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6692 6693 if (isNull(ArgA)) // adopt type of the other pointer 6694 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6695 6696 if (isNull(ArgB)) 6697 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6698 6699 TheCall->setArg(0, ArgExprA.get()); 6700 TheCall->setArg(1, ArgExprB.get()); 6701 TheCall->setType(Context.LongLongTy); 6702 return false; 6703 } 6704 assert(false && "Unhandled ARM MTE intrinsic"); 6705 return true; 6706 } 6707 6708 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6709 /// TheCall is an ARM/AArch64 special register string literal. 6710 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6711 int ArgNum, unsigned ExpectedFieldNum, 6712 bool AllowName) { 6713 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6714 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6715 BuiltinID == ARM::BI__builtin_arm_rsr || 6716 BuiltinID == ARM::BI__builtin_arm_rsrp || 6717 BuiltinID == ARM::BI__builtin_arm_wsr || 6718 BuiltinID == ARM::BI__builtin_arm_wsrp; 6719 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6720 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6721 BuiltinID == AArch64::BI__builtin_arm_rsr || 6722 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6723 BuiltinID == AArch64::BI__builtin_arm_wsr || 6724 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6725 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6726 6727 // We can't check the value of a dependent argument. 6728 Expr *Arg = TheCall->getArg(ArgNum); 6729 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6730 return false; 6731 6732 // Check if the argument is a string literal. 6733 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6734 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6735 << Arg->getSourceRange(); 6736 6737 // Check the type of special register given. 6738 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6739 SmallVector<StringRef, 6> Fields; 6740 Reg.split(Fields, ":"); 6741 6742 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6743 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6744 << Arg->getSourceRange(); 6745 6746 // If the string is the name of a register then we cannot check that it is 6747 // valid here but if the string is of one the forms described in ACLE then we 6748 // can check that the supplied fields are integers and within the valid 6749 // ranges. 6750 if (Fields.size() > 1) { 6751 bool FiveFields = Fields.size() == 5; 6752 6753 bool ValidString = true; 6754 if (IsARMBuiltin) { 6755 ValidString &= Fields[0].startswith_lower("cp") || 6756 Fields[0].startswith_lower("p"); 6757 if (ValidString) 6758 Fields[0] = 6759 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6760 6761 ValidString &= Fields[2].startswith_lower("c"); 6762 if (ValidString) 6763 Fields[2] = Fields[2].drop_front(1); 6764 6765 if (FiveFields) { 6766 ValidString &= Fields[3].startswith_lower("c"); 6767 if (ValidString) 6768 Fields[3] = Fields[3].drop_front(1); 6769 } 6770 } 6771 6772 SmallVector<int, 5> Ranges; 6773 if (FiveFields) 6774 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6775 else 6776 Ranges.append({15, 7, 15}); 6777 6778 for (unsigned i=0; i<Fields.size(); ++i) { 6779 int IntField; 6780 ValidString &= !Fields[i].getAsInteger(10, IntField); 6781 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6782 } 6783 6784 if (!ValidString) 6785 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6786 << Arg->getSourceRange(); 6787 } else if (IsAArch64Builtin && Fields.size() == 1) { 6788 // If the register name is one of those that appear in the condition below 6789 // and the special register builtin being used is one of the write builtins, 6790 // then we require that the argument provided for writing to the register 6791 // is an integer constant expression. This is because it will be lowered to 6792 // an MSR (immediate) instruction, so we need to know the immediate at 6793 // compile time. 6794 if (TheCall->getNumArgs() != 2) 6795 return false; 6796 6797 std::string RegLower = Reg.lower(); 6798 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6799 RegLower != "pan" && RegLower != "uao") 6800 return false; 6801 6802 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6803 } 6804 6805 return false; 6806 } 6807 6808 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 6809 /// Emit an error and return true on failure; return false on success. 6810 /// TypeStr is a string containing the type descriptor of the value returned by 6811 /// the builtin and the descriptors of the expected type of the arguments. 6812 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 6813 6814 assert((TypeStr[0] != '\0') && 6815 "Invalid types in PPC MMA builtin declaration"); 6816 6817 unsigned Mask = 0; 6818 unsigned ArgNum = 0; 6819 6820 // The first type in TypeStr is the type of the value returned by the 6821 // builtin. So we first read that type and change the type of TheCall. 6822 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6823 TheCall->setType(type); 6824 6825 while (*TypeStr != '\0') { 6826 Mask = 0; 6827 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6828 if (ArgNum >= TheCall->getNumArgs()) { 6829 ArgNum++; 6830 break; 6831 } 6832 6833 Expr *Arg = TheCall->getArg(ArgNum); 6834 QualType ArgType = Arg->getType(); 6835 6836 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 6837 (!ExpectedType->isVoidPointerType() && 6838 ArgType.getCanonicalType() != ExpectedType)) 6839 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6840 << ArgType << ExpectedType << 1 << 0 << 0; 6841 6842 // If the value of the Mask is not 0, we have a constraint in the size of 6843 // the integer argument so here we ensure the argument is a constant that 6844 // is in the valid range. 6845 if (Mask != 0 && 6846 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 6847 return true; 6848 6849 ArgNum++; 6850 } 6851 6852 // In case we exited early from the previous loop, there are other types to 6853 // read from TypeStr. So we need to read them all to ensure we have the right 6854 // number of arguments in TheCall and if it is not the case, to display a 6855 // better error message. 6856 while (*TypeStr != '\0') { 6857 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6858 ArgNum++; 6859 } 6860 if (checkArgCount(*this, TheCall, ArgNum)) 6861 return true; 6862 6863 return false; 6864 } 6865 6866 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6867 /// This checks that the target supports __builtin_longjmp and 6868 /// that val is a constant 1. 6869 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6870 if (!Context.getTargetInfo().hasSjLjLowering()) 6871 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6872 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6873 6874 Expr *Arg = TheCall->getArg(1); 6875 llvm::APSInt Result; 6876 6877 // TODO: This is less than ideal. Overload this to take a value. 6878 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6879 return true; 6880 6881 if (Result != 1) 6882 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6883 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6884 6885 return false; 6886 } 6887 6888 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6889 /// This checks that the target supports __builtin_setjmp. 6890 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6891 if (!Context.getTargetInfo().hasSjLjLowering()) 6892 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6893 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6894 return false; 6895 } 6896 6897 namespace { 6898 6899 class UncoveredArgHandler { 6900 enum { Unknown = -1, AllCovered = -2 }; 6901 6902 signed FirstUncoveredArg = Unknown; 6903 SmallVector<const Expr *, 4> DiagnosticExprs; 6904 6905 public: 6906 UncoveredArgHandler() = default; 6907 6908 bool hasUncoveredArg() const { 6909 return (FirstUncoveredArg >= 0); 6910 } 6911 6912 unsigned getUncoveredArg() const { 6913 assert(hasUncoveredArg() && "no uncovered argument"); 6914 return FirstUncoveredArg; 6915 } 6916 6917 void setAllCovered() { 6918 // A string has been found with all arguments covered, so clear out 6919 // the diagnostics. 6920 DiagnosticExprs.clear(); 6921 FirstUncoveredArg = AllCovered; 6922 } 6923 6924 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6925 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6926 6927 // Don't update if a previous string covers all arguments. 6928 if (FirstUncoveredArg == AllCovered) 6929 return; 6930 6931 // UncoveredArgHandler tracks the highest uncovered argument index 6932 // and with it all the strings that match this index. 6933 if (NewFirstUncoveredArg == FirstUncoveredArg) 6934 DiagnosticExprs.push_back(StrExpr); 6935 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6936 DiagnosticExprs.clear(); 6937 DiagnosticExprs.push_back(StrExpr); 6938 FirstUncoveredArg = NewFirstUncoveredArg; 6939 } 6940 } 6941 6942 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6943 }; 6944 6945 enum StringLiteralCheckType { 6946 SLCT_NotALiteral, 6947 SLCT_UncheckedLiteral, 6948 SLCT_CheckedLiteral 6949 }; 6950 6951 } // namespace 6952 6953 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6954 BinaryOperatorKind BinOpKind, 6955 bool AddendIsRight) { 6956 unsigned BitWidth = Offset.getBitWidth(); 6957 unsigned AddendBitWidth = Addend.getBitWidth(); 6958 // There might be negative interim results. 6959 if (Addend.isUnsigned()) { 6960 Addend = Addend.zext(++AddendBitWidth); 6961 Addend.setIsSigned(true); 6962 } 6963 // Adjust the bit width of the APSInts. 6964 if (AddendBitWidth > BitWidth) { 6965 Offset = Offset.sext(AddendBitWidth); 6966 BitWidth = AddendBitWidth; 6967 } else if (BitWidth > AddendBitWidth) { 6968 Addend = Addend.sext(BitWidth); 6969 } 6970 6971 bool Ov = false; 6972 llvm::APSInt ResOffset = Offset; 6973 if (BinOpKind == BO_Add) 6974 ResOffset = Offset.sadd_ov(Addend, Ov); 6975 else { 6976 assert(AddendIsRight && BinOpKind == BO_Sub && 6977 "operator must be add or sub with addend on the right"); 6978 ResOffset = Offset.ssub_ov(Addend, Ov); 6979 } 6980 6981 // We add an offset to a pointer here so we should support an offset as big as 6982 // possible. 6983 if (Ov) { 6984 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6985 "index (intermediate) result too big"); 6986 Offset = Offset.sext(2 * BitWidth); 6987 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6988 return; 6989 } 6990 6991 Offset = ResOffset; 6992 } 6993 6994 namespace { 6995 6996 // This is a wrapper class around StringLiteral to support offsetted string 6997 // literals as format strings. It takes the offset into account when returning 6998 // the string and its length or the source locations to display notes correctly. 6999 class FormatStringLiteral { 7000 const StringLiteral *FExpr; 7001 int64_t Offset; 7002 7003 public: 7004 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7005 : FExpr(fexpr), Offset(Offset) {} 7006 7007 StringRef getString() const { 7008 return FExpr->getString().drop_front(Offset); 7009 } 7010 7011 unsigned getByteLength() const { 7012 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7013 } 7014 7015 unsigned getLength() const { return FExpr->getLength() - Offset; } 7016 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7017 7018 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7019 7020 QualType getType() const { return FExpr->getType(); } 7021 7022 bool isAscii() const { return FExpr->isAscii(); } 7023 bool isWide() const { return FExpr->isWide(); } 7024 bool isUTF8() const { return FExpr->isUTF8(); } 7025 bool isUTF16() const { return FExpr->isUTF16(); } 7026 bool isUTF32() const { return FExpr->isUTF32(); } 7027 bool isPascal() const { return FExpr->isPascal(); } 7028 7029 SourceLocation getLocationOfByte( 7030 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7031 const TargetInfo &Target, unsigned *StartToken = nullptr, 7032 unsigned *StartTokenByteOffset = nullptr) const { 7033 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7034 StartToken, StartTokenByteOffset); 7035 } 7036 7037 SourceLocation getBeginLoc() const LLVM_READONLY { 7038 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7039 } 7040 7041 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7042 }; 7043 7044 } // namespace 7045 7046 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7047 const Expr *OrigFormatExpr, 7048 ArrayRef<const Expr *> Args, 7049 bool HasVAListArg, unsigned format_idx, 7050 unsigned firstDataArg, 7051 Sema::FormatStringType Type, 7052 bool inFunctionCall, 7053 Sema::VariadicCallType CallType, 7054 llvm::SmallBitVector &CheckedVarArgs, 7055 UncoveredArgHandler &UncoveredArg, 7056 bool IgnoreStringsWithoutSpecifiers); 7057 7058 // Determine if an expression is a string literal or constant string. 7059 // If this function returns false on the arguments to a function expecting a 7060 // format string, we will usually need to emit a warning. 7061 // True string literals are then checked by CheckFormatString. 7062 static StringLiteralCheckType 7063 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7064 bool HasVAListArg, unsigned format_idx, 7065 unsigned firstDataArg, Sema::FormatStringType Type, 7066 Sema::VariadicCallType CallType, bool InFunctionCall, 7067 llvm::SmallBitVector &CheckedVarArgs, 7068 UncoveredArgHandler &UncoveredArg, 7069 llvm::APSInt Offset, 7070 bool IgnoreStringsWithoutSpecifiers = false) { 7071 if (S.isConstantEvaluated()) 7072 return SLCT_NotALiteral; 7073 tryAgain: 7074 assert(Offset.isSigned() && "invalid offset"); 7075 7076 if (E->isTypeDependent() || E->isValueDependent()) 7077 return SLCT_NotALiteral; 7078 7079 E = E->IgnoreParenCasts(); 7080 7081 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7082 // Technically -Wformat-nonliteral does not warn about this case. 7083 // The behavior of printf and friends in this case is implementation 7084 // dependent. Ideally if the format string cannot be null then 7085 // it should have a 'nonnull' attribute in the function prototype. 7086 return SLCT_UncheckedLiteral; 7087 7088 switch (E->getStmtClass()) { 7089 case Stmt::BinaryConditionalOperatorClass: 7090 case Stmt::ConditionalOperatorClass: { 7091 // The expression is a literal if both sub-expressions were, and it was 7092 // completely checked only if both sub-expressions were checked. 7093 const AbstractConditionalOperator *C = 7094 cast<AbstractConditionalOperator>(E); 7095 7096 // Determine whether it is necessary to check both sub-expressions, for 7097 // example, because the condition expression is a constant that can be 7098 // evaluated at compile time. 7099 bool CheckLeft = true, CheckRight = true; 7100 7101 bool Cond; 7102 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7103 S.isConstantEvaluated())) { 7104 if (Cond) 7105 CheckRight = false; 7106 else 7107 CheckLeft = false; 7108 } 7109 7110 // We need to maintain the offsets for the right and the left hand side 7111 // separately to check if every possible indexed expression is a valid 7112 // string literal. They might have different offsets for different string 7113 // literals in the end. 7114 StringLiteralCheckType Left; 7115 if (!CheckLeft) 7116 Left = SLCT_UncheckedLiteral; 7117 else { 7118 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7119 HasVAListArg, format_idx, firstDataArg, 7120 Type, CallType, InFunctionCall, 7121 CheckedVarArgs, UncoveredArg, Offset, 7122 IgnoreStringsWithoutSpecifiers); 7123 if (Left == SLCT_NotALiteral || !CheckRight) { 7124 return Left; 7125 } 7126 } 7127 7128 StringLiteralCheckType Right = checkFormatStringExpr( 7129 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7130 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7131 IgnoreStringsWithoutSpecifiers); 7132 7133 return (CheckLeft && Left < Right) ? Left : Right; 7134 } 7135 7136 case Stmt::ImplicitCastExprClass: 7137 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7138 goto tryAgain; 7139 7140 case Stmt::OpaqueValueExprClass: 7141 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7142 E = src; 7143 goto tryAgain; 7144 } 7145 return SLCT_NotALiteral; 7146 7147 case Stmt::PredefinedExprClass: 7148 // While __func__, etc., are technically not string literals, they 7149 // cannot contain format specifiers and thus are not a security 7150 // liability. 7151 return SLCT_UncheckedLiteral; 7152 7153 case Stmt::DeclRefExprClass: { 7154 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7155 7156 // As an exception, do not flag errors for variables binding to 7157 // const string literals. 7158 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7159 bool isConstant = false; 7160 QualType T = DR->getType(); 7161 7162 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7163 isConstant = AT->getElementType().isConstant(S.Context); 7164 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7165 isConstant = T.isConstant(S.Context) && 7166 PT->getPointeeType().isConstant(S.Context); 7167 } else if (T->isObjCObjectPointerType()) { 7168 // In ObjC, there is usually no "const ObjectPointer" type, 7169 // so don't check if the pointee type is constant. 7170 isConstant = T.isConstant(S.Context); 7171 } 7172 7173 if (isConstant) { 7174 if (const Expr *Init = VD->getAnyInitializer()) { 7175 // Look through initializers like const char c[] = { "foo" } 7176 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7177 if (InitList->isStringLiteralInit()) 7178 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7179 } 7180 return checkFormatStringExpr(S, Init, Args, 7181 HasVAListArg, format_idx, 7182 firstDataArg, Type, CallType, 7183 /*InFunctionCall*/ false, CheckedVarArgs, 7184 UncoveredArg, Offset); 7185 } 7186 } 7187 7188 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7189 // special check to see if the format string is a function parameter 7190 // of the function calling the printf function. If the function 7191 // has an attribute indicating it is a printf-like function, then we 7192 // should suppress warnings concerning non-literals being used in a call 7193 // to a vprintf function. For example: 7194 // 7195 // void 7196 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7197 // va_list ap; 7198 // va_start(ap, fmt); 7199 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7200 // ... 7201 // } 7202 if (HasVAListArg) { 7203 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7204 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7205 int PVIndex = PV->getFunctionScopeIndex() + 1; 7206 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7207 // adjust for implicit parameter 7208 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7209 if (MD->isInstance()) 7210 ++PVIndex; 7211 // We also check if the formats are compatible. 7212 // We can't pass a 'scanf' string to a 'printf' function. 7213 if (PVIndex == PVFormat->getFormatIdx() && 7214 Type == S.GetFormatStringType(PVFormat)) 7215 return SLCT_UncheckedLiteral; 7216 } 7217 } 7218 } 7219 } 7220 } 7221 7222 return SLCT_NotALiteral; 7223 } 7224 7225 case Stmt::CallExprClass: 7226 case Stmt::CXXMemberCallExprClass: { 7227 const CallExpr *CE = cast<CallExpr>(E); 7228 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7229 bool IsFirst = true; 7230 StringLiteralCheckType CommonResult; 7231 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7232 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7233 StringLiteralCheckType Result = checkFormatStringExpr( 7234 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7235 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7236 IgnoreStringsWithoutSpecifiers); 7237 if (IsFirst) { 7238 CommonResult = Result; 7239 IsFirst = false; 7240 } 7241 } 7242 if (!IsFirst) 7243 return CommonResult; 7244 7245 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7246 unsigned BuiltinID = FD->getBuiltinID(); 7247 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7248 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7249 const Expr *Arg = CE->getArg(0); 7250 return checkFormatStringExpr(S, Arg, Args, 7251 HasVAListArg, format_idx, 7252 firstDataArg, Type, CallType, 7253 InFunctionCall, CheckedVarArgs, 7254 UncoveredArg, Offset, 7255 IgnoreStringsWithoutSpecifiers); 7256 } 7257 } 7258 } 7259 7260 return SLCT_NotALiteral; 7261 } 7262 case Stmt::ObjCMessageExprClass: { 7263 const auto *ME = cast<ObjCMessageExpr>(E); 7264 if (const auto *MD = ME->getMethodDecl()) { 7265 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7266 // As a special case heuristic, if we're using the method -[NSBundle 7267 // localizedStringForKey:value:table:], ignore any key strings that lack 7268 // format specifiers. The idea is that if the key doesn't have any 7269 // format specifiers then its probably just a key to map to the 7270 // localized strings. If it does have format specifiers though, then its 7271 // likely that the text of the key is the format string in the 7272 // programmer's language, and should be checked. 7273 const ObjCInterfaceDecl *IFace; 7274 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7275 IFace->getIdentifier()->isStr("NSBundle") && 7276 MD->getSelector().isKeywordSelector( 7277 {"localizedStringForKey", "value", "table"})) { 7278 IgnoreStringsWithoutSpecifiers = true; 7279 } 7280 7281 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7282 return checkFormatStringExpr( 7283 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7284 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7285 IgnoreStringsWithoutSpecifiers); 7286 } 7287 } 7288 7289 return SLCT_NotALiteral; 7290 } 7291 case Stmt::ObjCStringLiteralClass: 7292 case Stmt::StringLiteralClass: { 7293 const StringLiteral *StrE = nullptr; 7294 7295 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7296 StrE = ObjCFExpr->getString(); 7297 else 7298 StrE = cast<StringLiteral>(E); 7299 7300 if (StrE) { 7301 if (Offset.isNegative() || Offset > StrE->getLength()) { 7302 // TODO: It would be better to have an explicit warning for out of 7303 // bounds literals. 7304 return SLCT_NotALiteral; 7305 } 7306 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7307 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7308 firstDataArg, Type, InFunctionCall, CallType, 7309 CheckedVarArgs, UncoveredArg, 7310 IgnoreStringsWithoutSpecifiers); 7311 return SLCT_CheckedLiteral; 7312 } 7313 7314 return SLCT_NotALiteral; 7315 } 7316 case Stmt::BinaryOperatorClass: { 7317 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7318 7319 // A string literal + an int offset is still a string literal. 7320 if (BinOp->isAdditiveOp()) { 7321 Expr::EvalResult LResult, RResult; 7322 7323 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7324 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7325 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7326 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7327 7328 if (LIsInt != RIsInt) { 7329 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7330 7331 if (LIsInt) { 7332 if (BinOpKind == BO_Add) { 7333 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7334 E = BinOp->getRHS(); 7335 goto tryAgain; 7336 } 7337 } else { 7338 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7339 E = BinOp->getLHS(); 7340 goto tryAgain; 7341 } 7342 } 7343 } 7344 7345 return SLCT_NotALiteral; 7346 } 7347 case Stmt::UnaryOperatorClass: { 7348 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7349 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7350 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7351 Expr::EvalResult IndexResult; 7352 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7353 Expr::SE_NoSideEffects, 7354 S.isConstantEvaluated())) { 7355 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7356 /*RHS is int*/ true); 7357 E = ASE->getBase(); 7358 goto tryAgain; 7359 } 7360 } 7361 7362 return SLCT_NotALiteral; 7363 } 7364 7365 default: 7366 return SLCT_NotALiteral; 7367 } 7368 } 7369 7370 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7371 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7372 .Case("scanf", FST_Scanf) 7373 .Cases("printf", "printf0", FST_Printf) 7374 .Cases("NSString", "CFString", FST_NSString) 7375 .Case("strftime", FST_Strftime) 7376 .Case("strfmon", FST_Strfmon) 7377 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7378 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7379 .Case("os_trace", FST_OSLog) 7380 .Case("os_log", FST_OSLog) 7381 .Default(FST_Unknown); 7382 } 7383 7384 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7385 /// functions) for correct use of format strings. 7386 /// Returns true if a format string has been fully checked. 7387 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7388 ArrayRef<const Expr *> Args, 7389 bool IsCXXMember, 7390 VariadicCallType CallType, 7391 SourceLocation Loc, SourceRange Range, 7392 llvm::SmallBitVector &CheckedVarArgs) { 7393 FormatStringInfo FSI; 7394 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7395 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7396 FSI.FirstDataArg, GetFormatStringType(Format), 7397 CallType, Loc, Range, CheckedVarArgs); 7398 return false; 7399 } 7400 7401 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7402 bool HasVAListArg, unsigned format_idx, 7403 unsigned firstDataArg, FormatStringType Type, 7404 VariadicCallType CallType, 7405 SourceLocation Loc, SourceRange Range, 7406 llvm::SmallBitVector &CheckedVarArgs) { 7407 // CHECK: printf/scanf-like function is called with no format string. 7408 if (format_idx >= Args.size()) { 7409 Diag(Loc, diag::warn_missing_format_string) << Range; 7410 return false; 7411 } 7412 7413 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7414 7415 // CHECK: format string is not a string literal. 7416 // 7417 // Dynamically generated format strings are difficult to 7418 // automatically vet at compile time. Requiring that format strings 7419 // are string literals: (1) permits the checking of format strings by 7420 // the compiler and thereby (2) can practically remove the source of 7421 // many format string exploits. 7422 7423 // Format string can be either ObjC string (e.g. @"%d") or 7424 // C string (e.g. "%d") 7425 // ObjC string uses the same format specifiers as C string, so we can use 7426 // the same format string checking logic for both ObjC and C strings. 7427 UncoveredArgHandler UncoveredArg; 7428 StringLiteralCheckType CT = 7429 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7430 format_idx, firstDataArg, Type, CallType, 7431 /*IsFunctionCall*/ true, CheckedVarArgs, 7432 UncoveredArg, 7433 /*no string offset*/ llvm::APSInt(64, false) = 0); 7434 7435 // Generate a diagnostic where an uncovered argument is detected. 7436 if (UncoveredArg.hasUncoveredArg()) { 7437 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7438 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7439 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7440 } 7441 7442 if (CT != SLCT_NotALiteral) 7443 // Literal format string found, check done! 7444 return CT == SLCT_CheckedLiteral; 7445 7446 // Strftime is particular as it always uses a single 'time' argument, 7447 // so it is safe to pass a non-literal string. 7448 if (Type == FST_Strftime) 7449 return false; 7450 7451 // Do not emit diag when the string param is a macro expansion and the 7452 // format is either NSString or CFString. This is a hack to prevent 7453 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7454 // which are usually used in place of NS and CF string literals. 7455 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7456 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7457 return false; 7458 7459 // If there are no arguments specified, warn with -Wformat-security, otherwise 7460 // warn only with -Wformat-nonliteral. 7461 if (Args.size() == firstDataArg) { 7462 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7463 << OrigFormatExpr->getSourceRange(); 7464 switch (Type) { 7465 default: 7466 break; 7467 case FST_Kprintf: 7468 case FST_FreeBSDKPrintf: 7469 case FST_Printf: 7470 Diag(FormatLoc, diag::note_format_security_fixit) 7471 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7472 break; 7473 case FST_NSString: 7474 Diag(FormatLoc, diag::note_format_security_fixit) 7475 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7476 break; 7477 } 7478 } else { 7479 Diag(FormatLoc, diag::warn_format_nonliteral) 7480 << OrigFormatExpr->getSourceRange(); 7481 } 7482 return false; 7483 } 7484 7485 namespace { 7486 7487 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7488 protected: 7489 Sema &S; 7490 const FormatStringLiteral *FExpr; 7491 const Expr *OrigFormatExpr; 7492 const Sema::FormatStringType FSType; 7493 const unsigned FirstDataArg; 7494 const unsigned NumDataArgs; 7495 const char *Beg; // Start of format string. 7496 const bool HasVAListArg; 7497 ArrayRef<const Expr *> Args; 7498 unsigned FormatIdx; 7499 llvm::SmallBitVector CoveredArgs; 7500 bool usesPositionalArgs = false; 7501 bool atFirstArg = true; 7502 bool inFunctionCall; 7503 Sema::VariadicCallType CallType; 7504 llvm::SmallBitVector &CheckedVarArgs; 7505 UncoveredArgHandler &UncoveredArg; 7506 7507 public: 7508 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7509 const Expr *origFormatExpr, 7510 const Sema::FormatStringType type, unsigned firstDataArg, 7511 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7512 ArrayRef<const Expr *> Args, unsigned formatIdx, 7513 bool inFunctionCall, Sema::VariadicCallType callType, 7514 llvm::SmallBitVector &CheckedVarArgs, 7515 UncoveredArgHandler &UncoveredArg) 7516 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7517 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7518 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7519 inFunctionCall(inFunctionCall), CallType(callType), 7520 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7521 CoveredArgs.resize(numDataArgs); 7522 CoveredArgs.reset(); 7523 } 7524 7525 void DoneProcessing(); 7526 7527 void HandleIncompleteSpecifier(const char *startSpecifier, 7528 unsigned specifierLen) override; 7529 7530 void HandleInvalidLengthModifier( 7531 const analyze_format_string::FormatSpecifier &FS, 7532 const analyze_format_string::ConversionSpecifier &CS, 7533 const char *startSpecifier, unsigned specifierLen, 7534 unsigned DiagID); 7535 7536 void HandleNonStandardLengthModifier( 7537 const analyze_format_string::FormatSpecifier &FS, 7538 const char *startSpecifier, unsigned specifierLen); 7539 7540 void HandleNonStandardConversionSpecifier( 7541 const analyze_format_string::ConversionSpecifier &CS, 7542 const char *startSpecifier, unsigned specifierLen); 7543 7544 void HandlePosition(const char *startPos, unsigned posLen) override; 7545 7546 void HandleInvalidPosition(const char *startSpecifier, 7547 unsigned specifierLen, 7548 analyze_format_string::PositionContext p) override; 7549 7550 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7551 7552 void HandleNullChar(const char *nullCharacter) override; 7553 7554 template <typename Range> 7555 static void 7556 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7557 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7558 bool IsStringLocation, Range StringRange, 7559 ArrayRef<FixItHint> Fixit = None); 7560 7561 protected: 7562 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7563 const char *startSpec, 7564 unsigned specifierLen, 7565 const char *csStart, unsigned csLen); 7566 7567 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7568 const char *startSpec, 7569 unsigned specifierLen); 7570 7571 SourceRange getFormatStringRange(); 7572 CharSourceRange getSpecifierRange(const char *startSpecifier, 7573 unsigned specifierLen); 7574 SourceLocation getLocationOfByte(const char *x); 7575 7576 const Expr *getDataArg(unsigned i) const; 7577 7578 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7579 const analyze_format_string::ConversionSpecifier &CS, 7580 const char *startSpecifier, unsigned specifierLen, 7581 unsigned argIndex); 7582 7583 template <typename Range> 7584 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7585 bool IsStringLocation, Range StringRange, 7586 ArrayRef<FixItHint> Fixit = None); 7587 }; 7588 7589 } // namespace 7590 7591 SourceRange CheckFormatHandler::getFormatStringRange() { 7592 return OrigFormatExpr->getSourceRange(); 7593 } 7594 7595 CharSourceRange CheckFormatHandler:: 7596 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7597 SourceLocation Start = getLocationOfByte(startSpecifier); 7598 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7599 7600 // Advance the end SourceLocation by one due to half-open ranges. 7601 End = End.getLocWithOffset(1); 7602 7603 return CharSourceRange::getCharRange(Start, End); 7604 } 7605 7606 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7607 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7608 S.getLangOpts(), S.Context.getTargetInfo()); 7609 } 7610 7611 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7612 unsigned specifierLen){ 7613 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7614 getLocationOfByte(startSpecifier), 7615 /*IsStringLocation*/true, 7616 getSpecifierRange(startSpecifier, specifierLen)); 7617 } 7618 7619 void CheckFormatHandler::HandleInvalidLengthModifier( 7620 const analyze_format_string::FormatSpecifier &FS, 7621 const analyze_format_string::ConversionSpecifier &CS, 7622 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7623 using namespace analyze_format_string; 7624 7625 const LengthModifier &LM = FS.getLengthModifier(); 7626 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7627 7628 // See if we know how to fix this length modifier. 7629 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7630 if (FixedLM) { 7631 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7632 getLocationOfByte(LM.getStart()), 7633 /*IsStringLocation*/true, 7634 getSpecifierRange(startSpecifier, specifierLen)); 7635 7636 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7637 << FixedLM->toString() 7638 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7639 7640 } else { 7641 FixItHint Hint; 7642 if (DiagID == diag::warn_format_nonsensical_length) 7643 Hint = FixItHint::CreateRemoval(LMRange); 7644 7645 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7646 getLocationOfByte(LM.getStart()), 7647 /*IsStringLocation*/true, 7648 getSpecifierRange(startSpecifier, specifierLen), 7649 Hint); 7650 } 7651 } 7652 7653 void CheckFormatHandler::HandleNonStandardLengthModifier( 7654 const analyze_format_string::FormatSpecifier &FS, 7655 const char *startSpecifier, unsigned specifierLen) { 7656 using namespace analyze_format_string; 7657 7658 const LengthModifier &LM = FS.getLengthModifier(); 7659 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7660 7661 // See if we know how to fix this length modifier. 7662 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7663 if (FixedLM) { 7664 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7665 << LM.toString() << 0, 7666 getLocationOfByte(LM.getStart()), 7667 /*IsStringLocation*/true, 7668 getSpecifierRange(startSpecifier, specifierLen)); 7669 7670 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7671 << FixedLM->toString() 7672 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7673 7674 } else { 7675 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7676 << LM.toString() << 0, 7677 getLocationOfByte(LM.getStart()), 7678 /*IsStringLocation*/true, 7679 getSpecifierRange(startSpecifier, specifierLen)); 7680 } 7681 } 7682 7683 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7684 const analyze_format_string::ConversionSpecifier &CS, 7685 const char *startSpecifier, unsigned specifierLen) { 7686 using namespace analyze_format_string; 7687 7688 // See if we know how to fix this conversion specifier. 7689 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7690 if (FixedCS) { 7691 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7692 << CS.toString() << /*conversion specifier*/1, 7693 getLocationOfByte(CS.getStart()), 7694 /*IsStringLocation*/true, 7695 getSpecifierRange(startSpecifier, specifierLen)); 7696 7697 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7698 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7699 << FixedCS->toString() 7700 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7701 } else { 7702 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7703 << CS.toString() << /*conversion specifier*/1, 7704 getLocationOfByte(CS.getStart()), 7705 /*IsStringLocation*/true, 7706 getSpecifierRange(startSpecifier, specifierLen)); 7707 } 7708 } 7709 7710 void CheckFormatHandler::HandlePosition(const char *startPos, 7711 unsigned posLen) { 7712 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7713 getLocationOfByte(startPos), 7714 /*IsStringLocation*/true, 7715 getSpecifierRange(startPos, posLen)); 7716 } 7717 7718 void 7719 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7720 analyze_format_string::PositionContext p) { 7721 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7722 << (unsigned) p, 7723 getLocationOfByte(startPos), /*IsStringLocation*/true, 7724 getSpecifierRange(startPos, posLen)); 7725 } 7726 7727 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7728 unsigned posLen) { 7729 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7730 getLocationOfByte(startPos), 7731 /*IsStringLocation*/true, 7732 getSpecifierRange(startPos, posLen)); 7733 } 7734 7735 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7736 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7737 // The presence of a null character is likely an error. 7738 EmitFormatDiagnostic( 7739 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7740 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7741 getFormatStringRange()); 7742 } 7743 } 7744 7745 // Note that this may return NULL if there was an error parsing or building 7746 // one of the argument expressions. 7747 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7748 return Args[FirstDataArg + i]; 7749 } 7750 7751 void CheckFormatHandler::DoneProcessing() { 7752 // Does the number of data arguments exceed the number of 7753 // format conversions in the format string? 7754 if (!HasVAListArg) { 7755 // Find any arguments that weren't covered. 7756 CoveredArgs.flip(); 7757 signed notCoveredArg = CoveredArgs.find_first(); 7758 if (notCoveredArg >= 0) { 7759 assert((unsigned)notCoveredArg < NumDataArgs); 7760 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7761 } else { 7762 UncoveredArg.setAllCovered(); 7763 } 7764 } 7765 } 7766 7767 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7768 const Expr *ArgExpr) { 7769 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7770 "Invalid state"); 7771 7772 if (!ArgExpr) 7773 return; 7774 7775 SourceLocation Loc = ArgExpr->getBeginLoc(); 7776 7777 if (S.getSourceManager().isInSystemMacro(Loc)) 7778 return; 7779 7780 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7781 for (auto E : DiagnosticExprs) 7782 PDiag << E->getSourceRange(); 7783 7784 CheckFormatHandler::EmitFormatDiagnostic( 7785 S, IsFunctionCall, DiagnosticExprs[0], 7786 PDiag, Loc, /*IsStringLocation*/false, 7787 DiagnosticExprs[0]->getSourceRange()); 7788 } 7789 7790 bool 7791 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7792 SourceLocation Loc, 7793 const char *startSpec, 7794 unsigned specifierLen, 7795 const char *csStart, 7796 unsigned csLen) { 7797 bool keepGoing = true; 7798 if (argIndex < NumDataArgs) { 7799 // Consider the argument coverered, even though the specifier doesn't 7800 // make sense. 7801 CoveredArgs.set(argIndex); 7802 } 7803 else { 7804 // If argIndex exceeds the number of data arguments we 7805 // don't issue a warning because that is just a cascade of warnings (and 7806 // they may have intended '%%' anyway). We don't want to continue processing 7807 // the format string after this point, however, as we will like just get 7808 // gibberish when trying to match arguments. 7809 keepGoing = false; 7810 } 7811 7812 StringRef Specifier(csStart, csLen); 7813 7814 // If the specifier in non-printable, it could be the first byte of a UTF-8 7815 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7816 // hex value. 7817 std::string CodePointStr; 7818 if (!llvm::sys::locale::isPrint(*csStart)) { 7819 llvm::UTF32 CodePoint; 7820 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7821 const llvm::UTF8 *E = 7822 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7823 llvm::ConversionResult Result = 7824 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7825 7826 if (Result != llvm::conversionOK) { 7827 unsigned char FirstChar = *csStart; 7828 CodePoint = (llvm::UTF32)FirstChar; 7829 } 7830 7831 llvm::raw_string_ostream OS(CodePointStr); 7832 if (CodePoint < 256) 7833 OS << "\\x" << llvm::format("%02x", CodePoint); 7834 else if (CodePoint <= 0xFFFF) 7835 OS << "\\u" << llvm::format("%04x", CodePoint); 7836 else 7837 OS << "\\U" << llvm::format("%08x", CodePoint); 7838 OS.flush(); 7839 Specifier = CodePointStr; 7840 } 7841 7842 EmitFormatDiagnostic( 7843 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7844 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7845 7846 return keepGoing; 7847 } 7848 7849 void 7850 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7851 const char *startSpec, 7852 unsigned specifierLen) { 7853 EmitFormatDiagnostic( 7854 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7855 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7856 } 7857 7858 bool 7859 CheckFormatHandler::CheckNumArgs( 7860 const analyze_format_string::FormatSpecifier &FS, 7861 const analyze_format_string::ConversionSpecifier &CS, 7862 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7863 7864 if (argIndex >= NumDataArgs) { 7865 PartialDiagnostic PDiag = FS.usesPositionalArg() 7866 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7867 << (argIndex+1) << NumDataArgs) 7868 : S.PDiag(diag::warn_printf_insufficient_data_args); 7869 EmitFormatDiagnostic( 7870 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7871 getSpecifierRange(startSpecifier, specifierLen)); 7872 7873 // Since more arguments than conversion tokens are given, by extension 7874 // all arguments are covered, so mark this as so. 7875 UncoveredArg.setAllCovered(); 7876 return false; 7877 } 7878 return true; 7879 } 7880 7881 template<typename Range> 7882 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7883 SourceLocation Loc, 7884 bool IsStringLocation, 7885 Range StringRange, 7886 ArrayRef<FixItHint> FixIt) { 7887 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7888 Loc, IsStringLocation, StringRange, FixIt); 7889 } 7890 7891 /// If the format string is not within the function call, emit a note 7892 /// so that the function call and string are in diagnostic messages. 7893 /// 7894 /// \param InFunctionCall if true, the format string is within the function 7895 /// call and only one diagnostic message will be produced. Otherwise, an 7896 /// extra note will be emitted pointing to location of the format string. 7897 /// 7898 /// \param ArgumentExpr the expression that is passed as the format string 7899 /// argument in the function call. Used for getting locations when two 7900 /// diagnostics are emitted. 7901 /// 7902 /// \param PDiag the callee should already have provided any strings for the 7903 /// diagnostic message. This function only adds locations and fixits 7904 /// to diagnostics. 7905 /// 7906 /// \param Loc primary location for diagnostic. If two diagnostics are 7907 /// required, one will be at Loc and a new SourceLocation will be created for 7908 /// the other one. 7909 /// 7910 /// \param IsStringLocation if true, Loc points to the format string should be 7911 /// used for the note. Otherwise, Loc points to the argument list and will 7912 /// be used with PDiag. 7913 /// 7914 /// \param StringRange some or all of the string to highlight. This is 7915 /// templated so it can accept either a CharSourceRange or a SourceRange. 7916 /// 7917 /// \param FixIt optional fix it hint for the format string. 7918 template <typename Range> 7919 void CheckFormatHandler::EmitFormatDiagnostic( 7920 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7921 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7922 Range StringRange, ArrayRef<FixItHint> FixIt) { 7923 if (InFunctionCall) { 7924 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7925 D << StringRange; 7926 D << FixIt; 7927 } else { 7928 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7929 << ArgumentExpr->getSourceRange(); 7930 7931 const Sema::SemaDiagnosticBuilder &Note = 7932 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7933 diag::note_format_string_defined); 7934 7935 Note << StringRange; 7936 Note << FixIt; 7937 } 7938 } 7939 7940 //===--- CHECK: Printf format string checking ------------------------------===// 7941 7942 namespace { 7943 7944 class CheckPrintfHandler : public CheckFormatHandler { 7945 public: 7946 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7947 const Expr *origFormatExpr, 7948 const Sema::FormatStringType type, unsigned firstDataArg, 7949 unsigned numDataArgs, bool isObjC, const char *beg, 7950 bool hasVAListArg, ArrayRef<const Expr *> Args, 7951 unsigned formatIdx, bool inFunctionCall, 7952 Sema::VariadicCallType CallType, 7953 llvm::SmallBitVector &CheckedVarArgs, 7954 UncoveredArgHandler &UncoveredArg) 7955 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7956 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7957 inFunctionCall, CallType, CheckedVarArgs, 7958 UncoveredArg) {} 7959 7960 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7961 7962 /// Returns true if '%@' specifiers are allowed in the format string. 7963 bool allowsObjCArg() const { 7964 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7965 FSType == Sema::FST_OSTrace; 7966 } 7967 7968 bool HandleInvalidPrintfConversionSpecifier( 7969 const analyze_printf::PrintfSpecifier &FS, 7970 const char *startSpecifier, 7971 unsigned specifierLen) override; 7972 7973 void handleInvalidMaskType(StringRef MaskType) override; 7974 7975 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7976 const char *startSpecifier, 7977 unsigned specifierLen) override; 7978 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7979 const char *StartSpecifier, 7980 unsigned SpecifierLen, 7981 const Expr *E); 7982 7983 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7984 const char *startSpecifier, unsigned specifierLen); 7985 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7986 const analyze_printf::OptionalAmount &Amt, 7987 unsigned type, 7988 const char *startSpecifier, unsigned specifierLen); 7989 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7990 const analyze_printf::OptionalFlag &flag, 7991 const char *startSpecifier, unsigned specifierLen); 7992 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7993 const analyze_printf::OptionalFlag &ignoredFlag, 7994 const analyze_printf::OptionalFlag &flag, 7995 const char *startSpecifier, unsigned specifierLen); 7996 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7997 const Expr *E); 7998 7999 void HandleEmptyObjCModifierFlag(const char *startFlag, 8000 unsigned flagLen) override; 8001 8002 void HandleInvalidObjCModifierFlag(const char *startFlag, 8003 unsigned flagLen) override; 8004 8005 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8006 const char *flagsEnd, 8007 const char *conversionPosition) 8008 override; 8009 }; 8010 8011 } // namespace 8012 8013 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8014 const analyze_printf::PrintfSpecifier &FS, 8015 const char *startSpecifier, 8016 unsigned specifierLen) { 8017 const analyze_printf::PrintfConversionSpecifier &CS = 8018 FS.getConversionSpecifier(); 8019 8020 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8021 getLocationOfByte(CS.getStart()), 8022 startSpecifier, specifierLen, 8023 CS.getStart(), CS.getLength()); 8024 } 8025 8026 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8027 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8028 } 8029 8030 bool CheckPrintfHandler::HandleAmount( 8031 const analyze_format_string::OptionalAmount &Amt, 8032 unsigned k, const char *startSpecifier, 8033 unsigned specifierLen) { 8034 if (Amt.hasDataArgument()) { 8035 if (!HasVAListArg) { 8036 unsigned argIndex = Amt.getArgIndex(); 8037 if (argIndex >= NumDataArgs) { 8038 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8039 << k, 8040 getLocationOfByte(Amt.getStart()), 8041 /*IsStringLocation*/true, 8042 getSpecifierRange(startSpecifier, specifierLen)); 8043 // Don't do any more checking. We will just emit 8044 // spurious errors. 8045 return false; 8046 } 8047 8048 // Type check the data argument. It should be an 'int'. 8049 // Although not in conformance with C99, we also allow the argument to be 8050 // an 'unsigned int' as that is a reasonably safe case. GCC also 8051 // doesn't emit a warning for that case. 8052 CoveredArgs.set(argIndex); 8053 const Expr *Arg = getDataArg(argIndex); 8054 if (!Arg) 8055 return false; 8056 8057 QualType T = Arg->getType(); 8058 8059 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8060 assert(AT.isValid()); 8061 8062 if (!AT.matchesType(S.Context, T)) { 8063 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8064 << k << AT.getRepresentativeTypeName(S.Context) 8065 << T << Arg->getSourceRange(), 8066 getLocationOfByte(Amt.getStart()), 8067 /*IsStringLocation*/true, 8068 getSpecifierRange(startSpecifier, specifierLen)); 8069 // Don't do any more checking. We will just emit 8070 // spurious errors. 8071 return false; 8072 } 8073 } 8074 } 8075 return true; 8076 } 8077 8078 void CheckPrintfHandler::HandleInvalidAmount( 8079 const analyze_printf::PrintfSpecifier &FS, 8080 const analyze_printf::OptionalAmount &Amt, 8081 unsigned type, 8082 const char *startSpecifier, 8083 unsigned specifierLen) { 8084 const analyze_printf::PrintfConversionSpecifier &CS = 8085 FS.getConversionSpecifier(); 8086 8087 FixItHint fixit = 8088 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8089 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8090 Amt.getConstantLength())) 8091 : FixItHint(); 8092 8093 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8094 << type << CS.toString(), 8095 getLocationOfByte(Amt.getStart()), 8096 /*IsStringLocation*/true, 8097 getSpecifierRange(startSpecifier, specifierLen), 8098 fixit); 8099 } 8100 8101 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8102 const analyze_printf::OptionalFlag &flag, 8103 const char *startSpecifier, 8104 unsigned specifierLen) { 8105 // Warn about pointless flag with a fixit removal. 8106 const analyze_printf::PrintfConversionSpecifier &CS = 8107 FS.getConversionSpecifier(); 8108 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8109 << flag.toString() << CS.toString(), 8110 getLocationOfByte(flag.getPosition()), 8111 /*IsStringLocation*/true, 8112 getSpecifierRange(startSpecifier, specifierLen), 8113 FixItHint::CreateRemoval( 8114 getSpecifierRange(flag.getPosition(), 1))); 8115 } 8116 8117 void CheckPrintfHandler::HandleIgnoredFlag( 8118 const analyze_printf::PrintfSpecifier &FS, 8119 const analyze_printf::OptionalFlag &ignoredFlag, 8120 const analyze_printf::OptionalFlag &flag, 8121 const char *startSpecifier, 8122 unsigned specifierLen) { 8123 // Warn about ignored flag with a fixit removal. 8124 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8125 << ignoredFlag.toString() << flag.toString(), 8126 getLocationOfByte(ignoredFlag.getPosition()), 8127 /*IsStringLocation*/true, 8128 getSpecifierRange(startSpecifier, specifierLen), 8129 FixItHint::CreateRemoval( 8130 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8131 } 8132 8133 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8134 unsigned flagLen) { 8135 // Warn about an empty flag. 8136 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8137 getLocationOfByte(startFlag), 8138 /*IsStringLocation*/true, 8139 getSpecifierRange(startFlag, flagLen)); 8140 } 8141 8142 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8143 unsigned flagLen) { 8144 // Warn about an invalid flag. 8145 auto Range = getSpecifierRange(startFlag, flagLen); 8146 StringRef flag(startFlag, flagLen); 8147 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8148 getLocationOfByte(startFlag), 8149 /*IsStringLocation*/true, 8150 Range, FixItHint::CreateRemoval(Range)); 8151 } 8152 8153 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8154 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8155 // Warn about using '[...]' without a '@' conversion. 8156 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8157 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8158 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8159 getLocationOfByte(conversionPosition), 8160 /*IsStringLocation*/true, 8161 Range, FixItHint::CreateRemoval(Range)); 8162 } 8163 8164 // Determines if the specified is a C++ class or struct containing 8165 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8166 // "c_str()"). 8167 template<typename MemberKind> 8168 static llvm::SmallPtrSet<MemberKind*, 1> 8169 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8170 const RecordType *RT = Ty->getAs<RecordType>(); 8171 llvm::SmallPtrSet<MemberKind*, 1> Results; 8172 8173 if (!RT) 8174 return Results; 8175 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8176 if (!RD || !RD->getDefinition()) 8177 return Results; 8178 8179 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8180 Sema::LookupMemberName); 8181 R.suppressDiagnostics(); 8182 8183 // We just need to include all members of the right kind turned up by the 8184 // filter, at this point. 8185 if (S.LookupQualifiedName(R, RT->getDecl())) 8186 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8187 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8188 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8189 Results.insert(FK); 8190 } 8191 return Results; 8192 } 8193 8194 /// Check if we could call '.c_str()' on an object. 8195 /// 8196 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8197 /// allow the call, or if it would be ambiguous). 8198 bool Sema::hasCStrMethod(const Expr *E) { 8199 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8200 8201 MethodSet Results = 8202 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8203 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8204 MI != ME; ++MI) 8205 if ((*MI)->getMinRequiredArguments() == 0) 8206 return true; 8207 return false; 8208 } 8209 8210 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8211 // better diagnostic if so. AT is assumed to be valid. 8212 // Returns true when a c_str() conversion method is found. 8213 bool CheckPrintfHandler::checkForCStrMembers( 8214 const analyze_printf::ArgType &AT, const Expr *E) { 8215 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8216 8217 MethodSet Results = 8218 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8219 8220 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8221 MI != ME; ++MI) { 8222 const CXXMethodDecl *Method = *MI; 8223 if (Method->getMinRequiredArguments() == 0 && 8224 AT.matchesType(S.Context, Method->getReturnType())) { 8225 // FIXME: Suggest parens if the expression needs them. 8226 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8227 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8228 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8229 return true; 8230 } 8231 } 8232 8233 return false; 8234 } 8235 8236 bool 8237 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8238 &FS, 8239 const char *startSpecifier, 8240 unsigned specifierLen) { 8241 using namespace analyze_format_string; 8242 using namespace analyze_printf; 8243 8244 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8245 8246 if (FS.consumesDataArgument()) { 8247 if (atFirstArg) { 8248 atFirstArg = false; 8249 usesPositionalArgs = FS.usesPositionalArg(); 8250 } 8251 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8252 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8253 startSpecifier, specifierLen); 8254 return false; 8255 } 8256 } 8257 8258 // First check if the field width, precision, and conversion specifier 8259 // have matching data arguments. 8260 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8261 startSpecifier, specifierLen)) { 8262 return false; 8263 } 8264 8265 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8266 startSpecifier, specifierLen)) { 8267 return false; 8268 } 8269 8270 if (!CS.consumesDataArgument()) { 8271 // FIXME: Technically specifying a precision or field width here 8272 // makes no sense. Worth issuing a warning at some point. 8273 return true; 8274 } 8275 8276 // Consume the argument. 8277 unsigned argIndex = FS.getArgIndex(); 8278 if (argIndex < NumDataArgs) { 8279 // The check to see if the argIndex is valid will come later. 8280 // We set the bit here because we may exit early from this 8281 // function if we encounter some other error. 8282 CoveredArgs.set(argIndex); 8283 } 8284 8285 // FreeBSD kernel extensions. 8286 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8287 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8288 // We need at least two arguments. 8289 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8290 return false; 8291 8292 // Claim the second argument. 8293 CoveredArgs.set(argIndex + 1); 8294 8295 // Type check the first argument (int for %b, pointer for %D) 8296 const Expr *Ex = getDataArg(argIndex); 8297 const analyze_printf::ArgType &AT = 8298 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8299 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8300 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8301 EmitFormatDiagnostic( 8302 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8303 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8304 << false << Ex->getSourceRange(), 8305 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8306 getSpecifierRange(startSpecifier, specifierLen)); 8307 8308 // Type check the second argument (char * for both %b and %D) 8309 Ex = getDataArg(argIndex + 1); 8310 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8311 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8312 EmitFormatDiagnostic( 8313 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8314 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8315 << false << Ex->getSourceRange(), 8316 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8317 getSpecifierRange(startSpecifier, specifierLen)); 8318 8319 return true; 8320 } 8321 8322 // Check for using an Objective-C specific conversion specifier 8323 // in a non-ObjC literal. 8324 if (!allowsObjCArg() && CS.isObjCArg()) { 8325 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8326 specifierLen); 8327 } 8328 8329 // %P can only be used with os_log. 8330 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8331 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8332 specifierLen); 8333 } 8334 8335 // %n is not allowed with os_log. 8336 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8337 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8338 getLocationOfByte(CS.getStart()), 8339 /*IsStringLocation*/ false, 8340 getSpecifierRange(startSpecifier, specifierLen)); 8341 8342 return true; 8343 } 8344 8345 // Only scalars are allowed for os_trace. 8346 if (FSType == Sema::FST_OSTrace && 8347 (CS.getKind() == ConversionSpecifier::PArg || 8348 CS.getKind() == ConversionSpecifier::sArg || 8349 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8350 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8351 specifierLen); 8352 } 8353 8354 // Check for use of public/private annotation outside of os_log(). 8355 if (FSType != Sema::FST_OSLog) { 8356 if (FS.isPublic().isSet()) { 8357 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8358 << "public", 8359 getLocationOfByte(FS.isPublic().getPosition()), 8360 /*IsStringLocation*/ false, 8361 getSpecifierRange(startSpecifier, specifierLen)); 8362 } 8363 if (FS.isPrivate().isSet()) { 8364 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8365 << "private", 8366 getLocationOfByte(FS.isPrivate().getPosition()), 8367 /*IsStringLocation*/ false, 8368 getSpecifierRange(startSpecifier, specifierLen)); 8369 } 8370 } 8371 8372 // Check for invalid use of field width 8373 if (!FS.hasValidFieldWidth()) { 8374 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8375 startSpecifier, specifierLen); 8376 } 8377 8378 // Check for invalid use of precision 8379 if (!FS.hasValidPrecision()) { 8380 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8381 startSpecifier, specifierLen); 8382 } 8383 8384 // Precision is mandatory for %P specifier. 8385 if (CS.getKind() == ConversionSpecifier::PArg && 8386 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8387 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8388 getLocationOfByte(startSpecifier), 8389 /*IsStringLocation*/ false, 8390 getSpecifierRange(startSpecifier, specifierLen)); 8391 } 8392 8393 // Check each flag does not conflict with any other component. 8394 if (!FS.hasValidThousandsGroupingPrefix()) 8395 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8396 if (!FS.hasValidLeadingZeros()) 8397 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8398 if (!FS.hasValidPlusPrefix()) 8399 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8400 if (!FS.hasValidSpacePrefix()) 8401 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8402 if (!FS.hasValidAlternativeForm()) 8403 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8404 if (!FS.hasValidLeftJustified()) 8405 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8406 8407 // Check that flags are not ignored by another flag 8408 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8409 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8410 startSpecifier, specifierLen); 8411 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8412 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8413 startSpecifier, specifierLen); 8414 8415 // Check the length modifier is valid with the given conversion specifier. 8416 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8417 S.getLangOpts())) 8418 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8419 diag::warn_format_nonsensical_length); 8420 else if (!FS.hasStandardLengthModifier()) 8421 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8422 else if (!FS.hasStandardLengthConversionCombination()) 8423 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8424 diag::warn_format_non_standard_conversion_spec); 8425 8426 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8427 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8428 8429 // The remaining checks depend on the data arguments. 8430 if (HasVAListArg) 8431 return true; 8432 8433 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8434 return false; 8435 8436 const Expr *Arg = getDataArg(argIndex); 8437 if (!Arg) 8438 return true; 8439 8440 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8441 } 8442 8443 static bool requiresParensToAddCast(const Expr *E) { 8444 // FIXME: We should have a general way to reason about operator 8445 // precedence and whether parens are actually needed here. 8446 // Take care of a few common cases where they aren't. 8447 const Expr *Inside = E->IgnoreImpCasts(); 8448 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8449 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8450 8451 switch (Inside->getStmtClass()) { 8452 case Stmt::ArraySubscriptExprClass: 8453 case Stmt::CallExprClass: 8454 case Stmt::CharacterLiteralClass: 8455 case Stmt::CXXBoolLiteralExprClass: 8456 case Stmt::DeclRefExprClass: 8457 case Stmt::FloatingLiteralClass: 8458 case Stmt::IntegerLiteralClass: 8459 case Stmt::MemberExprClass: 8460 case Stmt::ObjCArrayLiteralClass: 8461 case Stmt::ObjCBoolLiteralExprClass: 8462 case Stmt::ObjCBoxedExprClass: 8463 case Stmt::ObjCDictionaryLiteralClass: 8464 case Stmt::ObjCEncodeExprClass: 8465 case Stmt::ObjCIvarRefExprClass: 8466 case Stmt::ObjCMessageExprClass: 8467 case Stmt::ObjCPropertyRefExprClass: 8468 case Stmt::ObjCStringLiteralClass: 8469 case Stmt::ObjCSubscriptRefExprClass: 8470 case Stmt::ParenExprClass: 8471 case Stmt::StringLiteralClass: 8472 case Stmt::UnaryOperatorClass: 8473 return false; 8474 default: 8475 return true; 8476 } 8477 } 8478 8479 static std::pair<QualType, StringRef> 8480 shouldNotPrintDirectly(const ASTContext &Context, 8481 QualType IntendedTy, 8482 const Expr *E) { 8483 // Use a 'while' to peel off layers of typedefs. 8484 QualType TyTy = IntendedTy; 8485 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8486 StringRef Name = UserTy->getDecl()->getName(); 8487 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8488 .Case("CFIndex", Context.getNSIntegerType()) 8489 .Case("NSInteger", Context.getNSIntegerType()) 8490 .Case("NSUInteger", Context.getNSUIntegerType()) 8491 .Case("SInt32", Context.IntTy) 8492 .Case("UInt32", Context.UnsignedIntTy) 8493 .Default(QualType()); 8494 8495 if (!CastTy.isNull()) 8496 return std::make_pair(CastTy, Name); 8497 8498 TyTy = UserTy->desugar(); 8499 } 8500 8501 // Strip parens if necessary. 8502 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8503 return shouldNotPrintDirectly(Context, 8504 PE->getSubExpr()->getType(), 8505 PE->getSubExpr()); 8506 8507 // If this is a conditional expression, then its result type is constructed 8508 // via usual arithmetic conversions and thus there might be no necessary 8509 // typedef sugar there. Recurse to operands to check for NSInteger & 8510 // Co. usage condition. 8511 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8512 QualType TrueTy, FalseTy; 8513 StringRef TrueName, FalseName; 8514 8515 std::tie(TrueTy, TrueName) = 8516 shouldNotPrintDirectly(Context, 8517 CO->getTrueExpr()->getType(), 8518 CO->getTrueExpr()); 8519 std::tie(FalseTy, FalseName) = 8520 shouldNotPrintDirectly(Context, 8521 CO->getFalseExpr()->getType(), 8522 CO->getFalseExpr()); 8523 8524 if (TrueTy == FalseTy) 8525 return std::make_pair(TrueTy, TrueName); 8526 else if (TrueTy.isNull()) 8527 return std::make_pair(FalseTy, FalseName); 8528 else if (FalseTy.isNull()) 8529 return std::make_pair(TrueTy, TrueName); 8530 } 8531 8532 return std::make_pair(QualType(), StringRef()); 8533 } 8534 8535 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8536 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8537 /// type do not count. 8538 static bool 8539 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8540 QualType From = ICE->getSubExpr()->getType(); 8541 QualType To = ICE->getType(); 8542 // It's an integer promotion if the destination type is the promoted 8543 // source type. 8544 if (ICE->getCastKind() == CK_IntegralCast && 8545 From->isPromotableIntegerType() && 8546 S.Context.getPromotedIntegerType(From) == To) 8547 return true; 8548 // Look through vector types, since we do default argument promotion for 8549 // those in OpenCL. 8550 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8551 From = VecTy->getElementType(); 8552 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8553 To = VecTy->getElementType(); 8554 // It's a floating promotion if the source type is a lower rank. 8555 return ICE->getCastKind() == CK_FloatingCast && 8556 S.Context.getFloatingTypeOrder(From, To) < 0; 8557 } 8558 8559 bool 8560 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8561 const char *StartSpecifier, 8562 unsigned SpecifierLen, 8563 const Expr *E) { 8564 using namespace analyze_format_string; 8565 using namespace analyze_printf; 8566 8567 // Now type check the data expression that matches the 8568 // format specifier. 8569 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8570 if (!AT.isValid()) 8571 return true; 8572 8573 QualType ExprTy = E->getType(); 8574 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8575 ExprTy = TET->getUnderlyingExpr()->getType(); 8576 } 8577 8578 // Diagnose attempts to print a boolean value as a character. Unlike other 8579 // -Wformat diagnostics, this is fine from a type perspective, but it still 8580 // doesn't make sense. 8581 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8582 E->isKnownToHaveBooleanValue()) { 8583 const CharSourceRange &CSR = 8584 getSpecifierRange(StartSpecifier, SpecifierLen); 8585 SmallString<4> FSString; 8586 llvm::raw_svector_ostream os(FSString); 8587 FS.toString(os); 8588 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8589 << FSString, 8590 E->getExprLoc(), false, CSR); 8591 return true; 8592 } 8593 8594 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8595 if (Match == analyze_printf::ArgType::Match) 8596 return true; 8597 8598 // Look through argument promotions for our error message's reported type. 8599 // This includes the integral and floating promotions, but excludes array 8600 // and function pointer decay (seeing that an argument intended to be a 8601 // string has type 'char [6]' is probably more confusing than 'char *') and 8602 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8603 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8604 if (isArithmeticArgumentPromotion(S, ICE)) { 8605 E = ICE->getSubExpr(); 8606 ExprTy = E->getType(); 8607 8608 // Check if we didn't match because of an implicit cast from a 'char' 8609 // or 'short' to an 'int'. This is done because printf is a varargs 8610 // function. 8611 if (ICE->getType() == S.Context.IntTy || 8612 ICE->getType() == S.Context.UnsignedIntTy) { 8613 // All further checking is done on the subexpression 8614 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8615 AT.matchesType(S.Context, ExprTy); 8616 if (ImplicitMatch == analyze_printf::ArgType::Match) 8617 return true; 8618 if (ImplicitMatch == ArgType::NoMatchPedantic || 8619 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8620 Match = ImplicitMatch; 8621 } 8622 } 8623 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8624 // Special case for 'a', which has type 'int' in C. 8625 // Note, however, that we do /not/ want to treat multibyte constants like 8626 // 'MooV' as characters! This form is deprecated but still exists. 8627 if (ExprTy == S.Context.IntTy) 8628 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8629 ExprTy = S.Context.CharTy; 8630 } 8631 8632 // Look through enums to their underlying type. 8633 bool IsEnum = false; 8634 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8635 ExprTy = EnumTy->getDecl()->getIntegerType(); 8636 IsEnum = true; 8637 } 8638 8639 // %C in an Objective-C context prints a unichar, not a wchar_t. 8640 // If the argument is an integer of some kind, believe the %C and suggest 8641 // a cast instead of changing the conversion specifier. 8642 QualType IntendedTy = ExprTy; 8643 if (isObjCContext() && 8644 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8645 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8646 !ExprTy->isCharType()) { 8647 // 'unichar' is defined as a typedef of unsigned short, but we should 8648 // prefer using the typedef if it is visible. 8649 IntendedTy = S.Context.UnsignedShortTy; 8650 8651 // While we are here, check if the value is an IntegerLiteral that happens 8652 // to be within the valid range. 8653 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8654 const llvm::APInt &V = IL->getValue(); 8655 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8656 return true; 8657 } 8658 8659 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8660 Sema::LookupOrdinaryName); 8661 if (S.LookupName(Result, S.getCurScope())) { 8662 NamedDecl *ND = Result.getFoundDecl(); 8663 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8664 if (TD->getUnderlyingType() == IntendedTy) 8665 IntendedTy = S.Context.getTypedefType(TD); 8666 } 8667 } 8668 } 8669 8670 // Special-case some of Darwin's platform-independence types by suggesting 8671 // casts to primitive types that are known to be large enough. 8672 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8673 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8674 QualType CastTy; 8675 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8676 if (!CastTy.isNull()) { 8677 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8678 // (long in ASTContext). Only complain to pedants. 8679 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8680 (AT.isSizeT() || AT.isPtrdiffT()) && 8681 AT.matchesType(S.Context, CastTy)) 8682 Match = ArgType::NoMatchPedantic; 8683 IntendedTy = CastTy; 8684 ShouldNotPrintDirectly = true; 8685 } 8686 } 8687 8688 // We may be able to offer a FixItHint if it is a supported type. 8689 PrintfSpecifier fixedFS = FS; 8690 bool Success = 8691 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8692 8693 if (Success) { 8694 // Get the fix string from the fixed format specifier 8695 SmallString<16> buf; 8696 llvm::raw_svector_ostream os(buf); 8697 fixedFS.toString(os); 8698 8699 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8700 8701 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8702 unsigned Diag; 8703 switch (Match) { 8704 case ArgType::Match: llvm_unreachable("expected non-matching"); 8705 case ArgType::NoMatchPedantic: 8706 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8707 break; 8708 case ArgType::NoMatchTypeConfusion: 8709 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8710 break; 8711 case ArgType::NoMatch: 8712 Diag = diag::warn_format_conversion_argument_type_mismatch; 8713 break; 8714 } 8715 8716 // In this case, the specifier is wrong and should be changed to match 8717 // the argument. 8718 EmitFormatDiagnostic(S.PDiag(Diag) 8719 << AT.getRepresentativeTypeName(S.Context) 8720 << IntendedTy << IsEnum << E->getSourceRange(), 8721 E->getBeginLoc(), 8722 /*IsStringLocation*/ false, SpecRange, 8723 FixItHint::CreateReplacement(SpecRange, os.str())); 8724 } else { 8725 // The canonical type for formatting this value is different from the 8726 // actual type of the expression. (This occurs, for example, with Darwin's 8727 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8728 // should be printed as 'long' for 64-bit compatibility.) 8729 // Rather than emitting a normal format/argument mismatch, we want to 8730 // add a cast to the recommended type (and correct the format string 8731 // if necessary). 8732 SmallString<16> CastBuf; 8733 llvm::raw_svector_ostream CastFix(CastBuf); 8734 CastFix << "("; 8735 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8736 CastFix << ")"; 8737 8738 SmallVector<FixItHint,4> Hints; 8739 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8740 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8741 8742 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8743 // If there's already a cast present, just replace it. 8744 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8745 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8746 8747 } else if (!requiresParensToAddCast(E)) { 8748 // If the expression has high enough precedence, 8749 // just write the C-style cast. 8750 Hints.push_back( 8751 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8752 } else { 8753 // Otherwise, add parens around the expression as well as the cast. 8754 CastFix << "("; 8755 Hints.push_back( 8756 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8757 8758 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8759 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8760 } 8761 8762 if (ShouldNotPrintDirectly) { 8763 // The expression has a type that should not be printed directly. 8764 // We extract the name from the typedef because we don't want to show 8765 // the underlying type in the diagnostic. 8766 StringRef Name; 8767 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8768 Name = TypedefTy->getDecl()->getName(); 8769 else 8770 Name = CastTyName; 8771 unsigned Diag = Match == ArgType::NoMatchPedantic 8772 ? diag::warn_format_argument_needs_cast_pedantic 8773 : diag::warn_format_argument_needs_cast; 8774 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8775 << E->getSourceRange(), 8776 E->getBeginLoc(), /*IsStringLocation=*/false, 8777 SpecRange, Hints); 8778 } else { 8779 // In this case, the expression could be printed using a different 8780 // specifier, but we've decided that the specifier is probably correct 8781 // and we should cast instead. Just use the normal warning message. 8782 EmitFormatDiagnostic( 8783 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8784 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8785 << E->getSourceRange(), 8786 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8787 } 8788 } 8789 } else { 8790 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8791 SpecifierLen); 8792 // Since the warning for passing non-POD types to variadic functions 8793 // was deferred until now, we emit a warning for non-POD 8794 // arguments here. 8795 switch (S.isValidVarArgType(ExprTy)) { 8796 case Sema::VAK_Valid: 8797 case Sema::VAK_ValidInCXX11: { 8798 unsigned Diag; 8799 switch (Match) { 8800 case ArgType::Match: llvm_unreachable("expected non-matching"); 8801 case ArgType::NoMatchPedantic: 8802 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8803 break; 8804 case ArgType::NoMatchTypeConfusion: 8805 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8806 break; 8807 case ArgType::NoMatch: 8808 Diag = diag::warn_format_conversion_argument_type_mismatch; 8809 break; 8810 } 8811 8812 EmitFormatDiagnostic( 8813 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8814 << IsEnum << CSR << E->getSourceRange(), 8815 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8816 break; 8817 } 8818 case Sema::VAK_Undefined: 8819 case Sema::VAK_MSVCUndefined: 8820 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8821 << S.getLangOpts().CPlusPlus11 << ExprTy 8822 << CallType 8823 << AT.getRepresentativeTypeName(S.Context) << CSR 8824 << E->getSourceRange(), 8825 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8826 checkForCStrMembers(AT, E); 8827 break; 8828 8829 case Sema::VAK_Invalid: 8830 if (ExprTy->isObjCObjectType()) 8831 EmitFormatDiagnostic( 8832 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8833 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8834 << AT.getRepresentativeTypeName(S.Context) << CSR 8835 << E->getSourceRange(), 8836 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8837 else 8838 // FIXME: If this is an initializer list, suggest removing the braces 8839 // or inserting a cast to the target type. 8840 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8841 << isa<InitListExpr>(E) << ExprTy << CallType 8842 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8843 break; 8844 } 8845 8846 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8847 "format string specifier index out of range"); 8848 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8849 } 8850 8851 return true; 8852 } 8853 8854 //===--- CHECK: Scanf format string checking ------------------------------===// 8855 8856 namespace { 8857 8858 class CheckScanfHandler : public CheckFormatHandler { 8859 public: 8860 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8861 const Expr *origFormatExpr, Sema::FormatStringType type, 8862 unsigned firstDataArg, unsigned numDataArgs, 8863 const char *beg, bool hasVAListArg, 8864 ArrayRef<const Expr *> Args, unsigned formatIdx, 8865 bool inFunctionCall, Sema::VariadicCallType CallType, 8866 llvm::SmallBitVector &CheckedVarArgs, 8867 UncoveredArgHandler &UncoveredArg) 8868 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8869 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8870 inFunctionCall, CallType, CheckedVarArgs, 8871 UncoveredArg) {} 8872 8873 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8874 const char *startSpecifier, 8875 unsigned specifierLen) override; 8876 8877 bool HandleInvalidScanfConversionSpecifier( 8878 const analyze_scanf::ScanfSpecifier &FS, 8879 const char *startSpecifier, 8880 unsigned specifierLen) override; 8881 8882 void HandleIncompleteScanList(const char *start, const char *end) override; 8883 }; 8884 8885 } // namespace 8886 8887 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8888 const char *end) { 8889 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8890 getLocationOfByte(end), /*IsStringLocation*/true, 8891 getSpecifierRange(start, end - start)); 8892 } 8893 8894 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8895 const analyze_scanf::ScanfSpecifier &FS, 8896 const char *startSpecifier, 8897 unsigned specifierLen) { 8898 const analyze_scanf::ScanfConversionSpecifier &CS = 8899 FS.getConversionSpecifier(); 8900 8901 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8902 getLocationOfByte(CS.getStart()), 8903 startSpecifier, specifierLen, 8904 CS.getStart(), CS.getLength()); 8905 } 8906 8907 bool CheckScanfHandler::HandleScanfSpecifier( 8908 const analyze_scanf::ScanfSpecifier &FS, 8909 const char *startSpecifier, 8910 unsigned specifierLen) { 8911 using namespace analyze_scanf; 8912 using namespace analyze_format_string; 8913 8914 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8915 8916 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8917 // be used to decide if we are using positional arguments consistently. 8918 if (FS.consumesDataArgument()) { 8919 if (atFirstArg) { 8920 atFirstArg = false; 8921 usesPositionalArgs = FS.usesPositionalArg(); 8922 } 8923 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8924 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8925 startSpecifier, specifierLen); 8926 return false; 8927 } 8928 } 8929 8930 // Check if the field with is non-zero. 8931 const OptionalAmount &Amt = FS.getFieldWidth(); 8932 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8933 if (Amt.getConstantAmount() == 0) { 8934 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8935 Amt.getConstantLength()); 8936 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8937 getLocationOfByte(Amt.getStart()), 8938 /*IsStringLocation*/true, R, 8939 FixItHint::CreateRemoval(R)); 8940 } 8941 } 8942 8943 if (!FS.consumesDataArgument()) { 8944 // FIXME: Technically specifying a precision or field width here 8945 // makes no sense. Worth issuing a warning at some point. 8946 return true; 8947 } 8948 8949 // Consume the argument. 8950 unsigned argIndex = FS.getArgIndex(); 8951 if (argIndex < NumDataArgs) { 8952 // The check to see if the argIndex is valid will come later. 8953 // We set the bit here because we may exit early from this 8954 // function if we encounter some other error. 8955 CoveredArgs.set(argIndex); 8956 } 8957 8958 // Check the length modifier is valid with the given conversion specifier. 8959 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8960 S.getLangOpts())) 8961 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8962 diag::warn_format_nonsensical_length); 8963 else if (!FS.hasStandardLengthModifier()) 8964 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8965 else if (!FS.hasStandardLengthConversionCombination()) 8966 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8967 diag::warn_format_non_standard_conversion_spec); 8968 8969 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8970 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8971 8972 // The remaining checks depend on the data arguments. 8973 if (HasVAListArg) 8974 return true; 8975 8976 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8977 return false; 8978 8979 // Check that the argument type matches the format specifier. 8980 const Expr *Ex = getDataArg(argIndex); 8981 if (!Ex) 8982 return true; 8983 8984 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8985 8986 if (!AT.isValid()) { 8987 return true; 8988 } 8989 8990 analyze_format_string::ArgType::MatchKind Match = 8991 AT.matchesType(S.Context, Ex->getType()); 8992 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8993 if (Match == analyze_format_string::ArgType::Match) 8994 return true; 8995 8996 ScanfSpecifier fixedFS = FS; 8997 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8998 S.getLangOpts(), S.Context); 8999 9000 unsigned Diag = 9001 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9002 : diag::warn_format_conversion_argument_type_mismatch; 9003 9004 if (Success) { 9005 // Get the fix string from the fixed format specifier. 9006 SmallString<128> buf; 9007 llvm::raw_svector_ostream os(buf); 9008 fixedFS.toString(os); 9009 9010 EmitFormatDiagnostic( 9011 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9012 << Ex->getType() << false << Ex->getSourceRange(), 9013 Ex->getBeginLoc(), 9014 /*IsStringLocation*/ false, 9015 getSpecifierRange(startSpecifier, specifierLen), 9016 FixItHint::CreateReplacement( 9017 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9018 } else { 9019 EmitFormatDiagnostic(S.PDiag(Diag) 9020 << AT.getRepresentativeTypeName(S.Context) 9021 << Ex->getType() << false << Ex->getSourceRange(), 9022 Ex->getBeginLoc(), 9023 /*IsStringLocation*/ false, 9024 getSpecifierRange(startSpecifier, specifierLen)); 9025 } 9026 9027 return true; 9028 } 9029 9030 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9031 const Expr *OrigFormatExpr, 9032 ArrayRef<const Expr *> Args, 9033 bool HasVAListArg, unsigned format_idx, 9034 unsigned firstDataArg, 9035 Sema::FormatStringType Type, 9036 bool inFunctionCall, 9037 Sema::VariadicCallType CallType, 9038 llvm::SmallBitVector &CheckedVarArgs, 9039 UncoveredArgHandler &UncoveredArg, 9040 bool IgnoreStringsWithoutSpecifiers) { 9041 // CHECK: is the format string a wide literal? 9042 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9043 CheckFormatHandler::EmitFormatDiagnostic( 9044 S, inFunctionCall, Args[format_idx], 9045 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9046 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9047 return; 9048 } 9049 9050 // Str - The format string. NOTE: this is NOT null-terminated! 9051 StringRef StrRef = FExpr->getString(); 9052 const char *Str = StrRef.data(); 9053 // Account for cases where the string literal is truncated in a declaration. 9054 const ConstantArrayType *T = 9055 S.Context.getAsConstantArrayType(FExpr->getType()); 9056 assert(T && "String literal not of constant array type!"); 9057 size_t TypeSize = T->getSize().getZExtValue(); 9058 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9059 const unsigned numDataArgs = Args.size() - firstDataArg; 9060 9061 if (IgnoreStringsWithoutSpecifiers && 9062 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9063 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9064 return; 9065 9066 // Emit a warning if the string literal is truncated and does not contain an 9067 // embedded null character. 9068 if (TypeSize <= StrRef.size() && 9069 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9070 CheckFormatHandler::EmitFormatDiagnostic( 9071 S, inFunctionCall, Args[format_idx], 9072 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9073 FExpr->getBeginLoc(), 9074 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9075 return; 9076 } 9077 9078 // CHECK: empty format string? 9079 if (StrLen == 0 && numDataArgs > 0) { 9080 CheckFormatHandler::EmitFormatDiagnostic( 9081 S, inFunctionCall, Args[format_idx], 9082 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9083 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9084 return; 9085 } 9086 9087 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9088 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9089 Type == Sema::FST_OSTrace) { 9090 CheckPrintfHandler H( 9091 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9092 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9093 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9094 CheckedVarArgs, UncoveredArg); 9095 9096 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9097 S.getLangOpts(), 9098 S.Context.getTargetInfo(), 9099 Type == Sema::FST_FreeBSDKPrintf)) 9100 H.DoneProcessing(); 9101 } else if (Type == Sema::FST_Scanf) { 9102 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9103 numDataArgs, Str, HasVAListArg, Args, format_idx, 9104 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9105 9106 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9107 S.getLangOpts(), 9108 S.Context.getTargetInfo())) 9109 H.DoneProcessing(); 9110 } // TODO: handle other formats 9111 } 9112 9113 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9114 // Str - The format string. NOTE: this is NOT null-terminated! 9115 StringRef StrRef = FExpr->getString(); 9116 const char *Str = StrRef.data(); 9117 // Account for cases where the string literal is truncated in a declaration. 9118 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9119 assert(T && "String literal not of constant array type!"); 9120 size_t TypeSize = T->getSize().getZExtValue(); 9121 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9122 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9123 getLangOpts(), 9124 Context.getTargetInfo()); 9125 } 9126 9127 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9128 9129 // Returns the related absolute value function that is larger, of 0 if one 9130 // does not exist. 9131 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9132 switch (AbsFunction) { 9133 default: 9134 return 0; 9135 9136 case Builtin::BI__builtin_abs: 9137 return Builtin::BI__builtin_labs; 9138 case Builtin::BI__builtin_labs: 9139 return Builtin::BI__builtin_llabs; 9140 case Builtin::BI__builtin_llabs: 9141 return 0; 9142 9143 case Builtin::BI__builtin_fabsf: 9144 return Builtin::BI__builtin_fabs; 9145 case Builtin::BI__builtin_fabs: 9146 return Builtin::BI__builtin_fabsl; 9147 case Builtin::BI__builtin_fabsl: 9148 return 0; 9149 9150 case Builtin::BI__builtin_cabsf: 9151 return Builtin::BI__builtin_cabs; 9152 case Builtin::BI__builtin_cabs: 9153 return Builtin::BI__builtin_cabsl; 9154 case Builtin::BI__builtin_cabsl: 9155 return 0; 9156 9157 case Builtin::BIabs: 9158 return Builtin::BIlabs; 9159 case Builtin::BIlabs: 9160 return Builtin::BIllabs; 9161 case Builtin::BIllabs: 9162 return 0; 9163 9164 case Builtin::BIfabsf: 9165 return Builtin::BIfabs; 9166 case Builtin::BIfabs: 9167 return Builtin::BIfabsl; 9168 case Builtin::BIfabsl: 9169 return 0; 9170 9171 case Builtin::BIcabsf: 9172 return Builtin::BIcabs; 9173 case Builtin::BIcabs: 9174 return Builtin::BIcabsl; 9175 case Builtin::BIcabsl: 9176 return 0; 9177 } 9178 } 9179 9180 // Returns the argument type of the absolute value function. 9181 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9182 unsigned AbsType) { 9183 if (AbsType == 0) 9184 return QualType(); 9185 9186 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9187 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9188 if (Error != ASTContext::GE_None) 9189 return QualType(); 9190 9191 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9192 if (!FT) 9193 return QualType(); 9194 9195 if (FT->getNumParams() != 1) 9196 return QualType(); 9197 9198 return FT->getParamType(0); 9199 } 9200 9201 // Returns the best absolute value function, or zero, based on type and 9202 // current absolute value function. 9203 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9204 unsigned AbsFunctionKind) { 9205 unsigned BestKind = 0; 9206 uint64_t ArgSize = Context.getTypeSize(ArgType); 9207 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9208 Kind = getLargerAbsoluteValueFunction(Kind)) { 9209 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9210 if (Context.getTypeSize(ParamType) >= ArgSize) { 9211 if (BestKind == 0) 9212 BestKind = Kind; 9213 else if (Context.hasSameType(ParamType, ArgType)) { 9214 BestKind = Kind; 9215 break; 9216 } 9217 } 9218 } 9219 return BestKind; 9220 } 9221 9222 enum AbsoluteValueKind { 9223 AVK_Integer, 9224 AVK_Floating, 9225 AVK_Complex 9226 }; 9227 9228 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9229 if (T->isIntegralOrEnumerationType()) 9230 return AVK_Integer; 9231 if (T->isRealFloatingType()) 9232 return AVK_Floating; 9233 if (T->isAnyComplexType()) 9234 return AVK_Complex; 9235 9236 llvm_unreachable("Type not integer, floating, or complex"); 9237 } 9238 9239 // Changes the absolute value function to a different type. Preserves whether 9240 // the function is a builtin. 9241 static unsigned changeAbsFunction(unsigned AbsKind, 9242 AbsoluteValueKind ValueKind) { 9243 switch (ValueKind) { 9244 case AVK_Integer: 9245 switch (AbsKind) { 9246 default: 9247 return 0; 9248 case Builtin::BI__builtin_fabsf: 9249 case Builtin::BI__builtin_fabs: 9250 case Builtin::BI__builtin_fabsl: 9251 case Builtin::BI__builtin_cabsf: 9252 case Builtin::BI__builtin_cabs: 9253 case Builtin::BI__builtin_cabsl: 9254 return Builtin::BI__builtin_abs; 9255 case Builtin::BIfabsf: 9256 case Builtin::BIfabs: 9257 case Builtin::BIfabsl: 9258 case Builtin::BIcabsf: 9259 case Builtin::BIcabs: 9260 case Builtin::BIcabsl: 9261 return Builtin::BIabs; 9262 } 9263 case AVK_Floating: 9264 switch (AbsKind) { 9265 default: 9266 return 0; 9267 case Builtin::BI__builtin_abs: 9268 case Builtin::BI__builtin_labs: 9269 case Builtin::BI__builtin_llabs: 9270 case Builtin::BI__builtin_cabsf: 9271 case Builtin::BI__builtin_cabs: 9272 case Builtin::BI__builtin_cabsl: 9273 return Builtin::BI__builtin_fabsf; 9274 case Builtin::BIabs: 9275 case Builtin::BIlabs: 9276 case Builtin::BIllabs: 9277 case Builtin::BIcabsf: 9278 case Builtin::BIcabs: 9279 case Builtin::BIcabsl: 9280 return Builtin::BIfabsf; 9281 } 9282 case AVK_Complex: 9283 switch (AbsKind) { 9284 default: 9285 return 0; 9286 case Builtin::BI__builtin_abs: 9287 case Builtin::BI__builtin_labs: 9288 case Builtin::BI__builtin_llabs: 9289 case Builtin::BI__builtin_fabsf: 9290 case Builtin::BI__builtin_fabs: 9291 case Builtin::BI__builtin_fabsl: 9292 return Builtin::BI__builtin_cabsf; 9293 case Builtin::BIabs: 9294 case Builtin::BIlabs: 9295 case Builtin::BIllabs: 9296 case Builtin::BIfabsf: 9297 case Builtin::BIfabs: 9298 case Builtin::BIfabsl: 9299 return Builtin::BIcabsf; 9300 } 9301 } 9302 llvm_unreachable("Unable to convert function"); 9303 } 9304 9305 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9306 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9307 if (!FnInfo) 9308 return 0; 9309 9310 switch (FDecl->getBuiltinID()) { 9311 default: 9312 return 0; 9313 case Builtin::BI__builtin_abs: 9314 case Builtin::BI__builtin_fabs: 9315 case Builtin::BI__builtin_fabsf: 9316 case Builtin::BI__builtin_fabsl: 9317 case Builtin::BI__builtin_labs: 9318 case Builtin::BI__builtin_llabs: 9319 case Builtin::BI__builtin_cabs: 9320 case Builtin::BI__builtin_cabsf: 9321 case Builtin::BI__builtin_cabsl: 9322 case Builtin::BIabs: 9323 case Builtin::BIlabs: 9324 case Builtin::BIllabs: 9325 case Builtin::BIfabs: 9326 case Builtin::BIfabsf: 9327 case Builtin::BIfabsl: 9328 case Builtin::BIcabs: 9329 case Builtin::BIcabsf: 9330 case Builtin::BIcabsl: 9331 return FDecl->getBuiltinID(); 9332 } 9333 llvm_unreachable("Unknown Builtin type"); 9334 } 9335 9336 // If the replacement is valid, emit a note with replacement function. 9337 // Additionally, suggest including the proper header if not already included. 9338 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9339 unsigned AbsKind, QualType ArgType) { 9340 bool EmitHeaderHint = true; 9341 const char *HeaderName = nullptr; 9342 const char *FunctionName = nullptr; 9343 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9344 FunctionName = "std::abs"; 9345 if (ArgType->isIntegralOrEnumerationType()) { 9346 HeaderName = "cstdlib"; 9347 } else if (ArgType->isRealFloatingType()) { 9348 HeaderName = "cmath"; 9349 } else { 9350 llvm_unreachable("Invalid Type"); 9351 } 9352 9353 // Lookup all std::abs 9354 if (NamespaceDecl *Std = S.getStdNamespace()) { 9355 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9356 R.suppressDiagnostics(); 9357 S.LookupQualifiedName(R, Std); 9358 9359 for (const auto *I : R) { 9360 const FunctionDecl *FDecl = nullptr; 9361 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9362 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9363 } else { 9364 FDecl = dyn_cast<FunctionDecl>(I); 9365 } 9366 if (!FDecl) 9367 continue; 9368 9369 // Found std::abs(), check that they are the right ones. 9370 if (FDecl->getNumParams() != 1) 9371 continue; 9372 9373 // Check that the parameter type can handle the argument. 9374 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9375 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9376 S.Context.getTypeSize(ArgType) <= 9377 S.Context.getTypeSize(ParamType)) { 9378 // Found a function, don't need the header hint. 9379 EmitHeaderHint = false; 9380 break; 9381 } 9382 } 9383 } 9384 } else { 9385 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9386 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9387 9388 if (HeaderName) { 9389 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9390 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9391 R.suppressDiagnostics(); 9392 S.LookupName(R, S.getCurScope()); 9393 9394 if (R.isSingleResult()) { 9395 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9396 if (FD && FD->getBuiltinID() == AbsKind) { 9397 EmitHeaderHint = false; 9398 } else { 9399 return; 9400 } 9401 } else if (!R.empty()) { 9402 return; 9403 } 9404 } 9405 } 9406 9407 S.Diag(Loc, diag::note_replace_abs_function) 9408 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9409 9410 if (!HeaderName) 9411 return; 9412 9413 if (!EmitHeaderHint) 9414 return; 9415 9416 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9417 << FunctionName; 9418 } 9419 9420 template <std::size_t StrLen> 9421 static bool IsStdFunction(const FunctionDecl *FDecl, 9422 const char (&Str)[StrLen]) { 9423 if (!FDecl) 9424 return false; 9425 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9426 return false; 9427 if (!FDecl->isInStdNamespace()) 9428 return false; 9429 9430 return true; 9431 } 9432 9433 // Warn when using the wrong abs() function. 9434 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9435 const FunctionDecl *FDecl) { 9436 if (Call->getNumArgs() != 1) 9437 return; 9438 9439 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9440 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9441 if (AbsKind == 0 && !IsStdAbs) 9442 return; 9443 9444 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9445 QualType ParamType = Call->getArg(0)->getType(); 9446 9447 // Unsigned types cannot be negative. Suggest removing the absolute value 9448 // function call. 9449 if (ArgType->isUnsignedIntegerType()) { 9450 const char *FunctionName = 9451 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9452 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9453 Diag(Call->getExprLoc(), diag::note_remove_abs) 9454 << FunctionName 9455 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9456 return; 9457 } 9458 9459 // Taking the absolute value of a pointer is very suspicious, they probably 9460 // wanted to index into an array, dereference a pointer, call a function, etc. 9461 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9462 unsigned DiagType = 0; 9463 if (ArgType->isFunctionType()) 9464 DiagType = 1; 9465 else if (ArgType->isArrayType()) 9466 DiagType = 2; 9467 9468 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9469 return; 9470 } 9471 9472 // std::abs has overloads which prevent most of the absolute value problems 9473 // from occurring. 9474 if (IsStdAbs) 9475 return; 9476 9477 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9478 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9479 9480 // The argument and parameter are the same kind. Check if they are the right 9481 // size. 9482 if (ArgValueKind == ParamValueKind) { 9483 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9484 return; 9485 9486 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9487 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9488 << FDecl << ArgType << ParamType; 9489 9490 if (NewAbsKind == 0) 9491 return; 9492 9493 emitReplacement(*this, Call->getExprLoc(), 9494 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9495 return; 9496 } 9497 9498 // ArgValueKind != ParamValueKind 9499 // The wrong type of absolute value function was used. Attempt to find the 9500 // proper one. 9501 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9502 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9503 if (NewAbsKind == 0) 9504 return; 9505 9506 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9507 << FDecl << ParamValueKind << ArgValueKind; 9508 9509 emitReplacement(*this, Call->getExprLoc(), 9510 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9511 } 9512 9513 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9514 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9515 const FunctionDecl *FDecl) { 9516 if (!Call || !FDecl) return; 9517 9518 // Ignore template specializations and macros. 9519 if (inTemplateInstantiation()) return; 9520 if (Call->getExprLoc().isMacroID()) return; 9521 9522 // Only care about the one template argument, two function parameter std::max 9523 if (Call->getNumArgs() != 2) return; 9524 if (!IsStdFunction(FDecl, "max")) return; 9525 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9526 if (!ArgList) return; 9527 if (ArgList->size() != 1) return; 9528 9529 // Check that template type argument is unsigned integer. 9530 const auto& TA = ArgList->get(0); 9531 if (TA.getKind() != TemplateArgument::Type) return; 9532 QualType ArgType = TA.getAsType(); 9533 if (!ArgType->isUnsignedIntegerType()) return; 9534 9535 // See if either argument is a literal zero. 9536 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9537 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9538 if (!MTE) return false; 9539 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9540 if (!Num) return false; 9541 if (Num->getValue() != 0) return false; 9542 return true; 9543 }; 9544 9545 const Expr *FirstArg = Call->getArg(0); 9546 const Expr *SecondArg = Call->getArg(1); 9547 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9548 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9549 9550 // Only warn when exactly one argument is zero. 9551 if (IsFirstArgZero == IsSecondArgZero) return; 9552 9553 SourceRange FirstRange = FirstArg->getSourceRange(); 9554 SourceRange SecondRange = SecondArg->getSourceRange(); 9555 9556 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9557 9558 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9559 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9560 9561 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9562 SourceRange RemovalRange; 9563 if (IsFirstArgZero) { 9564 RemovalRange = SourceRange(FirstRange.getBegin(), 9565 SecondRange.getBegin().getLocWithOffset(-1)); 9566 } else { 9567 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9568 SecondRange.getEnd()); 9569 } 9570 9571 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9572 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9573 << FixItHint::CreateRemoval(RemovalRange); 9574 } 9575 9576 //===--- CHECK: Standard memory functions ---------------------------------===// 9577 9578 /// Takes the expression passed to the size_t parameter of functions 9579 /// such as memcmp, strncat, etc and warns if it's a comparison. 9580 /// 9581 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9582 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9583 IdentifierInfo *FnName, 9584 SourceLocation FnLoc, 9585 SourceLocation RParenLoc) { 9586 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9587 if (!Size) 9588 return false; 9589 9590 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9591 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9592 return false; 9593 9594 SourceRange SizeRange = Size->getSourceRange(); 9595 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9596 << SizeRange << FnName; 9597 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9598 << FnName 9599 << FixItHint::CreateInsertion( 9600 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9601 << FixItHint::CreateRemoval(RParenLoc); 9602 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9603 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9604 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9605 ")"); 9606 9607 return true; 9608 } 9609 9610 /// Determine whether the given type is or contains a dynamic class type 9611 /// (e.g., whether it has a vtable). 9612 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9613 bool &IsContained) { 9614 // Look through array types while ignoring qualifiers. 9615 const Type *Ty = T->getBaseElementTypeUnsafe(); 9616 IsContained = false; 9617 9618 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9619 RD = RD ? RD->getDefinition() : nullptr; 9620 if (!RD || RD->isInvalidDecl()) 9621 return nullptr; 9622 9623 if (RD->isDynamicClass()) 9624 return RD; 9625 9626 // Check all the fields. If any bases were dynamic, the class is dynamic. 9627 // It's impossible for a class to transitively contain itself by value, so 9628 // infinite recursion is impossible. 9629 for (auto *FD : RD->fields()) { 9630 bool SubContained; 9631 if (const CXXRecordDecl *ContainedRD = 9632 getContainedDynamicClass(FD->getType(), SubContained)) { 9633 IsContained = true; 9634 return ContainedRD; 9635 } 9636 } 9637 9638 return nullptr; 9639 } 9640 9641 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9642 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9643 if (Unary->getKind() == UETT_SizeOf) 9644 return Unary; 9645 return nullptr; 9646 } 9647 9648 /// If E is a sizeof expression, returns its argument expression, 9649 /// otherwise returns NULL. 9650 static const Expr *getSizeOfExprArg(const Expr *E) { 9651 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9652 if (!SizeOf->isArgumentType()) 9653 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9654 return nullptr; 9655 } 9656 9657 /// If E is a sizeof expression, returns its argument type. 9658 static QualType getSizeOfArgType(const Expr *E) { 9659 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9660 return SizeOf->getTypeOfArgument(); 9661 return QualType(); 9662 } 9663 9664 namespace { 9665 9666 struct SearchNonTrivialToInitializeField 9667 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9668 using Super = 9669 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9670 9671 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9672 9673 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9674 SourceLocation SL) { 9675 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9676 asDerived().visitArray(PDIK, AT, SL); 9677 return; 9678 } 9679 9680 Super::visitWithKind(PDIK, FT, SL); 9681 } 9682 9683 void visitARCStrong(QualType FT, SourceLocation SL) { 9684 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9685 } 9686 void visitARCWeak(QualType FT, SourceLocation SL) { 9687 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9688 } 9689 void visitStruct(QualType FT, SourceLocation SL) { 9690 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9691 visit(FD->getType(), FD->getLocation()); 9692 } 9693 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9694 const ArrayType *AT, SourceLocation SL) { 9695 visit(getContext().getBaseElementType(AT), SL); 9696 } 9697 void visitTrivial(QualType FT, SourceLocation SL) {} 9698 9699 static void diag(QualType RT, const Expr *E, Sema &S) { 9700 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9701 } 9702 9703 ASTContext &getContext() { return S.getASTContext(); } 9704 9705 const Expr *E; 9706 Sema &S; 9707 }; 9708 9709 struct SearchNonTrivialToCopyField 9710 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9711 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9712 9713 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9714 9715 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9716 SourceLocation SL) { 9717 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9718 asDerived().visitArray(PCK, AT, SL); 9719 return; 9720 } 9721 9722 Super::visitWithKind(PCK, FT, SL); 9723 } 9724 9725 void visitARCStrong(QualType FT, SourceLocation SL) { 9726 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9727 } 9728 void visitARCWeak(QualType FT, SourceLocation SL) { 9729 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9730 } 9731 void visitStruct(QualType FT, SourceLocation SL) { 9732 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9733 visit(FD->getType(), FD->getLocation()); 9734 } 9735 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9736 SourceLocation SL) { 9737 visit(getContext().getBaseElementType(AT), SL); 9738 } 9739 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9740 SourceLocation SL) {} 9741 void visitTrivial(QualType FT, SourceLocation SL) {} 9742 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9743 9744 static void diag(QualType RT, const Expr *E, Sema &S) { 9745 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9746 } 9747 9748 ASTContext &getContext() { return S.getASTContext(); } 9749 9750 const Expr *E; 9751 Sema &S; 9752 }; 9753 9754 } 9755 9756 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9757 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9758 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9759 9760 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9761 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9762 return false; 9763 9764 return doesExprLikelyComputeSize(BO->getLHS()) || 9765 doesExprLikelyComputeSize(BO->getRHS()); 9766 } 9767 9768 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9769 } 9770 9771 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9772 /// 9773 /// \code 9774 /// #define MACRO 0 9775 /// foo(MACRO); 9776 /// foo(0); 9777 /// \endcode 9778 /// 9779 /// This should return true for the first call to foo, but not for the second 9780 /// (regardless of whether foo is a macro or function). 9781 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9782 SourceLocation CallLoc, 9783 SourceLocation ArgLoc) { 9784 if (!CallLoc.isMacroID()) 9785 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9786 9787 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9788 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9789 } 9790 9791 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9792 /// last two arguments transposed. 9793 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9794 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9795 return; 9796 9797 const Expr *SizeArg = 9798 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9799 9800 auto isLiteralZero = [](const Expr *E) { 9801 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9802 }; 9803 9804 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9805 SourceLocation CallLoc = Call->getRParenLoc(); 9806 SourceManager &SM = S.getSourceManager(); 9807 if (isLiteralZero(SizeArg) && 9808 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9809 9810 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9811 9812 // Some platforms #define bzero to __builtin_memset. See if this is the 9813 // case, and if so, emit a better diagnostic. 9814 if (BId == Builtin::BIbzero || 9815 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9816 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9817 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9818 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9819 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9820 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9821 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9822 } 9823 return; 9824 } 9825 9826 // If the second argument to a memset is a sizeof expression and the third 9827 // isn't, this is also likely an error. This should catch 9828 // 'memset(buf, sizeof(buf), 0xff)'. 9829 if (BId == Builtin::BImemset && 9830 doesExprLikelyComputeSize(Call->getArg(1)) && 9831 !doesExprLikelyComputeSize(Call->getArg(2))) { 9832 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9833 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9834 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9835 return; 9836 } 9837 } 9838 9839 /// Check for dangerous or invalid arguments to memset(). 9840 /// 9841 /// This issues warnings on known problematic, dangerous or unspecified 9842 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9843 /// function calls. 9844 /// 9845 /// \param Call The call expression to diagnose. 9846 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9847 unsigned BId, 9848 IdentifierInfo *FnName) { 9849 assert(BId != 0); 9850 9851 // It is possible to have a non-standard definition of memset. Validate 9852 // we have enough arguments, and if not, abort further checking. 9853 unsigned ExpectedNumArgs = 9854 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9855 if (Call->getNumArgs() < ExpectedNumArgs) 9856 return; 9857 9858 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9859 BId == Builtin::BIstrndup ? 1 : 2); 9860 unsigned LenArg = 9861 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9862 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9863 9864 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9865 Call->getBeginLoc(), Call->getRParenLoc())) 9866 return; 9867 9868 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9869 CheckMemaccessSize(*this, BId, Call); 9870 9871 // We have special checking when the length is a sizeof expression. 9872 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9873 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9874 llvm::FoldingSetNodeID SizeOfArgID; 9875 9876 // Although widely used, 'bzero' is not a standard function. Be more strict 9877 // with the argument types before allowing diagnostics and only allow the 9878 // form bzero(ptr, sizeof(...)). 9879 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9880 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9881 return; 9882 9883 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9884 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9885 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9886 9887 QualType DestTy = Dest->getType(); 9888 QualType PointeeTy; 9889 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9890 PointeeTy = DestPtrTy->getPointeeType(); 9891 9892 // Never warn about void type pointers. This can be used to suppress 9893 // false positives. 9894 if (PointeeTy->isVoidType()) 9895 continue; 9896 9897 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9898 // actually comparing the expressions for equality. Because computing the 9899 // expression IDs can be expensive, we only do this if the diagnostic is 9900 // enabled. 9901 if (SizeOfArg && 9902 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9903 SizeOfArg->getExprLoc())) { 9904 // We only compute IDs for expressions if the warning is enabled, and 9905 // cache the sizeof arg's ID. 9906 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9907 SizeOfArg->Profile(SizeOfArgID, Context, true); 9908 llvm::FoldingSetNodeID DestID; 9909 Dest->Profile(DestID, Context, true); 9910 if (DestID == SizeOfArgID) { 9911 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9912 // over sizeof(src) as well. 9913 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9914 StringRef ReadableName = FnName->getName(); 9915 9916 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9917 if (UnaryOp->getOpcode() == UO_AddrOf) 9918 ActionIdx = 1; // If its an address-of operator, just remove it. 9919 if (!PointeeTy->isIncompleteType() && 9920 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9921 ActionIdx = 2; // If the pointee's size is sizeof(char), 9922 // suggest an explicit length. 9923 9924 // If the function is defined as a builtin macro, do not show macro 9925 // expansion. 9926 SourceLocation SL = SizeOfArg->getExprLoc(); 9927 SourceRange DSR = Dest->getSourceRange(); 9928 SourceRange SSR = SizeOfArg->getSourceRange(); 9929 SourceManager &SM = getSourceManager(); 9930 9931 if (SM.isMacroArgExpansion(SL)) { 9932 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9933 SL = SM.getSpellingLoc(SL); 9934 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9935 SM.getSpellingLoc(DSR.getEnd())); 9936 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9937 SM.getSpellingLoc(SSR.getEnd())); 9938 } 9939 9940 DiagRuntimeBehavior(SL, SizeOfArg, 9941 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9942 << ReadableName 9943 << PointeeTy 9944 << DestTy 9945 << DSR 9946 << SSR); 9947 DiagRuntimeBehavior(SL, SizeOfArg, 9948 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9949 << ActionIdx 9950 << SSR); 9951 9952 break; 9953 } 9954 } 9955 9956 // Also check for cases where the sizeof argument is the exact same 9957 // type as the memory argument, and where it points to a user-defined 9958 // record type. 9959 if (SizeOfArgTy != QualType()) { 9960 if (PointeeTy->isRecordType() && 9961 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9962 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9963 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9964 << FnName << SizeOfArgTy << ArgIdx 9965 << PointeeTy << Dest->getSourceRange() 9966 << LenExpr->getSourceRange()); 9967 break; 9968 } 9969 } 9970 } else if (DestTy->isArrayType()) { 9971 PointeeTy = DestTy; 9972 } 9973 9974 if (PointeeTy == QualType()) 9975 continue; 9976 9977 // Always complain about dynamic classes. 9978 bool IsContained; 9979 if (const CXXRecordDecl *ContainedRD = 9980 getContainedDynamicClass(PointeeTy, IsContained)) { 9981 9982 unsigned OperationType = 0; 9983 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9984 // "overwritten" if we're warning about the destination for any call 9985 // but memcmp; otherwise a verb appropriate to the call. 9986 if (ArgIdx != 0 || IsCmp) { 9987 if (BId == Builtin::BImemcpy) 9988 OperationType = 1; 9989 else if(BId == Builtin::BImemmove) 9990 OperationType = 2; 9991 else if (IsCmp) 9992 OperationType = 3; 9993 } 9994 9995 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9996 PDiag(diag::warn_dyn_class_memaccess) 9997 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9998 << IsContained << ContainedRD << OperationType 9999 << Call->getCallee()->getSourceRange()); 10000 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10001 BId != Builtin::BImemset) 10002 DiagRuntimeBehavior( 10003 Dest->getExprLoc(), Dest, 10004 PDiag(diag::warn_arc_object_memaccess) 10005 << ArgIdx << FnName << PointeeTy 10006 << Call->getCallee()->getSourceRange()); 10007 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10008 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10009 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10010 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10011 PDiag(diag::warn_cstruct_memaccess) 10012 << ArgIdx << FnName << PointeeTy << 0); 10013 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10014 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10015 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10016 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10017 PDiag(diag::warn_cstruct_memaccess) 10018 << ArgIdx << FnName << PointeeTy << 1); 10019 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10020 } else { 10021 continue; 10022 } 10023 } else 10024 continue; 10025 10026 DiagRuntimeBehavior( 10027 Dest->getExprLoc(), Dest, 10028 PDiag(diag::note_bad_memaccess_silence) 10029 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10030 break; 10031 } 10032 } 10033 10034 // A little helper routine: ignore addition and subtraction of integer literals. 10035 // This intentionally does not ignore all integer constant expressions because 10036 // we don't want to remove sizeof(). 10037 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10038 Ex = Ex->IgnoreParenCasts(); 10039 10040 while (true) { 10041 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10042 if (!BO || !BO->isAdditiveOp()) 10043 break; 10044 10045 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10046 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10047 10048 if (isa<IntegerLiteral>(RHS)) 10049 Ex = LHS; 10050 else if (isa<IntegerLiteral>(LHS)) 10051 Ex = RHS; 10052 else 10053 break; 10054 } 10055 10056 return Ex; 10057 } 10058 10059 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10060 ASTContext &Context) { 10061 // Only handle constant-sized or VLAs, but not flexible members. 10062 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10063 // Only issue the FIXIT for arrays of size > 1. 10064 if (CAT->getSize().getSExtValue() <= 1) 10065 return false; 10066 } else if (!Ty->isVariableArrayType()) { 10067 return false; 10068 } 10069 return true; 10070 } 10071 10072 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10073 // be the size of the source, instead of the destination. 10074 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10075 IdentifierInfo *FnName) { 10076 10077 // Don't crash if the user has the wrong number of arguments 10078 unsigned NumArgs = Call->getNumArgs(); 10079 if ((NumArgs != 3) && (NumArgs != 4)) 10080 return; 10081 10082 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10083 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10084 const Expr *CompareWithSrc = nullptr; 10085 10086 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10087 Call->getBeginLoc(), Call->getRParenLoc())) 10088 return; 10089 10090 // Look for 'strlcpy(dst, x, sizeof(x))' 10091 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10092 CompareWithSrc = Ex; 10093 else { 10094 // Look for 'strlcpy(dst, x, strlen(x))' 10095 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10096 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10097 SizeCall->getNumArgs() == 1) 10098 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10099 } 10100 } 10101 10102 if (!CompareWithSrc) 10103 return; 10104 10105 // Determine if the argument to sizeof/strlen is equal to the source 10106 // argument. In principle there's all kinds of things you could do 10107 // here, for instance creating an == expression and evaluating it with 10108 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10109 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10110 if (!SrcArgDRE) 10111 return; 10112 10113 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10114 if (!CompareWithSrcDRE || 10115 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10116 return; 10117 10118 const Expr *OriginalSizeArg = Call->getArg(2); 10119 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10120 << OriginalSizeArg->getSourceRange() << FnName; 10121 10122 // Output a FIXIT hint if the destination is an array (rather than a 10123 // pointer to an array). This could be enhanced to handle some 10124 // pointers if we know the actual size, like if DstArg is 'array+2' 10125 // we could say 'sizeof(array)-2'. 10126 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10127 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10128 return; 10129 10130 SmallString<128> sizeString; 10131 llvm::raw_svector_ostream OS(sizeString); 10132 OS << "sizeof("; 10133 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10134 OS << ")"; 10135 10136 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10137 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10138 OS.str()); 10139 } 10140 10141 /// Check if two expressions refer to the same declaration. 10142 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10143 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10144 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10145 return D1->getDecl() == D2->getDecl(); 10146 return false; 10147 } 10148 10149 static const Expr *getStrlenExprArg(const Expr *E) { 10150 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10151 const FunctionDecl *FD = CE->getDirectCallee(); 10152 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10153 return nullptr; 10154 return CE->getArg(0)->IgnoreParenCasts(); 10155 } 10156 return nullptr; 10157 } 10158 10159 // Warn on anti-patterns as the 'size' argument to strncat. 10160 // The correct size argument should look like following: 10161 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10162 void Sema::CheckStrncatArguments(const CallExpr *CE, 10163 IdentifierInfo *FnName) { 10164 // Don't crash if the user has the wrong number of arguments. 10165 if (CE->getNumArgs() < 3) 10166 return; 10167 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10168 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10169 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10170 10171 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10172 CE->getRParenLoc())) 10173 return; 10174 10175 // Identify common expressions, which are wrongly used as the size argument 10176 // to strncat and may lead to buffer overflows. 10177 unsigned PatternType = 0; 10178 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10179 // - sizeof(dst) 10180 if (referToTheSameDecl(SizeOfArg, DstArg)) 10181 PatternType = 1; 10182 // - sizeof(src) 10183 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10184 PatternType = 2; 10185 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10186 if (BE->getOpcode() == BO_Sub) { 10187 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10188 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10189 // - sizeof(dst) - strlen(dst) 10190 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10191 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10192 PatternType = 1; 10193 // - sizeof(src) - (anything) 10194 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10195 PatternType = 2; 10196 } 10197 } 10198 10199 if (PatternType == 0) 10200 return; 10201 10202 // Generate the diagnostic. 10203 SourceLocation SL = LenArg->getBeginLoc(); 10204 SourceRange SR = LenArg->getSourceRange(); 10205 SourceManager &SM = getSourceManager(); 10206 10207 // If the function is defined as a builtin macro, do not show macro expansion. 10208 if (SM.isMacroArgExpansion(SL)) { 10209 SL = SM.getSpellingLoc(SL); 10210 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10211 SM.getSpellingLoc(SR.getEnd())); 10212 } 10213 10214 // Check if the destination is an array (rather than a pointer to an array). 10215 QualType DstTy = DstArg->getType(); 10216 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10217 Context); 10218 if (!isKnownSizeArray) { 10219 if (PatternType == 1) 10220 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10221 else 10222 Diag(SL, diag::warn_strncat_src_size) << SR; 10223 return; 10224 } 10225 10226 if (PatternType == 1) 10227 Diag(SL, diag::warn_strncat_large_size) << SR; 10228 else 10229 Diag(SL, diag::warn_strncat_src_size) << SR; 10230 10231 SmallString<128> sizeString; 10232 llvm::raw_svector_ostream OS(sizeString); 10233 OS << "sizeof("; 10234 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10235 OS << ") - "; 10236 OS << "strlen("; 10237 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10238 OS << ") - 1"; 10239 10240 Diag(SL, diag::note_strncat_wrong_size) 10241 << FixItHint::CreateReplacement(SR, OS.str()); 10242 } 10243 10244 namespace { 10245 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10246 const UnaryOperator *UnaryExpr, 10247 const VarDecl *Var) { 10248 StorageClass Class = Var->getStorageClass(); 10249 if (Class == StorageClass::SC_Extern || 10250 Class == StorageClass::SC_PrivateExtern || 10251 Var->getType()->isReferenceType()) 10252 return; 10253 10254 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10255 << CalleeName << Var; 10256 } 10257 10258 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10259 const UnaryOperator *UnaryExpr, const Decl *D) { 10260 if (const auto *Field = dyn_cast<FieldDecl>(D)) 10261 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10262 << CalleeName << Field; 10263 } 10264 10265 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10266 const UnaryOperator *UnaryExpr) { 10267 if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf) 10268 return; 10269 10270 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) 10271 if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl())) 10272 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var); 10273 10274 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10275 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10276 Lvalue->getMemberDecl()); 10277 } 10278 10279 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10280 const DeclRefExpr *Lvalue) { 10281 if (!Lvalue->getType()->isArrayType()) 10282 return; 10283 10284 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10285 if (Var == nullptr) 10286 return; 10287 10288 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10289 << CalleeName << Var; 10290 } 10291 } // namespace 10292 10293 /// Alerts the user that they are attempting to free a non-malloc'd object. 10294 void Sema::CheckFreeArguments(const CallExpr *E) { 10295 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10296 const std::string CalleeName = 10297 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10298 10299 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10300 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10301 10302 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10303 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10304 } 10305 10306 void 10307 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10308 SourceLocation ReturnLoc, 10309 bool isObjCMethod, 10310 const AttrVec *Attrs, 10311 const FunctionDecl *FD) { 10312 // Check if the return value is null but should not be. 10313 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10314 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10315 CheckNonNullExpr(*this, RetValExp)) 10316 Diag(ReturnLoc, diag::warn_null_ret) 10317 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10318 10319 // C++11 [basic.stc.dynamic.allocation]p4: 10320 // If an allocation function declared with a non-throwing 10321 // exception-specification fails to allocate storage, it shall return 10322 // a null pointer. Any other allocation function that fails to allocate 10323 // storage shall indicate failure only by throwing an exception [...] 10324 if (FD) { 10325 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10326 if (Op == OO_New || Op == OO_Array_New) { 10327 const FunctionProtoType *Proto 10328 = FD->getType()->castAs<FunctionProtoType>(); 10329 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10330 CheckNonNullExpr(*this, RetValExp)) 10331 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10332 << FD << getLangOpts().CPlusPlus11; 10333 } 10334 } 10335 10336 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10337 // here prevent the user from using a PPC MMA type as trailing return type. 10338 if (Context.getTargetInfo().getTriple().isPPC64()) 10339 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10340 } 10341 10342 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10343 10344 /// Check for comparisons of floating point operands using != and ==. 10345 /// Issue a warning if these are no self-comparisons, as they are not likely 10346 /// to do what the programmer intended. 10347 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10348 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10349 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10350 10351 // Special case: check for x == x (which is OK). 10352 // Do not emit warnings for such cases. 10353 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10354 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10355 if (DRL->getDecl() == DRR->getDecl()) 10356 return; 10357 10358 // Special case: check for comparisons against literals that can be exactly 10359 // represented by APFloat. In such cases, do not emit a warning. This 10360 // is a heuristic: often comparison against such literals are used to 10361 // detect if a value in a variable has not changed. This clearly can 10362 // lead to false negatives. 10363 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10364 if (FLL->isExact()) 10365 return; 10366 } else 10367 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10368 if (FLR->isExact()) 10369 return; 10370 10371 // Check for comparisons with builtin types. 10372 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10373 if (CL->getBuiltinCallee()) 10374 return; 10375 10376 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10377 if (CR->getBuiltinCallee()) 10378 return; 10379 10380 // Emit the diagnostic. 10381 Diag(Loc, diag::warn_floatingpoint_eq) 10382 << LHS->getSourceRange() << RHS->getSourceRange(); 10383 } 10384 10385 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10386 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10387 10388 namespace { 10389 10390 /// Structure recording the 'active' range of an integer-valued 10391 /// expression. 10392 struct IntRange { 10393 /// The number of bits active in the int. Note that this includes exactly one 10394 /// sign bit if !NonNegative. 10395 unsigned Width; 10396 10397 /// True if the int is known not to have negative values. If so, all leading 10398 /// bits before Width are known zero, otherwise they are known to be the 10399 /// same as the MSB within Width. 10400 bool NonNegative; 10401 10402 IntRange(unsigned Width, bool NonNegative) 10403 : Width(Width), NonNegative(NonNegative) {} 10404 10405 /// Number of bits excluding the sign bit. 10406 unsigned valueBits() const { 10407 return NonNegative ? Width : Width - 1; 10408 } 10409 10410 /// Returns the range of the bool type. 10411 static IntRange forBoolType() { 10412 return IntRange(1, true); 10413 } 10414 10415 /// Returns the range of an opaque value of the given integral type. 10416 static IntRange forValueOfType(ASTContext &C, QualType T) { 10417 return forValueOfCanonicalType(C, 10418 T->getCanonicalTypeInternal().getTypePtr()); 10419 } 10420 10421 /// Returns the range of an opaque value of a canonical integral type. 10422 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10423 assert(T->isCanonicalUnqualified()); 10424 10425 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10426 T = VT->getElementType().getTypePtr(); 10427 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10428 T = CT->getElementType().getTypePtr(); 10429 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10430 T = AT->getValueType().getTypePtr(); 10431 10432 if (!C.getLangOpts().CPlusPlus) { 10433 // For enum types in C code, use the underlying datatype. 10434 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10435 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10436 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10437 // For enum types in C++, use the known bit width of the enumerators. 10438 EnumDecl *Enum = ET->getDecl(); 10439 // In C++11, enums can have a fixed underlying type. Use this type to 10440 // compute the range. 10441 if (Enum->isFixed()) { 10442 return IntRange(C.getIntWidth(QualType(T, 0)), 10443 !ET->isSignedIntegerOrEnumerationType()); 10444 } 10445 10446 unsigned NumPositive = Enum->getNumPositiveBits(); 10447 unsigned NumNegative = Enum->getNumNegativeBits(); 10448 10449 if (NumNegative == 0) 10450 return IntRange(NumPositive, true/*NonNegative*/); 10451 else 10452 return IntRange(std::max(NumPositive + 1, NumNegative), 10453 false/*NonNegative*/); 10454 } 10455 10456 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10457 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10458 10459 const BuiltinType *BT = cast<BuiltinType>(T); 10460 assert(BT->isInteger()); 10461 10462 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10463 } 10464 10465 /// Returns the "target" range of a canonical integral type, i.e. 10466 /// the range of values expressible in the type. 10467 /// 10468 /// This matches forValueOfCanonicalType except that enums have the 10469 /// full range of their type, not the range of their enumerators. 10470 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10471 assert(T->isCanonicalUnqualified()); 10472 10473 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10474 T = VT->getElementType().getTypePtr(); 10475 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10476 T = CT->getElementType().getTypePtr(); 10477 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10478 T = AT->getValueType().getTypePtr(); 10479 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10480 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10481 10482 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10483 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10484 10485 const BuiltinType *BT = cast<BuiltinType>(T); 10486 assert(BT->isInteger()); 10487 10488 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10489 } 10490 10491 /// Returns the supremum of two ranges: i.e. their conservative merge. 10492 static IntRange join(IntRange L, IntRange R) { 10493 bool Unsigned = L.NonNegative && R.NonNegative; 10494 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10495 L.NonNegative && R.NonNegative); 10496 } 10497 10498 /// Return the range of a bitwise-AND of the two ranges. 10499 static IntRange bit_and(IntRange L, IntRange R) { 10500 unsigned Bits = std::max(L.Width, R.Width); 10501 bool NonNegative = false; 10502 if (L.NonNegative) { 10503 Bits = std::min(Bits, L.Width); 10504 NonNegative = true; 10505 } 10506 if (R.NonNegative) { 10507 Bits = std::min(Bits, R.Width); 10508 NonNegative = true; 10509 } 10510 return IntRange(Bits, NonNegative); 10511 } 10512 10513 /// Return the range of a sum of the two ranges. 10514 static IntRange sum(IntRange L, IntRange R) { 10515 bool Unsigned = L.NonNegative && R.NonNegative; 10516 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10517 Unsigned); 10518 } 10519 10520 /// Return the range of a difference of the two ranges. 10521 static IntRange difference(IntRange L, IntRange R) { 10522 // We need a 1-bit-wider range if: 10523 // 1) LHS can be negative: least value can be reduced. 10524 // 2) RHS can be negative: greatest value can be increased. 10525 bool CanWiden = !L.NonNegative || !R.NonNegative; 10526 bool Unsigned = L.NonNegative && R.Width == 0; 10527 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10528 !Unsigned, 10529 Unsigned); 10530 } 10531 10532 /// Return the range of a product of the two ranges. 10533 static IntRange product(IntRange L, IntRange R) { 10534 // If both LHS and RHS can be negative, we can form 10535 // -2^L * -2^R = 2^(L + R) 10536 // which requires L + R + 1 value bits to represent. 10537 bool CanWiden = !L.NonNegative && !R.NonNegative; 10538 bool Unsigned = L.NonNegative && R.NonNegative; 10539 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10540 Unsigned); 10541 } 10542 10543 /// Return the range of a remainder operation between the two ranges. 10544 static IntRange rem(IntRange L, IntRange R) { 10545 // The result of a remainder can't be larger than the result of 10546 // either side. The sign of the result is the sign of the LHS. 10547 bool Unsigned = L.NonNegative; 10548 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10549 Unsigned); 10550 } 10551 }; 10552 10553 } // namespace 10554 10555 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10556 unsigned MaxWidth) { 10557 if (value.isSigned() && value.isNegative()) 10558 return IntRange(value.getMinSignedBits(), false); 10559 10560 if (value.getBitWidth() > MaxWidth) 10561 value = value.trunc(MaxWidth); 10562 10563 // isNonNegative() just checks the sign bit without considering 10564 // signedness. 10565 return IntRange(value.getActiveBits(), true); 10566 } 10567 10568 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10569 unsigned MaxWidth) { 10570 if (result.isInt()) 10571 return GetValueRange(C, result.getInt(), MaxWidth); 10572 10573 if (result.isVector()) { 10574 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10575 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10576 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10577 R = IntRange::join(R, El); 10578 } 10579 return R; 10580 } 10581 10582 if (result.isComplexInt()) { 10583 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10584 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10585 return IntRange::join(R, I); 10586 } 10587 10588 // This can happen with lossless casts to intptr_t of "based" lvalues. 10589 // Assume it might use arbitrary bits. 10590 // FIXME: The only reason we need to pass the type in here is to get 10591 // the sign right on this one case. It would be nice if APValue 10592 // preserved this. 10593 assert(result.isLValue() || result.isAddrLabelDiff()); 10594 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10595 } 10596 10597 static QualType GetExprType(const Expr *E) { 10598 QualType Ty = E->getType(); 10599 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10600 Ty = AtomicRHS->getValueType(); 10601 return Ty; 10602 } 10603 10604 /// Pseudo-evaluate the given integer expression, estimating the 10605 /// range of values it might take. 10606 /// 10607 /// \param MaxWidth The width to which the value will be truncated. 10608 /// \param Approximate If \c true, return a likely range for the result: in 10609 /// particular, assume that aritmetic on narrower types doesn't leave 10610 /// those types. If \c false, return a range including all possible 10611 /// result values. 10612 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10613 bool InConstantContext, bool Approximate) { 10614 E = E->IgnoreParens(); 10615 10616 // Try a full evaluation first. 10617 Expr::EvalResult result; 10618 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10619 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10620 10621 // I think we only want to look through implicit casts here; if the 10622 // user has an explicit widening cast, we should treat the value as 10623 // being of the new, wider type. 10624 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10625 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10626 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10627 Approximate); 10628 10629 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10630 10631 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10632 CE->getCastKind() == CK_BooleanToSignedIntegral; 10633 10634 // Assume that non-integer casts can span the full range of the type. 10635 if (!isIntegerCast) 10636 return OutputTypeRange; 10637 10638 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10639 std::min(MaxWidth, OutputTypeRange.Width), 10640 InConstantContext, Approximate); 10641 10642 // Bail out if the subexpr's range is as wide as the cast type. 10643 if (SubRange.Width >= OutputTypeRange.Width) 10644 return OutputTypeRange; 10645 10646 // Otherwise, we take the smaller width, and we're non-negative if 10647 // either the output type or the subexpr is. 10648 return IntRange(SubRange.Width, 10649 SubRange.NonNegative || OutputTypeRange.NonNegative); 10650 } 10651 10652 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10653 // If we can fold the condition, just take that operand. 10654 bool CondResult; 10655 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10656 return GetExprRange(C, 10657 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10658 MaxWidth, InConstantContext, Approximate); 10659 10660 // Otherwise, conservatively merge. 10661 // GetExprRange requires an integer expression, but a throw expression 10662 // results in a void type. 10663 Expr *E = CO->getTrueExpr(); 10664 IntRange L = E->getType()->isVoidType() 10665 ? IntRange{0, true} 10666 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10667 E = CO->getFalseExpr(); 10668 IntRange R = E->getType()->isVoidType() 10669 ? IntRange{0, true} 10670 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10671 return IntRange::join(L, R); 10672 } 10673 10674 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10675 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10676 10677 switch (BO->getOpcode()) { 10678 case BO_Cmp: 10679 llvm_unreachable("builtin <=> should have class type"); 10680 10681 // Boolean-valued operations are single-bit and positive. 10682 case BO_LAnd: 10683 case BO_LOr: 10684 case BO_LT: 10685 case BO_GT: 10686 case BO_LE: 10687 case BO_GE: 10688 case BO_EQ: 10689 case BO_NE: 10690 return IntRange::forBoolType(); 10691 10692 // The type of the assignments is the type of the LHS, so the RHS 10693 // is not necessarily the same type. 10694 case BO_MulAssign: 10695 case BO_DivAssign: 10696 case BO_RemAssign: 10697 case BO_AddAssign: 10698 case BO_SubAssign: 10699 case BO_XorAssign: 10700 case BO_OrAssign: 10701 // TODO: bitfields? 10702 return IntRange::forValueOfType(C, GetExprType(E)); 10703 10704 // Simple assignments just pass through the RHS, which will have 10705 // been coerced to the LHS type. 10706 case BO_Assign: 10707 // TODO: bitfields? 10708 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10709 Approximate); 10710 10711 // Operations with opaque sources are black-listed. 10712 case BO_PtrMemD: 10713 case BO_PtrMemI: 10714 return IntRange::forValueOfType(C, GetExprType(E)); 10715 10716 // Bitwise-and uses the *infinum* of the two source ranges. 10717 case BO_And: 10718 case BO_AndAssign: 10719 Combine = IntRange::bit_and; 10720 break; 10721 10722 // Left shift gets black-listed based on a judgement call. 10723 case BO_Shl: 10724 // ...except that we want to treat '1 << (blah)' as logically 10725 // positive. It's an important idiom. 10726 if (IntegerLiteral *I 10727 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10728 if (I->getValue() == 1) { 10729 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10730 return IntRange(R.Width, /*NonNegative*/ true); 10731 } 10732 } 10733 LLVM_FALLTHROUGH; 10734 10735 case BO_ShlAssign: 10736 return IntRange::forValueOfType(C, GetExprType(E)); 10737 10738 // Right shift by a constant can narrow its left argument. 10739 case BO_Shr: 10740 case BO_ShrAssign: { 10741 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10742 Approximate); 10743 10744 // If the shift amount is a positive constant, drop the width by 10745 // that much. 10746 if (Optional<llvm::APSInt> shift = 10747 BO->getRHS()->getIntegerConstantExpr(C)) { 10748 if (shift->isNonNegative()) { 10749 unsigned zext = shift->getZExtValue(); 10750 if (zext >= L.Width) 10751 L.Width = (L.NonNegative ? 0 : 1); 10752 else 10753 L.Width -= zext; 10754 } 10755 } 10756 10757 return L; 10758 } 10759 10760 // Comma acts as its right operand. 10761 case BO_Comma: 10762 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10763 Approximate); 10764 10765 case BO_Add: 10766 if (!Approximate) 10767 Combine = IntRange::sum; 10768 break; 10769 10770 case BO_Sub: 10771 if (BO->getLHS()->getType()->isPointerType()) 10772 return IntRange::forValueOfType(C, GetExprType(E)); 10773 if (!Approximate) 10774 Combine = IntRange::difference; 10775 break; 10776 10777 case BO_Mul: 10778 if (!Approximate) 10779 Combine = IntRange::product; 10780 break; 10781 10782 // The width of a division result is mostly determined by the size 10783 // of the LHS. 10784 case BO_Div: { 10785 // Don't 'pre-truncate' the operands. 10786 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10787 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 10788 Approximate); 10789 10790 // If the divisor is constant, use that. 10791 if (Optional<llvm::APSInt> divisor = 10792 BO->getRHS()->getIntegerConstantExpr(C)) { 10793 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10794 if (log2 >= L.Width) 10795 L.Width = (L.NonNegative ? 0 : 1); 10796 else 10797 L.Width = std::min(L.Width - log2, MaxWidth); 10798 return L; 10799 } 10800 10801 // Otherwise, just use the LHS's width. 10802 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10803 // could be -1. 10804 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 10805 Approximate); 10806 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10807 } 10808 10809 case BO_Rem: 10810 Combine = IntRange::rem; 10811 break; 10812 10813 // The default behavior is okay for these. 10814 case BO_Xor: 10815 case BO_Or: 10816 break; 10817 } 10818 10819 // Combine the two ranges, but limit the result to the type in which we 10820 // performed the computation. 10821 QualType T = GetExprType(E); 10822 unsigned opWidth = C.getIntWidth(T); 10823 IntRange L = 10824 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10825 IntRange R = 10826 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10827 IntRange C = Combine(L, R); 10828 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10829 C.Width = std::min(C.Width, MaxWidth); 10830 return C; 10831 } 10832 10833 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10834 switch (UO->getOpcode()) { 10835 // Boolean-valued operations are white-listed. 10836 case UO_LNot: 10837 return IntRange::forBoolType(); 10838 10839 // Operations with opaque sources are black-listed. 10840 case UO_Deref: 10841 case UO_AddrOf: // should be impossible 10842 return IntRange::forValueOfType(C, GetExprType(E)); 10843 10844 default: 10845 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 10846 Approximate); 10847 } 10848 } 10849 10850 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10851 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 10852 Approximate); 10853 10854 if (const auto *BitField = E->getSourceBitField()) 10855 return IntRange(BitField->getBitWidthValue(C), 10856 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10857 10858 return IntRange::forValueOfType(C, GetExprType(E)); 10859 } 10860 10861 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10862 bool InConstantContext, bool Approximate) { 10863 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 10864 Approximate); 10865 } 10866 10867 /// Checks whether the given value, which currently has the given 10868 /// source semantics, has the same value when coerced through the 10869 /// target semantics. 10870 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10871 const llvm::fltSemantics &Src, 10872 const llvm::fltSemantics &Tgt) { 10873 llvm::APFloat truncated = value; 10874 10875 bool ignored; 10876 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10877 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10878 10879 return truncated.bitwiseIsEqual(value); 10880 } 10881 10882 /// Checks whether the given value, which currently has the given 10883 /// source semantics, has the same value when coerced through the 10884 /// target semantics. 10885 /// 10886 /// The value might be a vector of floats (or a complex number). 10887 static bool IsSameFloatAfterCast(const APValue &value, 10888 const llvm::fltSemantics &Src, 10889 const llvm::fltSemantics &Tgt) { 10890 if (value.isFloat()) 10891 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10892 10893 if (value.isVector()) { 10894 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10895 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10896 return false; 10897 return true; 10898 } 10899 10900 assert(value.isComplexFloat()); 10901 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10902 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10903 } 10904 10905 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10906 bool IsListInit = false); 10907 10908 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10909 // Suppress cases where we are comparing against an enum constant. 10910 if (const DeclRefExpr *DR = 10911 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10912 if (isa<EnumConstantDecl>(DR->getDecl())) 10913 return true; 10914 10915 // Suppress cases where the value is expanded from a macro, unless that macro 10916 // is how a language represents a boolean literal. This is the case in both C 10917 // and Objective-C. 10918 SourceLocation BeginLoc = E->getBeginLoc(); 10919 if (BeginLoc.isMacroID()) { 10920 StringRef MacroName = Lexer::getImmediateMacroName( 10921 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10922 return MacroName != "YES" && MacroName != "NO" && 10923 MacroName != "true" && MacroName != "false"; 10924 } 10925 10926 return false; 10927 } 10928 10929 static bool isKnownToHaveUnsignedValue(Expr *E) { 10930 return E->getType()->isIntegerType() && 10931 (!E->getType()->isSignedIntegerType() || 10932 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10933 } 10934 10935 namespace { 10936 /// The promoted range of values of a type. In general this has the 10937 /// following structure: 10938 /// 10939 /// |-----------| . . . |-----------| 10940 /// ^ ^ ^ ^ 10941 /// Min HoleMin HoleMax Max 10942 /// 10943 /// ... where there is only a hole if a signed type is promoted to unsigned 10944 /// (in which case Min and Max are the smallest and largest representable 10945 /// values). 10946 struct PromotedRange { 10947 // Min, or HoleMax if there is a hole. 10948 llvm::APSInt PromotedMin; 10949 // Max, or HoleMin if there is a hole. 10950 llvm::APSInt PromotedMax; 10951 10952 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10953 if (R.Width == 0) 10954 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10955 else if (R.Width >= BitWidth && !Unsigned) { 10956 // Promotion made the type *narrower*. This happens when promoting 10957 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10958 // Treat all values of 'signed int' as being in range for now. 10959 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10960 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10961 } else { 10962 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10963 .extOrTrunc(BitWidth); 10964 PromotedMin.setIsUnsigned(Unsigned); 10965 10966 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10967 .extOrTrunc(BitWidth); 10968 PromotedMax.setIsUnsigned(Unsigned); 10969 } 10970 } 10971 10972 // Determine whether this range is contiguous (has no hole). 10973 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10974 10975 // Where a constant value is within the range. 10976 enum ComparisonResult { 10977 LT = 0x1, 10978 LE = 0x2, 10979 GT = 0x4, 10980 GE = 0x8, 10981 EQ = 0x10, 10982 NE = 0x20, 10983 InRangeFlag = 0x40, 10984 10985 Less = LE | LT | NE, 10986 Min = LE | InRangeFlag, 10987 InRange = InRangeFlag, 10988 Max = GE | InRangeFlag, 10989 Greater = GE | GT | NE, 10990 10991 OnlyValue = LE | GE | EQ | InRangeFlag, 10992 InHole = NE 10993 }; 10994 10995 ComparisonResult compare(const llvm::APSInt &Value) const { 10996 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10997 Value.isUnsigned() == PromotedMin.isUnsigned()); 10998 if (!isContiguous()) { 10999 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11000 if (Value.isMinValue()) return Min; 11001 if (Value.isMaxValue()) return Max; 11002 if (Value >= PromotedMin) return InRange; 11003 if (Value <= PromotedMax) return InRange; 11004 return InHole; 11005 } 11006 11007 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11008 case -1: return Less; 11009 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11010 case 1: 11011 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11012 case -1: return InRange; 11013 case 0: return Max; 11014 case 1: return Greater; 11015 } 11016 } 11017 11018 llvm_unreachable("impossible compare result"); 11019 } 11020 11021 static llvm::Optional<StringRef> 11022 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11023 if (Op == BO_Cmp) { 11024 ComparisonResult LTFlag = LT, GTFlag = GT; 11025 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11026 11027 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11028 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11029 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11030 return llvm::None; 11031 } 11032 11033 ComparisonResult TrueFlag, FalseFlag; 11034 if (Op == BO_EQ) { 11035 TrueFlag = EQ; 11036 FalseFlag = NE; 11037 } else if (Op == BO_NE) { 11038 TrueFlag = NE; 11039 FalseFlag = EQ; 11040 } else { 11041 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11042 TrueFlag = LT; 11043 FalseFlag = GE; 11044 } else { 11045 TrueFlag = GT; 11046 FalseFlag = LE; 11047 } 11048 if (Op == BO_GE || Op == BO_LE) 11049 std::swap(TrueFlag, FalseFlag); 11050 } 11051 if (R & TrueFlag) 11052 return StringRef("true"); 11053 if (R & FalseFlag) 11054 return StringRef("false"); 11055 return llvm::None; 11056 } 11057 }; 11058 } 11059 11060 static bool HasEnumType(Expr *E) { 11061 // Strip off implicit integral promotions. 11062 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11063 if (ICE->getCastKind() != CK_IntegralCast && 11064 ICE->getCastKind() != CK_NoOp) 11065 break; 11066 E = ICE->getSubExpr(); 11067 } 11068 11069 return E->getType()->isEnumeralType(); 11070 } 11071 11072 static int classifyConstantValue(Expr *Constant) { 11073 // The values of this enumeration are used in the diagnostics 11074 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11075 enum ConstantValueKind { 11076 Miscellaneous = 0, 11077 LiteralTrue, 11078 LiteralFalse 11079 }; 11080 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11081 return BL->getValue() ? ConstantValueKind::LiteralTrue 11082 : ConstantValueKind::LiteralFalse; 11083 return ConstantValueKind::Miscellaneous; 11084 } 11085 11086 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11087 Expr *Constant, Expr *Other, 11088 const llvm::APSInt &Value, 11089 bool RhsConstant) { 11090 if (S.inTemplateInstantiation()) 11091 return false; 11092 11093 Expr *OriginalOther = Other; 11094 11095 Constant = Constant->IgnoreParenImpCasts(); 11096 Other = Other->IgnoreParenImpCasts(); 11097 11098 // Suppress warnings on tautological comparisons between values of the same 11099 // enumeration type. There are only two ways we could warn on this: 11100 // - If the constant is outside the range of representable values of 11101 // the enumeration. In such a case, we should warn about the cast 11102 // to enumeration type, not about the comparison. 11103 // - If the constant is the maximum / minimum in-range value. For an 11104 // enumeratin type, such comparisons can be meaningful and useful. 11105 if (Constant->getType()->isEnumeralType() && 11106 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11107 return false; 11108 11109 IntRange OtherValueRange = GetExprRange( 11110 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11111 11112 QualType OtherT = Other->getType(); 11113 if (const auto *AT = OtherT->getAs<AtomicType>()) 11114 OtherT = AT->getValueType(); 11115 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11116 11117 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11118 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11119 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11120 S.NSAPIObj->isObjCBOOLType(OtherT) && 11121 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11122 11123 // Whether we're treating Other as being a bool because of the form of 11124 // expression despite it having another type (typically 'int' in C). 11125 bool OtherIsBooleanDespiteType = 11126 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11127 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11128 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11129 11130 // Check if all values in the range of possible values of this expression 11131 // lead to the same comparison outcome. 11132 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11133 Value.isUnsigned()); 11134 auto Cmp = OtherPromotedValueRange.compare(Value); 11135 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11136 if (!Result) 11137 return false; 11138 11139 // Also consider the range determined by the type alone. This allows us to 11140 // classify the warning under the proper diagnostic group. 11141 bool TautologicalTypeCompare = false; 11142 { 11143 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11144 Value.isUnsigned()); 11145 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11146 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11147 RhsConstant)) { 11148 TautologicalTypeCompare = true; 11149 Cmp = TypeCmp; 11150 Result = TypeResult; 11151 } 11152 } 11153 11154 // Don't warn if the non-constant operand actually always evaluates to the 11155 // same value. 11156 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11157 return false; 11158 11159 // Suppress the diagnostic for an in-range comparison if the constant comes 11160 // from a macro or enumerator. We don't want to diagnose 11161 // 11162 // some_long_value <= INT_MAX 11163 // 11164 // when sizeof(int) == sizeof(long). 11165 bool InRange = Cmp & PromotedRange::InRangeFlag; 11166 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11167 return false; 11168 11169 // A comparison of an unsigned bit-field against 0 is really a type problem, 11170 // even though at the type level the bit-field might promote to 'signed int'. 11171 if (Other->refersToBitField() && InRange && Value == 0 && 11172 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11173 TautologicalTypeCompare = true; 11174 11175 // If this is a comparison to an enum constant, include that 11176 // constant in the diagnostic. 11177 const EnumConstantDecl *ED = nullptr; 11178 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11179 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11180 11181 // Should be enough for uint128 (39 decimal digits) 11182 SmallString<64> PrettySourceValue; 11183 llvm::raw_svector_ostream OS(PrettySourceValue); 11184 if (ED) { 11185 OS << '\'' << *ED << "' (" << Value << ")"; 11186 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11187 Constant->IgnoreParenImpCasts())) { 11188 OS << (BL->getValue() ? "YES" : "NO"); 11189 } else { 11190 OS << Value; 11191 } 11192 11193 if (!TautologicalTypeCompare) { 11194 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11195 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11196 << E->getOpcodeStr() << OS.str() << *Result 11197 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11198 return true; 11199 } 11200 11201 if (IsObjCSignedCharBool) { 11202 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11203 S.PDiag(diag::warn_tautological_compare_objc_bool) 11204 << OS.str() << *Result); 11205 return true; 11206 } 11207 11208 // FIXME: We use a somewhat different formatting for the in-range cases and 11209 // cases involving boolean values for historical reasons. We should pick a 11210 // consistent way of presenting these diagnostics. 11211 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11212 11213 S.DiagRuntimeBehavior( 11214 E->getOperatorLoc(), E, 11215 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11216 : diag::warn_tautological_bool_compare) 11217 << OS.str() << classifyConstantValue(Constant) << OtherT 11218 << OtherIsBooleanDespiteType << *Result 11219 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11220 } else { 11221 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11222 ? (HasEnumType(OriginalOther) 11223 ? diag::warn_unsigned_enum_always_true_comparison 11224 : diag::warn_unsigned_always_true_comparison) 11225 : diag::warn_tautological_constant_compare; 11226 11227 S.Diag(E->getOperatorLoc(), Diag) 11228 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11229 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11230 } 11231 11232 return true; 11233 } 11234 11235 /// Analyze the operands of the given comparison. Implements the 11236 /// fallback case from AnalyzeComparison. 11237 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11238 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11239 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11240 } 11241 11242 /// Implements -Wsign-compare. 11243 /// 11244 /// \param E the binary operator to check for warnings 11245 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11246 // The type the comparison is being performed in. 11247 QualType T = E->getLHS()->getType(); 11248 11249 // Only analyze comparison operators where both sides have been converted to 11250 // the same type. 11251 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11252 return AnalyzeImpConvsInComparison(S, E); 11253 11254 // Don't analyze value-dependent comparisons directly. 11255 if (E->isValueDependent()) 11256 return AnalyzeImpConvsInComparison(S, E); 11257 11258 Expr *LHS = E->getLHS(); 11259 Expr *RHS = E->getRHS(); 11260 11261 if (T->isIntegralType(S.Context)) { 11262 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11263 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11264 11265 // We don't care about expressions whose result is a constant. 11266 if (RHSValue && LHSValue) 11267 return AnalyzeImpConvsInComparison(S, E); 11268 11269 // We only care about expressions where just one side is literal 11270 if ((bool)RHSValue ^ (bool)LHSValue) { 11271 // Is the constant on the RHS or LHS? 11272 const bool RhsConstant = (bool)RHSValue; 11273 Expr *Const = RhsConstant ? RHS : LHS; 11274 Expr *Other = RhsConstant ? LHS : RHS; 11275 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11276 11277 // Check whether an integer constant comparison results in a value 11278 // of 'true' or 'false'. 11279 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11280 return AnalyzeImpConvsInComparison(S, E); 11281 } 11282 } 11283 11284 if (!T->hasUnsignedIntegerRepresentation()) { 11285 // We don't do anything special if this isn't an unsigned integral 11286 // comparison: we're only interested in integral comparisons, and 11287 // signed comparisons only happen in cases we don't care to warn about. 11288 return AnalyzeImpConvsInComparison(S, E); 11289 } 11290 11291 LHS = LHS->IgnoreParenImpCasts(); 11292 RHS = RHS->IgnoreParenImpCasts(); 11293 11294 if (!S.getLangOpts().CPlusPlus) { 11295 // Avoid warning about comparison of integers with different signs when 11296 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11297 // the type of `E`. 11298 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11299 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11300 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11301 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11302 } 11303 11304 // Check to see if one of the (unmodified) operands is of different 11305 // signedness. 11306 Expr *signedOperand, *unsignedOperand; 11307 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11308 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11309 "unsigned comparison between two signed integer expressions?"); 11310 signedOperand = LHS; 11311 unsignedOperand = RHS; 11312 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11313 signedOperand = RHS; 11314 unsignedOperand = LHS; 11315 } else { 11316 return AnalyzeImpConvsInComparison(S, E); 11317 } 11318 11319 // Otherwise, calculate the effective range of the signed operand. 11320 IntRange signedRange = GetExprRange( 11321 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11322 11323 // Go ahead and analyze implicit conversions in the operands. Note 11324 // that we skip the implicit conversions on both sides. 11325 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11326 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11327 11328 // If the signed range is non-negative, -Wsign-compare won't fire. 11329 if (signedRange.NonNegative) 11330 return; 11331 11332 // For (in)equality comparisons, if the unsigned operand is a 11333 // constant which cannot collide with a overflowed signed operand, 11334 // then reinterpreting the signed operand as unsigned will not 11335 // change the result of the comparison. 11336 if (E->isEqualityOp()) { 11337 unsigned comparisonWidth = S.Context.getIntWidth(T); 11338 IntRange unsignedRange = 11339 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11340 /*Approximate*/ true); 11341 11342 // We should never be unable to prove that the unsigned operand is 11343 // non-negative. 11344 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11345 11346 if (unsignedRange.Width < comparisonWidth) 11347 return; 11348 } 11349 11350 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11351 S.PDiag(diag::warn_mixed_sign_comparison) 11352 << LHS->getType() << RHS->getType() 11353 << LHS->getSourceRange() << RHS->getSourceRange()); 11354 } 11355 11356 /// Analyzes an attempt to assign the given value to a bitfield. 11357 /// 11358 /// Returns true if there was something fishy about the attempt. 11359 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11360 SourceLocation InitLoc) { 11361 assert(Bitfield->isBitField()); 11362 if (Bitfield->isInvalidDecl()) 11363 return false; 11364 11365 // White-list bool bitfields. 11366 QualType BitfieldType = Bitfield->getType(); 11367 if (BitfieldType->isBooleanType()) 11368 return false; 11369 11370 if (BitfieldType->isEnumeralType()) { 11371 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11372 // If the underlying enum type was not explicitly specified as an unsigned 11373 // type and the enum contain only positive values, MSVC++ will cause an 11374 // inconsistency by storing this as a signed type. 11375 if (S.getLangOpts().CPlusPlus11 && 11376 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11377 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11378 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11379 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11380 << BitfieldEnumDecl; 11381 } 11382 } 11383 11384 if (Bitfield->getType()->isBooleanType()) 11385 return false; 11386 11387 // Ignore value- or type-dependent expressions. 11388 if (Bitfield->getBitWidth()->isValueDependent() || 11389 Bitfield->getBitWidth()->isTypeDependent() || 11390 Init->isValueDependent() || 11391 Init->isTypeDependent()) 11392 return false; 11393 11394 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11395 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11396 11397 Expr::EvalResult Result; 11398 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11399 Expr::SE_AllowSideEffects)) { 11400 // The RHS is not constant. If the RHS has an enum type, make sure the 11401 // bitfield is wide enough to hold all the values of the enum without 11402 // truncation. 11403 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11404 EnumDecl *ED = EnumTy->getDecl(); 11405 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11406 11407 // Enum types are implicitly signed on Windows, so check if there are any 11408 // negative enumerators to see if the enum was intended to be signed or 11409 // not. 11410 bool SignedEnum = ED->getNumNegativeBits() > 0; 11411 11412 // Check for surprising sign changes when assigning enum values to a 11413 // bitfield of different signedness. If the bitfield is signed and we 11414 // have exactly the right number of bits to store this unsigned enum, 11415 // suggest changing the enum to an unsigned type. This typically happens 11416 // on Windows where unfixed enums always use an underlying type of 'int'. 11417 unsigned DiagID = 0; 11418 if (SignedEnum && !SignedBitfield) { 11419 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11420 } else if (SignedBitfield && !SignedEnum && 11421 ED->getNumPositiveBits() == FieldWidth) { 11422 DiagID = diag::warn_signed_bitfield_enum_conversion; 11423 } 11424 11425 if (DiagID) { 11426 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11427 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11428 SourceRange TypeRange = 11429 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11430 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11431 << SignedEnum << TypeRange; 11432 } 11433 11434 // Compute the required bitwidth. If the enum has negative values, we need 11435 // one more bit than the normal number of positive bits to represent the 11436 // sign bit. 11437 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11438 ED->getNumNegativeBits()) 11439 : ED->getNumPositiveBits(); 11440 11441 // Check the bitwidth. 11442 if (BitsNeeded > FieldWidth) { 11443 Expr *WidthExpr = Bitfield->getBitWidth(); 11444 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11445 << Bitfield << ED; 11446 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11447 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11448 } 11449 } 11450 11451 return false; 11452 } 11453 11454 llvm::APSInt Value = Result.Val.getInt(); 11455 11456 unsigned OriginalWidth = Value.getBitWidth(); 11457 11458 if (!Value.isSigned() || Value.isNegative()) 11459 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11460 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11461 OriginalWidth = Value.getMinSignedBits(); 11462 11463 if (OriginalWidth <= FieldWidth) 11464 return false; 11465 11466 // Compute the value which the bitfield will contain. 11467 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11468 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11469 11470 // Check whether the stored value is equal to the original value. 11471 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11472 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11473 return false; 11474 11475 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11476 // therefore don't strictly fit into a signed bitfield of width 1. 11477 if (FieldWidth == 1 && Value == 1) 11478 return false; 11479 11480 std::string PrettyValue = Value.toString(10); 11481 std::string PrettyTrunc = TruncatedValue.toString(10); 11482 11483 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11484 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11485 << Init->getSourceRange(); 11486 11487 return true; 11488 } 11489 11490 /// Analyze the given simple or compound assignment for warning-worthy 11491 /// operations. 11492 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11493 // Just recurse on the LHS. 11494 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11495 11496 // We want to recurse on the RHS as normal unless we're assigning to 11497 // a bitfield. 11498 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11499 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11500 E->getOperatorLoc())) { 11501 // Recurse, ignoring any implicit conversions on the RHS. 11502 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11503 E->getOperatorLoc()); 11504 } 11505 } 11506 11507 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11508 11509 // Diagnose implicitly sequentially-consistent atomic assignment. 11510 if (E->getLHS()->getType()->isAtomicType()) 11511 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11512 } 11513 11514 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11515 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11516 SourceLocation CContext, unsigned diag, 11517 bool pruneControlFlow = false) { 11518 if (pruneControlFlow) { 11519 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11520 S.PDiag(diag) 11521 << SourceType << T << E->getSourceRange() 11522 << SourceRange(CContext)); 11523 return; 11524 } 11525 S.Diag(E->getExprLoc(), diag) 11526 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11527 } 11528 11529 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11530 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11531 SourceLocation CContext, 11532 unsigned diag, bool pruneControlFlow = false) { 11533 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11534 } 11535 11536 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11537 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11538 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11539 } 11540 11541 static void adornObjCBoolConversionDiagWithTernaryFixit( 11542 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11543 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11544 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11545 Ignored = OVE->getSourceExpr(); 11546 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11547 isa<BinaryOperator>(Ignored) || 11548 isa<CXXOperatorCallExpr>(Ignored); 11549 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11550 if (NeedsParens) 11551 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11552 << FixItHint::CreateInsertion(EndLoc, ")"); 11553 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11554 } 11555 11556 /// Diagnose an implicit cast from a floating point value to an integer value. 11557 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11558 SourceLocation CContext) { 11559 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11560 const bool PruneWarnings = S.inTemplateInstantiation(); 11561 11562 Expr *InnerE = E->IgnoreParenImpCasts(); 11563 // We also want to warn on, e.g., "int i = -1.234" 11564 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11565 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11566 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11567 11568 const bool IsLiteral = 11569 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11570 11571 llvm::APFloat Value(0.0); 11572 bool IsConstant = 11573 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11574 if (!IsConstant) { 11575 if (isObjCSignedCharBool(S, T)) { 11576 return adornObjCBoolConversionDiagWithTernaryFixit( 11577 S, E, 11578 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11579 << E->getType()); 11580 } 11581 11582 return DiagnoseImpCast(S, E, T, CContext, 11583 diag::warn_impcast_float_integer, PruneWarnings); 11584 } 11585 11586 bool isExact = false; 11587 11588 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11589 T->hasUnsignedIntegerRepresentation()); 11590 llvm::APFloat::opStatus Result = Value.convertToInteger( 11591 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11592 11593 // FIXME: Force the precision of the source value down so we don't print 11594 // digits which are usually useless (we don't really care here if we 11595 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11596 // would automatically print the shortest representation, but it's a bit 11597 // tricky to implement. 11598 SmallString<16> PrettySourceValue; 11599 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11600 precision = (precision * 59 + 195) / 196; 11601 Value.toString(PrettySourceValue, precision); 11602 11603 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11604 return adornObjCBoolConversionDiagWithTernaryFixit( 11605 S, E, 11606 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11607 << PrettySourceValue); 11608 } 11609 11610 if (Result == llvm::APFloat::opOK && isExact) { 11611 if (IsLiteral) return; 11612 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11613 PruneWarnings); 11614 } 11615 11616 // Conversion of a floating-point value to a non-bool integer where the 11617 // integral part cannot be represented by the integer type is undefined. 11618 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11619 return DiagnoseImpCast( 11620 S, E, T, CContext, 11621 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11622 : diag::warn_impcast_float_to_integer_out_of_range, 11623 PruneWarnings); 11624 11625 unsigned DiagID = 0; 11626 if (IsLiteral) { 11627 // Warn on floating point literal to integer. 11628 DiagID = diag::warn_impcast_literal_float_to_integer; 11629 } else if (IntegerValue == 0) { 11630 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11631 return DiagnoseImpCast(S, E, T, CContext, 11632 diag::warn_impcast_float_integer, PruneWarnings); 11633 } 11634 // Warn on non-zero to zero conversion. 11635 DiagID = diag::warn_impcast_float_to_integer_zero; 11636 } else { 11637 if (IntegerValue.isUnsigned()) { 11638 if (!IntegerValue.isMaxValue()) { 11639 return DiagnoseImpCast(S, E, T, CContext, 11640 diag::warn_impcast_float_integer, PruneWarnings); 11641 } 11642 } else { // IntegerValue.isSigned() 11643 if (!IntegerValue.isMaxSignedValue() && 11644 !IntegerValue.isMinSignedValue()) { 11645 return DiagnoseImpCast(S, E, T, CContext, 11646 diag::warn_impcast_float_integer, PruneWarnings); 11647 } 11648 } 11649 // Warn on evaluatable floating point expression to integer conversion. 11650 DiagID = diag::warn_impcast_float_to_integer; 11651 } 11652 11653 SmallString<16> PrettyTargetValue; 11654 if (IsBool) 11655 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11656 else 11657 IntegerValue.toString(PrettyTargetValue); 11658 11659 if (PruneWarnings) { 11660 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11661 S.PDiag(DiagID) 11662 << E->getType() << T.getUnqualifiedType() 11663 << PrettySourceValue << PrettyTargetValue 11664 << E->getSourceRange() << SourceRange(CContext)); 11665 } else { 11666 S.Diag(E->getExprLoc(), DiagID) 11667 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11668 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11669 } 11670 } 11671 11672 /// Analyze the given compound assignment for the possible losing of 11673 /// floating-point precision. 11674 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11675 assert(isa<CompoundAssignOperator>(E) && 11676 "Must be compound assignment operation"); 11677 // Recurse on the LHS and RHS in here 11678 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11679 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11680 11681 if (E->getLHS()->getType()->isAtomicType()) 11682 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11683 11684 // Now check the outermost expression 11685 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11686 const auto *RBT = cast<CompoundAssignOperator>(E) 11687 ->getComputationResultType() 11688 ->getAs<BuiltinType>(); 11689 11690 // The below checks assume source is floating point. 11691 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11692 11693 // If source is floating point but target is an integer. 11694 if (ResultBT->isInteger()) 11695 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11696 E->getExprLoc(), diag::warn_impcast_float_integer); 11697 11698 if (!ResultBT->isFloatingPoint()) 11699 return; 11700 11701 // If both source and target are floating points, warn about losing precision. 11702 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11703 QualType(ResultBT, 0), QualType(RBT, 0)); 11704 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11705 // warn about dropping FP rank. 11706 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11707 diag::warn_impcast_float_result_precision); 11708 } 11709 11710 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11711 IntRange Range) { 11712 if (!Range.Width) return "0"; 11713 11714 llvm::APSInt ValueInRange = Value; 11715 ValueInRange.setIsSigned(!Range.NonNegative); 11716 ValueInRange = ValueInRange.trunc(Range.Width); 11717 return ValueInRange.toString(10); 11718 } 11719 11720 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11721 if (!isa<ImplicitCastExpr>(Ex)) 11722 return false; 11723 11724 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11725 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11726 const Type *Source = 11727 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11728 if (Target->isDependentType()) 11729 return false; 11730 11731 const BuiltinType *FloatCandidateBT = 11732 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11733 const Type *BoolCandidateType = ToBool ? Target : Source; 11734 11735 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11736 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11737 } 11738 11739 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11740 SourceLocation CC) { 11741 unsigned NumArgs = TheCall->getNumArgs(); 11742 for (unsigned i = 0; i < NumArgs; ++i) { 11743 Expr *CurrA = TheCall->getArg(i); 11744 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11745 continue; 11746 11747 bool IsSwapped = ((i > 0) && 11748 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11749 IsSwapped |= ((i < (NumArgs - 1)) && 11750 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11751 if (IsSwapped) { 11752 // Warn on this floating-point to bool conversion. 11753 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11754 CurrA->getType(), CC, 11755 diag::warn_impcast_floating_point_to_bool); 11756 } 11757 } 11758 } 11759 11760 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11761 SourceLocation CC) { 11762 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11763 E->getExprLoc())) 11764 return; 11765 11766 // Don't warn on functions which have return type nullptr_t. 11767 if (isa<CallExpr>(E)) 11768 return; 11769 11770 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11771 const Expr::NullPointerConstantKind NullKind = 11772 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11773 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11774 return; 11775 11776 // Return if target type is a safe conversion. 11777 if (T->isAnyPointerType() || T->isBlockPointerType() || 11778 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11779 return; 11780 11781 SourceLocation Loc = E->getSourceRange().getBegin(); 11782 11783 // Venture through the macro stacks to get to the source of macro arguments. 11784 // The new location is a better location than the complete location that was 11785 // passed in. 11786 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11787 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11788 11789 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11790 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11791 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11792 Loc, S.SourceMgr, S.getLangOpts()); 11793 if (MacroName == "NULL") 11794 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11795 } 11796 11797 // Only warn if the null and context location are in the same macro expansion. 11798 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11799 return; 11800 11801 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11802 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11803 << FixItHint::CreateReplacement(Loc, 11804 S.getFixItZeroLiteralForType(T, Loc)); 11805 } 11806 11807 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11808 ObjCArrayLiteral *ArrayLiteral); 11809 11810 static void 11811 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11812 ObjCDictionaryLiteral *DictionaryLiteral); 11813 11814 /// Check a single element within a collection literal against the 11815 /// target element type. 11816 static void checkObjCCollectionLiteralElement(Sema &S, 11817 QualType TargetElementType, 11818 Expr *Element, 11819 unsigned ElementKind) { 11820 // Skip a bitcast to 'id' or qualified 'id'. 11821 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11822 if (ICE->getCastKind() == CK_BitCast && 11823 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11824 Element = ICE->getSubExpr(); 11825 } 11826 11827 QualType ElementType = Element->getType(); 11828 ExprResult ElementResult(Element); 11829 if (ElementType->getAs<ObjCObjectPointerType>() && 11830 S.CheckSingleAssignmentConstraints(TargetElementType, 11831 ElementResult, 11832 false, false) 11833 != Sema::Compatible) { 11834 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11835 << ElementType << ElementKind << TargetElementType 11836 << Element->getSourceRange(); 11837 } 11838 11839 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11840 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11841 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11842 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11843 } 11844 11845 /// Check an Objective-C array literal being converted to the given 11846 /// target type. 11847 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11848 ObjCArrayLiteral *ArrayLiteral) { 11849 if (!S.NSArrayDecl) 11850 return; 11851 11852 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11853 if (!TargetObjCPtr) 11854 return; 11855 11856 if (TargetObjCPtr->isUnspecialized() || 11857 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11858 != S.NSArrayDecl->getCanonicalDecl()) 11859 return; 11860 11861 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11862 if (TypeArgs.size() != 1) 11863 return; 11864 11865 QualType TargetElementType = TypeArgs[0]; 11866 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11867 checkObjCCollectionLiteralElement(S, TargetElementType, 11868 ArrayLiteral->getElement(I), 11869 0); 11870 } 11871 } 11872 11873 /// Check an Objective-C dictionary literal being converted to the given 11874 /// target type. 11875 static void 11876 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11877 ObjCDictionaryLiteral *DictionaryLiteral) { 11878 if (!S.NSDictionaryDecl) 11879 return; 11880 11881 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11882 if (!TargetObjCPtr) 11883 return; 11884 11885 if (TargetObjCPtr->isUnspecialized() || 11886 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11887 != S.NSDictionaryDecl->getCanonicalDecl()) 11888 return; 11889 11890 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11891 if (TypeArgs.size() != 2) 11892 return; 11893 11894 QualType TargetKeyType = TypeArgs[0]; 11895 QualType TargetObjectType = TypeArgs[1]; 11896 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11897 auto Element = DictionaryLiteral->getKeyValueElement(I); 11898 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11899 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11900 } 11901 } 11902 11903 // Helper function to filter out cases for constant width constant conversion. 11904 // Don't warn on char array initialization or for non-decimal values. 11905 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11906 SourceLocation CC) { 11907 // If initializing from a constant, and the constant starts with '0', 11908 // then it is a binary, octal, or hexadecimal. Allow these constants 11909 // to fill all the bits, even if there is a sign change. 11910 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11911 const char FirstLiteralCharacter = 11912 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11913 if (FirstLiteralCharacter == '0') 11914 return false; 11915 } 11916 11917 // If the CC location points to a '{', and the type is char, then assume 11918 // assume it is an array initialization. 11919 if (CC.isValid() && T->isCharType()) { 11920 const char FirstContextCharacter = 11921 S.getSourceManager().getCharacterData(CC)[0]; 11922 if (FirstContextCharacter == '{') 11923 return false; 11924 } 11925 11926 return true; 11927 } 11928 11929 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11930 const auto *IL = dyn_cast<IntegerLiteral>(E); 11931 if (!IL) { 11932 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11933 if (UO->getOpcode() == UO_Minus) 11934 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11935 } 11936 } 11937 11938 return IL; 11939 } 11940 11941 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11942 E = E->IgnoreParenImpCasts(); 11943 SourceLocation ExprLoc = E->getExprLoc(); 11944 11945 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11946 BinaryOperator::Opcode Opc = BO->getOpcode(); 11947 Expr::EvalResult Result; 11948 // Do not diagnose unsigned shifts. 11949 if (Opc == BO_Shl) { 11950 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11951 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11952 if (LHS && LHS->getValue() == 0) 11953 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11954 else if (!E->isValueDependent() && LHS && RHS && 11955 RHS->getValue().isNonNegative() && 11956 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11957 S.Diag(ExprLoc, diag::warn_left_shift_always) 11958 << (Result.Val.getInt() != 0); 11959 else if (E->getType()->isSignedIntegerType()) 11960 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11961 } 11962 } 11963 11964 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11965 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11966 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11967 if (!LHS || !RHS) 11968 return; 11969 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11970 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11971 // Do not diagnose common idioms. 11972 return; 11973 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11974 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11975 } 11976 } 11977 11978 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11979 SourceLocation CC, 11980 bool *ICContext = nullptr, 11981 bool IsListInit = false) { 11982 if (E->isTypeDependent() || E->isValueDependent()) return; 11983 11984 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11985 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11986 if (Source == Target) return; 11987 if (Target->isDependentType()) return; 11988 11989 // If the conversion context location is invalid don't complain. We also 11990 // don't want to emit a warning if the issue occurs from the expansion of 11991 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11992 // delay this check as long as possible. Once we detect we are in that 11993 // scenario, we just return. 11994 if (CC.isInvalid()) 11995 return; 11996 11997 if (Source->isAtomicType()) 11998 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11999 12000 // Diagnose implicit casts to bool. 12001 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12002 if (isa<StringLiteral>(E)) 12003 // Warn on string literal to bool. Checks for string literals in logical 12004 // and expressions, for instance, assert(0 && "error here"), are 12005 // prevented by a check in AnalyzeImplicitConversions(). 12006 return DiagnoseImpCast(S, E, T, CC, 12007 diag::warn_impcast_string_literal_to_bool); 12008 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12009 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12010 // This covers the literal expressions that evaluate to Objective-C 12011 // objects. 12012 return DiagnoseImpCast(S, E, T, CC, 12013 diag::warn_impcast_objective_c_literal_to_bool); 12014 } 12015 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12016 // Warn on pointer to bool conversion that is always true. 12017 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12018 SourceRange(CC)); 12019 } 12020 } 12021 12022 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12023 // is a typedef for signed char (macOS), then that constant value has to be 1 12024 // or 0. 12025 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12026 Expr::EvalResult Result; 12027 if (E->EvaluateAsInt(Result, S.getASTContext(), 12028 Expr::SE_AllowSideEffects)) { 12029 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12030 adornObjCBoolConversionDiagWithTernaryFixit( 12031 S, E, 12032 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12033 << Result.Val.getInt().toString(10)); 12034 } 12035 return; 12036 } 12037 } 12038 12039 // Check implicit casts from Objective-C collection literals to specialized 12040 // collection types, e.g., NSArray<NSString *> *. 12041 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12042 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12043 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12044 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12045 12046 // Strip vector types. 12047 if (isa<VectorType>(Source)) { 12048 if (!isa<VectorType>(Target)) { 12049 if (S.SourceMgr.isInSystemMacro(CC)) 12050 return; 12051 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12052 } 12053 12054 // If the vector cast is cast between two vectors of the same size, it is 12055 // a bitcast, not a conversion. 12056 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12057 return; 12058 12059 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12060 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12061 } 12062 if (auto VecTy = dyn_cast<VectorType>(Target)) 12063 Target = VecTy->getElementType().getTypePtr(); 12064 12065 // Strip complex types. 12066 if (isa<ComplexType>(Source)) { 12067 if (!isa<ComplexType>(Target)) { 12068 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12069 return; 12070 12071 return DiagnoseImpCast(S, E, T, CC, 12072 S.getLangOpts().CPlusPlus 12073 ? diag::err_impcast_complex_scalar 12074 : diag::warn_impcast_complex_scalar); 12075 } 12076 12077 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12078 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12079 } 12080 12081 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12082 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12083 12084 // If the source is floating point... 12085 if (SourceBT && SourceBT->isFloatingPoint()) { 12086 // ...and the target is floating point... 12087 if (TargetBT && TargetBT->isFloatingPoint()) { 12088 // ...then warn if we're dropping FP rank. 12089 12090 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12091 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12092 if (Order > 0) { 12093 // Don't warn about float constants that are precisely 12094 // representable in the target type. 12095 Expr::EvalResult result; 12096 if (E->EvaluateAsRValue(result, S.Context)) { 12097 // Value might be a float, a float vector, or a float complex. 12098 if (IsSameFloatAfterCast(result.Val, 12099 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12100 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12101 return; 12102 } 12103 12104 if (S.SourceMgr.isInSystemMacro(CC)) 12105 return; 12106 12107 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12108 } 12109 // ... or possibly if we're increasing rank, too 12110 else if (Order < 0) { 12111 if (S.SourceMgr.isInSystemMacro(CC)) 12112 return; 12113 12114 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12115 } 12116 return; 12117 } 12118 12119 // If the target is integral, always warn. 12120 if (TargetBT && TargetBT->isInteger()) { 12121 if (S.SourceMgr.isInSystemMacro(CC)) 12122 return; 12123 12124 DiagnoseFloatingImpCast(S, E, T, CC); 12125 } 12126 12127 // Detect the case where a call result is converted from floating-point to 12128 // to bool, and the final argument to the call is converted from bool, to 12129 // discover this typo: 12130 // 12131 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12132 // 12133 // FIXME: This is an incredibly special case; is there some more general 12134 // way to detect this class of misplaced-parentheses bug? 12135 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12136 // Check last argument of function call to see if it is an 12137 // implicit cast from a type matching the type the result 12138 // is being cast to. 12139 CallExpr *CEx = cast<CallExpr>(E); 12140 if (unsigned NumArgs = CEx->getNumArgs()) { 12141 Expr *LastA = CEx->getArg(NumArgs - 1); 12142 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12143 if (isa<ImplicitCastExpr>(LastA) && 12144 InnerE->getType()->isBooleanType()) { 12145 // Warn on this floating-point to bool conversion 12146 DiagnoseImpCast(S, E, T, CC, 12147 diag::warn_impcast_floating_point_to_bool); 12148 } 12149 } 12150 } 12151 return; 12152 } 12153 12154 // Valid casts involving fixed point types should be accounted for here. 12155 if (Source->isFixedPointType()) { 12156 if (Target->isUnsaturatedFixedPointType()) { 12157 Expr::EvalResult Result; 12158 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12159 S.isConstantEvaluated())) { 12160 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12161 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12162 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12163 if (Value > MaxVal || Value < MinVal) { 12164 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12165 S.PDiag(diag::warn_impcast_fixed_point_range) 12166 << Value.toString() << T 12167 << E->getSourceRange() 12168 << clang::SourceRange(CC)); 12169 return; 12170 } 12171 } 12172 } else if (Target->isIntegerType()) { 12173 Expr::EvalResult Result; 12174 if (!S.isConstantEvaluated() && 12175 E->EvaluateAsFixedPoint(Result, S.Context, 12176 Expr::SE_AllowSideEffects)) { 12177 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12178 12179 bool Overflowed; 12180 llvm::APSInt IntResult = FXResult.convertToInt( 12181 S.Context.getIntWidth(T), 12182 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12183 12184 if (Overflowed) { 12185 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12186 S.PDiag(diag::warn_impcast_fixed_point_range) 12187 << FXResult.toString() << T 12188 << E->getSourceRange() 12189 << clang::SourceRange(CC)); 12190 return; 12191 } 12192 } 12193 } 12194 } else if (Target->isUnsaturatedFixedPointType()) { 12195 if (Source->isIntegerType()) { 12196 Expr::EvalResult Result; 12197 if (!S.isConstantEvaluated() && 12198 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12199 llvm::APSInt Value = Result.Val.getInt(); 12200 12201 bool Overflowed; 12202 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12203 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12204 12205 if (Overflowed) { 12206 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12207 S.PDiag(diag::warn_impcast_fixed_point_range) 12208 << Value.toString(/*Radix=*/10) << T 12209 << E->getSourceRange() 12210 << clang::SourceRange(CC)); 12211 return; 12212 } 12213 } 12214 } 12215 } 12216 12217 // If we are casting an integer type to a floating point type without 12218 // initialization-list syntax, we might lose accuracy if the floating 12219 // point type has a narrower significand than the integer type. 12220 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12221 TargetBT->isFloatingType() && !IsListInit) { 12222 // Determine the number of precision bits in the source integer type. 12223 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12224 /*Approximate*/ true); 12225 unsigned int SourcePrecision = SourceRange.Width; 12226 12227 // Determine the number of precision bits in the 12228 // target floating point type. 12229 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12230 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12231 12232 if (SourcePrecision > 0 && TargetPrecision > 0 && 12233 SourcePrecision > TargetPrecision) { 12234 12235 if (Optional<llvm::APSInt> SourceInt = 12236 E->getIntegerConstantExpr(S.Context)) { 12237 // If the source integer is a constant, convert it to the target 12238 // floating point type. Issue a warning if the value changes 12239 // during the whole conversion. 12240 llvm::APFloat TargetFloatValue( 12241 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12242 llvm::APFloat::opStatus ConversionStatus = 12243 TargetFloatValue.convertFromAPInt( 12244 *SourceInt, SourceBT->isSignedInteger(), 12245 llvm::APFloat::rmNearestTiesToEven); 12246 12247 if (ConversionStatus != llvm::APFloat::opOK) { 12248 std::string PrettySourceValue = SourceInt->toString(10); 12249 SmallString<32> PrettyTargetValue; 12250 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12251 12252 S.DiagRuntimeBehavior( 12253 E->getExprLoc(), E, 12254 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12255 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12256 << E->getSourceRange() << clang::SourceRange(CC)); 12257 } 12258 } else { 12259 // Otherwise, the implicit conversion may lose precision. 12260 DiagnoseImpCast(S, E, T, CC, 12261 diag::warn_impcast_integer_float_precision); 12262 } 12263 } 12264 } 12265 12266 DiagnoseNullConversion(S, E, T, CC); 12267 12268 S.DiscardMisalignedMemberAddress(Target, E); 12269 12270 if (Target->isBooleanType()) 12271 DiagnoseIntInBoolContext(S, E); 12272 12273 if (!Source->isIntegerType() || !Target->isIntegerType()) 12274 return; 12275 12276 // TODO: remove this early return once the false positives for constant->bool 12277 // in templates, macros, etc, are reduced or removed. 12278 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12279 return; 12280 12281 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12282 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12283 return adornObjCBoolConversionDiagWithTernaryFixit( 12284 S, E, 12285 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12286 << E->getType()); 12287 } 12288 12289 IntRange SourceTypeRange = 12290 IntRange::forTargetOfCanonicalType(S.Context, Source); 12291 IntRange LikelySourceRange = 12292 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12293 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12294 12295 if (LikelySourceRange.Width > TargetRange.Width) { 12296 // If the source is a constant, use a default-on diagnostic. 12297 // TODO: this should happen for bitfield stores, too. 12298 Expr::EvalResult Result; 12299 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12300 S.isConstantEvaluated())) { 12301 llvm::APSInt Value(32); 12302 Value = Result.Val.getInt(); 12303 12304 if (S.SourceMgr.isInSystemMacro(CC)) 12305 return; 12306 12307 std::string PrettySourceValue = Value.toString(10); 12308 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12309 12310 S.DiagRuntimeBehavior( 12311 E->getExprLoc(), E, 12312 S.PDiag(diag::warn_impcast_integer_precision_constant) 12313 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12314 << E->getSourceRange() << SourceRange(CC)); 12315 return; 12316 } 12317 12318 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12319 if (S.SourceMgr.isInSystemMacro(CC)) 12320 return; 12321 12322 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12323 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12324 /* pruneControlFlow */ true); 12325 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12326 } 12327 12328 if (TargetRange.Width > SourceTypeRange.Width) { 12329 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12330 if (UO->getOpcode() == UO_Minus) 12331 if (Source->isUnsignedIntegerType()) { 12332 if (Target->isUnsignedIntegerType()) 12333 return DiagnoseImpCast(S, E, T, CC, 12334 diag::warn_impcast_high_order_zero_bits); 12335 if (Target->isSignedIntegerType()) 12336 return DiagnoseImpCast(S, E, T, CC, 12337 diag::warn_impcast_nonnegative_result); 12338 } 12339 } 12340 12341 if (TargetRange.Width == LikelySourceRange.Width && 12342 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12343 Source->isSignedIntegerType()) { 12344 // Warn when doing a signed to signed conversion, warn if the positive 12345 // source value is exactly the width of the target type, which will 12346 // cause a negative value to be stored. 12347 12348 Expr::EvalResult Result; 12349 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12350 !S.SourceMgr.isInSystemMacro(CC)) { 12351 llvm::APSInt Value = Result.Val.getInt(); 12352 if (isSameWidthConstantConversion(S, E, T, CC)) { 12353 std::string PrettySourceValue = Value.toString(10); 12354 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12355 12356 S.DiagRuntimeBehavior( 12357 E->getExprLoc(), E, 12358 S.PDiag(diag::warn_impcast_integer_precision_constant) 12359 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12360 << E->getSourceRange() << SourceRange(CC)); 12361 return; 12362 } 12363 } 12364 12365 // Fall through for non-constants to give a sign conversion warning. 12366 } 12367 12368 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12369 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12370 LikelySourceRange.Width == TargetRange.Width)) { 12371 if (S.SourceMgr.isInSystemMacro(CC)) 12372 return; 12373 12374 unsigned DiagID = diag::warn_impcast_integer_sign; 12375 12376 // Traditionally, gcc has warned about this under -Wsign-compare. 12377 // We also want to warn about it in -Wconversion. 12378 // So if -Wconversion is off, use a completely identical diagnostic 12379 // in the sign-compare group. 12380 // The conditional-checking code will 12381 if (ICContext) { 12382 DiagID = diag::warn_impcast_integer_sign_conditional; 12383 *ICContext = true; 12384 } 12385 12386 return DiagnoseImpCast(S, E, T, CC, DiagID); 12387 } 12388 12389 // Diagnose conversions between different enumeration types. 12390 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12391 // type, to give us better diagnostics. 12392 QualType SourceType = E->getType(); 12393 if (!S.getLangOpts().CPlusPlus) { 12394 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12395 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12396 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12397 SourceType = S.Context.getTypeDeclType(Enum); 12398 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12399 } 12400 } 12401 12402 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12403 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12404 if (SourceEnum->getDecl()->hasNameForLinkage() && 12405 TargetEnum->getDecl()->hasNameForLinkage() && 12406 SourceEnum != TargetEnum) { 12407 if (S.SourceMgr.isInSystemMacro(CC)) 12408 return; 12409 12410 return DiagnoseImpCast(S, E, SourceType, T, CC, 12411 diag::warn_impcast_different_enum_types); 12412 } 12413 } 12414 12415 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12416 SourceLocation CC, QualType T); 12417 12418 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12419 SourceLocation CC, bool &ICContext) { 12420 E = E->IgnoreParenImpCasts(); 12421 12422 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12423 return CheckConditionalOperator(S, CO, CC, T); 12424 12425 AnalyzeImplicitConversions(S, E, CC); 12426 if (E->getType() != T) 12427 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12428 } 12429 12430 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12431 SourceLocation CC, QualType T) { 12432 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12433 12434 Expr *TrueExpr = E->getTrueExpr(); 12435 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12436 TrueExpr = BCO->getCommon(); 12437 12438 bool Suspicious = false; 12439 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12440 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12441 12442 if (T->isBooleanType()) 12443 DiagnoseIntInBoolContext(S, E); 12444 12445 // If -Wconversion would have warned about either of the candidates 12446 // for a signedness conversion to the context type... 12447 if (!Suspicious) return; 12448 12449 // ...but it's currently ignored... 12450 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12451 return; 12452 12453 // ...then check whether it would have warned about either of the 12454 // candidates for a signedness conversion to the condition type. 12455 if (E->getType() == T) return; 12456 12457 Suspicious = false; 12458 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12459 E->getType(), CC, &Suspicious); 12460 if (!Suspicious) 12461 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12462 E->getType(), CC, &Suspicious); 12463 } 12464 12465 /// Check conversion of given expression to boolean. 12466 /// Input argument E is a logical expression. 12467 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12468 if (S.getLangOpts().Bool) 12469 return; 12470 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12471 return; 12472 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12473 } 12474 12475 namespace { 12476 struct AnalyzeImplicitConversionsWorkItem { 12477 Expr *E; 12478 SourceLocation CC; 12479 bool IsListInit; 12480 }; 12481 } 12482 12483 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12484 /// that should be visited are added to WorkList. 12485 static void AnalyzeImplicitConversions( 12486 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12487 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12488 Expr *OrigE = Item.E; 12489 SourceLocation CC = Item.CC; 12490 12491 QualType T = OrigE->getType(); 12492 Expr *E = OrigE->IgnoreParenImpCasts(); 12493 12494 // Propagate whether we are in a C++ list initialization expression. 12495 // If so, we do not issue warnings for implicit int-float conversion 12496 // precision loss, because C++11 narrowing already handles it. 12497 bool IsListInit = Item.IsListInit || 12498 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12499 12500 if (E->isTypeDependent() || E->isValueDependent()) 12501 return; 12502 12503 Expr *SourceExpr = E; 12504 // Examine, but don't traverse into the source expression of an 12505 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12506 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12507 // evaluate it in the context of checking the specific conversion to T though. 12508 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12509 if (auto *Src = OVE->getSourceExpr()) 12510 SourceExpr = Src; 12511 12512 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12513 if (UO->getOpcode() == UO_Not && 12514 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12515 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12516 << OrigE->getSourceRange() << T->isBooleanType() 12517 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12518 12519 // For conditional operators, we analyze the arguments as if they 12520 // were being fed directly into the output. 12521 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12522 CheckConditionalOperator(S, CO, CC, T); 12523 return; 12524 } 12525 12526 // Check implicit argument conversions for function calls. 12527 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12528 CheckImplicitArgumentConversions(S, Call, CC); 12529 12530 // Go ahead and check any implicit conversions we might have skipped. 12531 // The non-canonical typecheck is just an optimization; 12532 // CheckImplicitConversion will filter out dead implicit conversions. 12533 if (SourceExpr->getType() != T) 12534 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12535 12536 // Now continue drilling into this expression. 12537 12538 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12539 // The bound subexpressions in a PseudoObjectExpr are not reachable 12540 // as transitive children. 12541 // FIXME: Use a more uniform representation for this. 12542 for (auto *SE : POE->semantics()) 12543 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12544 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12545 } 12546 12547 // Skip past explicit casts. 12548 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12549 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12550 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12551 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12552 WorkList.push_back({E, CC, IsListInit}); 12553 return; 12554 } 12555 12556 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12557 // Do a somewhat different check with comparison operators. 12558 if (BO->isComparisonOp()) 12559 return AnalyzeComparison(S, BO); 12560 12561 // And with simple assignments. 12562 if (BO->getOpcode() == BO_Assign) 12563 return AnalyzeAssignment(S, BO); 12564 // And with compound assignments. 12565 if (BO->isAssignmentOp()) 12566 return AnalyzeCompoundAssignment(S, BO); 12567 } 12568 12569 // These break the otherwise-useful invariant below. Fortunately, 12570 // we don't really need to recurse into them, because any internal 12571 // expressions should have been analyzed already when they were 12572 // built into statements. 12573 if (isa<StmtExpr>(E)) return; 12574 12575 // Don't descend into unevaluated contexts. 12576 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12577 12578 // Now just recurse over the expression's children. 12579 CC = E->getExprLoc(); 12580 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12581 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12582 for (Stmt *SubStmt : E->children()) { 12583 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12584 if (!ChildExpr) 12585 continue; 12586 12587 if (IsLogicalAndOperator && 12588 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12589 // Ignore checking string literals that are in logical and operators. 12590 // This is a common pattern for asserts. 12591 continue; 12592 WorkList.push_back({ChildExpr, CC, IsListInit}); 12593 } 12594 12595 if (BO && BO->isLogicalOp()) { 12596 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12597 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12598 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12599 12600 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12601 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12602 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12603 } 12604 12605 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12606 if (U->getOpcode() == UO_LNot) { 12607 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12608 } else if (U->getOpcode() != UO_AddrOf) { 12609 if (U->getSubExpr()->getType()->isAtomicType()) 12610 S.Diag(U->getSubExpr()->getBeginLoc(), 12611 diag::warn_atomic_implicit_seq_cst); 12612 } 12613 } 12614 } 12615 12616 /// AnalyzeImplicitConversions - Find and report any interesting 12617 /// implicit conversions in the given expression. There are a couple 12618 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12619 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12620 bool IsListInit/*= false*/) { 12621 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12622 WorkList.push_back({OrigE, CC, IsListInit}); 12623 while (!WorkList.empty()) 12624 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12625 } 12626 12627 /// Diagnose integer type and any valid implicit conversion to it. 12628 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12629 // Taking into account implicit conversions, 12630 // allow any integer. 12631 if (!E->getType()->isIntegerType()) { 12632 S.Diag(E->getBeginLoc(), 12633 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12634 return true; 12635 } 12636 // Potentially emit standard warnings for implicit conversions if enabled 12637 // using -Wconversion. 12638 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12639 return false; 12640 } 12641 12642 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12643 // Returns true when emitting a warning about taking the address of a reference. 12644 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12645 const PartialDiagnostic &PD) { 12646 E = E->IgnoreParenImpCasts(); 12647 12648 const FunctionDecl *FD = nullptr; 12649 12650 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12651 if (!DRE->getDecl()->getType()->isReferenceType()) 12652 return false; 12653 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12654 if (!M->getMemberDecl()->getType()->isReferenceType()) 12655 return false; 12656 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12657 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12658 return false; 12659 FD = Call->getDirectCallee(); 12660 } else { 12661 return false; 12662 } 12663 12664 SemaRef.Diag(E->getExprLoc(), PD); 12665 12666 // If possible, point to location of function. 12667 if (FD) { 12668 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12669 } 12670 12671 return true; 12672 } 12673 12674 // Returns true if the SourceLocation is expanded from any macro body. 12675 // Returns false if the SourceLocation is invalid, is from not in a macro 12676 // expansion, or is from expanded from a top-level macro argument. 12677 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12678 if (Loc.isInvalid()) 12679 return false; 12680 12681 while (Loc.isMacroID()) { 12682 if (SM.isMacroBodyExpansion(Loc)) 12683 return true; 12684 Loc = SM.getImmediateMacroCallerLoc(Loc); 12685 } 12686 12687 return false; 12688 } 12689 12690 /// Diagnose pointers that are always non-null. 12691 /// \param E the expression containing the pointer 12692 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12693 /// compared to a null pointer 12694 /// \param IsEqual True when the comparison is equal to a null pointer 12695 /// \param Range Extra SourceRange to highlight in the diagnostic 12696 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12697 Expr::NullPointerConstantKind NullKind, 12698 bool IsEqual, SourceRange Range) { 12699 if (!E) 12700 return; 12701 12702 // Don't warn inside macros. 12703 if (E->getExprLoc().isMacroID()) { 12704 const SourceManager &SM = getSourceManager(); 12705 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12706 IsInAnyMacroBody(SM, Range.getBegin())) 12707 return; 12708 } 12709 E = E->IgnoreImpCasts(); 12710 12711 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12712 12713 if (isa<CXXThisExpr>(E)) { 12714 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12715 : diag::warn_this_bool_conversion; 12716 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12717 return; 12718 } 12719 12720 bool IsAddressOf = false; 12721 12722 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12723 if (UO->getOpcode() != UO_AddrOf) 12724 return; 12725 IsAddressOf = true; 12726 E = UO->getSubExpr(); 12727 } 12728 12729 if (IsAddressOf) { 12730 unsigned DiagID = IsCompare 12731 ? diag::warn_address_of_reference_null_compare 12732 : diag::warn_address_of_reference_bool_conversion; 12733 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12734 << IsEqual; 12735 if (CheckForReference(*this, E, PD)) { 12736 return; 12737 } 12738 } 12739 12740 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12741 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12742 std::string Str; 12743 llvm::raw_string_ostream S(Str); 12744 E->printPretty(S, nullptr, getPrintingPolicy()); 12745 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12746 : diag::warn_cast_nonnull_to_bool; 12747 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12748 << E->getSourceRange() << Range << IsEqual; 12749 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12750 }; 12751 12752 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12753 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12754 if (auto *Callee = Call->getDirectCallee()) { 12755 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12756 ComplainAboutNonnullParamOrCall(A); 12757 return; 12758 } 12759 } 12760 } 12761 12762 // Expect to find a single Decl. Skip anything more complicated. 12763 ValueDecl *D = nullptr; 12764 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12765 D = R->getDecl(); 12766 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12767 D = M->getMemberDecl(); 12768 } 12769 12770 // Weak Decls can be null. 12771 if (!D || D->isWeak()) 12772 return; 12773 12774 // Check for parameter decl with nonnull attribute 12775 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12776 if (getCurFunction() && 12777 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12778 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12779 ComplainAboutNonnullParamOrCall(A); 12780 return; 12781 } 12782 12783 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12784 // Skip function template not specialized yet. 12785 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12786 return; 12787 auto ParamIter = llvm::find(FD->parameters(), PV); 12788 assert(ParamIter != FD->param_end()); 12789 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12790 12791 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12792 if (!NonNull->args_size()) { 12793 ComplainAboutNonnullParamOrCall(NonNull); 12794 return; 12795 } 12796 12797 for (const ParamIdx &ArgNo : NonNull->args()) { 12798 if (ArgNo.getASTIndex() == ParamNo) { 12799 ComplainAboutNonnullParamOrCall(NonNull); 12800 return; 12801 } 12802 } 12803 } 12804 } 12805 } 12806 } 12807 12808 QualType T = D->getType(); 12809 const bool IsArray = T->isArrayType(); 12810 const bool IsFunction = T->isFunctionType(); 12811 12812 // Address of function is used to silence the function warning. 12813 if (IsAddressOf && IsFunction) { 12814 return; 12815 } 12816 12817 // Found nothing. 12818 if (!IsAddressOf && !IsFunction && !IsArray) 12819 return; 12820 12821 // Pretty print the expression for the diagnostic. 12822 std::string Str; 12823 llvm::raw_string_ostream S(Str); 12824 E->printPretty(S, nullptr, getPrintingPolicy()); 12825 12826 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12827 : diag::warn_impcast_pointer_to_bool; 12828 enum { 12829 AddressOf, 12830 FunctionPointer, 12831 ArrayPointer 12832 } DiagType; 12833 if (IsAddressOf) 12834 DiagType = AddressOf; 12835 else if (IsFunction) 12836 DiagType = FunctionPointer; 12837 else if (IsArray) 12838 DiagType = ArrayPointer; 12839 else 12840 llvm_unreachable("Could not determine diagnostic."); 12841 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12842 << Range << IsEqual; 12843 12844 if (!IsFunction) 12845 return; 12846 12847 // Suggest '&' to silence the function warning. 12848 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12849 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12850 12851 // Check to see if '()' fixit should be emitted. 12852 QualType ReturnType; 12853 UnresolvedSet<4> NonTemplateOverloads; 12854 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12855 if (ReturnType.isNull()) 12856 return; 12857 12858 if (IsCompare) { 12859 // There are two cases here. If there is null constant, the only suggest 12860 // for a pointer return type. If the null is 0, then suggest if the return 12861 // type is a pointer or an integer type. 12862 if (!ReturnType->isPointerType()) { 12863 if (NullKind == Expr::NPCK_ZeroExpression || 12864 NullKind == Expr::NPCK_ZeroLiteral) { 12865 if (!ReturnType->isIntegerType()) 12866 return; 12867 } else { 12868 return; 12869 } 12870 } 12871 } else { // !IsCompare 12872 // For function to bool, only suggest if the function pointer has bool 12873 // return type. 12874 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12875 return; 12876 } 12877 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12878 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12879 } 12880 12881 /// Diagnoses "dangerous" implicit conversions within the given 12882 /// expression (which is a full expression). Implements -Wconversion 12883 /// and -Wsign-compare. 12884 /// 12885 /// \param CC the "context" location of the implicit conversion, i.e. 12886 /// the most location of the syntactic entity requiring the implicit 12887 /// conversion 12888 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12889 // Don't diagnose in unevaluated contexts. 12890 if (isUnevaluatedContext()) 12891 return; 12892 12893 // Don't diagnose for value- or type-dependent expressions. 12894 if (E->isTypeDependent() || E->isValueDependent()) 12895 return; 12896 12897 // Check for array bounds violations in cases where the check isn't triggered 12898 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12899 // ArraySubscriptExpr is on the RHS of a variable initialization. 12900 CheckArrayAccess(E); 12901 12902 // This is not the right CC for (e.g.) a variable initialization. 12903 AnalyzeImplicitConversions(*this, E, CC); 12904 } 12905 12906 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12907 /// Input argument E is a logical expression. 12908 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12909 ::CheckBoolLikeConversion(*this, E, CC); 12910 } 12911 12912 /// Diagnose when expression is an integer constant expression and its evaluation 12913 /// results in integer overflow 12914 void Sema::CheckForIntOverflow (Expr *E) { 12915 // Use a work list to deal with nested struct initializers. 12916 SmallVector<Expr *, 2> Exprs(1, E); 12917 12918 do { 12919 Expr *OriginalE = Exprs.pop_back_val(); 12920 Expr *E = OriginalE->IgnoreParenCasts(); 12921 12922 if (isa<BinaryOperator>(E)) { 12923 E->EvaluateForOverflow(Context); 12924 continue; 12925 } 12926 12927 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12928 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12929 else if (isa<ObjCBoxedExpr>(OriginalE)) 12930 E->EvaluateForOverflow(Context); 12931 else if (auto Call = dyn_cast<CallExpr>(E)) 12932 Exprs.append(Call->arg_begin(), Call->arg_end()); 12933 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12934 Exprs.append(Message->arg_begin(), Message->arg_end()); 12935 } while (!Exprs.empty()); 12936 } 12937 12938 namespace { 12939 12940 /// Visitor for expressions which looks for unsequenced operations on the 12941 /// same object. 12942 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12943 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12944 12945 /// A tree of sequenced regions within an expression. Two regions are 12946 /// unsequenced if one is an ancestor or a descendent of the other. When we 12947 /// finish processing an expression with sequencing, such as a comma 12948 /// expression, we fold its tree nodes into its parent, since they are 12949 /// unsequenced with respect to nodes we will visit later. 12950 class SequenceTree { 12951 struct Value { 12952 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12953 unsigned Parent : 31; 12954 unsigned Merged : 1; 12955 }; 12956 SmallVector<Value, 8> Values; 12957 12958 public: 12959 /// A region within an expression which may be sequenced with respect 12960 /// to some other region. 12961 class Seq { 12962 friend class SequenceTree; 12963 12964 unsigned Index; 12965 12966 explicit Seq(unsigned N) : Index(N) {} 12967 12968 public: 12969 Seq() : Index(0) {} 12970 }; 12971 12972 SequenceTree() { Values.push_back(Value(0)); } 12973 Seq root() const { return Seq(0); } 12974 12975 /// Create a new sequence of operations, which is an unsequenced 12976 /// subset of \p Parent. This sequence of operations is sequenced with 12977 /// respect to other children of \p Parent. 12978 Seq allocate(Seq Parent) { 12979 Values.push_back(Value(Parent.Index)); 12980 return Seq(Values.size() - 1); 12981 } 12982 12983 /// Merge a sequence of operations into its parent. 12984 void merge(Seq S) { 12985 Values[S.Index].Merged = true; 12986 } 12987 12988 /// Determine whether two operations are unsequenced. This operation 12989 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12990 /// should have been merged into its parent as appropriate. 12991 bool isUnsequenced(Seq Cur, Seq Old) { 12992 unsigned C = representative(Cur.Index); 12993 unsigned Target = representative(Old.Index); 12994 while (C >= Target) { 12995 if (C == Target) 12996 return true; 12997 C = Values[C].Parent; 12998 } 12999 return false; 13000 } 13001 13002 private: 13003 /// Pick a representative for a sequence. 13004 unsigned representative(unsigned K) { 13005 if (Values[K].Merged) 13006 // Perform path compression as we go. 13007 return Values[K].Parent = representative(Values[K].Parent); 13008 return K; 13009 } 13010 }; 13011 13012 /// An object for which we can track unsequenced uses. 13013 using Object = const NamedDecl *; 13014 13015 /// Different flavors of object usage which we track. We only track the 13016 /// least-sequenced usage of each kind. 13017 enum UsageKind { 13018 /// A read of an object. Multiple unsequenced reads are OK. 13019 UK_Use, 13020 13021 /// A modification of an object which is sequenced before the value 13022 /// computation of the expression, such as ++n in C++. 13023 UK_ModAsValue, 13024 13025 /// A modification of an object which is not sequenced before the value 13026 /// computation of the expression, such as n++. 13027 UK_ModAsSideEffect, 13028 13029 UK_Count = UK_ModAsSideEffect + 1 13030 }; 13031 13032 /// Bundle together a sequencing region and the expression corresponding 13033 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13034 struct Usage { 13035 const Expr *UsageExpr; 13036 SequenceTree::Seq Seq; 13037 13038 Usage() : UsageExpr(nullptr), Seq() {} 13039 }; 13040 13041 struct UsageInfo { 13042 Usage Uses[UK_Count]; 13043 13044 /// Have we issued a diagnostic for this object already? 13045 bool Diagnosed; 13046 13047 UsageInfo() : Uses(), Diagnosed(false) {} 13048 }; 13049 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13050 13051 Sema &SemaRef; 13052 13053 /// Sequenced regions within the expression. 13054 SequenceTree Tree; 13055 13056 /// Declaration modifications and references which we have seen. 13057 UsageInfoMap UsageMap; 13058 13059 /// The region we are currently within. 13060 SequenceTree::Seq Region; 13061 13062 /// Filled in with declarations which were modified as a side-effect 13063 /// (that is, post-increment operations). 13064 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13065 13066 /// Expressions to check later. We defer checking these to reduce 13067 /// stack usage. 13068 SmallVectorImpl<const Expr *> &WorkList; 13069 13070 /// RAII object wrapping the visitation of a sequenced subexpression of an 13071 /// expression. At the end of this process, the side-effects of the evaluation 13072 /// become sequenced with respect to the value computation of the result, so 13073 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13074 /// UK_ModAsValue. 13075 struct SequencedSubexpression { 13076 SequencedSubexpression(SequenceChecker &Self) 13077 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13078 Self.ModAsSideEffect = &ModAsSideEffect; 13079 } 13080 13081 ~SequencedSubexpression() { 13082 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13083 // Add a new usage with usage kind UK_ModAsValue, and then restore 13084 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13085 // the previous one was empty). 13086 UsageInfo &UI = Self.UsageMap[M.first]; 13087 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13088 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13089 SideEffectUsage = M.second; 13090 } 13091 Self.ModAsSideEffect = OldModAsSideEffect; 13092 } 13093 13094 SequenceChecker &Self; 13095 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13096 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13097 }; 13098 13099 /// RAII object wrapping the visitation of a subexpression which we might 13100 /// choose to evaluate as a constant. If any subexpression is evaluated and 13101 /// found to be non-constant, this allows us to suppress the evaluation of 13102 /// the outer expression. 13103 class EvaluationTracker { 13104 public: 13105 EvaluationTracker(SequenceChecker &Self) 13106 : Self(Self), Prev(Self.EvalTracker) { 13107 Self.EvalTracker = this; 13108 } 13109 13110 ~EvaluationTracker() { 13111 Self.EvalTracker = Prev; 13112 if (Prev) 13113 Prev->EvalOK &= EvalOK; 13114 } 13115 13116 bool evaluate(const Expr *E, bool &Result) { 13117 if (!EvalOK || E->isValueDependent()) 13118 return false; 13119 EvalOK = E->EvaluateAsBooleanCondition( 13120 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13121 return EvalOK; 13122 } 13123 13124 private: 13125 SequenceChecker &Self; 13126 EvaluationTracker *Prev; 13127 bool EvalOK = true; 13128 } *EvalTracker = nullptr; 13129 13130 /// Find the object which is produced by the specified expression, 13131 /// if any. 13132 Object getObject(const Expr *E, bool Mod) const { 13133 E = E->IgnoreParenCasts(); 13134 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13135 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13136 return getObject(UO->getSubExpr(), Mod); 13137 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13138 if (BO->getOpcode() == BO_Comma) 13139 return getObject(BO->getRHS(), Mod); 13140 if (Mod && BO->isAssignmentOp()) 13141 return getObject(BO->getLHS(), Mod); 13142 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13143 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13144 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13145 return ME->getMemberDecl(); 13146 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13147 // FIXME: If this is a reference, map through to its value. 13148 return DRE->getDecl(); 13149 return nullptr; 13150 } 13151 13152 /// Note that an object \p O was modified or used by an expression 13153 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13154 /// the object \p O as obtained via the \p UsageMap. 13155 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13156 // Get the old usage for the given object and usage kind. 13157 Usage &U = UI.Uses[UK]; 13158 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13159 // If we have a modification as side effect and are in a sequenced 13160 // subexpression, save the old Usage so that we can restore it later 13161 // in SequencedSubexpression::~SequencedSubexpression. 13162 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13163 ModAsSideEffect->push_back(std::make_pair(O, U)); 13164 // Then record the new usage with the current sequencing region. 13165 U.UsageExpr = UsageExpr; 13166 U.Seq = Region; 13167 } 13168 } 13169 13170 /// Check whether a modification or use of an object \p O in an expression 13171 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13172 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13173 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13174 /// usage and false we are checking for a mod-use unsequenced usage. 13175 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13176 UsageKind OtherKind, bool IsModMod) { 13177 if (UI.Diagnosed) 13178 return; 13179 13180 const Usage &U = UI.Uses[OtherKind]; 13181 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13182 return; 13183 13184 const Expr *Mod = U.UsageExpr; 13185 const Expr *ModOrUse = UsageExpr; 13186 if (OtherKind == UK_Use) 13187 std::swap(Mod, ModOrUse); 13188 13189 SemaRef.DiagRuntimeBehavior( 13190 Mod->getExprLoc(), {Mod, ModOrUse}, 13191 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13192 : diag::warn_unsequenced_mod_use) 13193 << O << SourceRange(ModOrUse->getExprLoc())); 13194 UI.Diagnosed = true; 13195 } 13196 13197 // A note on note{Pre, Post}{Use, Mod}: 13198 // 13199 // (It helps to follow the algorithm with an expression such as 13200 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13201 // operations before C++17 and both are well-defined in C++17). 13202 // 13203 // When visiting a node which uses/modify an object we first call notePreUse 13204 // or notePreMod before visiting its sub-expression(s). At this point the 13205 // children of the current node have not yet been visited and so the eventual 13206 // uses/modifications resulting from the children of the current node have not 13207 // been recorded yet. 13208 // 13209 // We then visit the children of the current node. After that notePostUse or 13210 // notePostMod is called. These will 1) detect an unsequenced modification 13211 // as side effect (as in "k++ + k") and 2) add a new usage with the 13212 // appropriate usage kind. 13213 // 13214 // We also have to be careful that some operation sequences modification as 13215 // side effect as well (for example: || or ,). To account for this we wrap 13216 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13217 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13218 // which record usages which are modifications as side effect, and then 13219 // downgrade them (or more accurately restore the previous usage which was a 13220 // modification as side effect) when exiting the scope of the sequenced 13221 // subexpression. 13222 13223 void notePreUse(Object O, const Expr *UseExpr) { 13224 UsageInfo &UI = UsageMap[O]; 13225 // Uses conflict with other modifications. 13226 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13227 } 13228 13229 void notePostUse(Object O, const Expr *UseExpr) { 13230 UsageInfo &UI = UsageMap[O]; 13231 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13232 /*IsModMod=*/false); 13233 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13234 } 13235 13236 void notePreMod(Object O, const Expr *ModExpr) { 13237 UsageInfo &UI = UsageMap[O]; 13238 // Modifications conflict with other modifications and with uses. 13239 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13240 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13241 } 13242 13243 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13244 UsageInfo &UI = UsageMap[O]; 13245 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13246 /*IsModMod=*/true); 13247 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13248 } 13249 13250 public: 13251 SequenceChecker(Sema &S, const Expr *E, 13252 SmallVectorImpl<const Expr *> &WorkList) 13253 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13254 Visit(E); 13255 // Silence a -Wunused-private-field since WorkList is now unused. 13256 // TODO: Evaluate if it can be used, and if not remove it. 13257 (void)this->WorkList; 13258 } 13259 13260 void VisitStmt(const Stmt *S) { 13261 // Skip all statements which aren't expressions for now. 13262 } 13263 13264 void VisitExpr(const Expr *E) { 13265 // By default, just recurse to evaluated subexpressions. 13266 Base::VisitStmt(E); 13267 } 13268 13269 void VisitCastExpr(const CastExpr *E) { 13270 Object O = Object(); 13271 if (E->getCastKind() == CK_LValueToRValue) 13272 O = getObject(E->getSubExpr(), false); 13273 13274 if (O) 13275 notePreUse(O, E); 13276 VisitExpr(E); 13277 if (O) 13278 notePostUse(O, E); 13279 } 13280 13281 void VisitSequencedExpressions(const Expr *SequencedBefore, 13282 const Expr *SequencedAfter) { 13283 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13284 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13285 SequenceTree::Seq OldRegion = Region; 13286 13287 { 13288 SequencedSubexpression SeqBefore(*this); 13289 Region = BeforeRegion; 13290 Visit(SequencedBefore); 13291 } 13292 13293 Region = AfterRegion; 13294 Visit(SequencedAfter); 13295 13296 Region = OldRegion; 13297 13298 Tree.merge(BeforeRegion); 13299 Tree.merge(AfterRegion); 13300 } 13301 13302 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13303 // C++17 [expr.sub]p1: 13304 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13305 // expression E1 is sequenced before the expression E2. 13306 if (SemaRef.getLangOpts().CPlusPlus17) 13307 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13308 else { 13309 Visit(ASE->getLHS()); 13310 Visit(ASE->getRHS()); 13311 } 13312 } 13313 13314 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13315 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13316 void VisitBinPtrMem(const BinaryOperator *BO) { 13317 // C++17 [expr.mptr.oper]p4: 13318 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13319 // the expression E1 is sequenced before the expression E2. 13320 if (SemaRef.getLangOpts().CPlusPlus17) 13321 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13322 else { 13323 Visit(BO->getLHS()); 13324 Visit(BO->getRHS()); 13325 } 13326 } 13327 13328 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13329 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13330 void VisitBinShlShr(const BinaryOperator *BO) { 13331 // C++17 [expr.shift]p4: 13332 // The expression E1 is sequenced before the expression E2. 13333 if (SemaRef.getLangOpts().CPlusPlus17) 13334 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13335 else { 13336 Visit(BO->getLHS()); 13337 Visit(BO->getRHS()); 13338 } 13339 } 13340 13341 void VisitBinComma(const BinaryOperator *BO) { 13342 // C++11 [expr.comma]p1: 13343 // Every value computation and side effect associated with the left 13344 // expression is sequenced before every value computation and side 13345 // effect associated with the right expression. 13346 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13347 } 13348 13349 void VisitBinAssign(const BinaryOperator *BO) { 13350 SequenceTree::Seq RHSRegion; 13351 SequenceTree::Seq LHSRegion; 13352 if (SemaRef.getLangOpts().CPlusPlus17) { 13353 RHSRegion = Tree.allocate(Region); 13354 LHSRegion = Tree.allocate(Region); 13355 } else { 13356 RHSRegion = Region; 13357 LHSRegion = Region; 13358 } 13359 SequenceTree::Seq OldRegion = Region; 13360 13361 // C++11 [expr.ass]p1: 13362 // [...] the assignment is sequenced after the value computation 13363 // of the right and left operands, [...] 13364 // 13365 // so check it before inspecting the operands and update the 13366 // map afterwards. 13367 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13368 if (O) 13369 notePreMod(O, BO); 13370 13371 if (SemaRef.getLangOpts().CPlusPlus17) { 13372 // C++17 [expr.ass]p1: 13373 // [...] The right operand is sequenced before the left operand. [...] 13374 { 13375 SequencedSubexpression SeqBefore(*this); 13376 Region = RHSRegion; 13377 Visit(BO->getRHS()); 13378 } 13379 13380 Region = LHSRegion; 13381 Visit(BO->getLHS()); 13382 13383 if (O && isa<CompoundAssignOperator>(BO)) 13384 notePostUse(O, BO); 13385 13386 } else { 13387 // C++11 does not specify any sequencing between the LHS and RHS. 13388 Region = LHSRegion; 13389 Visit(BO->getLHS()); 13390 13391 if (O && isa<CompoundAssignOperator>(BO)) 13392 notePostUse(O, BO); 13393 13394 Region = RHSRegion; 13395 Visit(BO->getRHS()); 13396 } 13397 13398 // C++11 [expr.ass]p1: 13399 // the assignment is sequenced [...] before the value computation of the 13400 // assignment expression. 13401 // C11 6.5.16/3 has no such rule. 13402 Region = OldRegion; 13403 if (O) 13404 notePostMod(O, BO, 13405 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13406 : UK_ModAsSideEffect); 13407 if (SemaRef.getLangOpts().CPlusPlus17) { 13408 Tree.merge(RHSRegion); 13409 Tree.merge(LHSRegion); 13410 } 13411 } 13412 13413 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13414 VisitBinAssign(CAO); 13415 } 13416 13417 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13418 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13419 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13420 Object O = getObject(UO->getSubExpr(), true); 13421 if (!O) 13422 return VisitExpr(UO); 13423 13424 notePreMod(O, UO); 13425 Visit(UO->getSubExpr()); 13426 // C++11 [expr.pre.incr]p1: 13427 // the expression ++x is equivalent to x+=1 13428 notePostMod(O, UO, 13429 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13430 : UK_ModAsSideEffect); 13431 } 13432 13433 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13434 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13435 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13436 Object O = getObject(UO->getSubExpr(), true); 13437 if (!O) 13438 return VisitExpr(UO); 13439 13440 notePreMod(O, UO); 13441 Visit(UO->getSubExpr()); 13442 notePostMod(O, UO, UK_ModAsSideEffect); 13443 } 13444 13445 void VisitBinLOr(const BinaryOperator *BO) { 13446 // C++11 [expr.log.or]p2: 13447 // If the second expression is evaluated, every value computation and 13448 // side effect associated with the first expression is sequenced before 13449 // every value computation and side effect associated with the 13450 // second expression. 13451 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13452 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13453 SequenceTree::Seq OldRegion = Region; 13454 13455 EvaluationTracker Eval(*this); 13456 { 13457 SequencedSubexpression Sequenced(*this); 13458 Region = LHSRegion; 13459 Visit(BO->getLHS()); 13460 } 13461 13462 // C++11 [expr.log.or]p1: 13463 // [...] the second operand is not evaluated if the first operand 13464 // evaluates to true. 13465 bool EvalResult = false; 13466 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13467 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13468 if (ShouldVisitRHS) { 13469 Region = RHSRegion; 13470 Visit(BO->getRHS()); 13471 } 13472 13473 Region = OldRegion; 13474 Tree.merge(LHSRegion); 13475 Tree.merge(RHSRegion); 13476 } 13477 13478 void VisitBinLAnd(const BinaryOperator *BO) { 13479 // C++11 [expr.log.and]p2: 13480 // If the second expression is evaluated, every value computation and 13481 // side effect associated with the first expression is sequenced before 13482 // every value computation and side effect associated with the 13483 // second expression. 13484 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13485 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13486 SequenceTree::Seq OldRegion = Region; 13487 13488 EvaluationTracker Eval(*this); 13489 { 13490 SequencedSubexpression Sequenced(*this); 13491 Region = LHSRegion; 13492 Visit(BO->getLHS()); 13493 } 13494 13495 // C++11 [expr.log.and]p1: 13496 // [...] the second operand is not evaluated if the first operand is false. 13497 bool EvalResult = false; 13498 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13499 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13500 if (ShouldVisitRHS) { 13501 Region = RHSRegion; 13502 Visit(BO->getRHS()); 13503 } 13504 13505 Region = OldRegion; 13506 Tree.merge(LHSRegion); 13507 Tree.merge(RHSRegion); 13508 } 13509 13510 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13511 // C++11 [expr.cond]p1: 13512 // [...] Every value computation and side effect associated with the first 13513 // expression is sequenced before every value computation and side effect 13514 // associated with the second or third expression. 13515 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13516 13517 // No sequencing is specified between the true and false expression. 13518 // However since exactly one of both is going to be evaluated we can 13519 // consider them to be sequenced. This is needed to avoid warning on 13520 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13521 // both the true and false expressions because we can't evaluate x. 13522 // This will still allow us to detect an expression like (pre C++17) 13523 // "(x ? y += 1 : y += 2) = y". 13524 // 13525 // We don't wrap the visitation of the true and false expression with 13526 // SequencedSubexpression because we don't want to downgrade modifications 13527 // as side effect in the true and false expressions after the visition 13528 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13529 // not warn between the two "y++", but we should warn between the "y++" 13530 // and the "y". 13531 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13532 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13533 SequenceTree::Seq OldRegion = Region; 13534 13535 EvaluationTracker Eval(*this); 13536 { 13537 SequencedSubexpression Sequenced(*this); 13538 Region = ConditionRegion; 13539 Visit(CO->getCond()); 13540 } 13541 13542 // C++11 [expr.cond]p1: 13543 // [...] The first expression is contextually converted to bool (Clause 4). 13544 // It is evaluated and if it is true, the result of the conditional 13545 // expression is the value of the second expression, otherwise that of the 13546 // third expression. Only one of the second and third expressions is 13547 // evaluated. [...] 13548 bool EvalResult = false; 13549 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13550 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13551 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13552 if (ShouldVisitTrueExpr) { 13553 Region = TrueRegion; 13554 Visit(CO->getTrueExpr()); 13555 } 13556 if (ShouldVisitFalseExpr) { 13557 Region = FalseRegion; 13558 Visit(CO->getFalseExpr()); 13559 } 13560 13561 Region = OldRegion; 13562 Tree.merge(ConditionRegion); 13563 Tree.merge(TrueRegion); 13564 Tree.merge(FalseRegion); 13565 } 13566 13567 void VisitCallExpr(const CallExpr *CE) { 13568 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13569 13570 if (CE->isUnevaluatedBuiltinCall(Context)) 13571 return; 13572 13573 // C++11 [intro.execution]p15: 13574 // When calling a function [...], every value computation and side effect 13575 // associated with any argument expression, or with the postfix expression 13576 // designating the called function, is sequenced before execution of every 13577 // expression or statement in the body of the function [and thus before 13578 // the value computation of its result]. 13579 SequencedSubexpression Sequenced(*this); 13580 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13581 // C++17 [expr.call]p5 13582 // The postfix-expression is sequenced before each expression in the 13583 // expression-list and any default argument. [...] 13584 SequenceTree::Seq CalleeRegion; 13585 SequenceTree::Seq OtherRegion; 13586 if (SemaRef.getLangOpts().CPlusPlus17) { 13587 CalleeRegion = Tree.allocate(Region); 13588 OtherRegion = Tree.allocate(Region); 13589 } else { 13590 CalleeRegion = Region; 13591 OtherRegion = Region; 13592 } 13593 SequenceTree::Seq OldRegion = Region; 13594 13595 // Visit the callee expression first. 13596 Region = CalleeRegion; 13597 if (SemaRef.getLangOpts().CPlusPlus17) { 13598 SequencedSubexpression Sequenced(*this); 13599 Visit(CE->getCallee()); 13600 } else { 13601 Visit(CE->getCallee()); 13602 } 13603 13604 // Then visit the argument expressions. 13605 Region = OtherRegion; 13606 for (const Expr *Argument : CE->arguments()) 13607 Visit(Argument); 13608 13609 Region = OldRegion; 13610 if (SemaRef.getLangOpts().CPlusPlus17) { 13611 Tree.merge(CalleeRegion); 13612 Tree.merge(OtherRegion); 13613 } 13614 }); 13615 } 13616 13617 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13618 // C++17 [over.match.oper]p2: 13619 // [...] the operator notation is first transformed to the equivalent 13620 // function-call notation as summarized in Table 12 (where @ denotes one 13621 // of the operators covered in the specified subclause). However, the 13622 // operands are sequenced in the order prescribed for the built-in 13623 // operator (Clause 8). 13624 // 13625 // From the above only overloaded binary operators and overloaded call 13626 // operators have sequencing rules in C++17 that we need to handle 13627 // separately. 13628 if (!SemaRef.getLangOpts().CPlusPlus17 || 13629 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13630 return VisitCallExpr(CXXOCE); 13631 13632 enum { 13633 NoSequencing, 13634 LHSBeforeRHS, 13635 RHSBeforeLHS, 13636 LHSBeforeRest 13637 } SequencingKind; 13638 switch (CXXOCE->getOperator()) { 13639 case OO_Equal: 13640 case OO_PlusEqual: 13641 case OO_MinusEqual: 13642 case OO_StarEqual: 13643 case OO_SlashEqual: 13644 case OO_PercentEqual: 13645 case OO_CaretEqual: 13646 case OO_AmpEqual: 13647 case OO_PipeEqual: 13648 case OO_LessLessEqual: 13649 case OO_GreaterGreaterEqual: 13650 SequencingKind = RHSBeforeLHS; 13651 break; 13652 13653 case OO_LessLess: 13654 case OO_GreaterGreater: 13655 case OO_AmpAmp: 13656 case OO_PipePipe: 13657 case OO_Comma: 13658 case OO_ArrowStar: 13659 case OO_Subscript: 13660 SequencingKind = LHSBeforeRHS; 13661 break; 13662 13663 case OO_Call: 13664 SequencingKind = LHSBeforeRest; 13665 break; 13666 13667 default: 13668 SequencingKind = NoSequencing; 13669 break; 13670 } 13671 13672 if (SequencingKind == NoSequencing) 13673 return VisitCallExpr(CXXOCE); 13674 13675 // This is a call, so all subexpressions are sequenced before the result. 13676 SequencedSubexpression Sequenced(*this); 13677 13678 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13679 assert(SemaRef.getLangOpts().CPlusPlus17 && 13680 "Should only get there with C++17 and above!"); 13681 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13682 "Should only get there with an overloaded binary operator" 13683 " or an overloaded call operator!"); 13684 13685 if (SequencingKind == LHSBeforeRest) { 13686 assert(CXXOCE->getOperator() == OO_Call && 13687 "We should only have an overloaded call operator here!"); 13688 13689 // This is very similar to VisitCallExpr, except that we only have the 13690 // C++17 case. The postfix-expression is the first argument of the 13691 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13692 // are in the following arguments. 13693 // 13694 // Note that we intentionally do not visit the callee expression since 13695 // it is just a decayed reference to a function. 13696 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13697 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13698 SequenceTree::Seq OldRegion = Region; 13699 13700 assert(CXXOCE->getNumArgs() >= 1 && 13701 "An overloaded call operator must have at least one argument" 13702 " for the postfix-expression!"); 13703 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13704 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13705 CXXOCE->getNumArgs() - 1); 13706 13707 // Visit the postfix-expression first. 13708 { 13709 Region = PostfixExprRegion; 13710 SequencedSubexpression Sequenced(*this); 13711 Visit(PostfixExpr); 13712 } 13713 13714 // Then visit the argument expressions. 13715 Region = ArgsRegion; 13716 for (const Expr *Arg : Args) 13717 Visit(Arg); 13718 13719 Region = OldRegion; 13720 Tree.merge(PostfixExprRegion); 13721 Tree.merge(ArgsRegion); 13722 } else { 13723 assert(CXXOCE->getNumArgs() == 2 && 13724 "Should only have two arguments here!"); 13725 assert((SequencingKind == LHSBeforeRHS || 13726 SequencingKind == RHSBeforeLHS) && 13727 "Unexpected sequencing kind!"); 13728 13729 // We do not visit the callee expression since it is just a decayed 13730 // reference to a function. 13731 const Expr *E1 = CXXOCE->getArg(0); 13732 const Expr *E2 = CXXOCE->getArg(1); 13733 if (SequencingKind == RHSBeforeLHS) 13734 std::swap(E1, E2); 13735 13736 return VisitSequencedExpressions(E1, E2); 13737 } 13738 }); 13739 } 13740 13741 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13742 // This is a call, so all subexpressions are sequenced before the result. 13743 SequencedSubexpression Sequenced(*this); 13744 13745 if (!CCE->isListInitialization()) 13746 return VisitExpr(CCE); 13747 13748 // In C++11, list initializations are sequenced. 13749 SmallVector<SequenceTree::Seq, 32> Elts; 13750 SequenceTree::Seq Parent = Region; 13751 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13752 E = CCE->arg_end(); 13753 I != E; ++I) { 13754 Region = Tree.allocate(Parent); 13755 Elts.push_back(Region); 13756 Visit(*I); 13757 } 13758 13759 // Forget that the initializers are sequenced. 13760 Region = Parent; 13761 for (unsigned I = 0; I < Elts.size(); ++I) 13762 Tree.merge(Elts[I]); 13763 } 13764 13765 void VisitInitListExpr(const InitListExpr *ILE) { 13766 if (!SemaRef.getLangOpts().CPlusPlus11) 13767 return VisitExpr(ILE); 13768 13769 // In C++11, list initializations are sequenced. 13770 SmallVector<SequenceTree::Seq, 32> Elts; 13771 SequenceTree::Seq Parent = Region; 13772 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13773 const Expr *E = ILE->getInit(I); 13774 if (!E) 13775 continue; 13776 Region = Tree.allocate(Parent); 13777 Elts.push_back(Region); 13778 Visit(E); 13779 } 13780 13781 // Forget that the initializers are sequenced. 13782 Region = Parent; 13783 for (unsigned I = 0; I < Elts.size(); ++I) 13784 Tree.merge(Elts[I]); 13785 } 13786 }; 13787 13788 } // namespace 13789 13790 void Sema::CheckUnsequencedOperations(const Expr *E) { 13791 SmallVector<const Expr *, 8> WorkList; 13792 WorkList.push_back(E); 13793 while (!WorkList.empty()) { 13794 const Expr *Item = WorkList.pop_back_val(); 13795 SequenceChecker(*this, Item, WorkList); 13796 } 13797 } 13798 13799 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13800 bool IsConstexpr) { 13801 llvm::SaveAndRestore<bool> ConstantContext( 13802 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13803 CheckImplicitConversions(E, CheckLoc); 13804 if (!E->isInstantiationDependent()) 13805 CheckUnsequencedOperations(E); 13806 if (!IsConstexpr && !E->isValueDependent()) 13807 CheckForIntOverflow(E); 13808 DiagnoseMisalignedMembers(); 13809 } 13810 13811 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13812 FieldDecl *BitField, 13813 Expr *Init) { 13814 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13815 } 13816 13817 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13818 SourceLocation Loc) { 13819 if (!PType->isVariablyModifiedType()) 13820 return; 13821 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13822 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13823 return; 13824 } 13825 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13826 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13827 return; 13828 } 13829 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13830 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13831 return; 13832 } 13833 13834 const ArrayType *AT = S.Context.getAsArrayType(PType); 13835 if (!AT) 13836 return; 13837 13838 if (AT->getSizeModifier() != ArrayType::Star) { 13839 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13840 return; 13841 } 13842 13843 S.Diag(Loc, diag::err_array_star_in_function_definition); 13844 } 13845 13846 /// CheckParmsForFunctionDef - Check that the parameters of the given 13847 /// function are appropriate for the definition of a function. This 13848 /// takes care of any checks that cannot be performed on the 13849 /// declaration itself, e.g., that the types of each of the function 13850 /// parameters are complete. 13851 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13852 bool CheckParameterNames) { 13853 bool HasInvalidParm = false; 13854 for (ParmVarDecl *Param : Parameters) { 13855 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13856 // function declarator that is part of a function definition of 13857 // that function shall not have incomplete type. 13858 // 13859 // This is also C++ [dcl.fct]p6. 13860 if (!Param->isInvalidDecl() && 13861 RequireCompleteType(Param->getLocation(), Param->getType(), 13862 diag::err_typecheck_decl_incomplete_type)) { 13863 Param->setInvalidDecl(); 13864 HasInvalidParm = true; 13865 } 13866 13867 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13868 // declaration of each parameter shall include an identifier. 13869 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13870 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13871 // Diagnose this as an extension in C17 and earlier. 13872 if (!getLangOpts().C2x) 13873 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13874 } 13875 13876 // C99 6.7.5.3p12: 13877 // If the function declarator is not part of a definition of that 13878 // function, parameters may have incomplete type and may use the [*] 13879 // notation in their sequences of declarator specifiers to specify 13880 // variable length array types. 13881 QualType PType = Param->getOriginalType(); 13882 // FIXME: This diagnostic should point the '[*]' if source-location 13883 // information is added for it. 13884 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13885 13886 // If the parameter is a c++ class type and it has to be destructed in the 13887 // callee function, declare the destructor so that it can be called by the 13888 // callee function. Do not perform any direct access check on the dtor here. 13889 if (!Param->isInvalidDecl()) { 13890 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13891 if (!ClassDecl->isInvalidDecl() && 13892 !ClassDecl->hasIrrelevantDestructor() && 13893 !ClassDecl->isDependentContext() && 13894 ClassDecl->isParamDestroyedInCallee()) { 13895 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13896 MarkFunctionReferenced(Param->getLocation(), Destructor); 13897 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13898 } 13899 } 13900 } 13901 13902 // Parameters with the pass_object_size attribute only need to be marked 13903 // constant at function definitions. Because we lack information about 13904 // whether we're on a declaration or definition when we're instantiating the 13905 // attribute, we need to check for constness here. 13906 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13907 if (!Param->getType().isConstQualified()) 13908 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13909 << Attr->getSpelling() << 1; 13910 13911 // Check for parameter names shadowing fields from the class. 13912 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13913 // The owning context for the parameter should be the function, but we 13914 // want to see if this function's declaration context is a record. 13915 DeclContext *DC = Param->getDeclContext(); 13916 if (DC && DC->isFunctionOrMethod()) { 13917 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13918 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13919 RD, /*DeclIsField*/ false); 13920 } 13921 } 13922 } 13923 13924 return HasInvalidParm; 13925 } 13926 13927 Optional<std::pair<CharUnits, CharUnits>> 13928 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13929 13930 /// Compute the alignment and offset of the base class object given the 13931 /// derived-to-base cast expression and the alignment and offset of the derived 13932 /// class object. 13933 static std::pair<CharUnits, CharUnits> 13934 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13935 CharUnits BaseAlignment, CharUnits Offset, 13936 ASTContext &Ctx) { 13937 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13938 ++PathI) { 13939 const CXXBaseSpecifier *Base = *PathI; 13940 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13941 if (Base->isVirtual()) { 13942 // The complete object may have a lower alignment than the non-virtual 13943 // alignment of the base, in which case the base may be misaligned. Choose 13944 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13945 // conservative lower bound of the complete object alignment. 13946 CharUnits NonVirtualAlignment = 13947 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13948 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13949 Offset = CharUnits::Zero(); 13950 } else { 13951 const ASTRecordLayout &RL = 13952 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13953 Offset += RL.getBaseClassOffset(BaseDecl); 13954 } 13955 DerivedType = Base->getType(); 13956 } 13957 13958 return std::make_pair(BaseAlignment, Offset); 13959 } 13960 13961 /// Compute the alignment and offset of a binary additive operator. 13962 static Optional<std::pair<CharUnits, CharUnits>> 13963 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13964 bool IsSub, ASTContext &Ctx) { 13965 QualType PointeeType = PtrE->getType()->getPointeeType(); 13966 13967 if (!PointeeType->isConstantSizeType()) 13968 return llvm::None; 13969 13970 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13971 13972 if (!P) 13973 return llvm::None; 13974 13975 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13976 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13977 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13978 if (IsSub) 13979 Offset = -Offset; 13980 return std::make_pair(P->first, P->second + Offset); 13981 } 13982 13983 // If the integer expression isn't a constant expression, compute the lower 13984 // bound of the alignment using the alignment and offset of the pointer 13985 // expression and the element size. 13986 return std::make_pair( 13987 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13988 CharUnits::Zero()); 13989 } 13990 13991 /// This helper function takes an lvalue expression and returns the alignment of 13992 /// a VarDecl and a constant offset from the VarDecl. 13993 Optional<std::pair<CharUnits, CharUnits>> 13994 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13995 E = E->IgnoreParens(); 13996 switch (E->getStmtClass()) { 13997 default: 13998 break; 13999 case Stmt::CStyleCastExprClass: 14000 case Stmt::CXXStaticCastExprClass: 14001 case Stmt::ImplicitCastExprClass: { 14002 auto *CE = cast<CastExpr>(E); 14003 const Expr *From = CE->getSubExpr(); 14004 switch (CE->getCastKind()) { 14005 default: 14006 break; 14007 case CK_NoOp: 14008 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14009 case CK_UncheckedDerivedToBase: 14010 case CK_DerivedToBase: { 14011 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14012 if (!P) 14013 break; 14014 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14015 P->second, Ctx); 14016 } 14017 } 14018 break; 14019 } 14020 case Stmt::ArraySubscriptExprClass: { 14021 auto *ASE = cast<ArraySubscriptExpr>(E); 14022 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14023 false, Ctx); 14024 } 14025 case Stmt::DeclRefExprClass: { 14026 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14027 // FIXME: If VD is captured by copy or is an escaping __block variable, 14028 // use the alignment of VD's type. 14029 if (!VD->getType()->isReferenceType()) 14030 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14031 if (VD->hasInit()) 14032 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14033 } 14034 break; 14035 } 14036 case Stmt::MemberExprClass: { 14037 auto *ME = cast<MemberExpr>(E); 14038 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14039 if (!FD || FD->getType()->isReferenceType()) 14040 break; 14041 Optional<std::pair<CharUnits, CharUnits>> P; 14042 if (ME->isArrow()) 14043 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14044 else 14045 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14046 if (!P) 14047 break; 14048 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14049 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14050 return std::make_pair(P->first, 14051 P->second + CharUnits::fromQuantity(Offset)); 14052 } 14053 case Stmt::UnaryOperatorClass: { 14054 auto *UO = cast<UnaryOperator>(E); 14055 switch (UO->getOpcode()) { 14056 default: 14057 break; 14058 case UO_Deref: 14059 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14060 } 14061 break; 14062 } 14063 case Stmt::BinaryOperatorClass: { 14064 auto *BO = cast<BinaryOperator>(E); 14065 auto Opcode = BO->getOpcode(); 14066 switch (Opcode) { 14067 default: 14068 break; 14069 case BO_Comma: 14070 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14071 } 14072 break; 14073 } 14074 } 14075 return llvm::None; 14076 } 14077 14078 /// This helper function takes a pointer expression and returns the alignment of 14079 /// a VarDecl and a constant offset from the VarDecl. 14080 Optional<std::pair<CharUnits, CharUnits>> 14081 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14082 E = E->IgnoreParens(); 14083 switch (E->getStmtClass()) { 14084 default: 14085 break; 14086 case Stmt::CStyleCastExprClass: 14087 case Stmt::CXXStaticCastExprClass: 14088 case Stmt::ImplicitCastExprClass: { 14089 auto *CE = cast<CastExpr>(E); 14090 const Expr *From = CE->getSubExpr(); 14091 switch (CE->getCastKind()) { 14092 default: 14093 break; 14094 case CK_NoOp: 14095 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14096 case CK_ArrayToPointerDecay: 14097 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14098 case CK_UncheckedDerivedToBase: 14099 case CK_DerivedToBase: { 14100 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14101 if (!P) 14102 break; 14103 return getDerivedToBaseAlignmentAndOffset( 14104 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14105 } 14106 } 14107 break; 14108 } 14109 case Stmt::CXXThisExprClass: { 14110 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14111 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14112 return std::make_pair(Alignment, CharUnits::Zero()); 14113 } 14114 case Stmt::UnaryOperatorClass: { 14115 auto *UO = cast<UnaryOperator>(E); 14116 if (UO->getOpcode() == UO_AddrOf) 14117 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14118 break; 14119 } 14120 case Stmt::BinaryOperatorClass: { 14121 auto *BO = cast<BinaryOperator>(E); 14122 auto Opcode = BO->getOpcode(); 14123 switch (Opcode) { 14124 default: 14125 break; 14126 case BO_Add: 14127 case BO_Sub: { 14128 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14129 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14130 std::swap(LHS, RHS); 14131 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14132 Ctx); 14133 } 14134 case BO_Comma: 14135 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14136 } 14137 break; 14138 } 14139 } 14140 return llvm::None; 14141 } 14142 14143 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14144 // See if we can compute the alignment of a VarDecl and an offset from it. 14145 Optional<std::pair<CharUnits, CharUnits>> P = 14146 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14147 14148 if (P) 14149 return P->first.alignmentAtOffset(P->second); 14150 14151 // If that failed, return the type's alignment. 14152 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14153 } 14154 14155 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14156 /// pointer cast increases the alignment requirements. 14157 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14158 // This is actually a lot of work to potentially be doing on every 14159 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14160 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14161 return; 14162 14163 // Ignore dependent types. 14164 if (T->isDependentType() || Op->getType()->isDependentType()) 14165 return; 14166 14167 // Require that the destination be a pointer type. 14168 const PointerType *DestPtr = T->getAs<PointerType>(); 14169 if (!DestPtr) return; 14170 14171 // If the destination has alignment 1, we're done. 14172 QualType DestPointee = DestPtr->getPointeeType(); 14173 if (DestPointee->isIncompleteType()) return; 14174 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14175 if (DestAlign.isOne()) return; 14176 14177 // Require that the source be a pointer type. 14178 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14179 if (!SrcPtr) return; 14180 QualType SrcPointee = SrcPtr->getPointeeType(); 14181 14182 // Explicitly allow casts from cv void*. We already implicitly 14183 // allowed casts to cv void*, since they have alignment 1. 14184 // Also allow casts involving incomplete types, which implicitly 14185 // includes 'void'. 14186 if (SrcPointee->isIncompleteType()) return; 14187 14188 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14189 14190 if (SrcAlign >= DestAlign) return; 14191 14192 Diag(TRange.getBegin(), diag::warn_cast_align) 14193 << Op->getType() << T 14194 << static_cast<unsigned>(SrcAlign.getQuantity()) 14195 << static_cast<unsigned>(DestAlign.getQuantity()) 14196 << TRange << Op->getSourceRange(); 14197 } 14198 14199 /// Check whether this array fits the idiom of a size-one tail padded 14200 /// array member of a struct. 14201 /// 14202 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14203 /// commonly used to emulate flexible arrays in C89 code. 14204 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14205 const NamedDecl *ND) { 14206 if (Size != 1 || !ND) return false; 14207 14208 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14209 if (!FD) return false; 14210 14211 // Don't consider sizes resulting from macro expansions or template argument 14212 // substitution to form C89 tail-padded arrays. 14213 14214 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14215 while (TInfo) { 14216 TypeLoc TL = TInfo->getTypeLoc(); 14217 // Look through typedefs. 14218 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14219 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14220 TInfo = TDL->getTypeSourceInfo(); 14221 continue; 14222 } 14223 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14224 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14225 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14226 return false; 14227 } 14228 break; 14229 } 14230 14231 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14232 if (!RD) return false; 14233 if (RD->isUnion()) return false; 14234 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14235 if (!CRD->isStandardLayout()) return false; 14236 } 14237 14238 // See if this is the last field decl in the record. 14239 const Decl *D = FD; 14240 while ((D = D->getNextDeclInContext())) 14241 if (isa<FieldDecl>(D)) 14242 return false; 14243 return true; 14244 } 14245 14246 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14247 const ArraySubscriptExpr *ASE, 14248 bool AllowOnePastEnd, bool IndexNegated) { 14249 // Already diagnosed by the constant evaluator. 14250 if (isConstantEvaluated()) 14251 return; 14252 14253 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14254 if (IndexExpr->isValueDependent()) 14255 return; 14256 14257 const Type *EffectiveType = 14258 BaseExpr->getType()->getPointeeOrArrayElementType(); 14259 BaseExpr = BaseExpr->IgnoreParenCasts(); 14260 const ConstantArrayType *ArrayTy = 14261 Context.getAsConstantArrayType(BaseExpr->getType()); 14262 14263 if (!ArrayTy) 14264 return; 14265 14266 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14267 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14268 return; 14269 14270 Expr::EvalResult Result; 14271 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14272 return; 14273 14274 llvm::APSInt index = Result.Val.getInt(); 14275 if (IndexNegated) 14276 index = -index; 14277 14278 const NamedDecl *ND = nullptr; 14279 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14280 ND = DRE->getDecl(); 14281 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14282 ND = ME->getMemberDecl(); 14283 14284 if (index.isUnsigned() || !index.isNegative()) { 14285 // It is possible that the type of the base expression after 14286 // IgnoreParenCasts is incomplete, even though the type of the base 14287 // expression before IgnoreParenCasts is complete (see PR39746 for an 14288 // example). In this case we have no information about whether the array 14289 // access exceeds the array bounds. However we can still diagnose an array 14290 // access which precedes the array bounds. 14291 if (BaseType->isIncompleteType()) 14292 return; 14293 14294 llvm::APInt size = ArrayTy->getSize(); 14295 if (!size.isStrictlyPositive()) 14296 return; 14297 14298 if (BaseType != EffectiveType) { 14299 // Make sure we're comparing apples to apples when comparing index to size 14300 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14301 uint64_t array_typesize = Context.getTypeSize(BaseType); 14302 // Handle ptrarith_typesize being zero, such as when casting to void* 14303 if (!ptrarith_typesize) ptrarith_typesize = 1; 14304 if (ptrarith_typesize != array_typesize) { 14305 // There's a cast to a different size type involved 14306 uint64_t ratio = array_typesize / ptrarith_typesize; 14307 // TODO: Be smarter about handling cases where array_typesize is not a 14308 // multiple of ptrarith_typesize 14309 if (ptrarith_typesize * ratio == array_typesize) 14310 size *= llvm::APInt(size.getBitWidth(), ratio); 14311 } 14312 } 14313 14314 if (size.getBitWidth() > index.getBitWidth()) 14315 index = index.zext(size.getBitWidth()); 14316 else if (size.getBitWidth() < index.getBitWidth()) 14317 size = size.zext(index.getBitWidth()); 14318 14319 // For array subscripting the index must be less than size, but for pointer 14320 // arithmetic also allow the index (offset) to be equal to size since 14321 // computing the next address after the end of the array is legal and 14322 // commonly done e.g. in C++ iterators and range-based for loops. 14323 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14324 return; 14325 14326 // Also don't warn for arrays of size 1 which are members of some 14327 // structure. These are often used to approximate flexible arrays in C89 14328 // code. 14329 if (IsTailPaddedMemberArray(*this, size, ND)) 14330 return; 14331 14332 // Suppress the warning if the subscript expression (as identified by the 14333 // ']' location) and the index expression are both from macro expansions 14334 // within a system header. 14335 if (ASE) { 14336 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14337 ASE->getRBracketLoc()); 14338 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14339 SourceLocation IndexLoc = 14340 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14341 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14342 return; 14343 } 14344 } 14345 14346 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14347 if (ASE) 14348 DiagID = diag::warn_array_index_exceeds_bounds; 14349 14350 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14351 PDiag(DiagID) << index.toString(10, true) 14352 << size.toString(10, true) 14353 << (unsigned)size.getLimitedValue(~0U) 14354 << IndexExpr->getSourceRange()); 14355 } else { 14356 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14357 if (!ASE) { 14358 DiagID = diag::warn_ptr_arith_precedes_bounds; 14359 if (index.isNegative()) index = -index; 14360 } 14361 14362 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14363 PDiag(DiagID) << index.toString(10, true) 14364 << IndexExpr->getSourceRange()); 14365 } 14366 14367 if (!ND) { 14368 // Try harder to find a NamedDecl to point at in the note. 14369 while (const ArraySubscriptExpr *ASE = 14370 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14371 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14372 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14373 ND = DRE->getDecl(); 14374 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14375 ND = ME->getMemberDecl(); 14376 } 14377 14378 if (ND) 14379 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14380 PDiag(diag::note_array_declared_here) << ND); 14381 } 14382 14383 void Sema::CheckArrayAccess(const Expr *expr) { 14384 int AllowOnePastEnd = 0; 14385 while (expr) { 14386 expr = expr->IgnoreParenImpCasts(); 14387 switch (expr->getStmtClass()) { 14388 case Stmt::ArraySubscriptExprClass: { 14389 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14390 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14391 AllowOnePastEnd > 0); 14392 expr = ASE->getBase(); 14393 break; 14394 } 14395 case Stmt::MemberExprClass: { 14396 expr = cast<MemberExpr>(expr)->getBase(); 14397 break; 14398 } 14399 case Stmt::OMPArraySectionExprClass: { 14400 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14401 if (ASE->getLowerBound()) 14402 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14403 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14404 return; 14405 } 14406 case Stmt::UnaryOperatorClass: { 14407 // Only unwrap the * and & unary operators 14408 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14409 expr = UO->getSubExpr(); 14410 switch (UO->getOpcode()) { 14411 case UO_AddrOf: 14412 AllowOnePastEnd++; 14413 break; 14414 case UO_Deref: 14415 AllowOnePastEnd--; 14416 break; 14417 default: 14418 return; 14419 } 14420 break; 14421 } 14422 case Stmt::ConditionalOperatorClass: { 14423 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14424 if (const Expr *lhs = cond->getLHS()) 14425 CheckArrayAccess(lhs); 14426 if (const Expr *rhs = cond->getRHS()) 14427 CheckArrayAccess(rhs); 14428 return; 14429 } 14430 case Stmt::CXXOperatorCallExprClass: { 14431 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14432 for (const auto *Arg : OCE->arguments()) 14433 CheckArrayAccess(Arg); 14434 return; 14435 } 14436 default: 14437 return; 14438 } 14439 } 14440 } 14441 14442 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14443 14444 namespace { 14445 14446 struct RetainCycleOwner { 14447 VarDecl *Variable = nullptr; 14448 SourceRange Range; 14449 SourceLocation Loc; 14450 bool Indirect = false; 14451 14452 RetainCycleOwner() = default; 14453 14454 void setLocsFrom(Expr *e) { 14455 Loc = e->getExprLoc(); 14456 Range = e->getSourceRange(); 14457 } 14458 }; 14459 14460 } // namespace 14461 14462 /// Consider whether capturing the given variable can possibly lead to 14463 /// a retain cycle. 14464 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14465 // In ARC, it's captured strongly iff the variable has __strong 14466 // lifetime. In MRR, it's captured strongly if the variable is 14467 // __block and has an appropriate type. 14468 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14469 return false; 14470 14471 owner.Variable = var; 14472 if (ref) 14473 owner.setLocsFrom(ref); 14474 return true; 14475 } 14476 14477 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14478 while (true) { 14479 e = e->IgnoreParens(); 14480 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14481 switch (cast->getCastKind()) { 14482 case CK_BitCast: 14483 case CK_LValueBitCast: 14484 case CK_LValueToRValue: 14485 case CK_ARCReclaimReturnedObject: 14486 e = cast->getSubExpr(); 14487 continue; 14488 14489 default: 14490 return false; 14491 } 14492 } 14493 14494 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14495 ObjCIvarDecl *ivar = ref->getDecl(); 14496 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14497 return false; 14498 14499 // Try to find a retain cycle in the base. 14500 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14501 return false; 14502 14503 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14504 owner.Indirect = true; 14505 return true; 14506 } 14507 14508 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14509 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14510 if (!var) return false; 14511 return considerVariable(var, ref, owner); 14512 } 14513 14514 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14515 if (member->isArrow()) return false; 14516 14517 // Don't count this as an indirect ownership. 14518 e = member->getBase(); 14519 continue; 14520 } 14521 14522 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14523 // Only pay attention to pseudo-objects on property references. 14524 ObjCPropertyRefExpr *pre 14525 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14526 ->IgnoreParens()); 14527 if (!pre) return false; 14528 if (pre->isImplicitProperty()) return false; 14529 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14530 if (!property->isRetaining() && 14531 !(property->getPropertyIvarDecl() && 14532 property->getPropertyIvarDecl()->getType() 14533 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14534 return false; 14535 14536 owner.Indirect = true; 14537 if (pre->isSuperReceiver()) { 14538 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14539 if (!owner.Variable) 14540 return false; 14541 owner.Loc = pre->getLocation(); 14542 owner.Range = pre->getSourceRange(); 14543 return true; 14544 } 14545 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14546 ->getSourceExpr()); 14547 continue; 14548 } 14549 14550 // Array ivars? 14551 14552 return false; 14553 } 14554 } 14555 14556 namespace { 14557 14558 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14559 ASTContext &Context; 14560 VarDecl *Variable; 14561 Expr *Capturer = nullptr; 14562 bool VarWillBeReased = false; 14563 14564 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14565 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14566 Context(Context), Variable(variable) {} 14567 14568 void VisitDeclRefExpr(DeclRefExpr *ref) { 14569 if (ref->getDecl() == Variable && !Capturer) 14570 Capturer = ref; 14571 } 14572 14573 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14574 if (Capturer) return; 14575 Visit(ref->getBase()); 14576 if (Capturer && ref->isFreeIvar()) 14577 Capturer = ref; 14578 } 14579 14580 void VisitBlockExpr(BlockExpr *block) { 14581 // Look inside nested blocks 14582 if (block->getBlockDecl()->capturesVariable(Variable)) 14583 Visit(block->getBlockDecl()->getBody()); 14584 } 14585 14586 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14587 if (Capturer) return; 14588 if (OVE->getSourceExpr()) 14589 Visit(OVE->getSourceExpr()); 14590 } 14591 14592 void VisitBinaryOperator(BinaryOperator *BinOp) { 14593 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14594 return; 14595 Expr *LHS = BinOp->getLHS(); 14596 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14597 if (DRE->getDecl() != Variable) 14598 return; 14599 if (Expr *RHS = BinOp->getRHS()) { 14600 RHS = RHS->IgnoreParenCasts(); 14601 Optional<llvm::APSInt> Value; 14602 VarWillBeReased = 14603 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14604 *Value == 0); 14605 } 14606 } 14607 } 14608 }; 14609 14610 } // namespace 14611 14612 /// Check whether the given argument is a block which captures a 14613 /// variable. 14614 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14615 assert(owner.Variable && owner.Loc.isValid()); 14616 14617 e = e->IgnoreParenCasts(); 14618 14619 // Look through [^{...} copy] and Block_copy(^{...}). 14620 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14621 Selector Cmd = ME->getSelector(); 14622 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14623 e = ME->getInstanceReceiver(); 14624 if (!e) 14625 return nullptr; 14626 e = e->IgnoreParenCasts(); 14627 } 14628 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14629 if (CE->getNumArgs() == 1) { 14630 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14631 if (Fn) { 14632 const IdentifierInfo *FnI = Fn->getIdentifier(); 14633 if (FnI && FnI->isStr("_Block_copy")) { 14634 e = CE->getArg(0)->IgnoreParenCasts(); 14635 } 14636 } 14637 } 14638 } 14639 14640 BlockExpr *block = dyn_cast<BlockExpr>(e); 14641 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14642 return nullptr; 14643 14644 FindCaptureVisitor visitor(S.Context, owner.Variable); 14645 visitor.Visit(block->getBlockDecl()->getBody()); 14646 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14647 } 14648 14649 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14650 RetainCycleOwner &owner) { 14651 assert(capturer); 14652 assert(owner.Variable && owner.Loc.isValid()); 14653 14654 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14655 << owner.Variable << capturer->getSourceRange(); 14656 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14657 << owner.Indirect << owner.Range; 14658 } 14659 14660 /// Check for a keyword selector that starts with the word 'add' or 14661 /// 'set'. 14662 static bool isSetterLikeSelector(Selector sel) { 14663 if (sel.isUnarySelector()) return false; 14664 14665 StringRef str = sel.getNameForSlot(0); 14666 while (!str.empty() && str.front() == '_') str = str.substr(1); 14667 if (str.startswith("set")) 14668 str = str.substr(3); 14669 else if (str.startswith("add")) { 14670 // Specially allow 'addOperationWithBlock:'. 14671 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14672 return false; 14673 str = str.substr(3); 14674 } 14675 else 14676 return false; 14677 14678 if (str.empty()) return true; 14679 return !isLowercase(str.front()); 14680 } 14681 14682 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14683 ObjCMessageExpr *Message) { 14684 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14685 Message->getReceiverInterface(), 14686 NSAPI::ClassId_NSMutableArray); 14687 if (!IsMutableArray) { 14688 return None; 14689 } 14690 14691 Selector Sel = Message->getSelector(); 14692 14693 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14694 S.NSAPIObj->getNSArrayMethodKind(Sel); 14695 if (!MKOpt) { 14696 return None; 14697 } 14698 14699 NSAPI::NSArrayMethodKind MK = *MKOpt; 14700 14701 switch (MK) { 14702 case NSAPI::NSMutableArr_addObject: 14703 case NSAPI::NSMutableArr_insertObjectAtIndex: 14704 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14705 return 0; 14706 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14707 return 1; 14708 14709 default: 14710 return None; 14711 } 14712 14713 return None; 14714 } 14715 14716 static 14717 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14718 ObjCMessageExpr *Message) { 14719 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14720 Message->getReceiverInterface(), 14721 NSAPI::ClassId_NSMutableDictionary); 14722 if (!IsMutableDictionary) { 14723 return None; 14724 } 14725 14726 Selector Sel = Message->getSelector(); 14727 14728 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14729 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14730 if (!MKOpt) { 14731 return None; 14732 } 14733 14734 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14735 14736 switch (MK) { 14737 case NSAPI::NSMutableDict_setObjectForKey: 14738 case NSAPI::NSMutableDict_setValueForKey: 14739 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14740 return 0; 14741 14742 default: 14743 return None; 14744 } 14745 14746 return None; 14747 } 14748 14749 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14750 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14751 Message->getReceiverInterface(), 14752 NSAPI::ClassId_NSMutableSet); 14753 14754 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14755 Message->getReceiverInterface(), 14756 NSAPI::ClassId_NSMutableOrderedSet); 14757 if (!IsMutableSet && !IsMutableOrderedSet) { 14758 return None; 14759 } 14760 14761 Selector Sel = Message->getSelector(); 14762 14763 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14764 if (!MKOpt) { 14765 return None; 14766 } 14767 14768 NSAPI::NSSetMethodKind MK = *MKOpt; 14769 14770 switch (MK) { 14771 case NSAPI::NSMutableSet_addObject: 14772 case NSAPI::NSOrderedSet_setObjectAtIndex: 14773 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14774 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14775 return 0; 14776 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14777 return 1; 14778 } 14779 14780 return None; 14781 } 14782 14783 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14784 if (!Message->isInstanceMessage()) { 14785 return; 14786 } 14787 14788 Optional<int> ArgOpt; 14789 14790 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14791 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14792 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14793 return; 14794 } 14795 14796 int ArgIndex = *ArgOpt; 14797 14798 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14799 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14800 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14801 } 14802 14803 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14804 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14805 if (ArgRE->isObjCSelfExpr()) { 14806 Diag(Message->getSourceRange().getBegin(), 14807 diag::warn_objc_circular_container) 14808 << ArgRE->getDecl() << StringRef("'super'"); 14809 } 14810 } 14811 } else { 14812 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14813 14814 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14815 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14816 } 14817 14818 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14819 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14820 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14821 ValueDecl *Decl = ReceiverRE->getDecl(); 14822 Diag(Message->getSourceRange().getBegin(), 14823 diag::warn_objc_circular_container) 14824 << Decl << Decl; 14825 if (!ArgRE->isObjCSelfExpr()) { 14826 Diag(Decl->getLocation(), 14827 diag::note_objc_circular_container_declared_here) 14828 << Decl; 14829 } 14830 } 14831 } 14832 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14833 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14834 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14835 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14836 Diag(Message->getSourceRange().getBegin(), 14837 diag::warn_objc_circular_container) 14838 << Decl << Decl; 14839 Diag(Decl->getLocation(), 14840 diag::note_objc_circular_container_declared_here) 14841 << Decl; 14842 } 14843 } 14844 } 14845 } 14846 } 14847 14848 /// Check a message send to see if it's likely to cause a retain cycle. 14849 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14850 // Only check instance methods whose selector looks like a setter. 14851 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14852 return; 14853 14854 // Try to find a variable that the receiver is strongly owned by. 14855 RetainCycleOwner owner; 14856 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14857 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14858 return; 14859 } else { 14860 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14861 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14862 owner.Loc = msg->getSuperLoc(); 14863 owner.Range = msg->getSuperLoc(); 14864 } 14865 14866 // Check whether the receiver is captured by any of the arguments. 14867 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14868 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14869 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14870 // noescape blocks should not be retained by the method. 14871 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14872 continue; 14873 return diagnoseRetainCycle(*this, capturer, owner); 14874 } 14875 } 14876 } 14877 14878 /// Check a property assign to see if it's likely to cause a retain cycle. 14879 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14880 RetainCycleOwner owner; 14881 if (!findRetainCycleOwner(*this, receiver, owner)) 14882 return; 14883 14884 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14885 diagnoseRetainCycle(*this, capturer, owner); 14886 } 14887 14888 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14889 RetainCycleOwner Owner; 14890 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14891 return; 14892 14893 // Because we don't have an expression for the variable, we have to set the 14894 // location explicitly here. 14895 Owner.Loc = Var->getLocation(); 14896 Owner.Range = Var->getSourceRange(); 14897 14898 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14899 diagnoseRetainCycle(*this, Capturer, Owner); 14900 } 14901 14902 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14903 Expr *RHS, bool isProperty) { 14904 // Check if RHS is an Objective-C object literal, which also can get 14905 // immediately zapped in a weak reference. Note that we explicitly 14906 // allow ObjCStringLiterals, since those are designed to never really die. 14907 RHS = RHS->IgnoreParenImpCasts(); 14908 14909 // This enum needs to match with the 'select' in 14910 // warn_objc_arc_literal_assign (off-by-1). 14911 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14912 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14913 return false; 14914 14915 S.Diag(Loc, diag::warn_arc_literal_assign) 14916 << (unsigned) Kind 14917 << (isProperty ? 0 : 1) 14918 << RHS->getSourceRange(); 14919 14920 return true; 14921 } 14922 14923 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14924 Qualifiers::ObjCLifetime LT, 14925 Expr *RHS, bool isProperty) { 14926 // Strip off any implicit cast added to get to the one ARC-specific. 14927 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14928 if (cast->getCastKind() == CK_ARCConsumeObject) { 14929 S.Diag(Loc, diag::warn_arc_retained_assign) 14930 << (LT == Qualifiers::OCL_ExplicitNone) 14931 << (isProperty ? 0 : 1) 14932 << RHS->getSourceRange(); 14933 return true; 14934 } 14935 RHS = cast->getSubExpr(); 14936 } 14937 14938 if (LT == Qualifiers::OCL_Weak && 14939 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14940 return true; 14941 14942 return false; 14943 } 14944 14945 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14946 QualType LHS, Expr *RHS) { 14947 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14948 14949 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14950 return false; 14951 14952 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14953 return true; 14954 14955 return false; 14956 } 14957 14958 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14959 Expr *LHS, Expr *RHS) { 14960 QualType LHSType; 14961 // PropertyRef on LHS type need be directly obtained from 14962 // its declaration as it has a PseudoType. 14963 ObjCPropertyRefExpr *PRE 14964 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14965 if (PRE && !PRE->isImplicitProperty()) { 14966 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14967 if (PD) 14968 LHSType = PD->getType(); 14969 } 14970 14971 if (LHSType.isNull()) 14972 LHSType = LHS->getType(); 14973 14974 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14975 14976 if (LT == Qualifiers::OCL_Weak) { 14977 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14978 getCurFunction()->markSafeWeakUse(LHS); 14979 } 14980 14981 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14982 return; 14983 14984 // FIXME. Check for other life times. 14985 if (LT != Qualifiers::OCL_None) 14986 return; 14987 14988 if (PRE) { 14989 if (PRE->isImplicitProperty()) 14990 return; 14991 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14992 if (!PD) 14993 return; 14994 14995 unsigned Attributes = PD->getPropertyAttributes(); 14996 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14997 // when 'assign' attribute was not explicitly specified 14998 // by user, ignore it and rely on property type itself 14999 // for lifetime info. 15000 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15001 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15002 LHSType->isObjCRetainableType()) 15003 return; 15004 15005 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15006 if (cast->getCastKind() == CK_ARCConsumeObject) { 15007 Diag(Loc, diag::warn_arc_retained_property_assign) 15008 << RHS->getSourceRange(); 15009 return; 15010 } 15011 RHS = cast->getSubExpr(); 15012 } 15013 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15014 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15015 return; 15016 } 15017 } 15018 } 15019 15020 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15021 15022 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15023 SourceLocation StmtLoc, 15024 const NullStmt *Body) { 15025 // Do not warn if the body is a macro that expands to nothing, e.g: 15026 // 15027 // #define CALL(x) 15028 // if (condition) 15029 // CALL(0); 15030 if (Body->hasLeadingEmptyMacro()) 15031 return false; 15032 15033 // Get line numbers of statement and body. 15034 bool StmtLineInvalid; 15035 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15036 &StmtLineInvalid); 15037 if (StmtLineInvalid) 15038 return false; 15039 15040 bool BodyLineInvalid; 15041 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15042 &BodyLineInvalid); 15043 if (BodyLineInvalid) 15044 return false; 15045 15046 // Warn if null statement and body are on the same line. 15047 if (StmtLine != BodyLine) 15048 return false; 15049 15050 return true; 15051 } 15052 15053 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15054 const Stmt *Body, 15055 unsigned DiagID) { 15056 // Since this is a syntactic check, don't emit diagnostic for template 15057 // instantiations, this just adds noise. 15058 if (CurrentInstantiationScope) 15059 return; 15060 15061 // The body should be a null statement. 15062 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15063 if (!NBody) 15064 return; 15065 15066 // Do the usual checks. 15067 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15068 return; 15069 15070 Diag(NBody->getSemiLoc(), DiagID); 15071 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15072 } 15073 15074 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15075 const Stmt *PossibleBody) { 15076 assert(!CurrentInstantiationScope); // Ensured by caller 15077 15078 SourceLocation StmtLoc; 15079 const Stmt *Body; 15080 unsigned DiagID; 15081 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15082 StmtLoc = FS->getRParenLoc(); 15083 Body = FS->getBody(); 15084 DiagID = diag::warn_empty_for_body; 15085 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15086 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15087 Body = WS->getBody(); 15088 DiagID = diag::warn_empty_while_body; 15089 } else 15090 return; // Neither `for' nor `while'. 15091 15092 // The body should be a null statement. 15093 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15094 if (!NBody) 15095 return; 15096 15097 // Skip expensive checks if diagnostic is disabled. 15098 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15099 return; 15100 15101 // Do the usual checks. 15102 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15103 return; 15104 15105 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15106 // noise level low, emit diagnostics only if for/while is followed by a 15107 // CompoundStmt, e.g.: 15108 // for (int i = 0; i < n; i++); 15109 // { 15110 // a(i); 15111 // } 15112 // or if for/while is followed by a statement with more indentation 15113 // than for/while itself: 15114 // for (int i = 0; i < n; i++); 15115 // a(i); 15116 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15117 if (!ProbableTypo) { 15118 bool BodyColInvalid; 15119 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15120 PossibleBody->getBeginLoc(), &BodyColInvalid); 15121 if (BodyColInvalid) 15122 return; 15123 15124 bool StmtColInvalid; 15125 unsigned StmtCol = 15126 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15127 if (StmtColInvalid) 15128 return; 15129 15130 if (BodyCol > StmtCol) 15131 ProbableTypo = true; 15132 } 15133 15134 if (ProbableTypo) { 15135 Diag(NBody->getSemiLoc(), DiagID); 15136 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15137 } 15138 } 15139 15140 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15141 15142 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15143 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15144 SourceLocation OpLoc) { 15145 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15146 return; 15147 15148 if (inTemplateInstantiation()) 15149 return; 15150 15151 // Strip parens and casts away. 15152 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15153 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15154 15155 // Check for a call expression 15156 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15157 if (!CE || CE->getNumArgs() != 1) 15158 return; 15159 15160 // Check for a call to std::move 15161 if (!CE->isCallToStdMove()) 15162 return; 15163 15164 // Get argument from std::move 15165 RHSExpr = CE->getArg(0); 15166 15167 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15168 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15169 15170 // Two DeclRefExpr's, check that the decls are the same. 15171 if (LHSDeclRef && RHSDeclRef) { 15172 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15173 return; 15174 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15175 RHSDeclRef->getDecl()->getCanonicalDecl()) 15176 return; 15177 15178 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15179 << LHSExpr->getSourceRange() 15180 << RHSExpr->getSourceRange(); 15181 return; 15182 } 15183 15184 // Member variables require a different approach to check for self moves. 15185 // MemberExpr's are the same if every nested MemberExpr refers to the same 15186 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15187 // the base Expr's are CXXThisExpr's. 15188 const Expr *LHSBase = LHSExpr; 15189 const Expr *RHSBase = RHSExpr; 15190 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15191 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15192 if (!LHSME || !RHSME) 15193 return; 15194 15195 while (LHSME && RHSME) { 15196 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15197 RHSME->getMemberDecl()->getCanonicalDecl()) 15198 return; 15199 15200 LHSBase = LHSME->getBase(); 15201 RHSBase = RHSME->getBase(); 15202 LHSME = dyn_cast<MemberExpr>(LHSBase); 15203 RHSME = dyn_cast<MemberExpr>(RHSBase); 15204 } 15205 15206 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15207 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15208 if (LHSDeclRef && RHSDeclRef) { 15209 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15210 return; 15211 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15212 RHSDeclRef->getDecl()->getCanonicalDecl()) 15213 return; 15214 15215 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15216 << LHSExpr->getSourceRange() 15217 << RHSExpr->getSourceRange(); 15218 return; 15219 } 15220 15221 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15222 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15223 << LHSExpr->getSourceRange() 15224 << RHSExpr->getSourceRange(); 15225 } 15226 15227 //===--- Layout compatibility ----------------------------------------------// 15228 15229 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15230 15231 /// Check if two enumeration types are layout-compatible. 15232 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15233 // C++11 [dcl.enum] p8: 15234 // Two enumeration types are layout-compatible if they have the same 15235 // underlying type. 15236 return ED1->isComplete() && ED2->isComplete() && 15237 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15238 } 15239 15240 /// Check if two fields are layout-compatible. 15241 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15242 FieldDecl *Field2) { 15243 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15244 return false; 15245 15246 if (Field1->isBitField() != Field2->isBitField()) 15247 return false; 15248 15249 if (Field1->isBitField()) { 15250 // Make sure that the bit-fields are the same length. 15251 unsigned Bits1 = Field1->getBitWidthValue(C); 15252 unsigned Bits2 = Field2->getBitWidthValue(C); 15253 15254 if (Bits1 != Bits2) 15255 return false; 15256 } 15257 15258 return true; 15259 } 15260 15261 /// Check if two standard-layout structs are layout-compatible. 15262 /// (C++11 [class.mem] p17) 15263 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15264 RecordDecl *RD2) { 15265 // If both records are C++ classes, check that base classes match. 15266 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15267 // If one of records is a CXXRecordDecl we are in C++ mode, 15268 // thus the other one is a CXXRecordDecl, too. 15269 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15270 // Check number of base classes. 15271 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15272 return false; 15273 15274 // Check the base classes. 15275 for (CXXRecordDecl::base_class_const_iterator 15276 Base1 = D1CXX->bases_begin(), 15277 BaseEnd1 = D1CXX->bases_end(), 15278 Base2 = D2CXX->bases_begin(); 15279 Base1 != BaseEnd1; 15280 ++Base1, ++Base2) { 15281 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15282 return false; 15283 } 15284 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15285 // If only RD2 is a C++ class, it should have zero base classes. 15286 if (D2CXX->getNumBases() > 0) 15287 return false; 15288 } 15289 15290 // Check the fields. 15291 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15292 Field2End = RD2->field_end(), 15293 Field1 = RD1->field_begin(), 15294 Field1End = RD1->field_end(); 15295 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15296 if (!isLayoutCompatible(C, *Field1, *Field2)) 15297 return false; 15298 } 15299 if (Field1 != Field1End || Field2 != Field2End) 15300 return false; 15301 15302 return true; 15303 } 15304 15305 /// Check if two standard-layout unions are layout-compatible. 15306 /// (C++11 [class.mem] p18) 15307 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15308 RecordDecl *RD2) { 15309 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15310 for (auto *Field2 : RD2->fields()) 15311 UnmatchedFields.insert(Field2); 15312 15313 for (auto *Field1 : RD1->fields()) { 15314 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15315 I = UnmatchedFields.begin(), 15316 E = UnmatchedFields.end(); 15317 15318 for ( ; I != E; ++I) { 15319 if (isLayoutCompatible(C, Field1, *I)) { 15320 bool Result = UnmatchedFields.erase(*I); 15321 (void) Result; 15322 assert(Result); 15323 break; 15324 } 15325 } 15326 if (I == E) 15327 return false; 15328 } 15329 15330 return UnmatchedFields.empty(); 15331 } 15332 15333 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15334 RecordDecl *RD2) { 15335 if (RD1->isUnion() != RD2->isUnion()) 15336 return false; 15337 15338 if (RD1->isUnion()) 15339 return isLayoutCompatibleUnion(C, RD1, RD2); 15340 else 15341 return isLayoutCompatibleStruct(C, RD1, RD2); 15342 } 15343 15344 /// Check if two types are layout-compatible in C++11 sense. 15345 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15346 if (T1.isNull() || T2.isNull()) 15347 return false; 15348 15349 // C++11 [basic.types] p11: 15350 // If two types T1 and T2 are the same type, then T1 and T2 are 15351 // layout-compatible types. 15352 if (C.hasSameType(T1, T2)) 15353 return true; 15354 15355 T1 = T1.getCanonicalType().getUnqualifiedType(); 15356 T2 = T2.getCanonicalType().getUnqualifiedType(); 15357 15358 const Type::TypeClass TC1 = T1->getTypeClass(); 15359 const Type::TypeClass TC2 = T2->getTypeClass(); 15360 15361 if (TC1 != TC2) 15362 return false; 15363 15364 if (TC1 == Type::Enum) { 15365 return isLayoutCompatible(C, 15366 cast<EnumType>(T1)->getDecl(), 15367 cast<EnumType>(T2)->getDecl()); 15368 } else if (TC1 == Type::Record) { 15369 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15370 return false; 15371 15372 return isLayoutCompatible(C, 15373 cast<RecordType>(T1)->getDecl(), 15374 cast<RecordType>(T2)->getDecl()); 15375 } 15376 15377 return false; 15378 } 15379 15380 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15381 15382 /// Given a type tag expression find the type tag itself. 15383 /// 15384 /// \param TypeExpr Type tag expression, as it appears in user's code. 15385 /// 15386 /// \param VD Declaration of an identifier that appears in a type tag. 15387 /// 15388 /// \param MagicValue Type tag magic value. 15389 /// 15390 /// \param isConstantEvaluated wether the evalaution should be performed in 15391 15392 /// constant context. 15393 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15394 const ValueDecl **VD, uint64_t *MagicValue, 15395 bool isConstantEvaluated) { 15396 while(true) { 15397 if (!TypeExpr) 15398 return false; 15399 15400 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15401 15402 switch (TypeExpr->getStmtClass()) { 15403 case Stmt::UnaryOperatorClass: { 15404 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15405 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15406 TypeExpr = UO->getSubExpr(); 15407 continue; 15408 } 15409 return false; 15410 } 15411 15412 case Stmt::DeclRefExprClass: { 15413 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15414 *VD = DRE->getDecl(); 15415 return true; 15416 } 15417 15418 case Stmt::IntegerLiteralClass: { 15419 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15420 llvm::APInt MagicValueAPInt = IL->getValue(); 15421 if (MagicValueAPInt.getActiveBits() <= 64) { 15422 *MagicValue = MagicValueAPInt.getZExtValue(); 15423 return true; 15424 } else 15425 return false; 15426 } 15427 15428 case Stmt::BinaryConditionalOperatorClass: 15429 case Stmt::ConditionalOperatorClass: { 15430 const AbstractConditionalOperator *ACO = 15431 cast<AbstractConditionalOperator>(TypeExpr); 15432 bool Result; 15433 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15434 isConstantEvaluated)) { 15435 if (Result) 15436 TypeExpr = ACO->getTrueExpr(); 15437 else 15438 TypeExpr = ACO->getFalseExpr(); 15439 continue; 15440 } 15441 return false; 15442 } 15443 15444 case Stmt::BinaryOperatorClass: { 15445 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15446 if (BO->getOpcode() == BO_Comma) { 15447 TypeExpr = BO->getRHS(); 15448 continue; 15449 } 15450 return false; 15451 } 15452 15453 default: 15454 return false; 15455 } 15456 } 15457 } 15458 15459 /// Retrieve the C type corresponding to type tag TypeExpr. 15460 /// 15461 /// \param TypeExpr Expression that specifies a type tag. 15462 /// 15463 /// \param MagicValues Registered magic values. 15464 /// 15465 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15466 /// kind. 15467 /// 15468 /// \param TypeInfo Information about the corresponding C type. 15469 /// 15470 /// \param isConstantEvaluated wether the evalaution should be performed in 15471 /// constant context. 15472 /// 15473 /// \returns true if the corresponding C type was found. 15474 static bool GetMatchingCType( 15475 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15476 const ASTContext &Ctx, 15477 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15478 *MagicValues, 15479 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15480 bool isConstantEvaluated) { 15481 FoundWrongKind = false; 15482 15483 // Variable declaration that has type_tag_for_datatype attribute. 15484 const ValueDecl *VD = nullptr; 15485 15486 uint64_t MagicValue; 15487 15488 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15489 return false; 15490 15491 if (VD) { 15492 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15493 if (I->getArgumentKind() != ArgumentKind) { 15494 FoundWrongKind = true; 15495 return false; 15496 } 15497 TypeInfo.Type = I->getMatchingCType(); 15498 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15499 TypeInfo.MustBeNull = I->getMustBeNull(); 15500 return true; 15501 } 15502 return false; 15503 } 15504 15505 if (!MagicValues) 15506 return false; 15507 15508 llvm::DenseMap<Sema::TypeTagMagicValue, 15509 Sema::TypeTagData>::const_iterator I = 15510 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15511 if (I == MagicValues->end()) 15512 return false; 15513 15514 TypeInfo = I->second; 15515 return true; 15516 } 15517 15518 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15519 uint64_t MagicValue, QualType Type, 15520 bool LayoutCompatible, 15521 bool MustBeNull) { 15522 if (!TypeTagForDatatypeMagicValues) 15523 TypeTagForDatatypeMagicValues.reset( 15524 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15525 15526 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15527 (*TypeTagForDatatypeMagicValues)[Magic] = 15528 TypeTagData(Type, LayoutCompatible, MustBeNull); 15529 } 15530 15531 static bool IsSameCharType(QualType T1, QualType T2) { 15532 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15533 if (!BT1) 15534 return false; 15535 15536 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15537 if (!BT2) 15538 return false; 15539 15540 BuiltinType::Kind T1Kind = BT1->getKind(); 15541 BuiltinType::Kind T2Kind = BT2->getKind(); 15542 15543 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15544 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15545 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15546 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15547 } 15548 15549 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15550 const ArrayRef<const Expr *> ExprArgs, 15551 SourceLocation CallSiteLoc) { 15552 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15553 bool IsPointerAttr = Attr->getIsPointer(); 15554 15555 // Retrieve the argument representing the 'type_tag'. 15556 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15557 if (TypeTagIdxAST >= ExprArgs.size()) { 15558 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15559 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15560 return; 15561 } 15562 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15563 bool FoundWrongKind; 15564 TypeTagData TypeInfo; 15565 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15566 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15567 TypeInfo, isConstantEvaluated())) { 15568 if (FoundWrongKind) 15569 Diag(TypeTagExpr->getExprLoc(), 15570 diag::warn_type_tag_for_datatype_wrong_kind) 15571 << TypeTagExpr->getSourceRange(); 15572 return; 15573 } 15574 15575 // Retrieve the argument representing the 'arg_idx'. 15576 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15577 if (ArgumentIdxAST >= ExprArgs.size()) { 15578 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15579 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15580 return; 15581 } 15582 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15583 if (IsPointerAttr) { 15584 // Skip implicit cast of pointer to `void *' (as a function argument). 15585 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15586 if (ICE->getType()->isVoidPointerType() && 15587 ICE->getCastKind() == CK_BitCast) 15588 ArgumentExpr = ICE->getSubExpr(); 15589 } 15590 QualType ArgumentType = ArgumentExpr->getType(); 15591 15592 // Passing a `void*' pointer shouldn't trigger a warning. 15593 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15594 return; 15595 15596 if (TypeInfo.MustBeNull) { 15597 // Type tag with matching void type requires a null pointer. 15598 if (!ArgumentExpr->isNullPointerConstant(Context, 15599 Expr::NPC_ValueDependentIsNotNull)) { 15600 Diag(ArgumentExpr->getExprLoc(), 15601 diag::warn_type_safety_null_pointer_required) 15602 << ArgumentKind->getName() 15603 << ArgumentExpr->getSourceRange() 15604 << TypeTagExpr->getSourceRange(); 15605 } 15606 return; 15607 } 15608 15609 QualType RequiredType = TypeInfo.Type; 15610 if (IsPointerAttr) 15611 RequiredType = Context.getPointerType(RequiredType); 15612 15613 bool mismatch = false; 15614 if (!TypeInfo.LayoutCompatible) { 15615 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15616 15617 // C++11 [basic.fundamental] p1: 15618 // Plain char, signed char, and unsigned char are three distinct types. 15619 // 15620 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15621 // char' depending on the current char signedness mode. 15622 if (mismatch) 15623 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15624 RequiredType->getPointeeType())) || 15625 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15626 mismatch = false; 15627 } else 15628 if (IsPointerAttr) 15629 mismatch = !isLayoutCompatible(Context, 15630 ArgumentType->getPointeeType(), 15631 RequiredType->getPointeeType()); 15632 else 15633 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15634 15635 if (mismatch) 15636 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15637 << ArgumentType << ArgumentKind 15638 << TypeInfo.LayoutCompatible << RequiredType 15639 << ArgumentExpr->getSourceRange() 15640 << TypeTagExpr->getSourceRange(); 15641 } 15642 15643 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15644 CharUnits Alignment) { 15645 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15646 } 15647 15648 void Sema::DiagnoseMisalignedMembers() { 15649 for (MisalignedMember &m : MisalignedMembers) { 15650 const NamedDecl *ND = m.RD; 15651 if (ND->getName().empty()) { 15652 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15653 ND = TD; 15654 } 15655 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15656 << m.MD << ND << m.E->getSourceRange(); 15657 } 15658 MisalignedMembers.clear(); 15659 } 15660 15661 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15662 E = E->IgnoreParens(); 15663 if (!T->isPointerType() && !T->isIntegerType()) 15664 return; 15665 if (isa<UnaryOperator>(E) && 15666 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15667 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15668 if (isa<MemberExpr>(Op)) { 15669 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15670 if (MA != MisalignedMembers.end() && 15671 (T->isIntegerType() || 15672 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15673 Context.getTypeAlignInChars( 15674 T->getPointeeType()) <= MA->Alignment)))) 15675 MisalignedMembers.erase(MA); 15676 } 15677 } 15678 } 15679 15680 void Sema::RefersToMemberWithReducedAlignment( 15681 Expr *E, 15682 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15683 Action) { 15684 const auto *ME = dyn_cast<MemberExpr>(E); 15685 if (!ME) 15686 return; 15687 15688 // No need to check expressions with an __unaligned-qualified type. 15689 if (E->getType().getQualifiers().hasUnaligned()) 15690 return; 15691 15692 // For a chain of MemberExpr like "a.b.c.d" this list 15693 // will keep FieldDecl's like [d, c, b]. 15694 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15695 const MemberExpr *TopME = nullptr; 15696 bool AnyIsPacked = false; 15697 do { 15698 QualType BaseType = ME->getBase()->getType(); 15699 if (BaseType->isDependentType()) 15700 return; 15701 if (ME->isArrow()) 15702 BaseType = BaseType->getPointeeType(); 15703 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15704 if (RD->isInvalidDecl()) 15705 return; 15706 15707 ValueDecl *MD = ME->getMemberDecl(); 15708 auto *FD = dyn_cast<FieldDecl>(MD); 15709 // We do not care about non-data members. 15710 if (!FD || FD->isInvalidDecl()) 15711 return; 15712 15713 AnyIsPacked = 15714 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15715 ReverseMemberChain.push_back(FD); 15716 15717 TopME = ME; 15718 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15719 } while (ME); 15720 assert(TopME && "We did not compute a topmost MemberExpr!"); 15721 15722 // Not the scope of this diagnostic. 15723 if (!AnyIsPacked) 15724 return; 15725 15726 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15727 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15728 // TODO: The innermost base of the member expression may be too complicated. 15729 // For now, just disregard these cases. This is left for future 15730 // improvement. 15731 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15732 return; 15733 15734 // Alignment expected by the whole expression. 15735 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15736 15737 // No need to do anything else with this case. 15738 if (ExpectedAlignment.isOne()) 15739 return; 15740 15741 // Synthesize offset of the whole access. 15742 CharUnits Offset; 15743 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15744 I++) { 15745 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15746 } 15747 15748 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15749 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15750 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15751 15752 // The base expression of the innermost MemberExpr may give 15753 // stronger guarantees than the class containing the member. 15754 if (DRE && !TopME->isArrow()) { 15755 const ValueDecl *VD = DRE->getDecl(); 15756 if (!VD->getType()->isReferenceType()) 15757 CompleteObjectAlignment = 15758 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15759 } 15760 15761 // Check if the synthesized offset fulfills the alignment. 15762 if (Offset % ExpectedAlignment != 0 || 15763 // It may fulfill the offset it but the effective alignment may still be 15764 // lower than the expected expression alignment. 15765 CompleteObjectAlignment < ExpectedAlignment) { 15766 // If this happens, we want to determine a sensible culprit of this. 15767 // Intuitively, watching the chain of member expressions from right to 15768 // left, we start with the required alignment (as required by the field 15769 // type) but some packed attribute in that chain has reduced the alignment. 15770 // It may happen that another packed structure increases it again. But if 15771 // we are here such increase has not been enough. So pointing the first 15772 // FieldDecl that either is packed or else its RecordDecl is, 15773 // seems reasonable. 15774 FieldDecl *FD = nullptr; 15775 CharUnits Alignment; 15776 for (FieldDecl *FDI : ReverseMemberChain) { 15777 if (FDI->hasAttr<PackedAttr>() || 15778 FDI->getParent()->hasAttr<PackedAttr>()) { 15779 FD = FDI; 15780 Alignment = std::min( 15781 Context.getTypeAlignInChars(FD->getType()), 15782 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15783 break; 15784 } 15785 } 15786 assert(FD && "We did not find a packed FieldDecl!"); 15787 Action(E, FD->getParent(), FD, Alignment); 15788 } 15789 } 15790 15791 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15792 using namespace std::placeholders; 15793 15794 RefersToMemberWithReducedAlignment( 15795 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15796 _2, _3, _4)); 15797 } 15798 15799 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15800 ExprResult CallResult) { 15801 if (checkArgCount(*this, TheCall, 1)) 15802 return ExprError(); 15803 15804 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15805 if (MatrixArg.isInvalid()) 15806 return MatrixArg; 15807 Expr *Matrix = MatrixArg.get(); 15808 15809 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15810 if (!MType) { 15811 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15812 return ExprError(); 15813 } 15814 15815 // Create returned matrix type by swapping rows and columns of the argument 15816 // matrix type. 15817 QualType ResultType = Context.getConstantMatrixType( 15818 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15819 15820 // Change the return type to the type of the returned matrix. 15821 TheCall->setType(ResultType); 15822 15823 // Update call argument to use the possibly converted matrix argument. 15824 TheCall->setArg(0, Matrix); 15825 return CallResult; 15826 } 15827 15828 // Get and verify the matrix dimensions. 15829 static llvm::Optional<unsigned> 15830 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15831 SourceLocation ErrorPos; 15832 Optional<llvm::APSInt> Value = 15833 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15834 if (!Value) { 15835 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15836 << Name; 15837 return {}; 15838 } 15839 uint64_t Dim = Value->getZExtValue(); 15840 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15841 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15842 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15843 return {}; 15844 } 15845 return Dim; 15846 } 15847 15848 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15849 ExprResult CallResult) { 15850 if (!getLangOpts().MatrixTypes) { 15851 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15852 return ExprError(); 15853 } 15854 15855 if (checkArgCount(*this, TheCall, 4)) 15856 return ExprError(); 15857 15858 unsigned PtrArgIdx = 0; 15859 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15860 Expr *RowsExpr = TheCall->getArg(1); 15861 Expr *ColumnsExpr = TheCall->getArg(2); 15862 Expr *StrideExpr = TheCall->getArg(3); 15863 15864 bool ArgError = false; 15865 15866 // Check pointer argument. 15867 { 15868 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15869 if (PtrConv.isInvalid()) 15870 return PtrConv; 15871 PtrExpr = PtrConv.get(); 15872 TheCall->setArg(0, PtrExpr); 15873 if (PtrExpr->isTypeDependent()) { 15874 TheCall->setType(Context.DependentTy); 15875 return TheCall; 15876 } 15877 } 15878 15879 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15880 QualType ElementTy; 15881 if (!PtrTy) { 15882 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15883 << PtrArgIdx + 1; 15884 ArgError = true; 15885 } else { 15886 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15887 15888 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15889 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15890 << PtrArgIdx + 1; 15891 ArgError = true; 15892 } 15893 } 15894 15895 // Apply default Lvalue conversions and convert the expression to size_t. 15896 auto ApplyArgumentConversions = [this](Expr *E) { 15897 ExprResult Conv = DefaultLvalueConversion(E); 15898 if (Conv.isInvalid()) 15899 return Conv; 15900 15901 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15902 }; 15903 15904 // Apply conversion to row and column expressions. 15905 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15906 if (!RowsConv.isInvalid()) { 15907 RowsExpr = RowsConv.get(); 15908 TheCall->setArg(1, RowsExpr); 15909 } else 15910 RowsExpr = nullptr; 15911 15912 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15913 if (!ColumnsConv.isInvalid()) { 15914 ColumnsExpr = ColumnsConv.get(); 15915 TheCall->setArg(2, ColumnsExpr); 15916 } else 15917 ColumnsExpr = nullptr; 15918 15919 // If any any part of the result matrix type is still pending, just use 15920 // Context.DependentTy, until all parts are resolved. 15921 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15922 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15923 TheCall->setType(Context.DependentTy); 15924 return CallResult; 15925 } 15926 15927 // Check row and column dimenions. 15928 llvm::Optional<unsigned> MaybeRows; 15929 if (RowsExpr) 15930 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15931 15932 llvm::Optional<unsigned> MaybeColumns; 15933 if (ColumnsExpr) 15934 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15935 15936 // Check stride argument. 15937 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15938 if (StrideConv.isInvalid()) 15939 return ExprError(); 15940 StrideExpr = StrideConv.get(); 15941 TheCall->setArg(3, StrideExpr); 15942 15943 if (MaybeRows) { 15944 if (Optional<llvm::APSInt> Value = 15945 StrideExpr->getIntegerConstantExpr(Context)) { 15946 uint64_t Stride = Value->getZExtValue(); 15947 if (Stride < *MaybeRows) { 15948 Diag(StrideExpr->getBeginLoc(), 15949 diag::err_builtin_matrix_stride_too_small); 15950 ArgError = true; 15951 } 15952 } 15953 } 15954 15955 if (ArgError || !MaybeRows || !MaybeColumns) 15956 return ExprError(); 15957 15958 TheCall->setType( 15959 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15960 return CallResult; 15961 } 15962 15963 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15964 ExprResult CallResult) { 15965 if (checkArgCount(*this, TheCall, 3)) 15966 return ExprError(); 15967 15968 unsigned PtrArgIdx = 1; 15969 Expr *MatrixExpr = TheCall->getArg(0); 15970 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15971 Expr *StrideExpr = TheCall->getArg(2); 15972 15973 bool ArgError = false; 15974 15975 { 15976 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15977 if (MatrixConv.isInvalid()) 15978 return MatrixConv; 15979 MatrixExpr = MatrixConv.get(); 15980 TheCall->setArg(0, MatrixExpr); 15981 } 15982 if (MatrixExpr->isTypeDependent()) { 15983 TheCall->setType(Context.DependentTy); 15984 return TheCall; 15985 } 15986 15987 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15988 if (!MatrixTy) { 15989 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15990 ArgError = true; 15991 } 15992 15993 { 15994 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15995 if (PtrConv.isInvalid()) 15996 return PtrConv; 15997 PtrExpr = PtrConv.get(); 15998 TheCall->setArg(1, PtrExpr); 15999 if (PtrExpr->isTypeDependent()) { 16000 TheCall->setType(Context.DependentTy); 16001 return TheCall; 16002 } 16003 } 16004 16005 // Check pointer argument. 16006 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16007 if (!PtrTy) { 16008 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16009 << PtrArgIdx + 1; 16010 ArgError = true; 16011 } else { 16012 QualType ElementTy = PtrTy->getPointeeType(); 16013 if (ElementTy.isConstQualified()) { 16014 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16015 ArgError = true; 16016 } 16017 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16018 if (MatrixTy && 16019 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16020 Diag(PtrExpr->getBeginLoc(), 16021 diag::err_builtin_matrix_pointer_arg_mismatch) 16022 << ElementTy << MatrixTy->getElementType(); 16023 ArgError = true; 16024 } 16025 } 16026 16027 // Apply default Lvalue conversions and convert the stride expression to 16028 // size_t. 16029 { 16030 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16031 if (StrideConv.isInvalid()) 16032 return StrideConv; 16033 16034 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16035 if (StrideConv.isInvalid()) 16036 return StrideConv; 16037 StrideExpr = StrideConv.get(); 16038 TheCall->setArg(2, StrideExpr); 16039 } 16040 16041 // Check stride argument. 16042 if (MatrixTy) { 16043 if (Optional<llvm::APSInt> Value = 16044 StrideExpr->getIntegerConstantExpr(Context)) { 16045 uint64_t Stride = Value->getZExtValue(); 16046 if (Stride < MatrixTy->getNumRows()) { 16047 Diag(StrideExpr->getBeginLoc(), 16048 diag::err_builtin_matrix_stride_too_small); 16049 ArgError = true; 16050 } 16051 } 16052 } 16053 16054 if (ArgError) 16055 return ExprError(); 16056 16057 return CallResult; 16058 } 16059