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::ppcle: 1426 case llvm::Triple::ppc64: 1427 case llvm::Triple::ppc64le: 1428 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1429 case llvm::Triple::amdgcn: 1430 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1431 } 1432 } 1433 1434 ExprResult 1435 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1436 CallExpr *TheCall) { 1437 ExprResult TheCallResult(TheCall); 1438 1439 // Find out if any arguments are required to be integer constant expressions. 1440 unsigned ICEArguments = 0; 1441 ASTContext::GetBuiltinTypeError Error; 1442 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1443 if (Error != ASTContext::GE_None) 1444 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1445 1446 // If any arguments are required to be ICE's, check and diagnose. 1447 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1448 // Skip arguments not required to be ICE's. 1449 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1450 1451 llvm::APSInt Result; 1452 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1453 return true; 1454 ICEArguments &= ~(1 << ArgNo); 1455 } 1456 1457 switch (BuiltinID) { 1458 case Builtin::BI__builtin___CFStringMakeConstantString: 1459 assert(TheCall->getNumArgs() == 1 && 1460 "Wrong # arguments to builtin CFStringMakeConstantString"); 1461 if (CheckObjCString(TheCall->getArg(0))) 1462 return ExprError(); 1463 break; 1464 case Builtin::BI__builtin_ms_va_start: 1465 case Builtin::BI__builtin_stdarg_start: 1466 case Builtin::BI__builtin_va_start: 1467 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1468 return ExprError(); 1469 break; 1470 case Builtin::BI__va_start: { 1471 switch (Context.getTargetInfo().getTriple().getArch()) { 1472 case llvm::Triple::aarch64: 1473 case llvm::Triple::arm: 1474 case llvm::Triple::thumb: 1475 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1476 return ExprError(); 1477 break; 1478 default: 1479 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1480 return ExprError(); 1481 break; 1482 } 1483 break; 1484 } 1485 1486 // The acquire, release, and no fence variants are ARM and AArch64 only. 1487 case Builtin::BI_interlockedbittestandset_acq: 1488 case Builtin::BI_interlockedbittestandset_rel: 1489 case Builtin::BI_interlockedbittestandset_nf: 1490 case Builtin::BI_interlockedbittestandreset_acq: 1491 case Builtin::BI_interlockedbittestandreset_rel: 1492 case Builtin::BI_interlockedbittestandreset_nf: 1493 if (CheckBuiltinTargetSupport( 1494 *this, BuiltinID, TheCall, 1495 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1496 return ExprError(); 1497 break; 1498 1499 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1500 case Builtin::BI_bittest64: 1501 case Builtin::BI_bittestandcomplement64: 1502 case Builtin::BI_bittestandreset64: 1503 case Builtin::BI_bittestandset64: 1504 case Builtin::BI_interlockedbittestandreset64: 1505 case Builtin::BI_interlockedbittestandset64: 1506 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1507 {llvm::Triple::x86_64, llvm::Triple::arm, 1508 llvm::Triple::thumb, llvm::Triple::aarch64})) 1509 return ExprError(); 1510 break; 1511 1512 case Builtin::BI__builtin_isgreater: 1513 case Builtin::BI__builtin_isgreaterequal: 1514 case Builtin::BI__builtin_isless: 1515 case Builtin::BI__builtin_islessequal: 1516 case Builtin::BI__builtin_islessgreater: 1517 case Builtin::BI__builtin_isunordered: 1518 if (SemaBuiltinUnorderedCompare(TheCall)) 1519 return ExprError(); 1520 break; 1521 case Builtin::BI__builtin_fpclassify: 1522 if (SemaBuiltinFPClassification(TheCall, 6)) 1523 return ExprError(); 1524 break; 1525 case Builtin::BI__builtin_isfinite: 1526 case Builtin::BI__builtin_isinf: 1527 case Builtin::BI__builtin_isinf_sign: 1528 case Builtin::BI__builtin_isnan: 1529 case Builtin::BI__builtin_isnormal: 1530 case Builtin::BI__builtin_signbit: 1531 case Builtin::BI__builtin_signbitf: 1532 case Builtin::BI__builtin_signbitl: 1533 if (SemaBuiltinFPClassification(TheCall, 1)) 1534 return ExprError(); 1535 break; 1536 case Builtin::BI__builtin_shufflevector: 1537 return SemaBuiltinShuffleVector(TheCall); 1538 // TheCall will be freed by the smart pointer here, but that's fine, since 1539 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1540 case Builtin::BI__builtin_prefetch: 1541 if (SemaBuiltinPrefetch(TheCall)) 1542 return ExprError(); 1543 break; 1544 case Builtin::BI__builtin_alloca_with_align: 1545 if (SemaBuiltinAllocaWithAlign(TheCall)) 1546 return ExprError(); 1547 LLVM_FALLTHROUGH; 1548 case Builtin::BI__builtin_alloca: 1549 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1550 << TheCall->getDirectCallee(); 1551 break; 1552 case Builtin::BI__assume: 1553 case Builtin::BI__builtin_assume: 1554 if (SemaBuiltinAssume(TheCall)) 1555 return ExprError(); 1556 break; 1557 case Builtin::BI__builtin_assume_aligned: 1558 if (SemaBuiltinAssumeAligned(TheCall)) 1559 return ExprError(); 1560 break; 1561 case Builtin::BI__builtin_dynamic_object_size: 1562 case Builtin::BI__builtin_object_size: 1563 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1564 return ExprError(); 1565 break; 1566 case Builtin::BI__builtin_longjmp: 1567 if (SemaBuiltinLongjmp(TheCall)) 1568 return ExprError(); 1569 break; 1570 case Builtin::BI__builtin_setjmp: 1571 if (SemaBuiltinSetjmp(TheCall)) 1572 return ExprError(); 1573 break; 1574 case Builtin::BI__builtin_classify_type: 1575 if (checkArgCount(*this, TheCall, 1)) return true; 1576 TheCall->setType(Context.IntTy); 1577 break; 1578 case Builtin::BI__builtin_complex: 1579 if (SemaBuiltinComplex(TheCall)) 1580 return ExprError(); 1581 break; 1582 case Builtin::BI__builtin_constant_p: { 1583 if (checkArgCount(*this, TheCall, 1)) return true; 1584 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1585 if (Arg.isInvalid()) return true; 1586 TheCall->setArg(0, Arg.get()); 1587 TheCall->setType(Context.IntTy); 1588 break; 1589 } 1590 case Builtin::BI__builtin_launder: 1591 return SemaBuiltinLaunder(*this, TheCall); 1592 case Builtin::BI__sync_fetch_and_add: 1593 case Builtin::BI__sync_fetch_and_add_1: 1594 case Builtin::BI__sync_fetch_and_add_2: 1595 case Builtin::BI__sync_fetch_and_add_4: 1596 case Builtin::BI__sync_fetch_and_add_8: 1597 case Builtin::BI__sync_fetch_and_add_16: 1598 case Builtin::BI__sync_fetch_and_sub: 1599 case Builtin::BI__sync_fetch_and_sub_1: 1600 case Builtin::BI__sync_fetch_and_sub_2: 1601 case Builtin::BI__sync_fetch_and_sub_4: 1602 case Builtin::BI__sync_fetch_and_sub_8: 1603 case Builtin::BI__sync_fetch_and_sub_16: 1604 case Builtin::BI__sync_fetch_and_or: 1605 case Builtin::BI__sync_fetch_and_or_1: 1606 case Builtin::BI__sync_fetch_and_or_2: 1607 case Builtin::BI__sync_fetch_and_or_4: 1608 case Builtin::BI__sync_fetch_and_or_8: 1609 case Builtin::BI__sync_fetch_and_or_16: 1610 case Builtin::BI__sync_fetch_and_and: 1611 case Builtin::BI__sync_fetch_and_and_1: 1612 case Builtin::BI__sync_fetch_and_and_2: 1613 case Builtin::BI__sync_fetch_and_and_4: 1614 case Builtin::BI__sync_fetch_and_and_8: 1615 case Builtin::BI__sync_fetch_and_and_16: 1616 case Builtin::BI__sync_fetch_and_xor: 1617 case Builtin::BI__sync_fetch_and_xor_1: 1618 case Builtin::BI__sync_fetch_and_xor_2: 1619 case Builtin::BI__sync_fetch_and_xor_4: 1620 case Builtin::BI__sync_fetch_and_xor_8: 1621 case Builtin::BI__sync_fetch_and_xor_16: 1622 case Builtin::BI__sync_fetch_and_nand: 1623 case Builtin::BI__sync_fetch_and_nand_1: 1624 case Builtin::BI__sync_fetch_and_nand_2: 1625 case Builtin::BI__sync_fetch_and_nand_4: 1626 case Builtin::BI__sync_fetch_and_nand_8: 1627 case Builtin::BI__sync_fetch_and_nand_16: 1628 case Builtin::BI__sync_add_and_fetch: 1629 case Builtin::BI__sync_add_and_fetch_1: 1630 case Builtin::BI__sync_add_and_fetch_2: 1631 case Builtin::BI__sync_add_and_fetch_4: 1632 case Builtin::BI__sync_add_and_fetch_8: 1633 case Builtin::BI__sync_add_and_fetch_16: 1634 case Builtin::BI__sync_sub_and_fetch: 1635 case Builtin::BI__sync_sub_and_fetch_1: 1636 case Builtin::BI__sync_sub_and_fetch_2: 1637 case Builtin::BI__sync_sub_and_fetch_4: 1638 case Builtin::BI__sync_sub_and_fetch_8: 1639 case Builtin::BI__sync_sub_and_fetch_16: 1640 case Builtin::BI__sync_and_and_fetch: 1641 case Builtin::BI__sync_and_and_fetch_1: 1642 case Builtin::BI__sync_and_and_fetch_2: 1643 case Builtin::BI__sync_and_and_fetch_4: 1644 case Builtin::BI__sync_and_and_fetch_8: 1645 case Builtin::BI__sync_and_and_fetch_16: 1646 case Builtin::BI__sync_or_and_fetch: 1647 case Builtin::BI__sync_or_and_fetch_1: 1648 case Builtin::BI__sync_or_and_fetch_2: 1649 case Builtin::BI__sync_or_and_fetch_4: 1650 case Builtin::BI__sync_or_and_fetch_8: 1651 case Builtin::BI__sync_or_and_fetch_16: 1652 case Builtin::BI__sync_xor_and_fetch: 1653 case Builtin::BI__sync_xor_and_fetch_1: 1654 case Builtin::BI__sync_xor_and_fetch_2: 1655 case Builtin::BI__sync_xor_and_fetch_4: 1656 case Builtin::BI__sync_xor_and_fetch_8: 1657 case Builtin::BI__sync_xor_and_fetch_16: 1658 case Builtin::BI__sync_nand_and_fetch: 1659 case Builtin::BI__sync_nand_and_fetch_1: 1660 case Builtin::BI__sync_nand_and_fetch_2: 1661 case Builtin::BI__sync_nand_and_fetch_4: 1662 case Builtin::BI__sync_nand_and_fetch_8: 1663 case Builtin::BI__sync_nand_and_fetch_16: 1664 case Builtin::BI__sync_val_compare_and_swap: 1665 case Builtin::BI__sync_val_compare_and_swap_1: 1666 case Builtin::BI__sync_val_compare_and_swap_2: 1667 case Builtin::BI__sync_val_compare_and_swap_4: 1668 case Builtin::BI__sync_val_compare_and_swap_8: 1669 case Builtin::BI__sync_val_compare_and_swap_16: 1670 case Builtin::BI__sync_bool_compare_and_swap: 1671 case Builtin::BI__sync_bool_compare_and_swap_1: 1672 case Builtin::BI__sync_bool_compare_and_swap_2: 1673 case Builtin::BI__sync_bool_compare_and_swap_4: 1674 case Builtin::BI__sync_bool_compare_and_swap_8: 1675 case Builtin::BI__sync_bool_compare_and_swap_16: 1676 case Builtin::BI__sync_lock_test_and_set: 1677 case Builtin::BI__sync_lock_test_and_set_1: 1678 case Builtin::BI__sync_lock_test_and_set_2: 1679 case Builtin::BI__sync_lock_test_and_set_4: 1680 case Builtin::BI__sync_lock_test_and_set_8: 1681 case Builtin::BI__sync_lock_test_and_set_16: 1682 case Builtin::BI__sync_lock_release: 1683 case Builtin::BI__sync_lock_release_1: 1684 case Builtin::BI__sync_lock_release_2: 1685 case Builtin::BI__sync_lock_release_4: 1686 case Builtin::BI__sync_lock_release_8: 1687 case Builtin::BI__sync_lock_release_16: 1688 case Builtin::BI__sync_swap: 1689 case Builtin::BI__sync_swap_1: 1690 case Builtin::BI__sync_swap_2: 1691 case Builtin::BI__sync_swap_4: 1692 case Builtin::BI__sync_swap_8: 1693 case Builtin::BI__sync_swap_16: 1694 return SemaBuiltinAtomicOverloaded(TheCallResult); 1695 case Builtin::BI__sync_synchronize: 1696 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1697 << TheCall->getCallee()->getSourceRange(); 1698 break; 1699 case Builtin::BI__builtin_nontemporal_load: 1700 case Builtin::BI__builtin_nontemporal_store: 1701 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1702 case Builtin::BI__builtin_memcpy_inline: { 1703 clang::Expr *SizeOp = TheCall->getArg(2); 1704 // We warn about copying to or from `nullptr` pointers when `size` is 1705 // greater than 0. When `size` is value dependent we cannot evaluate its 1706 // value so we bail out. 1707 if (SizeOp->isValueDependent()) 1708 break; 1709 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1710 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1711 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1712 } 1713 break; 1714 } 1715 #define BUILTIN(ID, TYPE, ATTRS) 1716 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1717 case Builtin::BI##ID: \ 1718 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1719 #include "clang/Basic/Builtins.def" 1720 case Builtin::BI__annotation: 1721 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1722 return ExprError(); 1723 break; 1724 case Builtin::BI__builtin_annotation: 1725 if (SemaBuiltinAnnotation(*this, TheCall)) 1726 return ExprError(); 1727 break; 1728 case Builtin::BI__builtin_addressof: 1729 if (SemaBuiltinAddressof(*this, TheCall)) 1730 return ExprError(); 1731 break; 1732 case Builtin::BI__builtin_is_aligned: 1733 case Builtin::BI__builtin_align_up: 1734 case Builtin::BI__builtin_align_down: 1735 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1736 return ExprError(); 1737 break; 1738 case Builtin::BI__builtin_add_overflow: 1739 case Builtin::BI__builtin_sub_overflow: 1740 case Builtin::BI__builtin_mul_overflow: 1741 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1742 return ExprError(); 1743 break; 1744 case Builtin::BI__builtin_operator_new: 1745 case Builtin::BI__builtin_operator_delete: { 1746 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1747 ExprResult Res = 1748 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1749 if (Res.isInvalid()) 1750 CorrectDelayedTyposInExpr(TheCallResult.get()); 1751 return Res; 1752 } 1753 case Builtin::BI__builtin_dump_struct: { 1754 // We first want to ensure we are called with 2 arguments 1755 if (checkArgCount(*this, TheCall, 2)) 1756 return ExprError(); 1757 // Ensure that the first argument is of type 'struct XX *' 1758 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1759 const QualType PtrArgType = PtrArg->getType(); 1760 if (!PtrArgType->isPointerType() || 1761 !PtrArgType->getPointeeType()->isRecordType()) { 1762 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1763 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1764 << "structure pointer"; 1765 return ExprError(); 1766 } 1767 1768 // Ensure that the second argument is of type 'FunctionType' 1769 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1770 const QualType FnPtrArgType = FnPtrArg->getType(); 1771 if (!FnPtrArgType->isPointerType()) { 1772 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1773 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1774 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1775 return ExprError(); 1776 } 1777 1778 const auto *FuncType = 1779 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1780 1781 if (!FuncType) { 1782 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1783 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1784 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1785 return ExprError(); 1786 } 1787 1788 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1789 if (!FT->getNumParams()) { 1790 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1791 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1792 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1793 return ExprError(); 1794 } 1795 QualType PT = FT->getParamType(0); 1796 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1797 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1798 !PT->getPointeeType().isConstQualified()) { 1799 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1800 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1801 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1802 return ExprError(); 1803 } 1804 } 1805 1806 TheCall->setType(Context.IntTy); 1807 break; 1808 } 1809 case Builtin::BI__builtin_expect_with_probability: { 1810 // We first want to ensure we are called with 3 arguments 1811 if (checkArgCount(*this, TheCall, 3)) 1812 return ExprError(); 1813 // then check probability is constant float in range [0.0, 1.0] 1814 const Expr *ProbArg = TheCall->getArg(2); 1815 SmallVector<PartialDiagnosticAt, 8> Notes; 1816 Expr::EvalResult Eval; 1817 Eval.Diag = &Notes; 1818 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1819 !Eval.Val.isFloat()) { 1820 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1821 << ProbArg->getSourceRange(); 1822 for (const PartialDiagnosticAt &PDiag : Notes) 1823 Diag(PDiag.first, PDiag.second); 1824 return ExprError(); 1825 } 1826 llvm::APFloat Probability = Eval.Val.getFloat(); 1827 bool LoseInfo = false; 1828 Probability.convert(llvm::APFloat::IEEEdouble(), 1829 llvm::RoundingMode::Dynamic, &LoseInfo); 1830 if (!(Probability >= llvm::APFloat(0.0) && 1831 Probability <= llvm::APFloat(1.0))) { 1832 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1833 << ProbArg->getSourceRange(); 1834 return ExprError(); 1835 } 1836 break; 1837 } 1838 case Builtin::BI__builtin_preserve_access_index: 1839 if (SemaBuiltinPreserveAI(*this, TheCall)) 1840 return ExprError(); 1841 break; 1842 case Builtin::BI__builtin_call_with_static_chain: 1843 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1844 return ExprError(); 1845 break; 1846 case Builtin::BI__exception_code: 1847 case Builtin::BI_exception_code: 1848 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1849 diag::err_seh___except_block)) 1850 return ExprError(); 1851 break; 1852 case Builtin::BI__exception_info: 1853 case Builtin::BI_exception_info: 1854 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1855 diag::err_seh___except_filter)) 1856 return ExprError(); 1857 break; 1858 case Builtin::BI__GetExceptionInfo: 1859 if (checkArgCount(*this, TheCall, 1)) 1860 return ExprError(); 1861 1862 if (CheckCXXThrowOperand( 1863 TheCall->getBeginLoc(), 1864 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1865 TheCall)) 1866 return ExprError(); 1867 1868 TheCall->setType(Context.VoidPtrTy); 1869 break; 1870 // OpenCL v2.0, s6.13.16 - Pipe functions 1871 case Builtin::BIread_pipe: 1872 case Builtin::BIwrite_pipe: 1873 // Since those two functions are declared with var args, we need a semantic 1874 // check for the argument. 1875 if (SemaBuiltinRWPipe(*this, TheCall)) 1876 return ExprError(); 1877 break; 1878 case Builtin::BIreserve_read_pipe: 1879 case Builtin::BIreserve_write_pipe: 1880 case Builtin::BIwork_group_reserve_read_pipe: 1881 case Builtin::BIwork_group_reserve_write_pipe: 1882 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1883 return ExprError(); 1884 break; 1885 case Builtin::BIsub_group_reserve_read_pipe: 1886 case Builtin::BIsub_group_reserve_write_pipe: 1887 if (checkOpenCLSubgroupExt(*this, TheCall) || 1888 SemaBuiltinReserveRWPipe(*this, TheCall)) 1889 return ExprError(); 1890 break; 1891 case Builtin::BIcommit_read_pipe: 1892 case Builtin::BIcommit_write_pipe: 1893 case Builtin::BIwork_group_commit_read_pipe: 1894 case Builtin::BIwork_group_commit_write_pipe: 1895 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1896 return ExprError(); 1897 break; 1898 case Builtin::BIsub_group_commit_read_pipe: 1899 case Builtin::BIsub_group_commit_write_pipe: 1900 if (checkOpenCLSubgroupExt(*this, TheCall) || 1901 SemaBuiltinCommitRWPipe(*this, TheCall)) 1902 return ExprError(); 1903 break; 1904 case Builtin::BIget_pipe_num_packets: 1905 case Builtin::BIget_pipe_max_packets: 1906 if (SemaBuiltinPipePackets(*this, TheCall)) 1907 return ExprError(); 1908 break; 1909 case Builtin::BIto_global: 1910 case Builtin::BIto_local: 1911 case Builtin::BIto_private: 1912 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1913 return ExprError(); 1914 break; 1915 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1916 case Builtin::BIenqueue_kernel: 1917 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1918 return ExprError(); 1919 break; 1920 case Builtin::BIget_kernel_work_group_size: 1921 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1922 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1923 return ExprError(); 1924 break; 1925 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1926 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1927 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1928 return ExprError(); 1929 break; 1930 case Builtin::BI__builtin_os_log_format: 1931 Cleanup.setExprNeedsCleanups(true); 1932 LLVM_FALLTHROUGH; 1933 case Builtin::BI__builtin_os_log_format_buffer_size: 1934 if (SemaBuiltinOSLogFormat(TheCall)) 1935 return ExprError(); 1936 break; 1937 case Builtin::BI__builtin_frame_address: 1938 case Builtin::BI__builtin_return_address: { 1939 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1940 return ExprError(); 1941 1942 // -Wframe-address warning if non-zero passed to builtin 1943 // return/frame address. 1944 Expr::EvalResult Result; 1945 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1946 Result.Val.getInt() != 0) 1947 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1948 << ((BuiltinID == Builtin::BI__builtin_return_address) 1949 ? "__builtin_return_address" 1950 : "__builtin_frame_address") 1951 << TheCall->getSourceRange(); 1952 break; 1953 } 1954 1955 case Builtin::BI__builtin_matrix_transpose: 1956 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1957 1958 case Builtin::BI__builtin_matrix_column_major_load: 1959 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1960 1961 case Builtin::BI__builtin_matrix_column_major_store: 1962 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1963 } 1964 1965 // Since the target specific builtins for each arch overlap, only check those 1966 // of the arch we are compiling for. 1967 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1968 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1969 assert(Context.getAuxTargetInfo() && 1970 "Aux Target Builtin, but not an aux target?"); 1971 1972 if (CheckTSBuiltinFunctionCall( 1973 *Context.getAuxTargetInfo(), 1974 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1975 return ExprError(); 1976 } else { 1977 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1978 TheCall)) 1979 return ExprError(); 1980 } 1981 } 1982 1983 return TheCallResult; 1984 } 1985 1986 // Get the valid immediate range for the specified NEON type code. 1987 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1988 NeonTypeFlags Type(t); 1989 int IsQuad = ForceQuad ? true : Type.isQuad(); 1990 switch (Type.getEltType()) { 1991 case NeonTypeFlags::Int8: 1992 case NeonTypeFlags::Poly8: 1993 return shift ? 7 : (8 << IsQuad) - 1; 1994 case NeonTypeFlags::Int16: 1995 case NeonTypeFlags::Poly16: 1996 return shift ? 15 : (4 << IsQuad) - 1; 1997 case NeonTypeFlags::Int32: 1998 return shift ? 31 : (2 << IsQuad) - 1; 1999 case NeonTypeFlags::Int64: 2000 case NeonTypeFlags::Poly64: 2001 return shift ? 63 : (1 << IsQuad) - 1; 2002 case NeonTypeFlags::Poly128: 2003 return shift ? 127 : (1 << IsQuad) - 1; 2004 case NeonTypeFlags::Float16: 2005 assert(!shift && "cannot shift float types!"); 2006 return (4 << IsQuad) - 1; 2007 case NeonTypeFlags::Float32: 2008 assert(!shift && "cannot shift float types!"); 2009 return (2 << IsQuad) - 1; 2010 case NeonTypeFlags::Float64: 2011 assert(!shift && "cannot shift float types!"); 2012 return (1 << IsQuad) - 1; 2013 case NeonTypeFlags::BFloat16: 2014 assert(!shift && "cannot shift float types!"); 2015 return (4 << IsQuad) - 1; 2016 } 2017 llvm_unreachable("Invalid NeonTypeFlag!"); 2018 } 2019 2020 /// getNeonEltType - Return the QualType corresponding to the elements of 2021 /// the vector type specified by the NeonTypeFlags. This is used to check 2022 /// the pointer arguments for Neon load/store intrinsics. 2023 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2024 bool IsPolyUnsigned, bool IsInt64Long) { 2025 switch (Flags.getEltType()) { 2026 case NeonTypeFlags::Int8: 2027 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2028 case NeonTypeFlags::Int16: 2029 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2030 case NeonTypeFlags::Int32: 2031 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2032 case NeonTypeFlags::Int64: 2033 if (IsInt64Long) 2034 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2035 else 2036 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2037 : Context.LongLongTy; 2038 case NeonTypeFlags::Poly8: 2039 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2040 case NeonTypeFlags::Poly16: 2041 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2042 case NeonTypeFlags::Poly64: 2043 if (IsInt64Long) 2044 return Context.UnsignedLongTy; 2045 else 2046 return Context.UnsignedLongLongTy; 2047 case NeonTypeFlags::Poly128: 2048 break; 2049 case NeonTypeFlags::Float16: 2050 return Context.HalfTy; 2051 case NeonTypeFlags::Float32: 2052 return Context.FloatTy; 2053 case NeonTypeFlags::Float64: 2054 return Context.DoubleTy; 2055 case NeonTypeFlags::BFloat16: 2056 return Context.BFloat16Ty; 2057 } 2058 llvm_unreachable("Invalid NeonTypeFlag!"); 2059 } 2060 2061 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2062 // Range check SVE intrinsics that take immediate values. 2063 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2064 2065 switch (BuiltinID) { 2066 default: 2067 return false; 2068 #define GET_SVE_IMMEDIATE_CHECK 2069 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2070 #undef GET_SVE_IMMEDIATE_CHECK 2071 } 2072 2073 // Perform all the immediate checks for this builtin call. 2074 bool HasError = false; 2075 for (auto &I : ImmChecks) { 2076 int ArgNum, CheckTy, ElementSizeInBits; 2077 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2078 2079 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2080 2081 // Function that checks whether the operand (ArgNum) is an immediate 2082 // that is one of the predefined values. 2083 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2084 int ErrDiag) -> bool { 2085 // We can't check the value of a dependent argument. 2086 Expr *Arg = TheCall->getArg(ArgNum); 2087 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2088 return false; 2089 2090 // Check constant-ness first. 2091 llvm::APSInt Imm; 2092 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2093 return true; 2094 2095 if (!CheckImm(Imm.getSExtValue())) 2096 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2097 return false; 2098 }; 2099 2100 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2101 case SVETypeFlags::ImmCheck0_31: 2102 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2103 HasError = true; 2104 break; 2105 case SVETypeFlags::ImmCheck0_13: 2106 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2107 HasError = true; 2108 break; 2109 case SVETypeFlags::ImmCheck1_16: 2110 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2111 HasError = true; 2112 break; 2113 case SVETypeFlags::ImmCheck0_7: 2114 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2115 HasError = true; 2116 break; 2117 case SVETypeFlags::ImmCheckExtract: 2118 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2119 (2048 / ElementSizeInBits) - 1)) 2120 HasError = true; 2121 break; 2122 case SVETypeFlags::ImmCheckShiftRight: 2123 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2124 HasError = true; 2125 break; 2126 case SVETypeFlags::ImmCheckShiftRightNarrow: 2127 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2128 ElementSizeInBits / 2)) 2129 HasError = true; 2130 break; 2131 case SVETypeFlags::ImmCheckShiftLeft: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2133 ElementSizeInBits - 1)) 2134 HasError = true; 2135 break; 2136 case SVETypeFlags::ImmCheckLaneIndex: 2137 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2138 (128 / (1 * ElementSizeInBits)) - 1)) 2139 HasError = true; 2140 break; 2141 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2142 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2143 (128 / (2 * ElementSizeInBits)) - 1)) 2144 HasError = true; 2145 break; 2146 case SVETypeFlags::ImmCheckLaneIndexDot: 2147 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2148 (128 / (4 * ElementSizeInBits)) - 1)) 2149 HasError = true; 2150 break; 2151 case SVETypeFlags::ImmCheckComplexRot90_270: 2152 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2153 diag::err_rotation_argument_to_cadd)) 2154 HasError = true; 2155 break; 2156 case SVETypeFlags::ImmCheckComplexRotAll90: 2157 if (CheckImmediateInSet( 2158 [](int64_t V) { 2159 return V == 0 || V == 90 || V == 180 || V == 270; 2160 }, 2161 diag::err_rotation_argument_to_cmla)) 2162 HasError = true; 2163 break; 2164 case SVETypeFlags::ImmCheck0_1: 2165 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2166 HasError = true; 2167 break; 2168 case SVETypeFlags::ImmCheck0_2: 2169 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2170 HasError = true; 2171 break; 2172 case SVETypeFlags::ImmCheck0_3: 2173 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2174 HasError = true; 2175 break; 2176 } 2177 } 2178 2179 return HasError; 2180 } 2181 2182 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2183 unsigned BuiltinID, CallExpr *TheCall) { 2184 llvm::APSInt Result; 2185 uint64_t mask = 0; 2186 unsigned TV = 0; 2187 int PtrArgNum = -1; 2188 bool HasConstPtr = false; 2189 switch (BuiltinID) { 2190 #define GET_NEON_OVERLOAD_CHECK 2191 #include "clang/Basic/arm_neon.inc" 2192 #include "clang/Basic/arm_fp16.inc" 2193 #undef GET_NEON_OVERLOAD_CHECK 2194 } 2195 2196 // For NEON intrinsics which are overloaded on vector element type, validate 2197 // the immediate which specifies which variant to emit. 2198 unsigned ImmArg = TheCall->getNumArgs()-1; 2199 if (mask) { 2200 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2201 return true; 2202 2203 TV = Result.getLimitedValue(64); 2204 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2205 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2206 << TheCall->getArg(ImmArg)->getSourceRange(); 2207 } 2208 2209 if (PtrArgNum >= 0) { 2210 // Check that pointer arguments have the specified type. 2211 Expr *Arg = TheCall->getArg(PtrArgNum); 2212 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2213 Arg = ICE->getSubExpr(); 2214 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2215 QualType RHSTy = RHS.get()->getType(); 2216 2217 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2218 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2219 Arch == llvm::Triple::aarch64_32 || 2220 Arch == llvm::Triple::aarch64_be; 2221 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2222 QualType EltTy = 2223 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2224 if (HasConstPtr) 2225 EltTy = EltTy.withConst(); 2226 QualType LHSTy = Context.getPointerType(EltTy); 2227 AssignConvertType ConvTy; 2228 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2229 if (RHS.isInvalid()) 2230 return true; 2231 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2232 RHS.get(), AA_Assigning)) 2233 return true; 2234 } 2235 2236 // For NEON intrinsics which take an immediate value as part of the 2237 // instruction, range check them here. 2238 unsigned i = 0, l = 0, u = 0; 2239 switch (BuiltinID) { 2240 default: 2241 return false; 2242 #define GET_NEON_IMMEDIATE_CHECK 2243 #include "clang/Basic/arm_neon.inc" 2244 #include "clang/Basic/arm_fp16.inc" 2245 #undef GET_NEON_IMMEDIATE_CHECK 2246 } 2247 2248 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2249 } 2250 2251 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2252 switch (BuiltinID) { 2253 default: 2254 return false; 2255 #include "clang/Basic/arm_mve_builtin_sema.inc" 2256 } 2257 } 2258 2259 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2260 CallExpr *TheCall) { 2261 bool Err = false; 2262 switch (BuiltinID) { 2263 default: 2264 return false; 2265 #include "clang/Basic/arm_cde_builtin_sema.inc" 2266 } 2267 2268 if (Err) 2269 return true; 2270 2271 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2272 } 2273 2274 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2275 const Expr *CoprocArg, bool WantCDE) { 2276 if (isConstantEvaluated()) 2277 return false; 2278 2279 // We can't check the value of a dependent argument. 2280 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2281 return false; 2282 2283 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2284 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2285 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2286 2287 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2288 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2289 2290 if (IsCDECoproc != WantCDE) 2291 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2292 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2293 2294 return false; 2295 } 2296 2297 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2298 unsigned MaxWidth) { 2299 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2300 BuiltinID == ARM::BI__builtin_arm_ldaex || 2301 BuiltinID == ARM::BI__builtin_arm_strex || 2302 BuiltinID == ARM::BI__builtin_arm_stlex || 2303 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2304 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2305 BuiltinID == AArch64::BI__builtin_arm_strex || 2306 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2307 "unexpected ARM builtin"); 2308 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2309 BuiltinID == ARM::BI__builtin_arm_ldaex || 2310 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2311 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2312 2313 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2314 2315 // Ensure that we have the proper number of arguments. 2316 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2317 return true; 2318 2319 // Inspect the pointer argument of the atomic builtin. This should always be 2320 // a pointer type, whose element is an integral scalar or pointer type. 2321 // Because it is a pointer type, we don't have to worry about any implicit 2322 // casts here. 2323 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2324 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2325 if (PointerArgRes.isInvalid()) 2326 return true; 2327 PointerArg = PointerArgRes.get(); 2328 2329 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2330 if (!pointerType) { 2331 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2332 << PointerArg->getType() << PointerArg->getSourceRange(); 2333 return true; 2334 } 2335 2336 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2337 // task is to insert the appropriate casts into the AST. First work out just 2338 // what the appropriate type is. 2339 QualType ValType = pointerType->getPointeeType(); 2340 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2341 if (IsLdrex) 2342 AddrType.addConst(); 2343 2344 // Issue a warning if the cast is dodgy. 2345 CastKind CastNeeded = CK_NoOp; 2346 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2347 CastNeeded = CK_BitCast; 2348 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2349 << PointerArg->getType() << Context.getPointerType(AddrType) 2350 << AA_Passing << PointerArg->getSourceRange(); 2351 } 2352 2353 // Finally, do the cast and replace the argument with the corrected version. 2354 AddrType = Context.getPointerType(AddrType); 2355 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2356 if (PointerArgRes.isInvalid()) 2357 return true; 2358 PointerArg = PointerArgRes.get(); 2359 2360 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2361 2362 // In general, we allow ints, floats and pointers to be loaded and stored. 2363 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2364 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2365 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2366 << PointerArg->getType() << PointerArg->getSourceRange(); 2367 return true; 2368 } 2369 2370 // But ARM doesn't have instructions to deal with 128-bit versions. 2371 if (Context.getTypeSize(ValType) > MaxWidth) { 2372 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2373 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2374 << PointerArg->getType() << PointerArg->getSourceRange(); 2375 return true; 2376 } 2377 2378 switch (ValType.getObjCLifetime()) { 2379 case Qualifiers::OCL_None: 2380 case Qualifiers::OCL_ExplicitNone: 2381 // okay 2382 break; 2383 2384 case Qualifiers::OCL_Weak: 2385 case Qualifiers::OCL_Strong: 2386 case Qualifiers::OCL_Autoreleasing: 2387 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2388 << ValType << PointerArg->getSourceRange(); 2389 return true; 2390 } 2391 2392 if (IsLdrex) { 2393 TheCall->setType(ValType); 2394 return false; 2395 } 2396 2397 // Initialize the argument to be stored. 2398 ExprResult ValArg = TheCall->getArg(0); 2399 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2400 Context, ValType, /*consume*/ false); 2401 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2402 if (ValArg.isInvalid()) 2403 return true; 2404 TheCall->setArg(0, ValArg.get()); 2405 2406 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2407 // but the custom checker bypasses all default analysis. 2408 TheCall->setType(Context.IntTy); 2409 return false; 2410 } 2411 2412 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2413 CallExpr *TheCall) { 2414 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2415 BuiltinID == ARM::BI__builtin_arm_ldaex || 2416 BuiltinID == ARM::BI__builtin_arm_strex || 2417 BuiltinID == ARM::BI__builtin_arm_stlex) { 2418 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2419 } 2420 2421 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2422 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2423 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2424 } 2425 2426 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2427 BuiltinID == ARM::BI__builtin_arm_wsr64) 2428 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2429 2430 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2431 BuiltinID == ARM::BI__builtin_arm_rsrp || 2432 BuiltinID == ARM::BI__builtin_arm_wsr || 2433 BuiltinID == ARM::BI__builtin_arm_wsrp) 2434 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2435 2436 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2437 return true; 2438 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2439 return true; 2440 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2441 return true; 2442 2443 // For intrinsics which take an immediate value as part of the instruction, 2444 // range check them here. 2445 // FIXME: VFP Intrinsics should error if VFP not present. 2446 switch (BuiltinID) { 2447 default: return false; 2448 case ARM::BI__builtin_arm_ssat: 2449 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2450 case ARM::BI__builtin_arm_usat: 2451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2452 case ARM::BI__builtin_arm_ssat16: 2453 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2454 case ARM::BI__builtin_arm_usat16: 2455 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2456 case ARM::BI__builtin_arm_vcvtr_f: 2457 case ARM::BI__builtin_arm_vcvtr_d: 2458 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2459 case ARM::BI__builtin_arm_dmb: 2460 case ARM::BI__builtin_arm_dsb: 2461 case ARM::BI__builtin_arm_isb: 2462 case ARM::BI__builtin_arm_dbg: 2463 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2464 case ARM::BI__builtin_arm_cdp: 2465 case ARM::BI__builtin_arm_cdp2: 2466 case ARM::BI__builtin_arm_mcr: 2467 case ARM::BI__builtin_arm_mcr2: 2468 case ARM::BI__builtin_arm_mrc: 2469 case ARM::BI__builtin_arm_mrc2: 2470 case ARM::BI__builtin_arm_mcrr: 2471 case ARM::BI__builtin_arm_mcrr2: 2472 case ARM::BI__builtin_arm_mrrc: 2473 case ARM::BI__builtin_arm_mrrc2: 2474 case ARM::BI__builtin_arm_ldc: 2475 case ARM::BI__builtin_arm_ldcl: 2476 case ARM::BI__builtin_arm_ldc2: 2477 case ARM::BI__builtin_arm_ldc2l: 2478 case ARM::BI__builtin_arm_stc: 2479 case ARM::BI__builtin_arm_stcl: 2480 case ARM::BI__builtin_arm_stc2: 2481 case ARM::BI__builtin_arm_stc2l: 2482 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2483 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2484 /*WantCDE*/ false); 2485 } 2486 } 2487 2488 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2489 unsigned BuiltinID, 2490 CallExpr *TheCall) { 2491 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2492 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2493 BuiltinID == AArch64::BI__builtin_arm_strex || 2494 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2495 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2496 } 2497 2498 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2500 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2501 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2502 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2503 } 2504 2505 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2506 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2507 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2508 2509 // Memory Tagging Extensions (MTE) Intrinsics 2510 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2511 BuiltinID == AArch64::BI__builtin_arm_addg || 2512 BuiltinID == AArch64::BI__builtin_arm_gmi || 2513 BuiltinID == AArch64::BI__builtin_arm_ldg || 2514 BuiltinID == AArch64::BI__builtin_arm_stg || 2515 BuiltinID == AArch64::BI__builtin_arm_subp) { 2516 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2517 } 2518 2519 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2520 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2521 BuiltinID == AArch64::BI__builtin_arm_wsr || 2522 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2523 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2524 2525 // Only check the valid encoding range. Any constant in this range would be 2526 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2527 // an exception for incorrect registers. This matches MSVC behavior. 2528 if (BuiltinID == AArch64::BI_ReadStatusReg || 2529 BuiltinID == AArch64::BI_WriteStatusReg) 2530 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2531 2532 if (BuiltinID == AArch64::BI__getReg) 2533 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2534 2535 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2536 return true; 2537 2538 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2539 return true; 2540 2541 // For intrinsics which take an immediate value as part of the instruction, 2542 // range check them here. 2543 unsigned i = 0, l = 0, u = 0; 2544 switch (BuiltinID) { 2545 default: return false; 2546 case AArch64::BI__builtin_arm_dmb: 2547 case AArch64::BI__builtin_arm_dsb: 2548 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2549 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2550 } 2551 2552 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2553 } 2554 2555 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2556 if (Arg->getType()->getAsPlaceholderType()) 2557 return false; 2558 2559 // The first argument needs to be a record field access. 2560 // If it is an array element access, we delay decision 2561 // to BPF backend to check whether the access is a 2562 // field access or not. 2563 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2564 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2565 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2566 } 2567 2568 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2569 QualType VectorTy, QualType EltTy) { 2570 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2571 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2572 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2573 << Call->getSourceRange() << VectorEltTy << EltTy; 2574 return false; 2575 } 2576 return true; 2577 } 2578 2579 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2580 QualType ArgType = Arg->getType(); 2581 if (ArgType->getAsPlaceholderType()) 2582 return false; 2583 2584 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2585 // format: 2586 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2587 // 2. <type> var; 2588 // __builtin_preserve_type_info(var, flag); 2589 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2590 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2591 return false; 2592 2593 // Typedef type. 2594 if (ArgType->getAs<TypedefType>()) 2595 return true; 2596 2597 // Record type or Enum type. 2598 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2599 if (const auto *RT = Ty->getAs<RecordType>()) { 2600 if (!RT->getDecl()->getDeclName().isEmpty()) 2601 return true; 2602 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2603 if (!ET->getDecl()->getDeclName().isEmpty()) 2604 return true; 2605 } 2606 2607 return false; 2608 } 2609 2610 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2611 QualType ArgType = Arg->getType(); 2612 if (ArgType->getAsPlaceholderType()) 2613 return false; 2614 2615 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2616 // format: 2617 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2618 // flag); 2619 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2620 if (!UO) 2621 return false; 2622 2623 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2624 if (!CE || CE->getCastKind() != CK_IntegralToPointer) 2625 return false; 2626 2627 // The integer must be from an EnumConstantDecl. 2628 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2629 if (!DR) 2630 return false; 2631 2632 const EnumConstantDecl *Enumerator = 2633 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2634 if (!Enumerator) 2635 return false; 2636 2637 // The type must be EnumType. 2638 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2639 const auto *ET = Ty->getAs<EnumType>(); 2640 if (!ET) 2641 return false; 2642 2643 // The enum value must be supported. 2644 for (auto *EDI : ET->getDecl()->enumerators()) { 2645 if (EDI == Enumerator) 2646 return true; 2647 } 2648 2649 return false; 2650 } 2651 2652 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2653 CallExpr *TheCall) { 2654 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2655 BuiltinID == BPF::BI__builtin_btf_type_id || 2656 BuiltinID == BPF::BI__builtin_preserve_type_info || 2657 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2658 "unexpected BPF builtin"); 2659 2660 if (checkArgCount(*this, TheCall, 2)) 2661 return true; 2662 2663 // The second argument needs to be a constant int 2664 Expr *Arg = TheCall->getArg(1); 2665 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2666 diag::kind kind; 2667 if (!Value) { 2668 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2669 kind = diag::err_preserve_field_info_not_const; 2670 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2671 kind = diag::err_btf_type_id_not_const; 2672 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2673 kind = diag::err_preserve_type_info_not_const; 2674 else 2675 kind = diag::err_preserve_enum_value_not_const; 2676 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2677 return true; 2678 } 2679 2680 // The first argument 2681 Arg = TheCall->getArg(0); 2682 bool InvalidArg = false; 2683 bool ReturnUnsignedInt = true; 2684 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2685 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2686 InvalidArg = true; 2687 kind = diag::err_preserve_field_info_not_field; 2688 } 2689 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2690 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2691 InvalidArg = true; 2692 kind = diag::err_preserve_type_info_invalid; 2693 } 2694 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2695 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2696 InvalidArg = true; 2697 kind = diag::err_preserve_enum_value_invalid; 2698 } 2699 ReturnUnsignedInt = false; 2700 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2701 ReturnUnsignedInt = false; 2702 } 2703 2704 if (InvalidArg) { 2705 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2706 return true; 2707 } 2708 2709 if (ReturnUnsignedInt) 2710 TheCall->setType(Context.UnsignedIntTy); 2711 else 2712 TheCall->setType(Context.UnsignedLongTy); 2713 return false; 2714 } 2715 2716 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2717 struct ArgInfo { 2718 uint8_t OpNum; 2719 bool IsSigned; 2720 uint8_t BitWidth; 2721 uint8_t Align; 2722 }; 2723 struct BuiltinInfo { 2724 unsigned BuiltinID; 2725 ArgInfo Infos[2]; 2726 }; 2727 2728 static BuiltinInfo Infos[] = { 2729 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2730 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2731 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2732 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2733 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2734 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2735 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2736 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2737 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2738 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2739 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2740 2741 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2752 2753 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2805 {{ 1, false, 6, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2813 {{ 1, false, 5, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2820 { 2, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2822 { 2, false, 6, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2824 { 3, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2826 { 3, false, 6, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2843 {{ 2, false, 4, 0 }, 2844 { 3, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2846 {{ 2, false, 4, 0 }, 2847 { 3, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2849 {{ 2, false, 4, 0 }, 2850 { 3, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2852 {{ 2, false, 4, 0 }, 2853 { 3, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2865 { 2, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2867 { 2, false, 6, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2877 {{ 1, false, 4, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2880 {{ 1, false, 4, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2901 {{ 3, false, 1, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2906 {{ 3, false, 1, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2911 {{ 3, false, 1, 0 }} }, 2912 }; 2913 2914 // Use a dynamically initialized static to sort the table exactly once on 2915 // first run. 2916 static const bool SortOnce = 2917 (llvm::sort(Infos, 2918 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2919 return LHS.BuiltinID < RHS.BuiltinID; 2920 }), 2921 true); 2922 (void)SortOnce; 2923 2924 const BuiltinInfo *F = llvm::partition_point( 2925 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2926 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2927 return false; 2928 2929 bool Error = false; 2930 2931 for (const ArgInfo &A : F->Infos) { 2932 // Ignore empty ArgInfo elements. 2933 if (A.BitWidth == 0) 2934 continue; 2935 2936 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2937 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2938 if (!A.Align) { 2939 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2940 } else { 2941 unsigned M = 1 << A.Align; 2942 Min *= M; 2943 Max *= M; 2944 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2945 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2946 } 2947 } 2948 return Error; 2949 } 2950 2951 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2952 CallExpr *TheCall) { 2953 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2954 } 2955 2956 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2957 unsigned BuiltinID, CallExpr *TheCall) { 2958 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2959 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2960 } 2961 2962 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2963 CallExpr *TheCall) { 2964 2965 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2966 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2967 if (!TI.hasFeature("dsp")) 2968 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2969 } 2970 2971 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2972 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2973 if (!TI.hasFeature("dspr2")) 2974 return Diag(TheCall->getBeginLoc(), 2975 diag::err_mips_builtin_requires_dspr2); 2976 } 2977 2978 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2979 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2980 if (!TI.hasFeature("msa")) 2981 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2982 } 2983 2984 return false; 2985 } 2986 2987 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2988 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2989 // ordering for DSP is unspecified. MSA is ordered by the data format used 2990 // by the underlying instruction i.e., df/m, df/n and then by size. 2991 // 2992 // FIXME: The size tests here should instead be tablegen'd along with the 2993 // definitions from include/clang/Basic/BuiltinsMips.def. 2994 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2995 // be too. 2996 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2997 unsigned i = 0, l = 0, u = 0, m = 0; 2998 switch (BuiltinID) { 2999 default: return false; 3000 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3001 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3002 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3003 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3004 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3005 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3006 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3007 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3008 // df/m field. 3009 // These intrinsics take an unsigned 3 bit immediate. 3010 case Mips::BI__builtin_msa_bclri_b: 3011 case Mips::BI__builtin_msa_bnegi_b: 3012 case Mips::BI__builtin_msa_bseti_b: 3013 case Mips::BI__builtin_msa_sat_s_b: 3014 case Mips::BI__builtin_msa_sat_u_b: 3015 case Mips::BI__builtin_msa_slli_b: 3016 case Mips::BI__builtin_msa_srai_b: 3017 case Mips::BI__builtin_msa_srari_b: 3018 case Mips::BI__builtin_msa_srli_b: 3019 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3020 case Mips::BI__builtin_msa_binsli_b: 3021 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3022 // These intrinsics take an unsigned 4 bit immediate. 3023 case Mips::BI__builtin_msa_bclri_h: 3024 case Mips::BI__builtin_msa_bnegi_h: 3025 case Mips::BI__builtin_msa_bseti_h: 3026 case Mips::BI__builtin_msa_sat_s_h: 3027 case Mips::BI__builtin_msa_sat_u_h: 3028 case Mips::BI__builtin_msa_slli_h: 3029 case Mips::BI__builtin_msa_srai_h: 3030 case Mips::BI__builtin_msa_srari_h: 3031 case Mips::BI__builtin_msa_srli_h: 3032 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3033 case Mips::BI__builtin_msa_binsli_h: 3034 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3035 // These intrinsics take an unsigned 5 bit immediate. 3036 // The first block of intrinsics actually have an unsigned 5 bit field, 3037 // not a df/n field. 3038 case Mips::BI__builtin_msa_cfcmsa: 3039 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3040 case Mips::BI__builtin_msa_clei_u_b: 3041 case Mips::BI__builtin_msa_clei_u_h: 3042 case Mips::BI__builtin_msa_clei_u_w: 3043 case Mips::BI__builtin_msa_clei_u_d: 3044 case Mips::BI__builtin_msa_clti_u_b: 3045 case Mips::BI__builtin_msa_clti_u_h: 3046 case Mips::BI__builtin_msa_clti_u_w: 3047 case Mips::BI__builtin_msa_clti_u_d: 3048 case Mips::BI__builtin_msa_maxi_u_b: 3049 case Mips::BI__builtin_msa_maxi_u_h: 3050 case Mips::BI__builtin_msa_maxi_u_w: 3051 case Mips::BI__builtin_msa_maxi_u_d: 3052 case Mips::BI__builtin_msa_mini_u_b: 3053 case Mips::BI__builtin_msa_mini_u_h: 3054 case Mips::BI__builtin_msa_mini_u_w: 3055 case Mips::BI__builtin_msa_mini_u_d: 3056 case Mips::BI__builtin_msa_addvi_b: 3057 case Mips::BI__builtin_msa_addvi_h: 3058 case Mips::BI__builtin_msa_addvi_w: 3059 case Mips::BI__builtin_msa_addvi_d: 3060 case Mips::BI__builtin_msa_bclri_w: 3061 case Mips::BI__builtin_msa_bnegi_w: 3062 case Mips::BI__builtin_msa_bseti_w: 3063 case Mips::BI__builtin_msa_sat_s_w: 3064 case Mips::BI__builtin_msa_sat_u_w: 3065 case Mips::BI__builtin_msa_slli_w: 3066 case Mips::BI__builtin_msa_srai_w: 3067 case Mips::BI__builtin_msa_srari_w: 3068 case Mips::BI__builtin_msa_srli_w: 3069 case Mips::BI__builtin_msa_srlri_w: 3070 case Mips::BI__builtin_msa_subvi_b: 3071 case Mips::BI__builtin_msa_subvi_h: 3072 case Mips::BI__builtin_msa_subvi_w: 3073 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3074 case Mips::BI__builtin_msa_binsli_w: 3075 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3076 // These intrinsics take an unsigned 6 bit immediate. 3077 case Mips::BI__builtin_msa_bclri_d: 3078 case Mips::BI__builtin_msa_bnegi_d: 3079 case Mips::BI__builtin_msa_bseti_d: 3080 case Mips::BI__builtin_msa_sat_s_d: 3081 case Mips::BI__builtin_msa_sat_u_d: 3082 case Mips::BI__builtin_msa_slli_d: 3083 case Mips::BI__builtin_msa_srai_d: 3084 case Mips::BI__builtin_msa_srari_d: 3085 case Mips::BI__builtin_msa_srli_d: 3086 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3087 case Mips::BI__builtin_msa_binsli_d: 3088 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3089 // These intrinsics take a signed 5 bit immediate. 3090 case Mips::BI__builtin_msa_ceqi_b: 3091 case Mips::BI__builtin_msa_ceqi_h: 3092 case Mips::BI__builtin_msa_ceqi_w: 3093 case Mips::BI__builtin_msa_ceqi_d: 3094 case Mips::BI__builtin_msa_clti_s_b: 3095 case Mips::BI__builtin_msa_clti_s_h: 3096 case Mips::BI__builtin_msa_clti_s_w: 3097 case Mips::BI__builtin_msa_clti_s_d: 3098 case Mips::BI__builtin_msa_clei_s_b: 3099 case Mips::BI__builtin_msa_clei_s_h: 3100 case Mips::BI__builtin_msa_clei_s_w: 3101 case Mips::BI__builtin_msa_clei_s_d: 3102 case Mips::BI__builtin_msa_maxi_s_b: 3103 case Mips::BI__builtin_msa_maxi_s_h: 3104 case Mips::BI__builtin_msa_maxi_s_w: 3105 case Mips::BI__builtin_msa_maxi_s_d: 3106 case Mips::BI__builtin_msa_mini_s_b: 3107 case Mips::BI__builtin_msa_mini_s_h: 3108 case Mips::BI__builtin_msa_mini_s_w: 3109 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3110 // These intrinsics take an unsigned 8 bit immediate. 3111 case Mips::BI__builtin_msa_andi_b: 3112 case Mips::BI__builtin_msa_nori_b: 3113 case Mips::BI__builtin_msa_ori_b: 3114 case Mips::BI__builtin_msa_shf_b: 3115 case Mips::BI__builtin_msa_shf_h: 3116 case Mips::BI__builtin_msa_shf_w: 3117 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3118 case Mips::BI__builtin_msa_bseli_b: 3119 case Mips::BI__builtin_msa_bmnzi_b: 3120 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3121 // df/n format 3122 // These intrinsics take an unsigned 4 bit immediate. 3123 case Mips::BI__builtin_msa_copy_s_b: 3124 case Mips::BI__builtin_msa_copy_u_b: 3125 case Mips::BI__builtin_msa_insve_b: 3126 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3127 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3128 // These intrinsics take an unsigned 3 bit immediate. 3129 case Mips::BI__builtin_msa_copy_s_h: 3130 case Mips::BI__builtin_msa_copy_u_h: 3131 case Mips::BI__builtin_msa_insve_h: 3132 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3133 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3134 // These intrinsics take an unsigned 2 bit immediate. 3135 case Mips::BI__builtin_msa_copy_s_w: 3136 case Mips::BI__builtin_msa_copy_u_w: 3137 case Mips::BI__builtin_msa_insve_w: 3138 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3139 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3140 // These intrinsics take an unsigned 1 bit immediate. 3141 case Mips::BI__builtin_msa_copy_s_d: 3142 case Mips::BI__builtin_msa_copy_u_d: 3143 case Mips::BI__builtin_msa_insve_d: 3144 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3145 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3146 // Memory offsets and immediate loads. 3147 // These intrinsics take a signed 10 bit immediate. 3148 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3149 case Mips::BI__builtin_msa_ldi_h: 3150 case Mips::BI__builtin_msa_ldi_w: 3151 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3152 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3153 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3154 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3155 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3156 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3157 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3158 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3159 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3160 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3161 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3162 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3163 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3164 } 3165 3166 if (!m) 3167 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3168 3169 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3170 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3171 } 3172 3173 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3174 /// advancing the pointer over the consumed characters. The decoded type is 3175 /// returned. If the decoded type represents a constant integer with a 3176 /// constraint on its value then Mask is set to that value. The type descriptors 3177 /// used in Str are specific to PPC MMA builtins and are documented in the file 3178 /// defining the PPC builtins. 3179 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3180 unsigned &Mask) { 3181 bool RequireICE = false; 3182 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3183 switch (*Str++) { 3184 case 'V': 3185 return Context.getVectorType(Context.UnsignedCharTy, 16, 3186 VectorType::VectorKind::AltiVecVector); 3187 case 'i': { 3188 char *End; 3189 unsigned size = strtoul(Str, &End, 10); 3190 assert(End != Str && "Missing constant parameter constraint"); 3191 Str = End; 3192 Mask = size; 3193 return Context.IntTy; 3194 } 3195 case 'W': { 3196 char *End; 3197 unsigned size = strtoul(Str, &End, 10); 3198 assert(End != Str && "Missing PowerPC MMA type size"); 3199 Str = End; 3200 QualType Type; 3201 switch (size) { 3202 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3203 case size: Type = Context.Id##Ty; break; 3204 #include "clang/Basic/PPCTypes.def" 3205 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3206 } 3207 bool CheckVectorArgs = false; 3208 while (!CheckVectorArgs) { 3209 switch (*Str++) { 3210 case '*': 3211 Type = Context.getPointerType(Type); 3212 break; 3213 case 'C': 3214 Type = Type.withConst(); 3215 break; 3216 default: 3217 CheckVectorArgs = true; 3218 --Str; 3219 break; 3220 } 3221 } 3222 return Type; 3223 } 3224 default: 3225 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3226 } 3227 } 3228 3229 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3230 CallExpr *TheCall) { 3231 unsigned i = 0, l = 0, u = 0; 3232 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3233 BuiltinID == PPC::BI__builtin_divdeu || 3234 BuiltinID == PPC::BI__builtin_bpermd; 3235 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3236 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3237 BuiltinID == PPC::BI__builtin_divweu || 3238 BuiltinID == PPC::BI__builtin_divde || 3239 BuiltinID == PPC::BI__builtin_divdeu; 3240 3241 if (Is64BitBltin && !IsTarget64Bit) 3242 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3243 << TheCall->getSourceRange(); 3244 3245 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3246 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3247 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3248 << TheCall->getSourceRange(); 3249 3250 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3251 if (!TI.hasFeature("vsx")) 3252 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3253 << TheCall->getSourceRange(); 3254 return false; 3255 }; 3256 3257 switch (BuiltinID) { 3258 default: return false; 3259 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3260 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3261 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3262 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3263 case PPC::BI__builtin_altivec_dss: 3264 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3265 case PPC::BI__builtin_tbegin: 3266 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3267 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3268 case PPC::BI__builtin_tabortwc: 3269 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3270 case PPC::BI__builtin_tabortwci: 3271 case PPC::BI__builtin_tabortdci: 3272 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3273 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3274 case PPC::BI__builtin_altivec_dst: 3275 case PPC::BI__builtin_altivec_dstt: 3276 case PPC::BI__builtin_altivec_dstst: 3277 case PPC::BI__builtin_altivec_dststt: 3278 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3279 case PPC::BI__builtin_vsx_xxpermdi: 3280 case PPC::BI__builtin_vsx_xxsldwi: 3281 return SemaBuiltinVSX(TheCall); 3282 case PPC::BI__builtin_unpack_vector_int128: 3283 return SemaVSXCheck(TheCall) || 3284 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3285 case PPC::BI__builtin_pack_vector_int128: 3286 return SemaVSXCheck(TheCall); 3287 case PPC::BI__builtin_altivec_vgnb: 3288 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3289 case PPC::BI__builtin_altivec_vec_replace_elt: 3290 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3291 QualType VecTy = TheCall->getArg(0)->getType(); 3292 QualType EltTy = TheCall->getArg(1)->getType(); 3293 unsigned Width = Context.getIntWidth(EltTy); 3294 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3295 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3296 } 3297 case PPC::BI__builtin_vsx_xxeval: 3298 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3299 case PPC::BI__builtin_altivec_vsldbi: 3300 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3301 case PPC::BI__builtin_altivec_vsrdbi: 3302 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3303 case PPC::BI__builtin_vsx_xxpermx: 3304 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3305 #define CUSTOM_BUILTIN(Name, Types, Acc) \ 3306 case PPC::BI__builtin_##Name: \ 3307 return SemaBuiltinPPCMMACall(TheCall, Types); 3308 #include "clang/Basic/BuiltinsPPC.def" 3309 } 3310 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3311 } 3312 3313 // Check if the given type is a non-pointer PPC MMA type. This function is used 3314 // in Sema to prevent invalid uses of restricted PPC MMA types. 3315 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3316 if (Type->isPointerType() || Type->isArrayType()) 3317 return false; 3318 3319 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3320 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3321 if (false 3322 #include "clang/Basic/PPCTypes.def" 3323 ) { 3324 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3325 return true; 3326 } 3327 return false; 3328 } 3329 3330 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3331 CallExpr *TheCall) { 3332 // position of memory order and scope arguments in the builtin 3333 unsigned OrderIndex, ScopeIndex; 3334 switch (BuiltinID) { 3335 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3336 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3337 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3338 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3339 OrderIndex = 2; 3340 ScopeIndex = 3; 3341 break; 3342 case AMDGPU::BI__builtin_amdgcn_fence: 3343 OrderIndex = 0; 3344 ScopeIndex = 1; 3345 break; 3346 default: 3347 return false; 3348 } 3349 3350 ExprResult Arg = TheCall->getArg(OrderIndex); 3351 auto ArgExpr = Arg.get(); 3352 Expr::EvalResult ArgResult; 3353 3354 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3355 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3356 << ArgExpr->getType(); 3357 int ord = ArgResult.Val.getInt().getZExtValue(); 3358 3359 // Check valididty of memory ordering as per C11 / C++11's memody model. 3360 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3361 case llvm::AtomicOrderingCABI::acquire: 3362 case llvm::AtomicOrderingCABI::release: 3363 case llvm::AtomicOrderingCABI::acq_rel: 3364 case llvm::AtomicOrderingCABI::seq_cst: 3365 break; 3366 default: { 3367 return Diag(ArgExpr->getBeginLoc(), 3368 diag::warn_atomic_op_has_invalid_memory_order) 3369 << ArgExpr->getSourceRange(); 3370 } 3371 } 3372 3373 Arg = TheCall->getArg(ScopeIndex); 3374 ArgExpr = Arg.get(); 3375 Expr::EvalResult ArgResult1; 3376 // Check that sync scope is a constant literal 3377 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3378 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3379 << ArgExpr->getType(); 3380 3381 return false; 3382 } 3383 3384 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3385 CallExpr *TheCall) { 3386 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3387 Expr *Arg = TheCall->getArg(0); 3388 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3389 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3390 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3391 << Arg->getSourceRange(); 3392 } 3393 3394 // For intrinsics which take an immediate value as part of the instruction, 3395 // range check them here. 3396 unsigned i = 0, l = 0, u = 0; 3397 switch (BuiltinID) { 3398 default: return false; 3399 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3400 case SystemZ::BI__builtin_s390_verimb: 3401 case SystemZ::BI__builtin_s390_verimh: 3402 case SystemZ::BI__builtin_s390_verimf: 3403 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3404 case SystemZ::BI__builtin_s390_vfaeb: 3405 case SystemZ::BI__builtin_s390_vfaeh: 3406 case SystemZ::BI__builtin_s390_vfaef: 3407 case SystemZ::BI__builtin_s390_vfaebs: 3408 case SystemZ::BI__builtin_s390_vfaehs: 3409 case SystemZ::BI__builtin_s390_vfaefs: 3410 case SystemZ::BI__builtin_s390_vfaezb: 3411 case SystemZ::BI__builtin_s390_vfaezh: 3412 case SystemZ::BI__builtin_s390_vfaezf: 3413 case SystemZ::BI__builtin_s390_vfaezbs: 3414 case SystemZ::BI__builtin_s390_vfaezhs: 3415 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3416 case SystemZ::BI__builtin_s390_vfisb: 3417 case SystemZ::BI__builtin_s390_vfidb: 3418 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3419 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3420 case SystemZ::BI__builtin_s390_vftcisb: 3421 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3422 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3423 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3424 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3425 case SystemZ::BI__builtin_s390_vstrcb: 3426 case SystemZ::BI__builtin_s390_vstrch: 3427 case SystemZ::BI__builtin_s390_vstrcf: 3428 case SystemZ::BI__builtin_s390_vstrczb: 3429 case SystemZ::BI__builtin_s390_vstrczh: 3430 case SystemZ::BI__builtin_s390_vstrczf: 3431 case SystemZ::BI__builtin_s390_vstrcbs: 3432 case SystemZ::BI__builtin_s390_vstrchs: 3433 case SystemZ::BI__builtin_s390_vstrcfs: 3434 case SystemZ::BI__builtin_s390_vstrczbs: 3435 case SystemZ::BI__builtin_s390_vstrczhs: 3436 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3437 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3438 case SystemZ::BI__builtin_s390_vfminsb: 3439 case SystemZ::BI__builtin_s390_vfmaxsb: 3440 case SystemZ::BI__builtin_s390_vfmindb: 3441 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3442 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3443 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3444 } 3445 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3446 } 3447 3448 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3449 /// This checks that the target supports __builtin_cpu_supports and 3450 /// that the string argument is constant and valid. 3451 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3452 CallExpr *TheCall) { 3453 Expr *Arg = TheCall->getArg(0); 3454 3455 // Check if the argument is a string literal. 3456 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3457 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3458 << Arg->getSourceRange(); 3459 3460 // Check the contents of the string. 3461 StringRef Feature = 3462 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3463 if (!TI.validateCpuSupports(Feature)) 3464 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3465 << Arg->getSourceRange(); 3466 return false; 3467 } 3468 3469 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3470 /// This checks that the target supports __builtin_cpu_is and 3471 /// that the string argument is constant and valid. 3472 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3473 Expr *Arg = TheCall->getArg(0); 3474 3475 // Check if the argument is a string literal. 3476 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3477 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3478 << Arg->getSourceRange(); 3479 3480 // Check the contents of the string. 3481 StringRef Feature = 3482 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3483 if (!TI.validateCpuIs(Feature)) 3484 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3485 << Arg->getSourceRange(); 3486 return false; 3487 } 3488 3489 // Check if the rounding mode is legal. 3490 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3491 // Indicates if this instruction has rounding control or just SAE. 3492 bool HasRC = false; 3493 3494 unsigned ArgNum = 0; 3495 switch (BuiltinID) { 3496 default: 3497 return false; 3498 case X86::BI__builtin_ia32_vcvttsd2si32: 3499 case X86::BI__builtin_ia32_vcvttsd2si64: 3500 case X86::BI__builtin_ia32_vcvttsd2usi32: 3501 case X86::BI__builtin_ia32_vcvttsd2usi64: 3502 case X86::BI__builtin_ia32_vcvttss2si32: 3503 case X86::BI__builtin_ia32_vcvttss2si64: 3504 case X86::BI__builtin_ia32_vcvttss2usi32: 3505 case X86::BI__builtin_ia32_vcvttss2usi64: 3506 ArgNum = 1; 3507 break; 3508 case X86::BI__builtin_ia32_maxpd512: 3509 case X86::BI__builtin_ia32_maxps512: 3510 case X86::BI__builtin_ia32_minpd512: 3511 case X86::BI__builtin_ia32_minps512: 3512 ArgNum = 2; 3513 break; 3514 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3515 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3516 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3517 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3518 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3519 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3520 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3521 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3522 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3523 case X86::BI__builtin_ia32_exp2pd_mask: 3524 case X86::BI__builtin_ia32_exp2ps_mask: 3525 case X86::BI__builtin_ia32_getexppd512_mask: 3526 case X86::BI__builtin_ia32_getexpps512_mask: 3527 case X86::BI__builtin_ia32_rcp28pd_mask: 3528 case X86::BI__builtin_ia32_rcp28ps_mask: 3529 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3530 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3531 case X86::BI__builtin_ia32_vcomisd: 3532 case X86::BI__builtin_ia32_vcomiss: 3533 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3534 ArgNum = 3; 3535 break; 3536 case X86::BI__builtin_ia32_cmppd512_mask: 3537 case X86::BI__builtin_ia32_cmpps512_mask: 3538 case X86::BI__builtin_ia32_cmpsd_mask: 3539 case X86::BI__builtin_ia32_cmpss_mask: 3540 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3541 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3542 case X86::BI__builtin_ia32_getexpss128_round_mask: 3543 case X86::BI__builtin_ia32_getmantpd512_mask: 3544 case X86::BI__builtin_ia32_getmantps512_mask: 3545 case X86::BI__builtin_ia32_maxsd_round_mask: 3546 case X86::BI__builtin_ia32_maxss_round_mask: 3547 case X86::BI__builtin_ia32_minsd_round_mask: 3548 case X86::BI__builtin_ia32_minss_round_mask: 3549 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3550 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3551 case X86::BI__builtin_ia32_reducepd512_mask: 3552 case X86::BI__builtin_ia32_reduceps512_mask: 3553 case X86::BI__builtin_ia32_rndscalepd_mask: 3554 case X86::BI__builtin_ia32_rndscaleps_mask: 3555 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3556 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3557 ArgNum = 4; 3558 break; 3559 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3560 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3561 case X86::BI__builtin_ia32_fixupimmps512_mask: 3562 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3563 case X86::BI__builtin_ia32_fixupimmsd_mask: 3564 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3565 case X86::BI__builtin_ia32_fixupimmss_mask: 3566 case X86::BI__builtin_ia32_fixupimmss_maskz: 3567 case X86::BI__builtin_ia32_getmantsd_round_mask: 3568 case X86::BI__builtin_ia32_getmantss_round_mask: 3569 case X86::BI__builtin_ia32_rangepd512_mask: 3570 case X86::BI__builtin_ia32_rangeps512_mask: 3571 case X86::BI__builtin_ia32_rangesd128_round_mask: 3572 case X86::BI__builtin_ia32_rangess128_round_mask: 3573 case X86::BI__builtin_ia32_reducesd_mask: 3574 case X86::BI__builtin_ia32_reducess_mask: 3575 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3576 case X86::BI__builtin_ia32_rndscaless_round_mask: 3577 ArgNum = 5; 3578 break; 3579 case X86::BI__builtin_ia32_vcvtsd2si64: 3580 case X86::BI__builtin_ia32_vcvtsd2si32: 3581 case X86::BI__builtin_ia32_vcvtsd2usi32: 3582 case X86::BI__builtin_ia32_vcvtsd2usi64: 3583 case X86::BI__builtin_ia32_vcvtss2si32: 3584 case X86::BI__builtin_ia32_vcvtss2si64: 3585 case X86::BI__builtin_ia32_vcvtss2usi32: 3586 case X86::BI__builtin_ia32_vcvtss2usi64: 3587 case X86::BI__builtin_ia32_sqrtpd512: 3588 case X86::BI__builtin_ia32_sqrtps512: 3589 ArgNum = 1; 3590 HasRC = true; 3591 break; 3592 case X86::BI__builtin_ia32_addpd512: 3593 case X86::BI__builtin_ia32_addps512: 3594 case X86::BI__builtin_ia32_divpd512: 3595 case X86::BI__builtin_ia32_divps512: 3596 case X86::BI__builtin_ia32_mulpd512: 3597 case X86::BI__builtin_ia32_mulps512: 3598 case X86::BI__builtin_ia32_subpd512: 3599 case X86::BI__builtin_ia32_subps512: 3600 case X86::BI__builtin_ia32_cvtsi2sd64: 3601 case X86::BI__builtin_ia32_cvtsi2ss32: 3602 case X86::BI__builtin_ia32_cvtsi2ss64: 3603 case X86::BI__builtin_ia32_cvtusi2sd64: 3604 case X86::BI__builtin_ia32_cvtusi2ss32: 3605 case X86::BI__builtin_ia32_cvtusi2ss64: 3606 ArgNum = 2; 3607 HasRC = true; 3608 break; 3609 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3610 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3611 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3612 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3613 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3614 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3615 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3616 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3617 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3618 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3619 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3620 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3621 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3622 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3623 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3624 ArgNum = 3; 3625 HasRC = true; 3626 break; 3627 case X86::BI__builtin_ia32_addss_round_mask: 3628 case X86::BI__builtin_ia32_addsd_round_mask: 3629 case X86::BI__builtin_ia32_divss_round_mask: 3630 case X86::BI__builtin_ia32_divsd_round_mask: 3631 case X86::BI__builtin_ia32_mulss_round_mask: 3632 case X86::BI__builtin_ia32_mulsd_round_mask: 3633 case X86::BI__builtin_ia32_subss_round_mask: 3634 case X86::BI__builtin_ia32_subsd_round_mask: 3635 case X86::BI__builtin_ia32_scalefpd512_mask: 3636 case X86::BI__builtin_ia32_scalefps512_mask: 3637 case X86::BI__builtin_ia32_scalefsd_round_mask: 3638 case X86::BI__builtin_ia32_scalefss_round_mask: 3639 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3640 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3641 case X86::BI__builtin_ia32_sqrtss_round_mask: 3642 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3643 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3644 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3645 case X86::BI__builtin_ia32_vfmaddss3_mask: 3646 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3647 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3648 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3649 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3650 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3651 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3652 case X86::BI__builtin_ia32_vfmaddps512_mask: 3653 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3654 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3655 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3656 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3657 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3658 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3659 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3660 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3661 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3662 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3663 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3664 ArgNum = 4; 3665 HasRC = true; 3666 break; 3667 } 3668 3669 llvm::APSInt Result; 3670 3671 // We can't check the value of a dependent argument. 3672 Expr *Arg = TheCall->getArg(ArgNum); 3673 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3674 return false; 3675 3676 // Check constant-ness first. 3677 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3678 return true; 3679 3680 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3681 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3682 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3683 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3684 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3685 Result == 8/*ROUND_NO_EXC*/ || 3686 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3687 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3688 return false; 3689 3690 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3691 << Arg->getSourceRange(); 3692 } 3693 3694 // Check if the gather/scatter scale is legal. 3695 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3696 CallExpr *TheCall) { 3697 unsigned ArgNum = 0; 3698 switch (BuiltinID) { 3699 default: 3700 return false; 3701 case X86::BI__builtin_ia32_gatherpfdpd: 3702 case X86::BI__builtin_ia32_gatherpfdps: 3703 case X86::BI__builtin_ia32_gatherpfqpd: 3704 case X86::BI__builtin_ia32_gatherpfqps: 3705 case X86::BI__builtin_ia32_scatterpfdpd: 3706 case X86::BI__builtin_ia32_scatterpfdps: 3707 case X86::BI__builtin_ia32_scatterpfqpd: 3708 case X86::BI__builtin_ia32_scatterpfqps: 3709 ArgNum = 3; 3710 break; 3711 case X86::BI__builtin_ia32_gatherd_pd: 3712 case X86::BI__builtin_ia32_gatherd_pd256: 3713 case X86::BI__builtin_ia32_gatherq_pd: 3714 case X86::BI__builtin_ia32_gatherq_pd256: 3715 case X86::BI__builtin_ia32_gatherd_ps: 3716 case X86::BI__builtin_ia32_gatherd_ps256: 3717 case X86::BI__builtin_ia32_gatherq_ps: 3718 case X86::BI__builtin_ia32_gatherq_ps256: 3719 case X86::BI__builtin_ia32_gatherd_q: 3720 case X86::BI__builtin_ia32_gatherd_q256: 3721 case X86::BI__builtin_ia32_gatherq_q: 3722 case X86::BI__builtin_ia32_gatherq_q256: 3723 case X86::BI__builtin_ia32_gatherd_d: 3724 case X86::BI__builtin_ia32_gatherd_d256: 3725 case X86::BI__builtin_ia32_gatherq_d: 3726 case X86::BI__builtin_ia32_gatherq_d256: 3727 case X86::BI__builtin_ia32_gather3div2df: 3728 case X86::BI__builtin_ia32_gather3div2di: 3729 case X86::BI__builtin_ia32_gather3div4df: 3730 case X86::BI__builtin_ia32_gather3div4di: 3731 case X86::BI__builtin_ia32_gather3div4sf: 3732 case X86::BI__builtin_ia32_gather3div4si: 3733 case X86::BI__builtin_ia32_gather3div8sf: 3734 case X86::BI__builtin_ia32_gather3div8si: 3735 case X86::BI__builtin_ia32_gather3siv2df: 3736 case X86::BI__builtin_ia32_gather3siv2di: 3737 case X86::BI__builtin_ia32_gather3siv4df: 3738 case X86::BI__builtin_ia32_gather3siv4di: 3739 case X86::BI__builtin_ia32_gather3siv4sf: 3740 case X86::BI__builtin_ia32_gather3siv4si: 3741 case X86::BI__builtin_ia32_gather3siv8sf: 3742 case X86::BI__builtin_ia32_gather3siv8si: 3743 case X86::BI__builtin_ia32_gathersiv8df: 3744 case X86::BI__builtin_ia32_gathersiv16sf: 3745 case X86::BI__builtin_ia32_gatherdiv8df: 3746 case X86::BI__builtin_ia32_gatherdiv16sf: 3747 case X86::BI__builtin_ia32_gathersiv8di: 3748 case X86::BI__builtin_ia32_gathersiv16si: 3749 case X86::BI__builtin_ia32_gatherdiv8di: 3750 case X86::BI__builtin_ia32_gatherdiv16si: 3751 case X86::BI__builtin_ia32_scatterdiv2df: 3752 case X86::BI__builtin_ia32_scatterdiv2di: 3753 case X86::BI__builtin_ia32_scatterdiv4df: 3754 case X86::BI__builtin_ia32_scatterdiv4di: 3755 case X86::BI__builtin_ia32_scatterdiv4sf: 3756 case X86::BI__builtin_ia32_scatterdiv4si: 3757 case X86::BI__builtin_ia32_scatterdiv8sf: 3758 case X86::BI__builtin_ia32_scatterdiv8si: 3759 case X86::BI__builtin_ia32_scattersiv2df: 3760 case X86::BI__builtin_ia32_scattersiv2di: 3761 case X86::BI__builtin_ia32_scattersiv4df: 3762 case X86::BI__builtin_ia32_scattersiv4di: 3763 case X86::BI__builtin_ia32_scattersiv4sf: 3764 case X86::BI__builtin_ia32_scattersiv4si: 3765 case X86::BI__builtin_ia32_scattersiv8sf: 3766 case X86::BI__builtin_ia32_scattersiv8si: 3767 case X86::BI__builtin_ia32_scattersiv8df: 3768 case X86::BI__builtin_ia32_scattersiv16sf: 3769 case X86::BI__builtin_ia32_scatterdiv8df: 3770 case X86::BI__builtin_ia32_scatterdiv16sf: 3771 case X86::BI__builtin_ia32_scattersiv8di: 3772 case X86::BI__builtin_ia32_scattersiv16si: 3773 case X86::BI__builtin_ia32_scatterdiv8di: 3774 case X86::BI__builtin_ia32_scatterdiv16si: 3775 ArgNum = 4; 3776 break; 3777 } 3778 3779 llvm::APSInt Result; 3780 3781 // We can't check the value of a dependent argument. 3782 Expr *Arg = TheCall->getArg(ArgNum); 3783 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3784 return false; 3785 3786 // Check constant-ness first. 3787 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3788 return true; 3789 3790 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3791 return false; 3792 3793 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3794 << Arg->getSourceRange(); 3795 } 3796 3797 enum { TileRegLow = 0, TileRegHigh = 7 }; 3798 3799 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3800 ArrayRef<int> ArgNums) { 3801 for (int ArgNum : ArgNums) { 3802 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3803 return true; 3804 } 3805 return false; 3806 } 3807 3808 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3809 ArrayRef<int> ArgNums) { 3810 // Because the max number of tile register is TileRegHigh + 1, so here we use 3811 // each bit to represent the usage of them in bitset. 3812 std::bitset<TileRegHigh + 1> ArgValues; 3813 for (int ArgNum : ArgNums) { 3814 Expr *Arg = TheCall->getArg(ArgNum); 3815 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3816 continue; 3817 3818 llvm::APSInt Result; 3819 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3820 return true; 3821 int ArgExtValue = Result.getExtValue(); 3822 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3823 "Incorrect tile register num."); 3824 if (ArgValues.test(ArgExtValue)) 3825 return Diag(TheCall->getBeginLoc(), 3826 diag::err_x86_builtin_tile_arg_duplicate) 3827 << TheCall->getArg(ArgNum)->getSourceRange(); 3828 ArgValues.set(ArgExtValue); 3829 } 3830 return false; 3831 } 3832 3833 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3834 ArrayRef<int> ArgNums) { 3835 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3836 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3837 } 3838 3839 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3840 switch (BuiltinID) { 3841 default: 3842 return false; 3843 case X86::BI__builtin_ia32_tileloadd64: 3844 case X86::BI__builtin_ia32_tileloaddt164: 3845 case X86::BI__builtin_ia32_tilestored64: 3846 case X86::BI__builtin_ia32_tilezero: 3847 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3848 case X86::BI__builtin_ia32_tdpbssd: 3849 case X86::BI__builtin_ia32_tdpbsud: 3850 case X86::BI__builtin_ia32_tdpbusd: 3851 case X86::BI__builtin_ia32_tdpbuud: 3852 case X86::BI__builtin_ia32_tdpbf16ps: 3853 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3854 } 3855 } 3856 static bool isX86_32Builtin(unsigned BuiltinID) { 3857 // These builtins only work on x86-32 targets. 3858 switch (BuiltinID) { 3859 case X86::BI__builtin_ia32_readeflags_u32: 3860 case X86::BI__builtin_ia32_writeeflags_u32: 3861 return true; 3862 } 3863 3864 return false; 3865 } 3866 3867 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3868 CallExpr *TheCall) { 3869 if (BuiltinID == X86::BI__builtin_cpu_supports) 3870 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3871 3872 if (BuiltinID == X86::BI__builtin_cpu_is) 3873 return SemaBuiltinCpuIs(*this, TI, TheCall); 3874 3875 // Check for 32-bit only builtins on a 64-bit target. 3876 const llvm::Triple &TT = TI.getTriple(); 3877 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3878 return Diag(TheCall->getCallee()->getBeginLoc(), 3879 diag::err_32_bit_builtin_64_bit_tgt); 3880 3881 // If the intrinsic has rounding or SAE make sure its valid. 3882 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3883 return true; 3884 3885 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3886 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3887 return true; 3888 3889 // If the intrinsic has a tile arguments, make sure they are valid. 3890 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3891 return true; 3892 3893 // For intrinsics which take an immediate value as part of the instruction, 3894 // range check them here. 3895 int i = 0, l = 0, u = 0; 3896 switch (BuiltinID) { 3897 default: 3898 return false; 3899 case X86::BI__builtin_ia32_vec_ext_v2si: 3900 case X86::BI__builtin_ia32_vec_ext_v2di: 3901 case X86::BI__builtin_ia32_vextractf128_pd256: 3902 case X86::BI__builtin_ia32_vextractf128_ps256: 3903 case X86::BI__builtin_ia32_vextractf128_si256: 3904 case X86::BI__builtin_ia32_extract128i256: 3905 case X86::BI__builtin_ia32_extractf64x4_mask: 3906 case X86::BI__builtin_ia32_extracti64x4_mask: 3907 case X86::BI__builtin_ia32_extractf32x8_mask: 3908 case X86::BI__builtin_ia32_extracti32x8_mask: 3909 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3910 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3911 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3912 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3913 i = 1; l = 0; u = 1; 3914 break; 3915 case X86::BI__builtin_ia32_vec_set_v2di: 3916 case X86::BI__builtin_ia32_vinsertf128_pd256: 3917 case X86::BI__builtin_ia32_vinsertf128_ps256: 3918 case X86::BI__builtin_ia32_vinsertf128_si256: 3919 case X86::BI__builtin_ia32_insert128i256: 3920 case X86::BI__builtin_ia32_insertf32x8: 3921 case X86::BI__builtin_ia32_inserti32x8: 3922 case X86::BI__builtin_ia32_insertf64x4: 3923 case X86::BI__builtin_ia32_inserti64x4: 3924 case X86::BI__builtin_ia32_insertf64x2_256: 3925 case X86::BI__builtin_ia32_inserti64x2_256: 3926 case X86::BI__builtin_ia32_insertf32x4_256: 3927 case X86::BI__builtin_ia32_inserti32x4_256: 3928 i = 2; l = 0; u = 1; 3929 break; 3930 case X86::BI__builtin_ia32_vpermilpd: 3931 case X86::BI__builtin_ia32_vec_ext_v4hi: 3932 case X86::BI__builtin_ia32_vec_ext_v4si: 3933 case X86::BI__builtin_ia32_vec_ext_v4sf: 3934 case X86::BI__builtin_ia32_vec_ext_v4di: 3935 case X86::BI__builtin_ia32_extractf32x4_mask: 3936 case X86::BI__builtin_ia32_extracti32x4_mask: 3937 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3938 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3939 i = 1; l = 0; u = 3; 3940 break; 3941 case X86::BI_mm_prefetch: 3942 case X86::BI__builtin_ia32_vec_ext_v8hi: 3943 case X86::BI__builtin_ia32_vec_ext_v8si: 3944 i = 1; l = 0; u = 7; 3945 break; 3946 case X86::BI__builtin_ia32_sha1rnds4: 3947 case X86::BI__builtin_ia32_blendpd: 3948 case X86::BI__builtin_ia32_shufpd: 3949 case X86::BI__builtin_ia32_vec_set_v4hi: 3950 case X86::BI__builtin_ia32_vec_set_v4si: 3951 case X86::BI__builtin_ia32_vec_set_v4di: 3952 case X86::BI__builtin_ia32_shuf_f32x4_256: 3953 case X86::BI__builtin_ia32_shuf_f64x2_256: 3954 case X86::BI__builtin_ia32_shuf_i32x4_256: 3955 case X86::BI__builtin_ia32_shuf_i64x2_256: 3956 case X86::BI__builtin_ia32_insertf64x2_512: 3957 case X86::BI__builtin_ia32_inserti64x2_512: 3958 case X86::BI__builtin_ia32_insertf32x4: 3959 case X86::BI__builtin_ia32_inserti32x4: 3960 i = 2; l = 0; u = 3; 3961 break; 3962 case X86::BI__builtin_ia32_vpermil2pd: 3963 case X86::BI__builtin_ia32_vpermil2pd256: 3964 case X86::BI__builtin_ia32_vpermil2ps: 3965 case X86::BI__builtin_ia32_vpermil2ps256: 3966 i = 3; l = 0; u = 3; 3967 break; 3968 case X86::BI__builtin_ia32_cmpb128_mask: 3969 case X86::BI__builtin_ia32_cmpw128_mask: 3970 case X86::BI__builtin_ia32_cmpd128_mask: 3971 case X86::BI__builtin_ia32_cmpq128_mask: 3972 case X86::BI__builtin_ia32_cmpb256_mask: 3973 case X86::BI__builtin_ia32_cmpw256_mask: 3974 case X86::BI__builtin_ia32_cmpd256_mask: 3975 case X86::BI__builtin_ia32_cmpq256_mask: 3976 case X86::BI__builtin_ia32_cmpb512_mask: 3977 case X86::BI__builtin_ia32_cmpw512_mask: 3978 case X86::BI__builtin_ia32_cmpd512_mask: 3979 case X86::BI__builtin_ia32_cmpq512_mask: 3980 case X86::BI__builtin_ia32_ucmpb128_mask: 3981 case X86::BI__builtin_ia32_ucmpw128_mask: 3982 case X86::BI__builtin_ia32_ucmpd128_mask: 3983 case X86::BI__builtin_ia32_ucmpq128_mask: 3984 case X86::BI__builtin_ia32_ucmpb256_mask: 3985 case X86::BI__builtin_ia32_ucmpw256_mask: 3986 case X86::BI__builtin_ia32_ucmpd256_mask: 3987 case X86::BI__builtin_ia32_ucmpq256_mask: 3988 case X86::BI__builtin_ia32_ucmpb512_mask: 3989 case X86::BI__builtin_ia32_ucmpw512_mask: 3990 case X86::BI__builtin_ia32_ucmpd512_mask: 3991 case X86::BI__builtin_ia32_ucmpq512_mask: 3992 case X86::BI__builtin_ia32_vpcomub: 3993 case X86::BI__builtin_ia32_vpcomuw: 3994 case X86::BI__builtin_ia32_vpcomud: 3995 case X86::BI__builtin_ia32_vpcomuq: 3996 case X86::BI__builtin_ia32_vpcomb: 3997 case X86::BI__builtin_ia32_vpcomw: 3998 case X86::BI__builtin_ia32_vpcomd: 3999 case X86::BI__builtin_ia32_vpcomq: 4000 case X86::BI__builtin_ia32_vec_set_v8hi: 4001 case X86::BI__builtin_ia32_vec_set_v8si: 4002 i = 2; l = 0; u = 7; 4003 break; 4004 case X86::BI__builtin_ia32_vpermilpd256: 4005 case X86::BI__builtin_ia32_roundps: 4006 case X86::BI__builtin_ia32_roundpd: 4007 case X86::BI__builtin_ia32_roundps256: 4008 case X86::BI__builtin_ia32_roundpd256: 4009 case X86::BI__builtin_ia32_getmantpd128_mask: 4010 case X86::BI__builtin_ia32_getmantpd256_mask: 4011 case X86::BI__builtin_ia32_getmantps128_mask: 4012 case X86::BI__builtin_ia32_getmantps256_mask: 4013 case X86::BI__builtin_ia32_getmantpd512_mask: 4014 case X86::BI__builtin_ia32_getmantps512_mask: 4015 case X86::BI__builtin_ia32_vec_ext_v16qi: 4016 case X86::BI__builtin_ia32_vec_ext_v16hi: 4017 i = 1; l = 0; u = 15; 4018 break; 4019 case X86::BI__builtin_ia32_pblendd128: 4020 case X86::BI__builtin_ia32_blendps: 4021 case X86::BI__builtin_ia32_blendpd256: 4022 case X86::BI__builtin_ia32_shufpd256: 4023 case X86::BI__builtin_ia32_roundss: 4024 case X86::BI__builtin_ia32_roundsd: 4025 case X86::BI__builtin_ia32_rangepd128_mask: 4026 case X86::BI__builtin_ia32_rangepd256_mask: 4027 case X86::BI__builtin_ia32_rangepd512_mask: 4028 case X86::BI__builtin_ia32_rangeps128_mask: 4029 case X86::BI__builtin_ia32_rangeps256_mask: 4030 case X86::BI__builtin_ia32_rangeps512_mask: 4031 case X86::BI__builtin_ia32_getmantsd_round_mask: 4032 case X86::BI__builtin_ia32_getmantss_round_mask: 4033 case X86::BI__builtin_ia32_vec_set_v16qi: 4034 case X86::BI__builtin_ia32_vec_set_v16hi: 4035 i = 2; l = 0; u = 15; 4036 break; 4037 case X86::BI__builtin_ia32_vec_ext_v32qi: 4038 i = 1; l = 0; u = 31; 4039 break; 4040 case X86::BI__builtin_ia32_cmpps: 4041 case X86::BI__builtin_ia32_cmpss: 4042 case X86::BI__builtin_ia32_cmppd: 4043 case X86::BI__builtin_ia32_cmpsd: 4044 case X86::BI__builtin_ia32_cmpps256: 4045 case X86::BI__builtin_ia32_cmppd256: 4046 case X86::BI__builtin_ia32_cmpps128_mask: 4047 case X86::BI__builtin_ia32_cmppd128_mask: 4048 case X86::BI__builtin_ia32_cmpps256_mask: 4049 case X86::BI__builtin_ia32_cmppd256_mask: 4050 case X86::BI__builtin_ia32_cmpps512_mask: 4051 case X86::BI__builtin_ia32_cmppd512_mask: 4052 case X86::BI__builtin_ia32_cmpsd_mask: 4053 case X86::BI__builtin_ia32_cmpss_mask: 4054 case X86::BI__builtin_ia32_vec_set_v32qi: 4055 i = 2; l = 0; u = 31; 4056 break; 4057 case X86::BI__builtin_ia32_permdf256: 4058 case X86::BI__builtin_ia32_permdi256: 4059 case X86::BI__builtin_ia32_permdf512: 4060 case X86::BI__builtin_ia32_permdi512: 4061 case X86::BI__builtin_ia32_vpermilps: 4062 case X86::BI__builtin_ia32_vpermilps256: 4063 case X86::BI__builtin_ia32_vpermilpd512: 4064 case X86::BI__builtin_ia32_vpermilps512: 4065 case X86::BI__builtin_ia32_pshufd: 4066 case X86::BI__builtin_ia32_pshufd256: 4067 case X86::BI__builtin_ia32_pshufd512: 4068 case X86::BI__builtin_ia32_pshufhw: 4069 case X86::BI__builtin_ia32_pshufhw256: 4070 case X86::BI__builtin_ia32_pshufhw512: 4071 case X86::BI__builtin_ia32_pshuflw: 4072 case X86::BI__builtin_ia32_pshuflw256: 4073 case X86::BI__builtin_ia32_pshuflw512: 4074 case X86::BI__builtin_ia32_vcvtps2ph: 4075 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4076 case X86::BI__builtin_ia32_vcvtps2ph256: 4077 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4078 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4079 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4080 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4081 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4082 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4083 case X86::BI__builtin_ia32_rndscaleps_mask: 4084 case X86::BI__builtin_ia32_rndscalepd_mask: 4085 case X86::BI__builtin_ia32_reducepd128_mask: 4086 case X86::BI__builtin_ia32_reducepd256_mask: 4087 case X86::BI__builtin_ia32_reducepd512_mask: 4088 case X86::BI__builtin_ia32_reduceps128_mask: 4089 case X86::BI__builtin_ia32_reduceps256_mask: 4090 case X86::BI__builtin_ia32_reduceps512_mask: 4091 case X86::BI__builtin_ia32_prold512: 4092 case X86::BI__builtin_ia32_prolq512: 4093 case X86::BI__builtin_ia32_prold128: 4094 case X86::BI__builtin_ia32_prold256: 4095 case X86::BI__builtin_ia32_prolq128: 4096 case X86::BI__builtin_ia32_prolq256: 4097 case X86::BI__builtin_ia32_prord512: 4098 case X86::BI__builtin_ia32_prorq512: 4099 case X86::BI__builtin_ia32_prord128: 4100 case X86::BI__builtin_ia32_prord256: 4101 case X86::BI__builtin_ia32_prorq128: 4102 case X86::BI__builtin_ia32_prorq256: 4103 case X86::BI__builtin_ia32_fpclasspd128_mask: 4104 case X86::BI__builtin_ia32_fpclasspd256_mask: 4105 case X86::BI__builtin_ia32_fpclassps128_mask: 4106 case X86::BI__builtin_ia32_fpclassps256_mask: 4107 case X86::BI__builtin_ia32_fpclassps512_mask: 4108 case X86::BI__builtin_ia32_fpclasspd512_mask: 4109 case X86::BI__builtin_ia32_fpclasssd_mask: 4110 case X86::BI__builtin_ia32_fpclassss_mask: 4111 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4112 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4113 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4114 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4115 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4116 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4117 case X86::BI__builtin_ia32_kshiftliqi: 4118 case X86::BI__builtin_ia32_kshiftlihi: 4119 case X86::BI__builtin_ia32_kshiftlisi: 4120 case X86::BI__builtin_ia32_kshiftlidi: 4121 case X86::BI__builtin_ia32_kshiftriqi: 4122 case X86::BI__builtin_ia32_kshiftrihi: 4123 case X86::BI__builtin_ia32_kshiftrisi: 4124 case X86::BI__builtin_ia32_kshiftridi: 4125 i = 1; l = 0; u = 255; 4126 break; 4127 case X86::BI__builtin_ia32_vperm2f128_pd256: 4128 case X86::BI__builtin_ia32_vperm2f128_ps256: 4129 case X86::BI__builtin_ia32_vperm2f128_si256: 4130 case X86::BI__builtin_ia32_permti256: 4131 case X86::BI__builtin_ia32_pblendw128: 4132 case X86::BI__builtin_ia32_pblendw256: 4133 case X86::BI__builtin_ia32_blendps256: 4134 case X86::BI__builtin_ia32_pblendd256: 4135 case X86::BI__builtin_ia32_palignr128: 4136 case X86::BI__builtin_ia32_palignr256: 4137 case X86::BI__builtin_ia32_palignr512: 4138 case X86::BI__builtin_ia32_alignq512: 4139 case X86::BI__builtin_ia32_alignd512: 4140 case X86::BI__builtin_ia32_alignd128: 4141 case X86::BI__builtin_ia32_alignd256: 4142 case X86::BI__builtin_ia32_alignq128: 4143 case X86::BI__builtin_ia32_alignq256: 4144 case X86::BI__builtin_ia32_vcomisd: 4145 case X86::BI__builtin_ia32_vcomiss: 4146 case X86::BI__builtin_ia32_shuf_f32x4: 4147 case X86::BI__builtin_ia32_shuf_f64x2: 4148 case X86::BI__builtin_ia32_shuf_i32x4: 4149 case X86::BI__builtin_ia32_shuf_i64x2: 4150 case X86::BI__builtin_ia32_shufpd512: 4151 case X86::BI__builtin_ia32_shufps: 4152 case X86::BI__builtin_ia32_shufps256: 4153 case X86::BI__builtin_ia32_shufps512: 4154 case X86::BI__builtin_ia32_dbpsadbw128: 4155 case X86::BI__builtin_ia32_dbpsadbw256: 4156 case X86::BI__builtin_ia32_dbpsadbw512: 4157 case X86::BI__builtin_ia32_vpshldd128: 4158 case X86::BI__builtin_ia32_vpshldd256: 4159 case X86::BI__builtin_ia32_vpshldd512: 4160 case X86::BI__builtin_ia32_vpshldq128: 4161 case X86::BI__builtin_ia32_vpshldq256: 4162 case X86::BI__builtin_ia32_vpshldq512: 4163 case X86::BI__builtin_ia32_vpshldw128: 4164 case X86::BI__builtin_ia32_vpshldw256: 4165 case X86::BI__builtin_ia32_vpshldw512: 4166 case X86::BI__builtin_ia32_vpshrdd128: 4167 case X86::BI__builtin_ia32_vpshrdd256: 4168 case X86::BI__builtin_ia32_vpshrdd512: 4169 case X86::BI__builtin_ia32_vpshrdq128: 4170 case X86::BI__builtin_ia32_vpshrdq256: 4171 case X86::BI__builtin_ia32_vpshrdq512: 4172 case X86::BI__builtin_ia32_vpshrdw128: 4173 case X86::BI__builtin_ia32_vpshrdw256: 4174 case X86::BI__builtin_ia32_vpshrdw512: 4175 i = 2; l = 0; u = 255; 4176 break; 4177 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4178 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4179 case X86::BI__builtin_ia32_fixupimmps512_mask: 4180 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4181 case X86::BI__builtin_ia32_fixupimmsd_mask: 4182 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4183 case X86::BI__builtin_ia32_fixupimmss_mask: 4184 case X86::BI__builtin_ia32_fixupimmss_maskz: 4185 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4186 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4187 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4188 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4189 case X86::BI__builtin_ia32_fixupimmps128_mask: 4190 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4191 case X86::BI__builtin_ia32_fixupimmps256_mask: 4192 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4193 case X86::BI__builtin_ia32_pternlogd512_mask: 4194 case X86::BI__builtin_ia32_pternlogd512_maskz: 4195 case X86::BI__builtin_ia32_pternlogq512_mask: 4196 case X86::BI__builtin_ia32_pternlogq512_maskz: 4197 case X86::BI__builtin_ia32_pternlogd128_mask: 4198 case X86::BI__builtin_ia32_pternlogd128_maskz: 4199 case X86::BI__builtin_ia32_pternlogd256_mask: 4200 case X86::BI__builtin_ia32_pternlogd256_maskz: 4201 case X86::BI__builtin_ia32_pternlogq128_mask: 4202 case X86::BI__builtin_ia32_pternlogq128_maskz: 4203 case X86::BI__builtin_ia32_pternlogq256_mask: 4204 case X86::BI__builtin_ia32_pternlogq256_maskz: 4205 i = 3; l = 0; u = 255; 4206 break; 4207 case X86::BI__builtin_ia32_gatherpfdpd: 4208 case X86::BI__builtin_ia32_gatherpfdps: 4209 case X86::BI__builtin_ia32_gatherpfqpd: 4210 case X86::BI__builtin_ia32_gatherpfqps: 4211 case X86::BI__builtin_ia32_scatterpfdpd: 4212 case X86::BI__builtin_ia32_scatterpfdps: 4213 case X86::BI__builtin_ia32_scatterpfqpd: 4214 case X86::BI__builtin_ia32_scatterpfqps: 4215 i = 4; l = 2; u = 3; 4216 break; 4217 case X86::BI__builtin_ia32_reducesd_mask: 4218 case X86::BI__builtin_ia32_reducess_mask: 4219 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4220 case X86::BI__builtin_ia32_rndscaless_round_mask: 4221 i = 4; l = 0; u = 255; 4222 break; 4223 } 4224 4225 // Note that we don't force a hard error on the range check here, allowing 4226 // template-generated or macro-generated dead code to potentially have out-of- 4227 // range values. These need to code generate, but don't need to necessarily 4228 // make any sense. We use a warning that defaults to an error. 4229 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4230 } 4231 4232 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4233 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4234 /// Returns true when the format fits the function and the FormatStringInfo has 4235 /// been populated. 4236 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4237 FormatStringInfo *FSI) { 4238 FSI->HasVAListArg = Format->getFirstArg() == 0; 4239 FSI->FormatIdx = Format->getFormatIdx() - 1; 4240 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4241 4242 // The way the format attribute works in GCC, the implicit this argument 4243 // of member functions is counted. However, it doesn't appear in our own 4244 // lists, so decrement format_idx in that case. 4245 if (IsCXXMember) { 4246 if(FSI->FormatIdx == 0) 4247 return false; 4248 --FSI->FormatIdx; 4249 if (FSI->FirstDataArg != 0) 4250 --FSI->FirstDataArg; 4251 } 4252 return true; 4253 } 4254 4255 /// Checks if a the given expression evaluates to null. 4256 /// 4257 /// Returns true if the value evaluates to null. 4258 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4259 // If the expression has non-null type, it doesn't evaluate to null. 4260 if (auto nullability 4261 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4262 if (*nullability == NullabilityKind::NonNull) 4263 return false; 4264 } 4265 4266 // As a special case, transparent unions initialized with zero are 4267 // considered null for the purposes of the nonnull attribute. 4268 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4269 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4270 if (const CompoundLiteralExpr *CLE = 4271 dyn_cast<CompoundLiteralExpr>(Expr)) 4272 if (const InitListExpr *ILE = 4273 dyn_cast<InitListExpr>(CLE->getInitializer())) 4274 Expr = ILE->getInit(0); 4275 } 4276 4277 bool Result; 4278 return (!Expr->isValueDependent() && 4279 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4280 !Result); 4281 } 4282 4283 static void CheckNonNullArgument(Sema &S, 4284 const Expr *ArgExpr, 4285 SourceLocation CallSiteLoc) { 4286 if (CheckNonNullExpr(S, ArgExpr)) 4287 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4288 S.PDiag(diag::warn_null_arg) 4289 << ArgExpr->getSourceRange()); 4290 } 4291 4292 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4293 FormatStringInfo FSI; 4294 if ((GetFormatStringType(Format) == FST_NSString) && 4295 getFormatStringInfo(Format, false, &FSI)) { 4296 Idx = FSI.FormatIdx; 4297 return true; 4298 } 4299 return false; 4300 } 4301 4302 /// Diagnose use of %s directive in an NSString which is being passed 4303 /// as formatting string to formatting method. 4304 static void 4305 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4306 const NamedDecl *FDecl, 4307 Expr **Args, 4308 unsigned NumArgs) { 4309 unsigned Idx = 0; 4310 bool Format = false; 4311 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4312 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4313 Idx = 2; 4314 Format = true; 4315 } 4316 else 4317 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4318 if (S.GetFormatNSStringIdx(I, Idx)) { 4319 Format = true; 4320 break; 4321 } 4322 } 4323 if (!Format || NumArgs <= Idx) 4324 return; 4325 const Expr *FormatExpr = Args[Idx]; 4326 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4327 FormatExpr = CSCE->getSubExpr(); 4328 const StringLiteral *FormatString; 4329 if (const ObjCStringLiteral *OSL = 4330 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4331 FormatString = OSL->getString(); 4332 else 4333 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4334 if (!FormatString) 4335 return; 4336 if (S.FormatStringHasSArg(FormatString)) { 4337 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4338 << "%s" << 1 << 1; 4339 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4340 << FDecl->getDeclName(); 4341 } 4342 } 4343 4344 /// Determine whether the given type has a non-null nullability annotation. 4345 static bool isNonNullType(ASTContext &ctx, QualType type) { 4346 if (auto nullability = type->getNullability(ctx)) 4347 return *nullability == NullabilityKind::NonNull; 4348 4349 return false; 4350 } 4351 4352 static void CheckNonNullArguments(Sema &S, 4353 const NamedDecl *FDecl, 4354 const FunctionProtoType *Proto, 4355 ArrayRef<const Expr *> Args, 4356 SourceLocation CallSiteLoc) { 4357 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4358 4359 // Already checked by by constant evaluator. 4360 if (S.isConstantEvaluated()) 4361 return; 4362 // Check the attributes attached to the method/function itself. 4363 llvm::SmallBitVector NonNullArgs; 4364 if (FDecl) { 4365 // Handle the nonnull attribute on the function/method declaration itself. 4366 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4367 if (!NonNull->args_size()) { 4368 // Easy case: all pointer arguments are nonnull. 4369 for (const auto *Arg : Args) 4370 if (S.isValidPointerAttrType(Arg->getType())) 4371 CheckNonNullArgument(S, Arg, CallSiteLoc); 4372 return; 4373 } 4374 4375 for (const ParamIdx &Idx : NonNull->args()) { 4376 unsigned IdxAST = Idx.getASTIndex(); 4377 if (IdxAST >= Args.size()) 4378 continue; 4379 if (NonNullArgs.empty()) 4380 NonNullArgs.resize(Args.size()); 4381 NonNullArgs.set(IdxAST); 4382 } 4383 } 4384 } 4385 4386 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4387 // Handle the nonnull attribute on the parameters of the 4388 // function/method. 4389 ArrayRef<ParmVarDecl*> parms; 4390 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4391 parms = FD->parameters(); 4392 else 4393 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4394 4395 unsigned ParamIndex = 0; 4396 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4397 I != E; ++I, ++ParamIndex) { 4398 const ParmVarDecl *PVD = *I; 4399 if (PVD->hasAttr<NonNullAttr>() || 4400 isNonNullType(S.Context, PVD->getType())) { 4401 if (NonNullArgs.empty()) 4402 NonNullArgs.resize(Args.size()); 4403 4404 NonNullArgs.set(ParamIndex); 4405 } 4406 } 4407 } else { 4408 // If we have a non-function, non-method declaration but no 4409 // function prototype, try to dig out the function prototype. 4410 if (!Proto) { 4411 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4412 QualType type = VD->getType().getNonReferenceType(); 4413 if (auto pointerType = type->getAs<PointerType>()) 4414 type = pointerType->getPointeeType(); 4415 else if (auto blockType = type->getAs<BlockPointerType>()) 4416 type = blockType->getPointeeType(); 4417 // FIXME: data member pointers? 4418 4419 // Dig out the function prototype, if there is one. 4420 Proto = type->getAs<FunctionProtoType>(); 4421 } 4422 } 4423 4424 // Fill in non-null argument information from the nullability 4425 // information on the parameter types (if we have them). 4426 if (Proto) { 4427 unsigned Index = 0; 4428 for (auto paramType : Proto->getParamTypes()) { 4429 if (isNonNullType(S.Context, paramType)) { 4430 if (NonNullArgs.empty()) 4431 NonNullArgs.resize(Args.size()); 4432 4433 NonNullArgs.set(Index); 4434 } 4435 4436 ++Index; 4437 } 4438 } 4439 } 4440 4441 // Check for non-null arguments. 4442 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4443 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4444 if (NonNullArgs[ArgIndex]) 4445 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4446 } 4447 } 4448 4449 /// Handles the checks for format strings, non-POD arguments to vararg 4450 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4451 /// attributes. 4452 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4453 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4454 bool IsMemberFunction, SourceLocation Loc, 4455 SourceRange Range, VariadicCallType CallType) { 4456 // FIXME: We should check as much as we can in the template definition. 4457 if (CurContext->isDependentContext()) 4458 return; 4459 4460 // Printf and scanf checking. 4461 llvm::SmallBitVector CheckedVarArgs; 4462 if (FDecl) { 4463 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4464 // Only create vector if there are format attributes. 4465 CheckedVarArgs.resize(Args.size()); 4466 4467 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4468 CheckedVarArgs); 4469 } 4470 } 4471 4472 // Refuse POD arguments that weren't caught by the format string 4473 // checks above. 4474 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4475 if (CallType != VariadicDoesNotApply && 4476 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4477 unsigned NumParams = Proto ? Proto->getNumParams() 4478 : FDecl && isa<FunctionDecl>(FDecl) 4479 ? cast<FunctionDecl>(FDecl)->getNumParams() 4480 : FDecl && isa<ObjCMethodDecl>(FDecl) 4481 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4482 : 0; 4483 4484 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4485 // Args[ArgIdx] can be null in malformed code. 4486 if (const Expr *Arg = Args[ArgIdx]) { 4487 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4488 checkVariadicArgument(Arg, CallType); 4489 } 4490 } 4491 } 4492 4493 if (FDecl || Proto) { 4494 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4495 4496 // Type safety checking. 4497 if (FDecl) { 4498 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4499 CheckArgumentWithTypeTag(I, Args, Loc); 4500 } 4501 } 4502 4503 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4504 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4505 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4506 if (!Arg->isValueDependent()) { 4507 Expr::EvalResult Align; 4508 if (Arg->EvaluateAsInt(Align, Context)) { 4509 const llvm::APSInt &I = Align.Val.getInt(); 4510 if (!I.isPowerOf2()) 4511 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4512 << Arg->getSourceRange(); 4513 4514 if (I > Sema::MaximumAlignment) 4515 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4516 << Arg->getSourceRange() << Sema::MaximumAlignment; 4517 } 4518 } 4519 } 4520 4521 if (FD) 4522 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4523 } 4524 4525 /// CheckConstructorCall - Check a constructor call for correctness and safety 4526 /// properties not enforced by the C type system. 4527 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4528 ArrayRef<const Expr *> Args, 4529 const FunctionProtoType *Proto, 4530 SourceLocation Loc) { 4531 VariadicCallType CallType = 4532 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4533 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4534 Loc, SourceRange(), CallType); 4535 } 4536 4537 /// CheckFunctionCall - Check a direct function call for various correctness 4538 /// and safety properties not strictly enforced by the C type system. 4539 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4540 const FunctionProtoType *Proto) { 4541 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4542 isa<CXXMethodDecl>(FDecl); 4543 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4544 IsMemberOperatorCall; 4545 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4546 TheCall->getCallee()); 4547 Expr** Args = TheCall->getArgs(); 4548 unsigned NumArgs = TheCall->getNumArgs(); 4549 4550 Expr *ImplicitThis = nullptr; 4551 if (IsMemberOperatorCall) { 4552 // If this is a call to a member operator, hide the first argument 4553 // from checkCall. 4554 // FIXME: Our choice of AST representation here is less than ideal. 4555 ImplicitThis = Args[0]; 4556 ++Args; 4557 --NumArgs; 4558 } else if (IsMemberFunction) 4559 ImplicitThis = 4560 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4561 4562 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4563 IsMemberFunction, TheCall->getRParenLoc(), 4564 TheCall->getCallee()->getSourceRange(), CallType); 4565 4566 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4567 // None of the checks below are needed for functions that don't have 4568 // simple names (e.g., C++ conversion functions). 4569 if (!FnInfo) 4570 return false; 4571 4572 CheckAbsoluteValueFunction(TheCall, FDecl); 4573 CheckMaxUnsignedZero(TheCall, FDecl); 4574 4575 if (getLangOpts().ObjC) 4576 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4577 4578 unsigned CMId = FDecl->getMemoryFunctionKind(); 4579 4580 // Handle memory setting and copying functions. 4581 switch (CMId) { 4582 case 0: 4583 return false; 4584 case Builtin::BIstrlcpy: // fallthrough 4585 case Builtin::BIstrlcat: 4586 CheckStrlcpycatArguments(TheCall, FnInfo); 4587 break; 4588 case Builtin::BIstrncat: 4589 CheckStrncatArguments(TheCall, FnInfo); 4590 break; 4591 case Builtin::BIfree: 4592 CheckFreeArguments(TheCall); 4593 break; 4594 default: 4595 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4596 } 4597 4598 return false; 4599 } 4600 4601 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4602 ArrayRef<const Expr *> Args) { 4603 VariadicCallType CallType = 4604 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4605 4606 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4607 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4608 CallType); 4609 4610 return false; 4611 } 4612 4613 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4614 const FunctionProtoType *Proto) { 4615 QualType Ty; 4616 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4617 Ty = V->getType().getNonReferenceType(); 4618 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4619 Ty = F->getType().getNonReferenceType(); 4620 else 4621 return false; 4622 4623 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4624 !Ty->isFunctionProtoType()) 4625 return false; 4626 4627 VariadicCallType CallType; 4628 if (!Proto || !Proto->isVariadic()) { 4629 CallType = VariadicDoesNotApply; 4630 } else if (Ty->isBlockPointerType()) { 4631 CallType = VariadicBlock; 4632 } else { // Ty->isFunctionPointerType() 4633 CallType = VariadicFunction; 4634 } 4635 4636 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4637 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4638 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4639 TheCall->getCallee()->getSourceRange(), CallType); 4640 4641 return false; 4642 } 4643 4644 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4645 /// such as function pointers returned from functions. 4646 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4647 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4648 TheCall->getCallee()); 4649 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4650 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4651 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4652 TheCall->getCallee()->getSourceRange(), CallType); 4653 4654 return false; 4655 } 4656 4657 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4658 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4659 return false; 4660 4661 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4662 switch (Op) { 4663 case AtomicExpr::AO__c11_atomic_init: 4664 case AtomicExpr::AO__opencl_atomic_init: 4665 llvm_unreachable("There is no ordering argument for an init"); 4666 4667 case AtomicExpr::AO__c11_atomic_load: 4668 case AtomicExpr::AO__opencl_atomic_load: 4669 case AtomicExpr::AO__atomic_load_n: 4670 case AtomicExpr::AO__atomic_load: 4671 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4672 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4673 4674 case AtomicExpr::AO__c11_atomic_store: 4675 case AtomicExpr::AO__opencl_atomic_store: 4676 case AtomicExpr::AO__atomic_store: 4677 case AtomicExpr::AO__atomic_store_n: 4678 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4679 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4680 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4681 4682 default: 4683 return true; 4684 } 4685 } 4686 4687 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4688 AtomicExpr::AtomicOp Op) { 4689 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4690 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4691 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4692 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4693 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4694 Op); 4695 } 4696 4697 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4698 SourceLocation RParenLoc, MultiExprArg Args, 4699 AtomicExpr::AtomicOp Op, 4700 AtomicArgumentOrder ArgOrder) { 4701 // All the non-OpenCL operations take one of the following forms. 4702 // The OpenCL operations take the __c11 forms with one extra argument for 4703 // synchronization scope. 4704 enum { 4705 // C __c11_atomic_init(A *, C) 4706 Init, 4707 4708 // C __c11_atomic_load(A *, int) 4709 Load, 4710 4711 // void __atomic_load(A *, CP, int) 4712 LoadCopy, 4713 4714 // void __atomic_store(A *, CP, int) 4715 Copy, 4716 4717 // C __c11_atomic_add(A *, M, int) 4718 Arithmetic, 4719 4720 // C __atomic_exchange_n(A *, CP, int) 4721 Xchg, 4722 4723 // void __atomic_exchange(A *, C *, CP, int) 4724 GNUXchg, 4725 4726 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4727 C11CmpXchg, 4728 4729 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4730 GNUCmpXchg 4731 } Form = Init; 4732 4733 const unsigned NumForm = GNUCmpXchg + 1; 4734 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4735 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4736 // where: 4737 // C is an appropriate type, 4738 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4739 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4740 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4741 // the int parameters are for orderings. 4742 4743 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4744 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4745 "need to update code for modified forms"); 4746 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4747 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4748 AtomicExpr::AO__atomic_load, 4749 "need to update code for modified C11 atomics"); 4750 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4751 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4752 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4753 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4754 IsOpenCL; 4755 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4756 Op == AtomicExpr::AO__atomic_store_n || 4757 Op == AtomicExpr::AO__atomic_exchange_n || 4758 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4759 bool IsAddSub = false; 4760 4761 switch (Op) { 4762 case AtomicExpr::AO__c11_atomic_init: 4763 case AtomicExpr::AO__opencl_atomic_init: 4764 Form = Init; 4765 break; 4766 4767 case AtomicExpr::AO__c11_atomic_load: 4768 case AtomicExpr::AO__opencl_atomic_load: 4769 case AtomicExpr::AO__atomic_load_n: 4770 Form = Load; 4771 break; 4772 4773 case AtomicExpr::AO__atomic_load: 4774 Form = LoadCopy; 4775 break; 4776 4777 case AtomicExpr::AO__c11_atomic_store: 4778 case AtomicExpr::AO__opencl_atomic_store: 4779 case AtomicExpr::AO__atomic_store: 4780 case AtomicExpr::AO__atomic_store_n: 4781 Form = Copy; 4782 break; 4783 4784 case AtomicExpr::AO__c11_atomic_fetch_add: 4785 case AtomicExpr::AO__c11_atomic_fetch_sub: 4786 case AtomicExpr::AO__opencl_atomic_fetch_add: 4787 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4788 case AtomicExpr::AO__atomic_fetch_add: 4789 case AtomicExpr::AO__atomic_fetch_sub: 4790 case AtomicExpr::AO__atomic_add_fetch: 4791 case AtomicExpr::AO__atomic_sub_fetch: 4792 IsAddSub = true; 4793 LLVM_FALLTHROUGH; 4794 case AtomicExpr::AO__c11_atomic_fetch_and: 4795 case AtomicExpr::AO__c11_atomic_fetch_or: 4796 case AtomicExpr::AO__c11_atomic_fetch_xor: 4797 case AtomicExpr::AO__opencl_atomic_fetch_and: 4798 case AtomicExpr::AO__opencl_atomic_fetch_or: 4799 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4800 case AtomicExpr::AO__atomic_fetch_and: 4801 case AtomicExpr::AO__atomic_fetch_or: 4802 case AtomicExpr::AO__atomic_fetch_xor: 4803 case AtomicExpr::AO__atomic_fetch_nand: 4804 case AtomicExpr::AO__atomic_and_fetch: 4805 case AtomicExpr::AO__atomic_or_fetch: 4806 case AtomicExpr::AO__atomic_xor_fetch: 4807 case AtomicExpr::AO__atomic_nand_fetch: 4808 case AtomicExpr::AO__c11_atomic_fetch_min: 4809 case AtomicExpr::AO__c11_atomic_fetch_max: 4810 case AtomicExpr::AO__opencl_atomic_fetch_min: 4811 case AtomicExpr::AO__opencl_atomic_fetch_max: 4812 case AtomicExpr::AO__atomic_min_fetch: 4813 case AtomicExpr::AO__atomic_max_fetch: 4814 case AtomicExpr::AO__atomic_fetch_min: 4815 case AtomicExpr::AO__atomic_fetch_max: 4816 Form = Arithmetic; 4817 break; 4818 4819 case AtomicExpr::AO__c11_atomic_exchange: 4820 case AtomicExpr::AO__opencl_atomic_exchange: 4821 case AtomicExpr::AO__atomic_exchange_n: 4822 Form = Xchg; 4823 break; 4824 4825 case AtomicExpr::AO__atomic_exchange: 4826 Form = GNUXchg; 4827 break; 4828 4829 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4830 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4831 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4832 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4833 Form = C11CmpXchg; 4834 break; 4835 4836 case AtomicExpr::AO__atomic_compare_exchange: 4837 case AtomicExpr::AO__atomic_compare_exchange_n: 4838 Form = GNUCmpXchg; 4839 break; 4840 } 4841 4842 unsigned AdjustedNumArgs = NumArgs[Form]; 4843 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4844 ++AdjustedNumArgs; 4845 // Check we have the right number of arguments. 4846 if (Args.size() < AdjustedNumArgs) { 4847 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4848 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4849 << ExprRange; 4850 return ExprError(); 4851 } else if (Args.size() > AdjustedNumArgs) { 4852 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4853 diag::err_typecheck_call_too_many_args) 4854 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4855 << ExprRange; 4856 return ExprError(); 4857 } 4858 4859 // Inspect the first argument of the atomic operation. 4860 Expr *Ptr = Args[0]; 4861 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4862 if (ConvertedPtr.isInvalid()) 4863 return ExprError(); 4864 4865 Ptr = ConvertedPtr.get(); 4866 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4867 if (!pointerType) { 4868 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4869 << Ptr->getType() << Ptr->getSourceRange(); 4870 return ExprError(); 4871 } 4872 4873 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4874 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4875 QualType ValType = AtomTy; // 'C' 4876 if (IsC11) { 4877 if (!AtomTy->isAtomicType()) { 4878 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4879 << Ptr->getType() << Ptr->getSourceRange(); 4880 return ExprError(); 4881 } 4882 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4883 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4884 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4885 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4886 << Ptr->getSourceRange(); 4887 return ExprError(); 4888 } 4889 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4890 } else if (Form != Load && Form != LoadCopy) { 4891 if (ValType.isConstQualified()) { 4892 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4893 << Ptr->getType() << Ptr->getSourceRange(); 4894 return ExprError(); 4895 } 4896 } 4897 4898 // For an arithmetic operation, the implied arithmetic must be well-formed. 4899 if (Form == Arithmetic) { 4900 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4901 if (IsAddSub && !ValType->isIntegerType() 4902 && !ValType->isPointerType()) { 4903 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4904 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4905 return ExprError(); 4906 } 4907 if (!IsAddSub && !ValType->isIntegerType()) { 4908 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4909 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4910 return ExprError(); 4911 } 4912 if (IsC11 && ValType->isPointerType() && 4913 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4914 diag::err_incomplete_type)) { 4915 return ExprError(); 4916 } 4917 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4918 // For __atomic_*_n operations, the value type must be a scalar integral or 4919 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4920 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4921 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4922 return ExprError(); 4923 } 4924 4925 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4926 !AtomTy->isScalarType()) { 4927 // For GNU atomics, require a trivially-copyable type. This is not part of 4928 // the GNU atomics specification, but we enforce it for sanity. 4929 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4930 << Ptr->getType() << Ptr->getSourceRange(); 4931 return ExprError(); 4932 } 4933 4934 switch (ValType.getObjCLifetime()) { 4935 case Qualifiers::OCL_None: 4936 case Qualifiers::OCL_ExplicitNone: 4937 // okay 4938 break; 4939 4940 case Qualifiers::OCL_Weak: 4941 case Qualifiers::OCL_Strong: 4942 case Qualifiers::OCL_Autoreleasing: 4943 // FIXME: Can this happen? By this point, ValType should be known 4944 // to be trivially copyable. 4945 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4946 << ValType << Ptr->getSourceRange(); 4947 return ExprError(); 4948 } 4949 4950 // All atomic operations have an overload which takes a pointer to a volatile 4951 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4952 // into the result or the other operands. Similarly atomic_load takes a 4953 // pointer to a const 'A'. 4954 ValType.removeLocalVolatile(); 4955 ValType.removeLocalConst(); 4956 QualType ResultType = ValType; 4957 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4958 Form == Init) 4959 ResultType = Context.VoidTy; 4960 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4961 ResultType = Context.BoolTy; 4962 4963 // The type of a parameter passed 'by value'. In the GNU atomics, such 4964 // arguments are actually passed as pointers. 4965 QualType ByValType = ValType; // 'CP' 4966 bool IsPassedByAddress = false; 4967 if (!IsC11 && !IsN) { 4968 ByValType = Ptr->getType(); 4969 IsPassedByAddress = true; 4970 } 4971 4972 SmallVector<Expr *, 5> APIOrderedArgs; 4973 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4974 APIOrderedArgs.push_back(Args[0]); 4975 switch (Form) { 4976 case Init: 4977 case Load: 4978 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4979 break; 4980 case LoadCopy: 4981 case Copy: 4982 case Arithmetic: 4983 case Xchg: 4984 APIOrderedArgs.push_back(Args[2]); // Val1 4985 APIOrderedArgs.push_back(Args[1]); // Order 4986 break; 4987 case GNUXchg: 4988 APIOrderedArgs.push_back(Args[2]); // Val1 4989 APIOrderedArgs.push_back(Args[3]); // Val2 4990 APIOrderedArgs.push_back(Args[1]); // Order 4991 break; 4992 case C11CmpXchg: 4993 APIOrderedArgs.push_back(Args[2]); // Val1 4994 APIOrderedArgs.push_back(Args[4]); // Val2 4995 APIOrderedArgs.push_back(Args[1]); // Order 4996 APIOrderedArgs.push_back(Args[3]); // OrderFail 4997 break; 4998 case GNUCmpXchg: 4999 APIOrderedArgs.push_back(Args[2]); // Val1 5000 APIOrderedArgs.push_back(Args[4]); // Val2 5001 APIOrderedArgs.push_back(Args[5]); // Weak 5002 APIOrderedArgs.push_back(Args[1]); // Order 5003 APIOrderedArgs.push_back(Args[3]); // OrderFail 5004 break; 5005 } 5006 } else 5007 APIOrderedArgs.append(Args.begin(), Args.end()); 5008 5009 // The first argument's non-CV pointer type is used to deduce the type of 5010 // subsequent arguments, except for: 5011 // - weak flag (always converted to bool) 5012 // - memory order (always converted to int) 5013 // - scope (always converted to int) 5014 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5015 QualType Ty; 5016 if (i < NumVals[Form] + 1) { 5017 switch (i) { 5018 case 0: 5019 // The first argument is always a pointer. It has a fixed type. 5020 // It is always dereferenced, a nullptr is undefined. 5021 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5022 // Nothing else to do: we already know all we want about this pointer. 5023 continue; 5024 case 1: 5025 // The second argument is the non-atomic operand. For arithmetic, this 5026 // is always passed by value, and for a compare_exchange it is always 5027 // passed by address. For the rest, GNU uses by-address and C11 uses 5028 // by-value. 5029 assert(Form != Load); 5030 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 5031 Ty = ValType; 5032 else if (Form == Copy || Form == Xchg) { 5033 if (IsPassedByAddress) { 5034 // The value pointer is always dereferenced, a nullptr is undefined. 5035 CheckNonNullArgument(*this, APIOrderedArgs[i], 5036 ExprRange.getBegin()); 5037 } 5038 Ty = ByValType; 5039 } else if (Form == Arithmetic) 5040 Ty = Context.getPointerDiffType(); 5041 else { 5042 Expr *ValArg = APIOrderedArgs[i]; 5043 // The value pointer is always dereferenced, a nullptr is undefined. 5044 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5045 LangAS AS = LangAS::Default; 5046 // Keep address space of non-atomic pointer type. 5047 if (const PointerType *PtrTy = 5048 ValArg->getType()->getAs<PointerType>()) { 5049 AS = PtrTy->getPointeeType().getAddressSpace(); 5050 } 5051 Ty = Context.getPointerType( 5052 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5053 } 5054 break; 5055 case 2: 5056 // The third argument to compare_exchange / GNU exchange is the desired 5057 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5058 if (IsPassedByAddress) 5059 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5060 Ty = ByValType; 5061 break; 5062 case 3: 5063 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5064 Ty = Context.BoolTy; 5065 break; 5066 } 5067 } else { 5068 // The order(s) and scope are always converted to int. 5069 Ty = Context.IntTy; 5070 } 5071 5072 InitializedEntity Entity = 5073 InitializedEntity::InitializeParameter(Context, Ty, false); 5074 ExprResult Arg = APIOrderedArgs[i]; 5075 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5076 if (Arg.isInvalid()) 5077 return true; 5078 APIOrderedArgs[i] = Arg.get(); 5079 } 5080 5081 // Permute the arguments into a 'consistent' order. 5082 SmallVector<Expr*, 5> SubExprs; 5083 SubExprs.push_back(Ptr); 5084 switch (Form) { 5085 case Init: 5086 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5087 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5088 break; 5089 case Load: 5090 SubExprs.push_back(APIOrderedArgs[1]); // Order 5091 break; 5092 case LoadCopy: 5093 case Copy: 5094 case Arithmetic: 5095 case Xchg: 5096 SubExprs.push_back(APIOrderedArgs[2]); // Order 5097 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5098 break; 5099 case GNUXchg: 5100 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5101 SubExprs.push_back(APIOrderedArgs[3]); // Order 5102 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5103 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5104 break; 5105 case C11CmpXchg: 5106 SubExprs.push_back(APIOrderedArgs[3]); // Order 5107 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5108 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5109 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5110 break; 5111 case GNUCmpXchg: 5112 SubExprs.push_back(APIOrderedArgs[4]); // Order 5113 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5114 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5115 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5116 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5117 break; 5118 } 5119 5120 if (SubExprs.size() >= 2 && Form != Init) { 5121 if (Optional<llvm::APSInt> Result = 5122 SubExprs[1]->getIntegerConstantExpr(Context)) 5123 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5124 Diag(SubExprs[1]->getBeginLoc(), 5125 diag::warn_atomic_op_has_invalid_memory_order) 5126 << SubExprs[1]->getSourceRange(); 5127 } 5128 5129 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5130 auto *Scope = Args[Args.size() - 1]; 5131 if (Optional<llvm::APSInt> Result = 5132 Scope->getIntegerConstantExpr(Context)) { 5133 if (!ScopeModel->isValid(Result->getZExtValue())) 5134 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5135 << Scope->getSourceRange(); 5136 } 5137 SubExprs.push_back(Scope); 5138 } 5139 5140 AtomicExpr *AE = new (Context) 5141 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5142 5143 if ((Op == AtomicExpr::AO__c11_atomic_load || 5144 Op == AtomicExpr::AO__c11_atomic_store || 5145 Op == AtomicExpr::AO__opencl_atomic_load || 5146 Op == AtomicExpr::AO__opencl_atomic_store ) && 5147 Context.AtomicUsesUnsupportedLibcall(AE)) 5148 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5149 << ((Op == AtomicExpr::AO__c11_atomic_load || 5150 Op == AtomicExpr::AO__opencl_atomic_load) 5151 ? 0 5152 : 1); 5153 5154 if (ValType->isExtIntType()) { 5155 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5156 return ExprError(); 5157 } 5158 5159 return AE; 5160 } 5161 5162 /// checkBuiltinArgument - Given a call to a builtin function, perform 5163 /// normal type-checking on the given argument, updating the call in 5164 /// place. This is useful when a builtin function requires custom 5165 /// type-checking for some of its arguments but not necessarily all of 5166 /// them. 5167 /// 5168 /// Returns true on error. 5169 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5170 FunctionDecl *Fn = E->getDirectCallee(); 5171 assert(Fn && "builtin call without direct callee!"); 5172 5173 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5174 InitializedEntity Entity = 5175 InitializedEntity::InitializeParameter(S.Context, Param); 5176 5177 ExprResult Arg = E->getArg(0); 5178 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5179 if (Arg.isInvalid()) 5180 return true; 5181 5182 E->setArg(ArgIndex, Arg.get()); 5183 return false; 5184 } 5185 5186 /// We have a call to a function like __sync_fetch_and_add, which is an 5187 /// overloaded function based on the pointer type of its first argument. 5188 /// The main BuildCallExpr routines have already promoted the types of 5189 /// arguments because all of these calls are prototyped as void(...). 5190 /// 5191 /// This function goes through and does final semantic checking for these 5192 /// builtins, as well as generating any warnings. 5193 ExprResult 5194 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5195 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5196 Expr *Callee = TheCall->getCallee(); 5197 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5198 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5199 5200 // Ensure that we have at least one argument to do type inference from. 5201 if (TheCall->getNumArgs() < 1) { 5202 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5203 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5204 return ExprError(); 5205 } 5206 5207 // Inspect the first argument of the atomic builtin. This should always be 5208 // a pointer type, whose element is an integral scalar or pointer type. 5209 // Because it is a pointer type, we don't have to worry about any implicit 5210 // casts here. 5211 // FIXME: We don't allow floating point scalars as input. 5212 Expr *FirstArg = TheCall->getArg(0); 5213 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5214 if (FirstArgResult.isInvalid()) 5215 return ExprError(); 5216 FirstArg = FirstArgResult.get(); 5217 TheCall->setArg(0, FirstArg); 5218 5219 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5220 if (!pointerType) { 5221 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5222 << FirstArg->getType() << FirstArg->getSourceRange(); 5223 return ExprError(); 5224 } 5225 5226 QualType ValType = pointerType->getPointeeType(); 5227 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5228 !ValType->isBlockPointerType()) { 5229 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5230 << FirstArg->getType() << FirstArg->getSourceRange(); 5231 return ExprError(); 5232 } 5233 5234 if (ValType.isConstQualified()) { 5235 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5236 << FirstArg->getType() << FirstArg->getSourceRange(); 5237 return ExprError(); 5238 } 5239 5240 switch (ValType.getObjCLifetime()) { 5241 case Qualifiers::OCL_None: 5242 case Qualifiers::OCL_ExplicitNone: 5243 // okay 5244 break; 5245 5246 case Qualifiers::OCL_Weak: 5247 case Qualifiers::OCL_Strong: 5248 case Qualifiers::OCL_Autoreleasing: 5249 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5250 << ValType << FirstArg->getSourceRange(); 5251 return ExprError(); 5252 } 5253 5254 // Strip any qualifiers off ValType. 5255 ValType = ValType.getUnqualifiedType(); 5256 5257 // The majority of builtins return a value, but a few have special return 5258 // types, so allow them to override appropriately below. 5259 QualType ResultType = ValType; 5260 5261 // We need to figure out which concrete builtin this maps onto. For example, 5262 // __sync_fetch_and_add with a 2 byte object turns into 5263 // __sync_fetch_and_add_2. 5264 #define BUILTIN_ROW(x) \ 5265 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5266 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5267 5268 static const unsigned BuiltinIndices[][5] = { 5269 BUILTIN_ROW(__sync_fetch_and_add), 5270 BUILTIN_ROW(__sync_fetch_and_sub), 5271 BUILTIN_ROW(__sync_fetch_and_or), 5272 BUILTIN_ROW(__sync_fetch_and_and), 5273 BUILTIN_ROW(__sync_fetch_and_xor), 5274 BUILTIN_ROW(__sync_fetch_and_nand), 5275 5276 BUILTIN_ROW(__sync_add_and_fetch), 5277 BUILTIN_ROW(__sync_sub_and_fetch), 5278 BUILTIN_ROW(__sync_and_and_fetch), 5279 BUILTIN_ROW(__sync_or_and_fetch), 5280 BUILTIN_ROW(__sync_xor_and_fetch), 5281 BUILTIN_ROW(__sync_nand_and_fetch), 5282 5283 BUILTIN_ROW(__sync_val_compare_and_swap), 5284 BUILTIN_ROW(__sync_bool_compare_and_swap), 5285 BUILTIN_ROW(__sync_lock_test_and_set), 5286 BUILTIN_ROW(__sync_lock_release), 5287 BUILTIN_ROW(__sync_swap) 5288 }; 5289 #undef BUILTIN_ROW 5290 5291 // Determine the index of the size. 5292 unsigned SizeIndex; 5293 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5294 case 1: SizeIndex = 0; break; 5295 case 2: SizeIndex = 1; break; 5296 case 4: SizeIndex = 2; break; 5297 case 8: SizeIndex = 3; break; 5298 case 16: SizeIndex = 4; break; 5299 default: 5300 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5301 << FirstArg->getType() << FirstArg->getSourceRange(); 5302 return ExprError(); 5303 } 5304 5305 // Each of these builtins has one pointer argument, followed by some number of 5306 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5307 // that we ignore. Find out which row of BuiltinIndices to read from as well 5308 // as the number of fixed args. 5309 unsigned BuiltinID = FDecl->getBuiltinID(); 5310 unsigned BuiltinIndex, NumFixed = 1; 5311 bool WarnAboutSemanticsChange = false; 5312 switch (BuiltinID) { 5313 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5314 case Builtin::BI__sync_fetch_and_add: 5315 case Builtin::BI__sync_fetch_and_add_1: 5316 case Builtin::BI__sync_fetch_and_add_2: 5317 case Builtin::BI__sync_fetch_and_add_4: 5318 case Builtin::BI__sync_fetch_and_add_8: 5319 case Builtin::BI__sync_fetch_and_add_16: 5320 BuiltinIndex = 0; 5321 break; 5322 5323 case Builtin::BI__sync_fetch_and_sub: 5324 case Builtin::BI__sync_fetch_and_sub_1: 5325 case Builtin::BI__sync_fetch_and_sub_2: 5326 case Builtin::BI__sync_fetch_and_sub_4: 5327 case Builtin::BI__sync_fetch_and_sub_8: 5328 case Builtin::BI__sync_fetch_and_sub_16: 5329 BuiltinIndex = 1; 5330 break; 5331 5332 case Builtin::BI__sync_fetch_and_or: 5333 case Builtin::BI__sync_fetch_and_or_1: 5334 case Builtin::BI__sync_fetch_and_or_2: 5335 case Builtin::BI__sync_fetch_and_or_4: 5336 case Builtin::BI__sync_fetch_and_or_8: 5337 case Builtin::BI__sync_fetch_and_or_16: 5338 BuiltinIndex = 2; 5339 break; 5340 5341 case Builtin::BI__sync_fetch_and_and: 5342 case Builtin::BI__sync_fetch_and_and_1: 5343 case Builtin::BI__sync_fetch_and_and_2: 5344 case Builtin::BI__sync_fetch_and_and_4: 5345 case Builtin::BI__sync_fetch_and_and_8: 5346 case Builtin::BI__sync_fetch_and_and_16: 5347 BuiltinIndex = 3; 5348 break; 5349 5350 case Builtin::BI__sync_fetch_and_xor: 5351 case Builtin::BI__sync_fetch_and_xor_1: 5352 case Builtin::BI__sync_fetch_and_xor_2: 5353 case Builtin::BI__sync_fetch_and_xor_4: 5354 case Builtin::BI__sync_fetch_and_xor_8: 5355 case Builtin::BI__sync_fetch_and_xor_16: 5356 BuiltinIndex = 4; 5357 break; 5358 5359 case Builtin::BI__sync_fetch_and_nand: 5360 case Builtin::BI__sync_fetch_and_nand_1: 5361 case Builtin::BI__sync_fetch_and_nand_2: 5362 case Builtin::BI__sync_fetch_and_nand_4: 5363 case Builtin::BI__sync_fetch_and_nand_8: 5364 case Builtin::BI__sync_fetch_and_nand_16: 5365 BuiltinIndex = 5; 5366 WarnAboutSemanticsChange = true; 5367 break; 5368 5369 case Builtin::BI__sync_add_and_fetch: 5370 case Builtin::BI__sync_add_and_fetch_1: 5371 case Builtin::BI__sync_add_and_fetch_2: 5372 case Builtin::BI__sync_add_and_fetch_4: 5373 case Builtin::BI__sync_add_and_fetch_8: 5374 case Builtin::BI__sync_add_and_fetch_16: 5375 BuiltinIndex = 6; 5376 break; 5377 5378 case Builtin::BI__sync_sub_and_fetch: 5379 case Builtin::BI__sync_sub_and_fetch_1: 5380 case Builtin::BI__sync_sub_and_fetch_2: 5381 case Builtin::BI__sync_sub_and_fetch_4: 5382 case Builtin::BI__sync_sub_and_fetch_8: 5383 case Builtin::BI__sync_sub_and_fetch_16: 5384 BuiltinIndex = 7; 5385 break; 5386 5387 case Builtin::BI__sync_and_and_fetch: 5388 case Builtin::BI__sync_and_and_fetch_1: 5389 case Builtin::BI__sync_and_and_fetch_2: 5390 case Builtin::BI__sync_and_and_fetch_4: 5391 case Builtin::BI__sync_and_and_fetch_8: 5392 case Builtin::BI__sync_and_and_fetch_16: 5393 BuiltinIndex = 8; 5394 break; 5395 5396 case Builtin::BI__sync_or_and_fetch: 5397 case Builtin::BI__sync_or_and_fetch_1: 5398 case Builtin::BI__sync_or_and_fetch_2: 5399 case Builtin::BI__sync_or_and_fetch_4: 5400 case Builtin::BI__sync_or_and_fetch_8: 5401 case Builtin::BI__sync_or_and_fetch_16: 5402 BuiltinIndex = 9; 5403 break; 5404 5405 case Builtin::BI__sync_xor_and_fetch: 5406 case Builtin::BI__sync_xor_and_fetch_1: 5407 case Builtin::BI__sync_xor_and_fetch_2: 5408 case Builtin::BI__sync_xor_and_fetch_4: 5409 case Builtin::BI__sync_xor_and_fetch_8: 5410 case Builtin::BI__sync_xor_and_fetch_16: 5411 BuiltinIndex = 10; 5412 break; 5413 5414 case Builtin::BI__sync_nand_and_fetch: 5415 case Builtin::BI__sync_nand_and_fetch_1: 5416 case Builtin::BI__sync_nand_and_fetch_2: 5417 case Builtin::BI__sync_nand_and_fetch_4: 5418 case Builtin::BI__sync_nand_and_fetch_8: 5419 case Builtin::BI__sync_nand_and_fetch_16: 5420 BuiltinIndex = 11; 5421 WarnAboutSemanticsChange = true; 5422 break; 5423 5424 case Builtin::BI__sync_val_compare_and_swap: 5425 case Builtin::BI__sync_val_compare_and_swap_1: 5426 case Builtin::BI__sync_val_compare_and_swap_2: 5427 case Builtin::BI__sync_val_compare_and_swap_4: 5428 case Builtin::BI__sync_val_compare_and_swap_8: 5429 case Builtin::BI__sync_val_compare_and_swap_16: 5430 BuiltinIndex = 12; 5431 NumFixed = 2; 5432 break; 5433 5434 case Builtin::BI__sync_bool_compare_and_swap: 5435 case Builtin::BI__sync_bool_compare_and_swap_1: 5436 case Builtin::BI__sync_bool_compare_and_swap_2: 5437 case Builtin::BI__sync_bool_compare_and_swap_4: 5438 case Builtin::BI__sync_bool_compare_and_swap_8: 5439 case Builtin::BI__sync_bool_compare_and_swap_16: 5440 BuiltinIndex = 13; 5441 NumFixed = 2; 5442 ResultType = Context.BoolTy; 5443 break; 5444 5445 case Builtin::BI__sync_lock_test_and_set: 5446 case Builtin::BI__sync_lock_test_and_set_1: 5447 case Builtin::BI__sync_lock_test_and_set_2: 5448 case Builtin::BI__sync_lock_test_and_set_4: 5449 case Builtin::BI__sync_lock_test_and_set_8: 5450 case Builtin::BI__sync_lock_test_and_set_16: 5451 BuiltinIndex = 14; 5452 break; 5453 5454 case Builtin::BI__sync_lock_release: 5455 case Builtin::BI__sync_lock_release_1: 5456 case Builtin::BI__sync_lock_release_2: 5457 case Builtin::BI__sync_lock_release_4: 5458 case Builtin::BI__sync_lock_release_8: 5459 case Builtin::BI__sync_lock_release_16: 5460 BuiltinIndex = 15; 5461 NumFixed = 0; 5462 ResultType = Context.VoidTy; 5463 break; 5464 5465 case Builtin::BI__sync_swap: 5466 case Builtin::BI__sync_swap_1: 5467 case Builtin::BI__sync_swap_2: 5468 case Builtin::BI__sync_swap_4: 5469 case Builtin::BI__sync_swap_8: 5470 case Builtin::BI__sync_swap_16: 5471 BuiltinIndex = 16; 5472 break; 5473 } 5474 5475 // Now that we know how many fixed arguments we expect, first check that we 5476 // have at least that many. 5477 if (TheCall->getNumArgs() < 1+NumFixed) { 5478 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5479 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5480 << Callee->getSourceRange(); 5481 return ExprError(); 5482 } 5483 5484 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5485 << Callee->getSourceRange(); 5486 5487 if (WarnAboutSemanticsChange) { 5488 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5489 << Callee->getSourceRange(); 5490 } 5491 5492 // Get the decl for the concrete builtin from this, we can tell what the 5493 // concrete integer type we should convert to is. 5494 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5495 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5496 FunctionDecl *NewBuiltinDecl; 5497 if (NewBuiltinID == BuiltinID) 5498 NewBuiltinDecl = FDecl; 5499 else { 5500 // Perform builtin lookup to avoid redeclaring it. 5501 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5502 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5503 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5504 assert(Res.getFoundDecl()); 5505 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5506 if (!NewBuiltinDecl) 5507 return ExprError(); 5508 } 5509 5510 // The first argument --- the pointer --- has a fixed type; we 5511 // deduce the types of the rest of the arguments accordingly. Walk 5512 // the remaining arguments, converting them to the deduced value type. 5513 for (unsigned i = 0; i != NumFixed; ++i) { 5514 ExprResult Arg = TheCall->getArg(i+1); 5515 5516 // GCC does an implicit conversion to the pointer or integer ValType. This 5517 // can fail in some cases (1i -> int**), check for this error case now. 5518 // Initialize the argument. 5519 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5520 ValType, /*consume*/ false); 5521 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5522 if (Arg.isInvalid()) 5523 return ExprError(); 5524 5525 // Okay, we have something that *can* be converted to the right type. Check 5526 // to see if there is a potentially weird extension going on here. This can 5527 // happen when you do an atomic operation on something like an char* and 5528 // pass in 42. The 42 gets converted to char. This is even more strange 5529 // for things like 45.123 -> char, etc. 5530 // FIXME: Do this check. 5531 TheCall->setArg(i+1, Arg.get()); 5532 } 5533 5534 // Create a new DeclRefExpr to refer to the new decl. 5535 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5536 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5537 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5538 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5539 5540 // Set the callee in the CallExpr. 5541 // FIXME: This loses syntactic information. 5542 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5543 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5544 CK_BuiltinFnToFnPtr); 5545 TheCall->setCallee(PromotedCall.get()); 5546 5547 // Change the result type of the call to match the original value type. This 5548 // is arbitrary, but the codegen for these builtins ins design to handle it 5549 // gracefully. 5550 TheCall->setType(ResultType); 5551 5552 // Prohibit use of _ExtInt with atomic builtins. 5553 // The arguments would have already been converted to the first argument's 5554 // type, so only need to check the first argument. 5555 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5556 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5557 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5558 return ExprError(); 5559 } 5560 5561 return TheCallResult; 5562 } 5563 5564 /// SemaBuiltinNontemporalOverloaded - We have a call to 5565 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5566 /// overloaded function based on the pointer type of its last argument. 5567 /// 5568 /// This function goes through and does final semantic checking for these 5569 /// builtins. 5570 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5571 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5572 DeclRefExpr *DRE = 5573 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5574 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5575 unsigned BuiltinID = FDecl->getBuiltinID(); 5576 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5577 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5578 "Unexpected nontemporal load/store builtin!"); 5579 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5580 unsigned numArgs = isStore ? 2 : 1; 5581 5582 // Ensure that we have the proper number of arguments. 5583 if (checkArgCount(*this, TheCall, numArgs)) 5584 return ExprError(); 5585 5586 // Inspect the last argument of the nontemporal builtin. This should always 5587 // be a pointer type, from which we imply the type of the memory access. 5588 // Because it is a pointer type, we don't have to worry about any implicit 5589 // casts here. 5590 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5591 ExprResult PointerArgResult = 5592 DefaultFunctionArrayLvalueConversion(PointerArg); 5593 5594 if (PointerArgResult.isInvalid()) 5595 return ExprError(); 5596 PointerArg = PointerArgResult.get(); 5597 TheCall->setArg(numArgs - 1, PointerArg); 5598 5599 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5600 if (!pointerType) { 5601 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5602 << PointerArg->getType() << PointerArg->getSourceRange(); 5603 return ExprError(); 5604 } 5605 5606 QualType ValType = pointerType->getPointeeType(); 5607 5608 // Strip any qualifiers off ValType. 5609 ValType = ValType.getUnqualifiedType(); 5610 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5611 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5612 !ValType->isVectorType()) { 5613 Diag(DRE->getBeginLoc(), 5614 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5615 << PointerArg->getType() << PointerArg->getSourceRange(); 5616 return ExprError(); 5617 } 5618 5619 if (!isStore) { 5620 TheCall->setType(ValType); 5621 return TheCallResult; 5622 } 5623 5624 ExprResult ValArg = TheCall->getArg(0); 5625 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5626 Context, ValType, /*consume*/ false); 5627 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5628 if (ValArg.isInvalid()) 5629 return ExprError(); 5630 5631 TheCall->setArg(0, ValArg.get()); 5632 TheCall->setType(Context.VoidTy); 5633 return TheCallResult; 5634 } 5635 5636 /// CheckObjCString - Checks that the argument to the builtin 5637 /// CFString constructor is correct 5638 /// Note: It might also make sense to do the UTF-16 conversion here (would 5639 /// simplify the backend). 5640 bool Sema::CheckObjCString(Expr *Arg) { 5641 Arg = Arg->IgnoreParenCasts(); 5642 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5643 5644 if (!Literal || !Literal->isAscii()) { 5645 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5646 << Arg->getSourceRange(); 5647 return true; 5648 } 5649 5650 if (Literal->containsNonAsciiOrNull()) { 5651 StringRef String = Literal->getString(); 5652 unsigned NumBytes = String.size(); 5653 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5654 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5655 llvm::UTF16 *ToPtr = &ToBuf[0]; 5656 5657 llvm::ConversionResult Result = 5658 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5659 ToPtr + NumBytes, llvm::strictConversion); 5660 // Check for conversion failure. 5661 if (Result != llvm::conversionOK) 5662 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5663 << Arg->getSourceRange(); 5664 } 5665 return false; 5666 } 5667 5668 /// CheckObjCString - Checks that the format string argument to the os_log() 5669 /// and os_trace() functions is correct, and converts it to const char *. 5670 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5671 Arg = Arg->IgnoreParenCasts(); 5672 auto *Literal = dyn_cast<StringLiteral>(Arg); 5673 if (!Literal) { 5674 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5675 Literal = ObjcLiteral->getString(); 5676 } 5677 } 5678 5679 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5680 return ExprError( 5681 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5682 << Arg->getSourceRange()); 5683 } 5684 5685 ExprResult Result(Literal); 5686 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5687 InitializedEntity Entity = 5688 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5689 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5690 return Result; 5691 } 5692 5693 /// Check that the user is calling the appropriate va_start builtin for the 5694 /// target and calling convention. 5695 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5696 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5697 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5698 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5699 TT.getArch() == llvm::Triple::aarch64_32); 5700 bool IsWindows = TT.isOSWindows(); 5701 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5702 if (IsX64 || IsAArch64) { 5703 CallingConv CC = CC_C; 5704 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5705 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5706 if (IsMSVAStart) { 5707 // Don't allow this in System V ABI functions. 5708 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5709 return S.Diag(Fn->getBeginLoc(), 5710 diag::err_ms_va_start_used_in_sysv_function); 5711 } else { 5712 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5713 // On x64 Windows, don't allow this in System V ABI functions. 5714 // (Yes, that means there's no corresponding way to support variadic 5715 // System V ABI functions on Windows.) 5716 if ((IsWindows && CC == CC_X86_64SysV) || 5717 (!IsWindows && CC == CC_Win64)) 5718 return S.Diag(Fn->getBeginLoc(), 5719 diag::err_va_start_used_in_wrong_abi_function) 5720 << !IsWindows; 5721 } 5722 return false; 5723 } 5724 5725 if (IsMSVAStart) 5726 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5727 return false; 5728 } 5729 5730 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5731 ParmVarDecl **LastParam = nullptr) { 5732 // Determine whether the current function, block, or obj-c method is variadic 5733 // and get its parameter list. 5734 bool IsVariadic = false; 5735 ArrayRef<ParmVarDecl *> Params; 5736 DeclContext *Caller = S.CurContext; 5737 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5738 IsVariadic = Block->isVariadic(); 5739 Params = Block->parameters(); 5740 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5741 IsVariadic = FD->isVariadic(); 5742 Params = FD->parameters(); 5743 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5744 IsVariadic = MD->isVariadic(); 5745 // FIXME: This isn't correct for methods (results in bogus warning). 5746 Params = MD->parameters(); 5747 } else if (isa<CapturedDecl>(Caller)) { 5748 // We don't support va_start in a CapturedDecl. 5749 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5750 return true; 5751 } else { 5752 // This must be some other declcontext that parses exprs. 5753 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5754 return true; 5755 } 5756 5757 if (!IsVariadic) { 5758 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5759 return true; 5760 } 5761 5762 if (LastParam) 5763 *LastParam = Params.empty() ? nullptr : Params.back(); 5764 5765 return false; 5766 } 5767 5768 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5769 /// for validity. Emit an error and return true on failure; return false 5770 /// on success. 5771 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5772 Expr *Fn = TheCall->getCallee(); 5773 5774 if (checkVAStartABI(*this, BuiltinID, Fn)) 5775 return true; 5776 5777 if (checkArgCount(*this, TheCall, 2)) 5778 return true; 5779 5780 // Type-check the first argument normally. 5781 if (checkBuiltinArgument(*this, TheCall, 0)) 5782 return true; 5783 5784 // Check that the current function is variadic, and get its last parameter. 5785 ParmVarDecl *LastParam; 5786 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5787 return true; 5788 5789 // Verify that the second argument to the builtin is the last argument of the 5790 // current function or method. 5791 bool SecondArgIsLastNamedArgument = false; 5792 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5793 5794 // These are valid if SecondArgIsLastNamedArgument is false after the next 5795 // block. 5796 QualType Type; 5797 SourceLocation ParamLoc; 5798 bool IsCRegister = false; 5799 5800 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5801 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5802 SecondArgIsLastNamedArgument = PV == LastParam; 5803 5804 Type = PV->getType(); 5805 ParamLoc = PV->getLocation(); 5806 IsCRegister = 5807 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5808 } 5809 } 5810 5811 if (!SecondArgIsLastNamedArgument) 5812 Diag(TheCall->getArg(1)->getBeginLoc(), 5813 diag::warn_second_arg_of_va_start_not_last_named_param); 5814 else if (IsCRegister || Type->isReferenceType() || 5815 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5816 // Promotable integers are UB, but enumerations need a bit of 5817 // extra checking to see what their promotable type actually is. 5818 if (!Type->isPromotableIntegerType()) 5819 return false; 5820 if (!Type->isEnumeralType()) 5821 return true; 5822 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5823 return !(ED && 5824 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5825 }()) { 5826 unsigned Reason = 0; 5827 if (Type->isReferenceType()) Reason = 1; 5828 else if (IsCRegister) Reason = 2; 5829 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5830 Diag(ParamLoc, diag::note_parameter_type) << Type; 5831 } 5832 5833 TheCall->setType(Context.VoidTy); 5834 return false; 5835 } 5836 5837 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5838 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5839 // const char *named_addr); 5840 5841 Expr *Func = Call->getCallee(); 5842 5843 if (Call->getNumArgs() < 3) 5844 return Diag(Call->getEndLoc(), 5845 diag::err_typecheck_call_too_few_args_at_least) 5846 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5847 5848 // Type-check the first argument normally. 5849 if (checkBuiltinArgument(*this, Call, 0)) 5850 return true; 5851 5852 // Check that the current function is variadic. 5853 if (checkVAStartIsInVariadicFunction(*this, Func)) 5854 return true; 5855 5856 // __va_start on Windows does not validate the parameter qualifiers 5857 5858 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5859 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5860 5861 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5862 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5863 5864 const QualType &ConstCharPtrTy = 5865 Context.getPointerType(Context.CharTy.withConst()); 5866 if (!Arg1Ty->isPointerType() || 5867 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5868 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5869 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5870 << 0 /* qualifier difference */ 5871 << 3 /* parameter mismatch */ 5872 << 2 << Arg1->getType() << ConstCharPtrTy; 5873 5874 const QualType SizeTy = Context.getSizeType(); 5875 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5876 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5877 << Arg2->getType() << SizeTy << 1 /* different class */ 5878 << 0 /* qualifier difference */ 5879 << 3 /* parameter mismatch */ 5880 << 3 << Arg2->getType() << SizeTy; 5881 5882 return false; 5883 } 5884 5885 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5886 /// friends. This is declared to take (...), so we have to check everything. 5887 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5888 if (checkArgCount(*this, TheCall, 2)) 5889 return true; 5890 5891 ExprResult OrigArg0 = TheCall->getArg(0); 5892 ExprResult OrigArg1 = TheCall->getArg(1); 5893 5894 // Do standard promotions between the two arguments, returning their common 5895 // type. 5896 QualType Res = UsualArithmeticConversions( 5897 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5898 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5899 return true; 5900 5901 // Make sure any conversions are pushed back into the call; this is 5902 // type safe since unordered compare builtins are declared as "_Bool 5903 // foo(...)". 5904 TheCall->setArg(0, OrigArg0.get()); 5905 TheCall->setArg(1, OrigArg1.get()); 5906 5907 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5908 return false; 5909 5910 // If the common type isn't a real floating type, then the arguments were 5911 // invalid for this operation. 5912 if (Res.isNull() || !Res->isRealFloatingType()) 5913 return Diag(OrigArg0.get()->getBeginLoc(), 5914 diag::err_typecheck_call_invalid_ordered_compare) 5915 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5916 << SourceRange(OrigArg0.get()->getBeginLoc(), 5917 OrigArg1.get()->getEndLoc()); 5918 5919 return false; 5920 } 5921 5922 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5923 /// __builtin_isnan and friends. This is declared to take (...), so we have 5924 /// to check everything. We expect the last argument to be a floating point 5925 /// value. 5926 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5927 if (checkArgCount(*this, TheCall, NumArgs)) 5928 return true; 5929 5930 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5931 // on all preceding parameters just being int. Try all of those. 5932 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5933 Expr *Arg = TheCall->getArg(i); 5934 5935 if (Arg->isTypeDependent()) 5936 return false; 5937 5938 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5939 5940 if (Res.isInvalid()) 5941 return true; 5942 TheCall->setArg(i, Res.get()); 5943 } 5944 5945 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5946 5947 if (OrigArg->isTypeDependent()) 5948 return false; 5949 5950 // Usual Unary Conversions will convert half to float, which we want for 5951 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5952 // type how it is, but do normal L->Rvalue conversions. 5953 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5954 OrigArg = UsualUnaryConversions(OrigArg).get(); 5955 else 5956 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5957 TheCall->setArg(NumArgs - 1, OrigArg); 5958 5959 // This operation requires a non-_Complex floating-point number. 5960 if (!OrigArg->getType()->isRealFloatingType()) 5961 return Diag(OrigArg->getBeginLoc(), 5962 diag::err_typecheck_call_invalid_unary_fp) 5963 << OrigArg->getType() << OrigArg->getSourceRange(); 5964 5965 return false; 5966 } 5967 5968 /// Perform semantic analysis for a call to __builtin_complex. 5969 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5970 if (checkArgCount(*this, TheCall, 2)) 5971 return true; 5972 5973 bool Dependent = false; 5974 for (unsigned I = 0; I != 2; ++I) { 5975 Expr *Arg = TheCall->getArg(I); 5976 QualType T = Arg->getType(); 5977 if (T->isDependentType()) { 5978 Dependent = true; 5979 continue; 5980 } 5981 5982 // Despite supporting _Complex int, GCC requires a real floating point type 5983 // for the operands of __builtin_complex. 5984 if (!T->isRealFloatingType()) { 5985 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5986 << Arg->getType() << Arg->getSourceRange(); 5987 } 5988 5989 ExprResult Converted = DefaultLvalueConversion(Arg); 5990 if (Converted.isInvalid()) 5991 return true; 5992 TheCall->setArg(I, Converted.get()); 5993 } 5994 5995 if (Dependent) { 5996 TheCall->setType(Context.DependentTy); 5997 return false; 5998 } 5999 6000 Expr *Real = TheCall->getArg(0); 6001 Expr *Imag = TheCall->getArg(1); 6002 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6003 return Diag(Real->getBeginLoc(), 6004 diag::err_typecheck_call_different_arg_types) 6005 << Real->getType() << Imag->getType() 6006 << Real->getSourceRange() << Imag->getSourceRange(); 6007 } 6008 6009 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6010 // don't allow this builtin to form those types either. 6011 // FIXME: Should we allow these types? 6012 if (Real->getType()->isFloat16Type()) 6013 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6014 << "_Float16"; 6015 if (Real->getType()->isHalfType()) 6016 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6017 << "half"; 6018 6019 TheCall->setType(Context.getComplexType(Real->getType())); 6020 return false; 6021 } 6022 6023 // Customized Sema Checking for VSX builtins that have the following signature: 6024 // vector [...] builtinName(vector [...], vector [...], const int); 6025 // Which takes the same type of vectors (any legal vector type) for the first 6026 // two arguments and takes compile time constant for the third argument. 6027 // Example builtins are : 6028 // vector double vec_xxpermdi(vector double, vector double, int); 6029 // vector short vec_xxsldwi(vector short, vector short, int); 6030 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6031 unsigned ExpectedNumArgs = 3; 6032 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6033 return true; 6034 6035 // Check the third argument is a compile time constant 6036 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6037 return Diag(TheCall->getBeginLoc(), 6038 diag::err_vsx_builtin_nonconstant_argument) 6039 << 3 /* argument index */ << TheCall->getDirectCallee() 6040 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6041 TheCall->getArg(2)->getEndLoc()); 6042 6043 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6044 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6045 6046 // Check the type of argument 1 and argument 2 are vectors. 6047 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6048 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6049 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6050 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6051 << TheCall->getDirectCallee() 6052 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6053 TheCall->getArg(1)->getEndLoc()); 6054 } 6055 6056 // Check the first two arguments are the same type. 6057 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6058 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6059 << TheCall->getDirectCallee() 6060 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6061 TheCall->getArg(1)->getEndLoc()); 6062 } 6063 6064 // When default clang type checking is turned off and the customized type 6065 // checking is used, the returning type of the function must be explicitly 6066 // set. Otherwise it is _Bool by default. 6067 TheCall->setType(Arg1Ty); 6068 6069 return false; 6070 } 6071 6072 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6073 // This is declared to take (...), so we have to check everything. 6074 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6075 if (TheCall->getNumArgs() < 2) 6076 return ExprError(Diag(TheCall->getEndLoc(), 6077 diag::err_typecheck_call_too_few_args_at_least) 6078 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6079 << TheCall->getSourceRange()); 6080 6081 // Determine which of the following types of shufflevector we're checking: 6082 // 1) unary, vector mask: (lhs, mask) 6083 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6084 QualType resType = TheCall->getArg(0)->getType(); 6085 unsigned numElements = 0; 6086 6087 if (!TheCall->getArg(0)->isTypeDependent() && 6088 !TheCall->getArg(1)->isTypeDependent()) { 6089 QualType LHSType = TheCall->getArg(0)->getType(); 6090 QualType RHSType = TheCall->getArg(1)->getType(); 6091 6092 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6093 return ExprError( 6094 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6095 << TheCall->getDirectCallee() 6096 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6097 TheCall->getArg(1)->getEndLoc())); 6098 6099 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6100 unsigned numResElements = TheCall->getNumArgs() - 2; 6101 6102 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6103 // with mask. If so, verify that RHS is an integer vector type with the 6104 // same number of elts as lhs. 6105 if (TheCall->getNumArgs() == 2) { 6106 if (!RHSType->hasIntegerRepresentation() || 6107 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6108 return ExprError(Diag(TheCall->getBeginLoc(), 6109 diag::err_vec_builtin_incompatible_vector) 6110 << TheCall->getDirectCallee() 6111 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6112 TheCall->getArg(1)->getEndLoc())); 6113 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6114 return ExprError(Diag(TheCall->getBeginLoc(), 6115 diag::err_vec_builtin_incompatible_vector) 6116 << TheCall->getDirectCallee() 6117 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6118 TheCall->getArg(1)->getEndLoc())); 6119 } else if (numElements != numResElements) { 6120 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6121 resType = Context.getVectorType(eltType, numResElements, 6122 VectorType::GenericVector); 6123 } 6124 } 6125 6126 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6127 if (TheCall->getArg(i)->isTypeDependent() || 6128 TheCall->getArg(i)->isValueDependent()) 6129 continue; 6130 6131 Optional<llvm::APSInt> Result; 6132 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6133 return ExprError(Diag(TheCall->getBeginLoc(), 6134 diag::err_shufflevector_nonconstant_argument) 6135 << TheCall->getArg(i)->getSourceRange()); 6136 6137 // Allow -1 which will be translated to undef in the IR. 6138 if (Result->isSigned() && Result->isAllOnesValue()) 6139 continue; 6140 6141 if (Result->getActiveBits() > 64 || 6142 Result->getZExtValue() >= numElements * 2) 6143 return ExprError(Diag(TheCall->getBeginLoc(), 6144 diag::err_shufflevector_argument_too_large) 6145 << TheCall->getArg(i)->getSourceRange()); 6146 } 6147 6148 SmallVector<Expr*, 32> exprs; 6149 6150 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6151 exprs.push_back(TheCall->getArg(i)); 6152 TheCall->setArg(i, nullptr); 6153 } 6154 6155 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6156 TheCall->getCallee()->getBeginLoc(), 6157 TheCall->getRParenLoc()); 6158 } 6159 6160 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6161 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6162 SourceLocation BuiltinLoc, 6163 SourceLocation RParenLoc) { 6164 ExprValueKind VK = VK_RValue; 6165 ExprObjectKind OK = OK_Ordinary; 6166 QualType DstTy = TInfo->getType(); 6167 QualType SrcTy = E->getType(); 6168 6169 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6170 return ExprError(Diag(BuiltinLoc, 6171 diag::err_convertvector_non_vector) 6172 << E->getSourceRange()); 6173 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6174 return ExprError(Diag(BuiltinLoc, 6175 diag::err_convertvector_non_vector_type)); 6176 6177 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6178 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6179 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6180 if (SrcElts != DstElts) 6181 return ExprError(Diag(BuiltinLoc, 6182 diag::err_convertvector_incompatible_vector) 6183 << E->getSourceRange()); 6184 } 6185 6186 return new (Context) 6187 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6188 } 6189 6190 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6191 // This is declared to take (const void*, ...) and can take two 6192 // optional constant int args. 6193 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6194 unsigned NumArgs = TheCall->getNumArgs(); 6195 6196 if (NumArgs > 3) 6197 return Diag(TheCall->getEndLoc(), 6198 diag::err_typecheck_call_too_many_args_at_most) 6199 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6200 6201 // Argument 0 is checked for us and the remaining arguments must be 6202 // constant integers. 6203 for (unsigned i = 1; i != NumArgs; ++i) 6204 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6205 return true; 6206 6207 return false; 6208 } 6209 6210 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6211 // __assume does not evaluate its arguments, and should warn if its argument 6212 // has side effects. 6213 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6214 Expr *Arg = TheCall->getArg(0); 6215 if (Arg->isInstantiationDependent()) return false; 6216 6217 if (Arg->HasSideEffects(Context)) 6218 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6219 << Arg->getSourceRange() 6220 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6221 6222 return false; 6223 } 6224 6225 /// Handle __builtin_alloca_with_align. This is declared 6226 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6227 /// than 8. 6228 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6229 // The alignment must be a constant integer. 6230 Expr *Arg = TheCall->getArg(1); 6231 6232 // We can't check the value of a dependent argument. 6233 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6234 if (const auto *UE = 6235 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6236 if (UE->getKind() == UETT_AlignOf || 6237 UE->getKind() == UETT_PreferredAlignOf) 6238 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6239 << Arg->getSourceRange(); 6240 6241 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6242 6243 if (!Result.isPowerOf2()) 6244 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6245 << Arg->getSourceRange(); 6246 6247 if (Result < Context.getCharWidth()) 6248 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6249 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6250 6251 if (Result > std::numeric_limits<int32_t>::max()) 6252 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6253 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6254 } 6255 6256 return false; 6257 } 6258 6259 /// Handle __builtin_assume_aligned. This is declared 6260 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6261 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6262 unsigned NumArgs = TheCall->getNumArgs(); 6263 6264 if (NumArgs > 3) 6265 return Diag(TheCall->getEndLoc(), 6266 diag::err_typecheck_call_too_many_args_at_most) 6267 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6268 6269 // The alignment must be a constant integer. 6270 Expr *Arg = TheCall->getArg(1); 6271 6272 // We can't check the value of a dependent argument. 6273 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6274 llvm::APSInt Result; 6275 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6276 return true; 6277 6278 if (!Result.isPowerOf2()) 6279 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6280 << Arg->getSourceRange(); 6281 6282 if (Result > Sema::MaximumAlignment) 6283 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6284 << Arg->getSourceRange() << Sema::MaximumAlignment; 6285 } 6286 6287 if (NumArgs > 2) { 6288 ExprResult Arg(TheCall->getArg(2)); 6289 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6290 Context.getSizeType(), false); 6291 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6292 if (Arg.isInvalid()) return true; 6293 TheCall->setArg(2, Arg.get()); 6294 } 6295 6296 return false; 6297 } 6298 6299 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6300 unsigned BuiltinID = 6301 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6302 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6303 6304 unsigned NumArgs = TheCall->getNumArgs(); 6305 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6306 if (NumArgs < NumRequiredArgs) { 6307 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6308 << 0 /* function call */ << NumRequiredArgs << NumArgs 6309 << TheCall->getSourceRange(); 6310 } 6311 if (NumArgs >= NumRequiredArgs + 0x100) { 6312 return Diag(TheCall->getEndLoc(), 6313 diag::err_typecheck_call_too_many_args_at_most) 6314 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6315 << TheCall->getSourceRange(); 6316 } 6317 unsigned i = 0; 6318 6319 // For formatting call, check buffer arg. 6320 if (!IsSizeCall) { 6321 ExprResult Arg(TheCall->getArg(i)); 6322 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6323 Context, Context.VoidPtrTy, false); 6324 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6325 if (Arg.isInvalid()) 6326 return true; 6327 TheCall->setArg(i, Arg.get()); 6328 i++; 6329 } 6330 6331 // Check string literal arg. 6332 unsigned FormatIdx = i; 6333 { 6334 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6335 if (Arg.isInvalid()) 6336 return true; 6337 TheCall->setArg(i, Arg.get()); 6338 i++; 6339 } 6340 6341 // Make sure variadic args are scalar. 6342 unsigned FirstDataArg = i; 6343 while (i < NumArgs) { 6344 ExprResult Arg = DefaultVariadicArgumentPromotion( 6345 TheCall->getArg(i), VariadicFunction, nullptr); 6346 if (Arg.isInvalid()) 6347 return true; 6348 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6349 if (ArgSize.getQuantity() >= 0x100) { 6350 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6351 << i << (int)ArgSize.getQuantity() << 0xff 6352 << TheCall->getSourceRange(); 6353 } 6354 TheCall->setArg(i, Arg.get()); 6355 i++; 6356 } 6357 6358 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6359 // call to avoid duplicate diagnostics. 6360 if (!IsSizeCall) { 6361 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6362 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6363 bool Success = CheckFormatArguments( 6364 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6365 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6366 CheckedVarArgs); 6367 if (!Success) 6368 return true; 6369 } 6370 6371 if (IsSizeCall) { 6372 TheCall->setType(Context.getSizeType()); 6373 } else { 6374 TheCall->setType(Context.VoidPtrTy); 6375 } 6376 return false; 6377 } 6378 6379 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6380 /// TheCall is a constant expression. 6381 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6382 llvm::APSInt &Result) { 6383 Expr *Arg = TheCall->getArg(ArgNum); 6384 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6385 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6386 6387 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6388 6389 Optional<llvm::APSInt> R; 6390 if (!(R = Arg->getIntegerConstantExpr(Context))) 6391 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6392 << FDecl->getDeclName() << Arg->getSourceRange(); 6393 Result = *R; 6394 return false; 6395 } 6396 6397 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6398 /// TheCall is a constant expression in the range [Low, High]. 6399 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6400 int Low, int High, bool RangeIsError) { 6401 if (isConstantEvaluated()) 6402 return false; 6403 llvm::APSInt Result; 6404 6405 // We can't check the value of a dependent argument. 6406 Expr *Arg = TheCall->getArg(ArgNum); 6407 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6408 return false; 6409 6410 // Check constant-ness first. 6411 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6412 return true; 6413 6414 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6415 if (RangeIsError) 6416 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6417 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6418 else 6419 // Defer the warning until we know if the code will be emitted so that 6420 // dead code can ignore this. 6421 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6422 PDiag(diag::warn_argument_invalid_range) 6423 << Result.toString(10) << Low << High 6424 << Arg->getSourceRange()); 6425 } 6426 6427 return false; 6428 } 6429 6430 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6431 /// TheCall is a constant expression is a multiple of Num.. 6432 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6433 unsigned Num) { 6434 llvm::APSInt Result; 6435 6436 // We can't check the value of a dependent argument. 6437 Expr *Arg = TheCall->getArg(ArgNum); 6438 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6439 return false; 6440 6441 // Check constant-ness first. 6442 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6443 return true; 6444 6445 if (Result.getSExtValue() % Num != 0) 6446 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6447 << Num << Arg->getSourceRange(); 6448 6449 return false; 6450 } 6451 6452 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6453 /// constant expression representing a power of 2. 6454 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6455 llvm::APSInt Result; 6456 6457 // We can't check the value of a dependent argument. 6458 Expr *Arg = TheCall->getArg(ArgNum); 6459 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6460 return false; 6461 6462 // Check constant-ness first. 6463 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6464 return true; 6465 6466 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6467 // and only if x is a power of 2. 6468 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6469 return false; 6470 6471 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6472 << Arg->getSourceRange(); 6473 } 6474 6475 static bool IsShiftedByte(llvm::APSInt Value) { 6476 if (Value.isNegative()) 6477 return false; 6478 6479 // Check if it's a shifted byte, by shifting it down 6480 while (true) { 6481 // If the value fits in the bottom byte, the check passes. 6482 if (Value < 0x100) 6483 return true; 6484 6485 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6486 // fails. 6487 if ((Value & 0xFF) != 0) 6488 return false; 6489 6490 // If the bottom 8 bits are all 0, but something above that is nonzero, 6491 // then shifting the value right by 8 bits won't affect whether it's a 6492 // shifted byte or not. So do that, and go round again. 6493 Value >>= 8; 6494 } 6495 } 6496 6497 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6498 /// a constant expression representing an arbitrary byte value shifted left by 6499 /// a multiple of 8 bits. 6500 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6501 unsigned ArgBits) { 6502 llvm::APSInt Result; 6503 6504 // We can't check the value of a dependent argument. 6505 Expr *Arg = TheCall->getArg(ArgNum); 6506 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6507 return false; 6508 6509 // Check constant-ness first. 6510 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6511 return true; 6512 6513 // Truncate to the given size. 6514 Result = Result.getLoBits(ArgBits); 6515 Result.setIsUnsigned(true); 6516 6517 if (IsShiftedByte(Result)) 6518 return false; 6519 6520 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6521 << Arg->getSourceRange(); 6522 } 6523 6524 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6525 /// TheCall is a constant expression representing either a shifted byte value, 6526 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6527 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6528 /// Arm MVE intrinsics. 6529 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6530 int ArgNum, 6531 unsigned ArgBits) { 6532 llvm::APSInt Result; 6533 6534 // We can't check the value of a dependent argument. 6535 Expr *Arg = TheCall->getArg(ArgNum); 6536 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6537 return false; 6538 6539 // Check constant-ness first. 6540 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6541 return true; 6542 6543 // Truncate to the given size. 6544 Result = Result.getLoBits(ArgBits); 6545 Result.setIsUnsigned(true); 6546 6547 // Check to see if it's in either of the required forms. 6548 if (IsShiftedByte(Result) || 6549 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6550 return false; 6551 6552 return Diag(TheCall->getBeginLoc(), 6553 diag::err_argument_not_shifted_byte_or_xxff) 6554 << Arg->getSourceRange(); 6555 } 6556 6557 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6558 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6559 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6560 if (checkArgCount(*this, TheCall, 2)) 6561 return true; 6562 Expr *Arg0 = TheCall->getArg(0); 6563 Expr *Arg1 = TheCall->getArg(1); 6564 6565 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6566 if (FirstArg.isInvalid()) 6567 return true; 6568 QualType FirstArgType = FirstArg.get()->getType(); 6569 if (!FirstArgType->isAnyPointerType()) 6570 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6571 << "first" << FirstArgType << Arg0->getSourceRange(); 6572 TheCall->setArg(0, FirstArg.get()); 6573 6574 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6575 if (SecArg.isInvalid()) 6576 return true; 6577 QualType SecArgType = SecArg.get()->getType(); 6578 if (!SecArgType->isIntegerType()) 6579 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6580 << "second" << SecArgType << Arg1->getSourceRange(); 6581 6582 // Derive the return type from the pointer argument. 6583 TheCall->setType(FirstArgType); 6584 return false; 6585 } 6586 6587 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6588 if (checkArgCount(*this, TheCall, 2)) 6589 return true; 6590 6591 Expr *Arg0 = TheCall->getArg(0); 6592 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6593 if (FirstArg.isInvalid()) 6594 return true; 6595 QualType FirstArgType = FirstArg.get()->getType(); 6596 if (!FirstArgType->isAnyPointerType()) 6597 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6598 << "first" << FirstArgType << Arg0->getSourceRange(); 6599 TheCall->setArg(0, FirstArg.get()); 6600 6601 // Derive the return type from the pointer argument. 6602 TheCall->setType(FirstArgType); 6603 6604 // Second arg must be an constant in range [0,15] 6605 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6606 } 6607 6608 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6609 if (checkArgCount(*this, TheCall, 2)) 6610 return true; 6611 Expr *Arg0 = TheCall->getArg(0); 6612 Expr *Arg1 = TheCall->getArg(1); 6613 6614 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6615 if (FirstArg.isInvalid()) 6616 return true; 6617 QualType FirstArgType = FirstArg.get()->getType(); 6618 if (!FirstArgType->isAnyPointerType()) 6619 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6620 << "first" << FirstArgType << Arg0->getSourceRange(); 6621 6622 QualType SecArgType = Arg1->getType(); 6623 if (!SecArgType->isIntegerType()) 6624 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6625 << "second" << SecArgType << Arg1->getSourceRange(); 6626 TheCall->setType(Context.IntTy); 6627 return false; 6628 } 6629 6630 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6631 BuiltinID == AArch64::BI__builtin_arm_stg) { 6632 if (checkArgCount(*this, TheCall, 1)) 6633 return true; 6634 Expr *Arg0 = TheCall->getArg(0); 6635 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6636 if (FirstArg.isInvalid()) 6637 return true; 6638 6639 QualType FirstArgType = FirstArg.get()->getType(); 6640 if (!FirstArgType->isAnyPointerType()) 6641 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6642 << "first" << FirstArgType << Arg0->getSourceRange(); 6643 TheCall->setArg(0, FirstArg.get()); 6644 6645 // Derive the return type from the pointer argument. 6646 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6647 TheCall->setType(FirstArgType); 6648 return false; 6649 } 6650 6651 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6652 Expr *ArgA = TheCall->getArg(0); 6653 Expr *ArgB = TheCall->getArg(1); 6654 6655 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6656 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6657 6658 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6659 return true; 6660 6661 QualType ArgTypeA = ArgExprA.get()->getType(); 6662 QualType ArgTypeB = ArgExprB.get()->getType(); 6663 6664 auto isNull = [&] (Expr *E) -> bool { 6665 return E->isNullPointerConstant( 6666 Context, Expr::NPC_ValueDependentIsNotNull); }; 6667 6668 // argument should be either a pointer or null 6669 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6670 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6671 << "first" << ArgTypeA << ArgA->getSourceRange(); 6672 6673 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6674 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6675 << "second" << ArgTypeB << ArgB->getSourceRange(); 6676 6677 // Ensure Pointee types are compatible 6678 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6679 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6680 QualType pointeeA = ArgTypeA->getPointeeType(); 6681 QualType pointeeB = ArgTypeB->getPointeeType(); 6682 if (!Context.typesAreCompatible( 6683 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6684 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6685 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6686 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6687 << ArgB->getSourceRange(); 6688 } 6689 } 6690 6691 // at least one argument should be pointer type 6692 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6693 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6694 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6695 6696 if (isNull(ArgA)) // adopt type of the other pointer 6697 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6698 6699 if (isNull(ArgB)) 6700 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6701 6702 TheCall->setArg(0, ArgExprA.get()); 6703 TheCall->setArg(1, ArgExprB.get()); 6704 TheCall->setType(Context.LongLongTy); 6705 return false; 6706 } 6707 assert(false && "Unhandled ARM MTE intrinsic"); 6708 return true; 6709 } 6710 6711 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6712 /// TheCall is an ARM/AArch64 special register string literal. 6713 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6714 int ArgNum, unsigned ExpectedFieldNum, 6715 bool AllowName) { 6716 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6717 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6718 BuiltinID == ARM::BI__builtin_arm_rsr || 6719 BuiltinID == ARM::BI__builtin_arm_rsrp || 6720 BuiltinID == ARM::BI__builtin_arm_wsr || 6721 BuiltinID == ARM::BI__builtin_arm_wsrp; 6722 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6723 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6724 BuiltinID == AArch64::BI__builtin_arm_rsr || 6725 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6726 BuiltinID == AArch64::BI__builtin_arm_wsr || 6727 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6728 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6729 6730 // We can't check the value of a dependent argument. 6731 Expr *Arg = TheCall->getArg(ArgNum); 6732 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6733 return false; 6734 6735 // Check if the argument is a string literal. 6736 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6737 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6738 << Arg->getSourceRange(); 6739 6740 // Check the type of special register given. 6741 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6742 SmallVector<StringRef, 6> Fields; 6743 Reg.split(Fields, ":"); 6744 6745 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6746 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6747 << Arg->getSourceRange(); 6748 6749 // If the string is the name of a register then we cannot check that it is 6750 // valid here but if the string is of one the forms described in ACLE then we 6751 // can check that the supplied fields are integers and within the valid 6752 // ranges. 6753 if (Fields.size() > 1) { 6754 bool FiveFields = Fields.size() == 5; 6755 6756 bool ValidString = true; 6757 if (IsARMBuiltin) { 6758 ValidString &= Fields[0].startswith_lower("cp") || 6759 Fields[0].startswith_lower("p"); 6760 if (ValidString) 6761 Fields[0] = 6762 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6763 6764 ValidString &= Fields[2].startswith_lower("c"); 6765 if (ValidString) 6766 Fields[2] = Fields[2].drop_front(1); 6767 6768 if (FiveFields) { 6769 ValidString &= Fields[3].startswith_lower("c"); 6770 if (ValidString) 6771 Fields[3] = Fields[3].drop_front(1); 6772 } 6773 } 6774 6775 SmallVector<int, 5> Ranges; 6776 if (FiveFields) 6777 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6778 else 6779 Ranges.append({15, 7, 15}); 6780 6781 for (unsigned i=0; i<Fields.size(); ++i) { 6782 int IntField; 6783 ValidString &= !Fields[i].getAsInteger(10, IntField); 6784 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6785 } 6786 6787 if (!ValidString) 6788 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6789 << Arg->getSourceRange(); 6790 } else if (IsAArch64Builtin && Fields.size() == 1) { 6791 // If the register name is one of those that appear in the condition below 6792 // and the special register builtin being used is one of the write builtins, 6793 // then we require that the argument provided for writing to the register 6794 // is an integer constant expression. This is because it will be lowered to 6795 // an MSR (immediate) instruction, so we need to know the immediate at 6796 // compile time. 6797 if (TheCall->getNumArgs() != 2) 6798 return false; 6799 6800 std::string RegLower = Reg.lower(); 6801 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6802 RegLower != "pan" && RegLower != "uao") 6803 return false; 6804 6805 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6806 } 6807 6808 return false; 6809 } 6810 6811 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 6812 /// Emit an error and return true on failure; return false on success. 6813 /// TypeStr is a string containing the type descriptor of the value returned by 6814 /// the builtin and the descriptors of the expected type of the arguments. 6815 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 6816 6817 assert((TypeStr[0] != '\0') && 6818 "Invalid types in PPC MMA builtin declaration"); 6819 6820 unsigned Mask = 0; 6821 unsigned ArgNum = 0; 6822 6823 // The first type in TypeStr is the type of the value returned by the 6824 // builtin. So we first read that type and change the type of TheCall. 6825 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6826 TheCall->setType(type); 6827 6828 while (*TypeStr != '\0') { 6829 Mask = 0; 6830 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6831 if (ArgNum >= TheCall->getNumArgs()) { 6832 ArgNum++; 6833 break; 6834 } 6835 6836 Expr *Arg = TheCall->getArg(ArgNum); 6837 QualType ArgType = Arg->getType(); 6838 6839 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 6840 (!ExpectedType->isVoidPointerType() && 6841 ArgType.getCanonicalType() != ExpectedType)) 6842 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6843 << ArgType << ExpectedType << 1 << 0 << 0; 6844 6845 // If the value of the Mask is not 0, we have a constraint in the size of 6846 // the integer argument so here we ensure the argument is a constant that 6847 // is in the valid range. 6848 if (Mask != 0 && 6849 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 6850 return true; 6851 6852 ArgNum++; 6853 } 6854 6855 // In case we exited early from the previous loop, there are other types to 6856 // read from TypeStr. So we need to read them all to ensure we have the right 6857 // number of arguments in TheCall and if it is not the case, to display a 6858 // better error message. 6859 while (*TypeStr != '\0') { 6860 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6861 ArgNum++; 6862 } 6863 if (checkArgCount(*this, TheCall, ArgNum)) 6864 return true; 6865 6866 return false; 6867 } 6868 6869 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6870 /// This checks that the target supports __builtin_longjmp and 6871 /// that val is a constant 1. 6872 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6873 if (!Context.getTargetInfo().hasSjLjLowering()) 6874 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6875 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6876 6877 Expr *Arg = TheCall->getArg(1); 6878 llvm::APSInt Result; 6879 6880 // TODO: This is less than ideal. Overload this to take a value. 6881 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6882 return true; 6883 6884 if (Result != 1) 6885 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6886 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6887 6888 return false; 6889 } 6890 6891 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6892 /// This checks that the target supports __builtin_setjmp. 6893 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6894 if (!Context.getTargetInfo().hasSjLjLowering()) 6895 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6896 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6897 return false; 6898 } 6899 6900 namespace { 6901 6902 class UncoveredArgHandler { 6903 enum { Unknown = -1, AllCovered = -2 }; 6904 6905 signed FirstUncoveredArg = Unknown; 6906 SmallVector<const Expr *, 4> DiagnosticExprs; 6907 6908 public: 6909 UncoveredArgHandler() = default; 6910 6911 bool hasUncoveredArg() const { 6912 return (FirstUncoveredArg >= 0); 6913 } 6914 6915 unsigned getUncoveredArg() const { 6916 assert(hasUncoveredArg() && "no uncovered argument"); 6917 return FirstUncoveredArg; 6918 } 6919 6920 void setAllCovered() { 6921 // A string has been found with all arguments covered, so clear out 6922 // the diagnostics. 6923 DiagnosticExprs.clear(); 6924 FirstUncoveredArg = AllCovered; 6925 } 6926 6927 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6928 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6929 6930 // Don't update if a previous string covers all arguments. 6931 if (FirstUncoveredArg == AllCovered) 6932 return; 6933 6934 // UncoveredArgHandler tracks the highest uncovered argument index 6935 // and with it all the strings that match this index. 6936 if (NewFirstUncoveredArg == FirstUncoveredArg) 6937 DiagnosticExprs.push_back(StrExpr); 6938 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6939 DiagnosticExprs.clear(); 6940 DiagnosticExprs.push_back(StrExpr); 6941 FirstUncoveredArg = NewFirstUncoveredArg; 6942 } 6943 } 6944 6945 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6946 }; 6947 6948 enum StringLiteralCheckType { 6949 SLCT_NotALiteral, 6950 SLCT_UncheckedLiteral, 6951 SLCT_CheckedLiteral 6952 }; 6953 6954 } // namespace 6955 6956 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6957 BinaryOperatorKind BinOpKind, 6958 bool AddendIsRight) { 6959 unsigned BitWidth = Offset.getBitWidth(); 6960 unsigned AddendBitWidth = Addend.getBitWidth(); 6961 // There might be negative interim results. 6962 if (Addend.isUnsigned()) { 6963 Addend = Addend.zext(++AddendBitWidth); 6964 Addend.setIsSigned(true); 6965 } 6966 // Adjust the bit width of the APSInts. 6967 if (AddendBitWidth > BitWidth) { 6968 Offset = Offset.sext(AddendBitWidth); 6969 BitWidth = AddendBitWidth; 6970 } else if (BitWidth > AddendBitWidth) { 6971 Addend = Addend.sext(BitWidth); 6972 } 6973 6974 bool Ov = false; 6975 llvm::APSInt ResOffset = Offset; 6976 if (BinOpKind == BO_Add) 6977 ResOffset = Offset.sadd_ov(Addend, Ov); 6978 else { 6979 assert(AddendIsRight && BinOpKind == BO_Sub && 6980 "operator must be add or sub with addend on the right"); 6981 ResOffset = Offset.ssub_ov(Addend, Ov); 6982 } 6983 6984 // We add an offset to a pointer here so we should support an offset as big as 6985 // possible. 6986 if (Ov) { 6987 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6988 "index (intermediate) result too big"); 6989 Offset = Offset.sext(2 * BitWidth); 6990 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6991 return; 6992 } 6993 6994 Offset = ResOffset; 6995 } 6996 6997 namespace { 6998 6999 // This is a wrapper class around StringLiteral to support offsetted string 7000 // literals as format strings. It takes the offset into account when returning 7001 // the string and its length or the source locations to display notes correctly. 7002 class FormatStringLiteral { 7003 const StringLiteral *FExpr; 7004 int64_t Offset; 7005 7006 public: 7007 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7008 : FExpr(fexpr), Offset(Offset) {} 7009 7010 StringRef getString() const { 7011 return FExpr->getString().drop_front(Offset); 7012 } 7013 7014 unsigned getByteLength() const { 7015 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7016 } 7017 7018 unsigned getLength() const { return FExpr->getLength() - Offset; } 7019 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7020 7021 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7022 7023 QualType getType() const { return FExpr->getType(); } 7024 7025 bool isAscii() const { return FExpr->isAscii(); } 7026 bool isWide() const { return FExpr->isWide(); } 7027 bool isUTF8() const { return FExpr->isUTF8(); } 7028 bool isUTF16() const { return FExpr->isUTF16(); } 7029 bool isUTF32() const { return FExpr->isUTF32(); } 7030 bool isPascal() const { return FExpr->isPascal(); } 7031 7032 SourceLocation getLocationOfByte( 7033 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7034 const TargetInfo &Target, unsigned *StartToken = nullptr, 7035 unsigned *StartTokenByteOffset = nullptr) const { 7036 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7037 StartToken, StartTokenByteOffset); 7038 } 7039 7040 SourceLocation getBeginLoc() const LLVM_READONLY { 7041 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7042 } 7043 7044 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7045 }; 7046 7047 } // namespace 7048 7049 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7050 const Expr *OrigFormatExpr, 7051 ArrayRef<const Expr *> Args, 7052 bool HasVAListArg, unsigned format_idx, 7053 unsigned firstDataArg, 7054 Sema::FormatStringType Type, 7055 bool inFunctionCall, 7056 Sema::VariadicCallType CallType, 7057 llvm::SmallBitVector &CheckedVarArgs, 7058 UncoveredArgHandler &UncoveredArg, 7059 bool IgnoreStringsWithoutSpecifiers); 7060 7061 // Determine if an expression is a string literal or constant string. 7062 // If this function returns false on the arguments to a function expecting a 7063 // format string, we will usually need to emit a warning. 7064 // True string literals are then checked by CheckFormatString. 7065 static StringLiteralCheckType 7066 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7067 bool HasVAListArg, unsigned format_idx, 7068 unsigned firstDataArg, Sema::FormatStringType Type, 7069 Sema::VariadicCallType CallType, bool InFunctionCall, 7070 llvm::SmallBitVector &CheckedVarArgs, 7071 UncoveredArgHandler &UncoveredArg, 7072 llvm::APSInt Offset, 7073 bool IgnoreStringsWithoutSpecifiers = false) { 7074 if (S.isConstantEvaluated()) 7075 return SLCT_NotALiteral; 7076 tryAgain: 7077 assert(Offset.isSigned() && "invalid offset"); 7078 7079 if (E->isTypeDependent() || E->isValueDependent()) 7080 return SLCT_NotALiteral; 7081 7082 E = E->IgnoreParenCasts(); 7083 7084 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7085 // Technically -Wformat-nonliteral does not warn about this case. 7086 // The behavior of printf and friends in this case is implementation 7087 // dependent. Ideally if the format string cannot be null then 7088 // it should have a 'nonnull' attribute in the function prototype. 7089 return SLCT_UncheckedLiteral; 7090 7091 switch (E->getStmtClass()) { 7092 case Stmt::BinaryConditionalOperatorClass: 7093 case Stmt::ConditionalOperatorClass: { 7094 // The expression is a literal if both sub-expressions were, and it was 7095 // completely checked only if both sub-expressions were checked. 7096 const AbstractConditionalOperator *C = 7097 cast<AbstractConditionalOperator>(E); 7098 7099 // Determine whether it is necessary to check both sub-expressions, for 7100 // example, because the condition expression is a constant that can be 7101 // evaluated at compile time. 7102 bool CheckLeft = true, CheckRight = true; 7103 7104 bool Cond; 7105 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7106 S.isConstantEvaluated())) { 7107 if (Cond) 7108 CheckRight = false; 7109 else 7110 CheckLeft = false; 7111 } 7112 7113 // We need to maintain the offsets for the right and the left hand side 7114 // separately to check if every possible indexed expression is a valid 7115 // string literal. They might have different offsets for different string 7116 // literals in the end. 7117 StringLiteralCheckType Left; 7118 if (!CheckLeft) 7119 Left = SLCT_UncheckedLiteral; 7120 else { 7121 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7122 HasVAListArg, format_idx, firstDataArg, 7123 Type, CallType, InFunctionCall, 7124 CheckedVarArgs, UncoveredArg, Offset, 7125 IgnoreStringsWithoutSpecifiers); 7126 if (Left == SLCT_NotALiteral || !CheckRight) { 7127 return Left; 7128 } 7129 } 7130 7131 StringLiteralCheckType Right = checkFormatStringExpr( 7132 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7133 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7134 IgnoreStringsWithoutSpecifiers); 7135 7136 return (CheckLeft && Left < Right) ? Left : Right; 7137 } 7138 7139 case Stmt::ImplicitCastExprClass: 7140 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7141 goto tryAgain; 7142 7143 case Stmt::OpaqueValueExprClass: 7144 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7145 E = src; 7146 goto tryAgain; 7147 } 7148 return SLCT_NotALiteral; 7149 7150 case Stmt::PredefinedExprClass: 7151 // While __func__, etc., are technically not string literals, they 7152 // cannot contain format specifiers and thus are not a security 7153 // liability. 7154 return SLCT_UncheckedLiteral; 7155 7156 case Stmt::DeclRefExprClass: { 7157 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7158 7159 // As an exception, do not flag errors for variables binding to 7160 // const string literals. 7161 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7162 bool isConstant = false; 7163 QualType T = DR->getType(); 7164 7165 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7166 isConstant = AT->getElementType().isConstant(S.Context); 7167 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7168 isConstant = T.isConstant(S.Context) && 7169 PT->getPointeeType().isConstant(S.Context); 7170 } else if (T->isObjCObjectPointerType()) { 7171 // In ObjC, there is usually no "const ObjectPointer" type, 7172 // so don't check if the pointee type is constant. 7173 isConstant = T.isConstant(S.Context); 7174 } 7175 7176 if (isConstant) { 7177 if (const Expr *Init = VD->getAnyInitializer()) { 7178 // Look through initializers like const char c[] = { "foo" } 7179 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7180 if (InitList->isStringLiteralInit()) 7181 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7182 } 7183 return checkFormatStringExpr(S, Init, Args, 7184 HasVAListArg, format_idx, 7185 firstDataArg, Type, CallType, 7186 /*InFunctionCall*/ false, CheckedVarArgs, 7187 UncoveredArg, Offset); 7188 } 7189 } 7190 7191 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7192 // special check to see if the format string is a function parameter 7193 // of the function calling the printf function. If the function 7194 // has an attribute indicating it is a printf-like function, then we 7195 // should suppress warnings concerning non-literals being used in a call 7196 // to a vprintf function. For example: 7197 // 7198 // void 7199 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7200 // va_list ap; 7201 // va_start(ap, fmt); 7202 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7203 // ... 7204 // } 7205 if (HasVAListArg) { 7206 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7207 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7208 int PVIndex = PV->getFunctionScopeIndex() + 1; 7209 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7210 // adjust for implicit parameter 7211 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7212 if (MD->isInstance()) 7213 ++PVIndex; 7214 // We also check if the formats are compatible. 7215 // We can't pass a 'scanf' string to a 'printf' function. 7216 if (PVIndex == PVFormat->getFormatIdx() && 7217 Type == S.GetFormatStringType(PVFormat)) 7218 return SLCT_UncheckedLiteral; 7219 } 7220 } 7221 } 7222 } 7223 } 7224 7225 return SLCT_NotALiteral; 7226 } 7227 7228 case Stmt::CallExprClass: 7229 case Stmt::CXXMemberCallExprClass: { 7230 const CallExpr *CE = cast<CallExpr>(E); 7231 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7232 bool IsFirst = true; 7233 StringLiteralCheckType CommonResult; 7234 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7235 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7236 StringLiteralCheckType Result = checkFormatStringExpr( 7237 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7238 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7239 IgnoreStringsWithoutSpecifiers); 7240 if (IsFirst) { 7241 CommonResult = Result; 7242 IsFirst = false; 7243 } 7244 } 7245 if (!IsFirst) 7246 return CommonResult; 7247 7248 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7249 unsigned BuiltinID = FD->getBuiltinID(); 7250 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7251 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7252 const Expr *Arg = CE->getArg(0); 7253 return checkFormatStringExpr(S, Arg, Args, 7254 HasVAListArg, format_idx, 7255 firstDataArg, Type, CallType, 7256 InFunctionCall, CheckedVarArgs, 7257 UncoveredArg, Offset, 7258 IgnoreStringsWithoutSpecifiers); 7259 } 7260 } 7261 } 7262 7263 return SLCT_NotALiteral; 7264 } 7265 case Stmt::ObjCMessageExprClass: { 7266 const auto *ME = cast<ObjCMessageExpr>(E); 7267 if (const auto *MD = ME->getMethodDecl()) { 7268 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7269 // As a special case heuristic, if we're using the method -[NSBundle 7270 // localizedStringForKey:value:table:], ignore any key strings that lack 7271 // format specifiers. The idea is that if the key doesn't have any 7272 // format specifiers then its probably just a key to map to the 7273 // localized strings. If it does have format specifiers though, then its 7274 // likely that the text of the key is the format string in the 7275 // programmer's language, and should be checked. 7276 const ObjCInterfaceDecl *IFace; 7277 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7278 IFace->getIdentifier()->isStr("NSBundle") && 7279 MD->getSelector().isKeywordSelector( 7280 {"localizedStringForKey", "value", "table"})) { 7281 IgnoreStringsWithoutSpecifiers = true; 7282 } 7283 7284 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7285 return checkFormatStringExpr( 7286 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7287 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7288 IgnoreStringsWithoutSpecifiers); 7289 } 7290 } 7291 7292 return SLCT_NotALiteral; 7293 } 7294 case Stmt::ObjCStringLiteralClass: 7295 case Stmt::StringLiteralClass: { 7296 const StringLiteral *StrE = nullptr; 7297 7298 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7299 StrE = ObjCFExpr->getString(); 7300 else 7301 StrE = cast<StringLiteral>(E); 7302 7303 if (StrE) { 7304 if (Offset.isNegative() || Offset > StrE->getLength()) { 7305 // TODO: It would be better to have an explicit warning for out of 7306 // bounds literals. 7307 return SLCT_NotALiteral; 7308 } 7309 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7310 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7311 firstDataArg, Type, InFunctionCall, CallType, 7312 CheckedVarArgs, UncoveredArg, 7313 IgnoreStringsWithoutSpecifiers); 7314 return SLCT_CheckedLiteral; 7315 } 7316 7317 return SLCT_NotALiteral; 7318 } 7319 case Stmt::BinaryOperatorClass: { 7320 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7321 7322 // A string literal + an int offset is still a string literal. 7323 if (BinOp->isAdditiveOp()) { 7324 Expr::EvalResult LResult, RResult; 7325 7326 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7327 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7328 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7329 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7330 7331 if (LIsInt != RIsInt) { 7332 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7333 7334 if (LIsInt) { 7335 if (BinOpKind == BO_Add) { 7336 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7337 E = BinOp->getRHS(); 7338 goto tryAgain; 7339 } 7340 } else { 7341 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7342 E = BinOp->getLHS(); 7343 goto tryAgain; 7344 } 7345 } 7346 } 7347 7348 return SLCT_NotALiteral; 7349 } 7350 case Stmt::UnaryOperatorClass: { 7351 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7352 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7353 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7354 Expr::EvalResult IndexResult; 7355 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7356 Expr::SE_NoSideEffects, 7357 S.isConstantEvaluated())) { 7358 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7359 /*RHS is int*/ true); 7360 E = ASE->getBase(); 7361 goto tryAgain; 7362 } 7363 } 7364 7365 return SLCT_NotALiteral; 7366 } 7367 7368 default: 7369 return SLCT_NotALiteral; 7370 } 7371 } 7372 7373 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7374 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7375 .Case("scanf", FST_Scanf) 7376 .Cases("printf", "printf0", FST_Printf) 7377 .Cases("NSString", "CFString", FST_NSString) 7378 .Case("strftime", FST_Strftime) 7379 .Case("strfmon", FST_Strfmon) 7380 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7381 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7382 .Case("os_trace", FST_OSLog) 7383 .Case("os_log", FST_OSLog) 7384 .Default(FST_Unknown); 7385 } 7386 7387 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7388 /// functions) for correct use of format strings. 7389 /// Returns true if a format string has been fully checked. 7390 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7391 ArrayRef<const Expr *> Args, 7392 bool IsCXXMember, 7393 VariadicCallType CallType, 7394 SourceLocation Loc, SourceRange Range, 7395 llvm::SmallBitVector &CheckedVarArgs) { 7396 FormatStringInfo FSI; 7397 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7398 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7399 FSI.FirstDataArg, GetFormatStringType(Format), 7400 CallType, Loc, Range, CheckedVarArgs); 7401 return false; 7402 } 7403 7404 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7405 bool HasVAListArg, unsigned format_idx, 7406 unsigned firstDataArg, FormatStringType Type, 7407 VariadicCallType CallType, 7408 SourceLocation Loc, SourceRange Range, 7409 llvm::SmallBitVector &CheckedVarArgs) { 7410 // CHECK: printf/scanf-like function is called with no format string. 7411 if (format_idx >= Args.size()) { 7412 Diag(Loc, diag::warn_missing_format_string) << Range; 7413 return false; 7414 } 7415 7416 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7417 7418 // CHECK: format string is not a string literal. 7419 // 7420 // Dynamically generated format strings are difficult to 7421 // automatically vet at compile time. Requiring that format strings 7422 // are string literals: (1) permits the checking of format strings by 7423 // the compiler and thereby (2) can practically remove the source of 7424 // many format string exploits. 7425 7426 // Format string can be either ObjC string (e.g. @"%d") or 7427 // C string (e.g. "%d") 7428 // ObjC string uses the same format specifiers as C string, so we can use 7429 // the same format string checking logic for both ObjC and C strings. 7430 UncoveredArgHandler UncoveredArg; 7431 StringLiteralCheckType CT = 7432 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7433 format_idx, firstDataArg, Type, CallType, 7434 /*IsFunctionCall*/ true, CheckedVarArgs, 7435 UncoveredArg, 7436 /*no string offset*/ llvm::APSInt(64, false) = 0); 7437 7438 // Generate a diagnostic where an uncovered argument is detected. 7439 if (UncoveredArg.hasUncoveredArg()) { 7440 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7441 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7442 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7443 } 7444 7445 if (CT != SLCT_NotALiteral) 7446 // Literal format string found, check done! 7447 return CT == SLCT_CheckedLiteral; 7448 7449 // Strftime is particular as it always uses a single 'time' argument, 7450 // so it is safe to pass a non-literal string. 7451 if (Type == FST_Strftime) 7452 return false; 7453 7454 // Do not emit diag when the string param is a macro expansion and the 7455 // format is either NSString or CFString. This is a hack to prevent 7456 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7457 // which are usually used in place of NS and CF string literals. 7458 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7459 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7460 return false; 7461 7462 // If there are no arguments specified, warn with -Wformat-security, otherwise 7463 // warn only with -Wformat-nonliteral. 7464 if (Args.size() == firstDataArg) { 7465 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7466 << OrigFormatExpr->getSourceRange(); 7467 switch (Type) { 7468 default: 7469 break; 7470 case FST_Kprintf: 7471 case FST_FreeBSDKPrintf: 7472 case FST_Printf: 7473 Diag(FormatLoc, diag::note_format_security_fixit) 7474 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7475 break; 7476 case FST_NSString: 7477 Diag(FormatLoc, diag::note_format_security_fixit) 7478 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7479 break; 7480 } 7481 } else { 7482 Diag(FormatLoc, diag::warn_format_nonliteral) 7483 << OrigFormatExpr->getSourceRange(); 7484 } 7485 return false; 7486 } 7487 7488 namespace { 7489 7490 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7491 protected: 7492 Sema &S; 7493 const FormatStringLiteral *FExpr; 7494 const Expr *OrigFormatExpr; 7495 const Sema::FormatStringType FSType; 7496 const unsigned FirstDataArg; 7497 const unsigned NumDataArgs; 7498 const char *Beg; // Start of format string. 7499 const bool HasVAListArg; 7500 ArrayRef<const Expr *> Args; 7501 unsigned FormatIdx; 7502 llvm::SmallBitVector CoveredArgs; 7503 bool usesPositionalArgs = false; 7504 bool atFirstArg = true; 7505 bool inFunctionCall; 7506 Sema::VariadicCallType CallType; 7507 llvm::SmallBitVector &CheckedVarArgs; 7508 UncoveredArgHandler &UncoveredArg; 7509 7510 public: 7511 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7512 const Expr *origFormatExpr, 7513 const Sema::FormatStringType type, unsigned firstDataArg, 7514 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7515 ArrayRef<const Expr *> Args, unsigned formatIdx, 7516 bool inFunctionCall, Sema::VariadicCallType callType, 7517 llvm::SmallBitVector &CheckedVarArgs, 7518 UncoveredArgHandler &UncoveredArg) 7519 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7520 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7521 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7522 inFunctionCall(inFunctionCall), CallType(callType), 7523 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7524 CoveredArgs.resize(numDataArgs); 7525 CoveredArgs.reset(); 7526 } 7527 7528 void DoneProcessing(); 7529 7530 void HandleIncompleteSpecifier(const char *startSpecifier, 7531 unsigned specifierLen) override; 7532 7533 void HandleInvalidLengthModifier( 7534 const analyze_format_string::FormatSpecifier &FS, 7535 const analyze_format_string::ConversionSpecifier &CS, 7536 const char *startSpecifier, unsigned specifierLen, 7537 unsigned DiagID); 7538 7539 void HandleNonStandardLengthModifier( 7540 const analyze_format_string::FormatSpecifier &FS, 7541 const char *startSpecifier, unsigned specifierLen); 7542 7543 void HandleNonStandardConversionSpecifier( 7544 const analyze_format_string::ConversionSpecifier &CS, 7545 const char *startSpecifier, unsigned specifierLen); 7546 7547 void HandlePosition(const char *startPos, unsigned posLen) override; 7548 7549 void HandleInvalidPosition(const char *startSpecifier, 7550 unsigned specifierLen, 7551 analyze_format_string::PositionContext p) override; 7552 7553 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7554 7555 void HandleNullChar(const char *nullCharacter) override; 7556 7557 template <typename Range> 7558 static void 7559 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7560 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7561 bool IsStringLocation, Range StringRange, 7562 ArrayRef<FixItHint> Fixit = None); 7563 7564 protected: 7565 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7566 const char *startSpec, 7567 unsigned specifierLen, 7568 const char *csStart, unsigned csLen); 7569 7570 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7571 const char *startSpec, 7572 unsigned specifierLen); 7573 7574 SourceRange getFormatStringRange(); 7575 CharSourceRange getSpecifierRange(const char *startSpecifier, 7576 unsigned specifierLen); 7577 SourceLocation getLocationOfByte(const char *x); 7578 7579 const Expr *getDataArg(unsigned i) const; 7580 7581 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7582 const analyze_format_string::ConversionSpecifier &CS, 7583 const char *startSpecifier, unsigned specifierLen, 7584 unsigned argIndex); 7585 7586 template <typename Range> 7587 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7588 bool IsStringLocation, Range StringRange, 7589 ArrayRef<FixItHint> Fixit = None); 7590 }; 7591 7592 } // namespace 7593 7594 SourceRange CheckFormatHandler::getFormatStringRange() { 7595 return OrigFormatExpr->getSourceRange(); 7596 } 7597 7598 CharSourceRange CheckFormatHandler:: 7599 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7600 SourceLocation Start = getLocationOfByte(startSpecifier); 7601 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7602 7603 // Advance the end SourceLocation by one due to half-open ranges. 7604 End = End.getLocWithOffset(1); 7605 7606 return CharSourceRange::getCharRange(Start, End); 7607 } 7608 7609 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7610 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7611 S.getLangOpts(), S.Context.getTargetInfo()); 7612 } 7613 7614 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7615 unsigned specifierLen){ 7616 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7617 getLocationOfByte(startSpecifier), 7618 /*IsStringLocation*/true, 7619 getSpecifierRange(startSpecifier, specifierLen)); 7620 } 7621 7622 void CheckFormatHandler::HandleInvalidLengthModifier( 7623 const analyze_format_string::FormatSpecifier &FS, 7624 const analyze_format_string::ConversionSpecifier &CS, 7625 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7626 using namespace analyze_format_string; 7627 7628 const LengthModifier &LM = FS.getLengthModifier(); 7629 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7630 7631 // See if we know how to fix this length modifier. 7632 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7633 if (FixedLM) { 7634 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7635 getLocationOfByte(LM.getStart()), 7636 /*IsStringLocation*/true, 7637 getSpecifierRange(startSpecifier, specifierLen)); 7638 7639 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7640 << FixedLM->toString() 7641 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7642 7643 } else { 7644 FixItHint Hint; 7645 if (DiagID == diag::warn_format_nonsensical_length) 7646 Hint = FixItHint::CreateRemoval(LMRange); 7647 7648 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7649 getLocationOfByte(LM.getStart()), 7650 /*IsStringLocation*/true, 7651 getSpecifierRange(startSpecifier, specifierLen), 7652 Hint); 7653 } 7654 } 7655 7656 void CheckFormatHandler::HandleNonStandardLengthModifier( 7657 const analyze_format_string::FormatSpecifier &FS, 7658 const char *startSpecifier, unsigned specifierLen) { 7659 using namespace analyze_format_string; 7660 7661 const LengthModifier &LM = FS.getLengthModifier(); 7662 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7663 7664 // See if we know how to fix this length modifier. 7665 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7666 if (FixedLM) { 7667 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7668 << LM.toString() << 0, 7669 getLocationOfByte(LM.getStart()), 7670 /*IsStringLocation*/true, 7671 getSpecifierRange(startSpecifier, specifierLen)); 7672 7673 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7674 << FixedLM->toString() 7675 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7676 7677 } else { 7678 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7679 << LM.toString() << 0, 7680 getLocationOfByte(LM.getStart()), 7681 /*IsStringLocation*/true, 7682 getSpecifierRange(startSpecifier, specifierLen)); 7683 } 7684 } 7685 7686 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7687 const analyze_format_string::ConversionSpecifier &CS, 7688 const char *startSpecifier, unsigned specifierLen) { 7689 using namespace analyze_format_string; 7690 7691 // See if we know how to fix this conversion specifier. 7692 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7693 if (FixedCS) { 7694 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7695 << CS.toString() << /*conversion specifier*/1, 7696 getLocationOfByte(CS.getStart()), 7697 /*IsStringLocation*/true, 7698 getSpecifierRange(startSpecifier, specifierLen)); 7699 7700 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7701 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7702 << FixedCS->toString() 7703 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7704 } else { 7705 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7706 << CS.toString() << /*conversion specifier*/1, 7707 getLocationOfByte(CS.getStart()), 7708 /*IsStringLocation*/true, 7709 getSpecifierRange(startSpecifier, specifierLen)); 7710 } 7711 } 7712 7713 void CheckFormatHandler::HandlePosition(const char *startPos, 7714 unsigned posLen) { 7715 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7716 getLocationOfByte(startPos), 7717 /*IsStringLocation*/true, 7718 getSpecifierRange(startPos, posLen)); 7719 } 7720 7721 void 7722 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7723 analyze_format_string::PositionContext p) { 7724 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7725 << (unsigned) p, 7726 getLocationOfByte(startPos), /*IsStringLocation*/true, 7727 getSpecifierRange(startPos, posLen)); 7728 } 7729 7730 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7731 unsigned posLen) { 7732 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7733 getLocationOfByte(startPos), 7734 /*IsStringLocation*/true, 7735 getSpecifierRange(startPos, posLen)); 7736 } 7737 7738 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7739 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7740 // The presence of a null character is likely an error. 7741 EmitFormatDiagnostic( 7742 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7743 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7744 getFormatStringRange()); 7745 } 7746 } 7747 7748 // Note that this may return NULL if there was an error parsing or building 7749 // one of the argument expressions. 7750 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7751 return Args[FirstDataArg + i]; 7752 } 7753 7754 void CheckFormatHandler::DoneProcessing() { 7755 // Does the number of data arguments exceed the number of 7756 // format conversions in the format string? 7757 if (!HasVAListArg) { 7758 // Find any arguments that weren't covered. 7759 CoveredArgs.flip(); 7760 signed notCoveredArg = CoveredArgs.find_first(); 7761 if (notCoveredArg >= 0) { 7762 assert((unsigned)notCoveredArg < NumDataArgs); 7763 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7764 } else { 7765 UncoveredArg.setAllCovered(); 7766 } 7767 } 7768 } 7769 7770 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7771 const Expr *ArgExpr) { 7772 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7773 "Invalid state"); 7774 7775 if (!ArgExpr) 7776 return; 7777 7778 SourceLocation Loc = ArgExpr->getBeginLoc(); 7779 7780 if (S.getSourceManager().isInSystemMacro(Loc)) 7781 return; 7782 7783 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7784 for (auto E : DiagnosticExprs) 7785 PDiag << E->getSourceRange(); 7786 7787 CheckFormatHandler::EmitFormatDiagnostic( 7788 S, IsFunctionCall, DiagnosticExprs[0], 7789 PDiag, Loc, /*IsStringLocation*/false, 7790 DiagnosticExprs[0]->getSourceRange()); 7791 } 7792 7793 bool 7794 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7795 SourceLocation Loc, 7796 const char *startSpec, 7797 unsigned specifierLen, 7798 const char *csStart, 7799 unsigned csLen) { 7800 bool keepGoing = true; 7801 if (argIndex < NumDataArgs) { 7802 // Consider the argument coverered, even though the specifier doesn't 7803 // make sense. 7804 CoveredArgs.set(argIndex); 7805 } 7806 else { 7807 // If argIndex exceeds the number of data arguments we 7808 // don't issue a warning because that is just a cascade of warnings (and 7809 // they may have intended '%%' anyway). We don't want to continue processing 7810 // the format string after this point, however, as we will like just get 7811 // gibberish when trying to match arguments. 7812 keepGoing = false; 7813 } 7814 7815 StringRef Specifier(csStart, csLen); 7816 7817 // If the specifier in non-printable, it could be the first byte of a UTF-8 7818 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7819 // hex value. 7820 std::string CodePointStr; 7821 if (!llvm::sys::locale::isPrint(*csStart)) { 7822 llvm::UTF32 CodePoint; 7823 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7824 const llvm::UTF8 *E = 7825 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7826 llvm::ConversionResult Result = 7827 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7828 7829 if (Result != llvm::conversionOK) { 7830 unsigned char FirstChar = *csStart; 7831 CodePoint = (llvm::UTF32)FirstChar; 7832 } 7833 7834 llvm::raw_string_ostream OS(CodePointStr); 7835 if (CodePoint < 256) 7836 OS << "\\x" << llvm::format("%02x", CodePoint); 7837 else if (CodePoint <= 0xFFFF) 7838 OS << "\\u" << llvm::format("%04x", CodePoint); 7839 else 7840 OS << "\\U" << llvm::format("%08x", CodePoint); 7841 OS.flush(); 7842 Specifier = CodePointStr; 7843 } 7844 7845 EmitFormatDiagnostic( 7846 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7847 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7848 7849 return keepGoing; 7850 } 7851 7852 void 7853 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7854 const char *startSpec, 7855 unsigned specifierLen) { 7856 EmitFormatDiagnostic( 7857 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7858 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7859 } 7860 7861 bool 7862 CheckFormatHandler::CheckNumArgs( 7863 const analyze_format_string::FormatSpecifier &FS, 7864 const analyze_format_string::ConversionSpecifier &CS, 7865 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7866 7867 if (argIndex >= NumDataArgs) { 7868 PartialDiagnostic PDiag = FS.usesPositionalArg() 7869 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7870 << (argIndex+1) << NumDataArgs) 7871 : S.PDiag(diag::warn_printf_insufficient_data_args); 7872 EmitFormatDiagnostic( 7873 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7874 getSpecifierRange(startSpecifier, specifierLen)); 7875 7876 // Since more arguments than conversion tokens are given, by extension 7877 // all arguments are covered, so mark this as so. 7878 UncoveredArg.setAllCovered(); 7879 return false; 7880 } 7881 return true; 7882 } 7883 7884 template<typename Range> 7885 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7886 SourceLocation Loc, 7887 bool IsStringLocation, 7888 Range StringRange, 7889 ArrayRef<FixItHint> FixIt) { 7890 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7891 Loc, IsStringLocation, StringRange, FixIt); 7892 } 7893 7894 /// If the format string is not within the function call, emit a note 7895 /// so that the function call and string are in diagnostic messages. 7896 /// 7897 /// \param InFunctionCall if true, the format string is within the function 7898 /// call and only one diagnostic message will be produced. Otherwise, an 7899 /// extra note will be emitted pointing to location of the format string. 7900 /// 7901 /// \param ArgumentExpr the expression that is passed as the format string 7902 /// argument in the function call. Used for getting locations when two 7903 /// diagnostics are emitted. 7904 /// 7905 /// \param PDiag the callee should already have provided any strings for the 7906 /// diagnostic message. This function only adds locations and fixits 7907 /// to diagnostics. 7908 /// 7909 /// \param Loc primary location for diagnostic. If two diagnostics are 7910 /// required, one will be at Loc and a new SourceLocation will be created for 7911 /// the other one. 7912 /// 7913 /// \param IsStringLocation if true, Loc points to the format string should be 7914 /// used for the note. Otherwise, Loc points to the argument list and will 7915 /// be used with PDiag. 7916 /// 7917 /// \param StringRange some or all of the string to highlight. This is 7918 /// templated so it can accept either a CharSourceRange or a SourceRange. 7919 /// 7920 /// \param FixIt optional fix it hint for the format string. 7921 template <typename Range> 7922 void CheckFormatHandler::EmitFormatDiagnostic( 7923 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7924 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7925 Range StringRange, ArrayRef<FixItHint> FixIt) { 7926 if (InFunctionCall) { 7927 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7928 D << StringRange; 7929 D << FixIt; 7930 } else { 7931 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7932 << ArgumentExpr->getSourceRange(); 7933 7934 const Sema::SemaDiagnosticBuilder &Note = 7935 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7936 diag::note_format_string_defined); 7937 7938 Note << StringRange; 7939 Note << FixIt; 7940 } 7941 } 7942 7943 //===--- CHECK: Printf format string checking ------------------------------===// 7944 7945 namespace { 7946 7947 class CheckPrintfHandler : public CheckFormatHandler { 7948 public: 7949 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7950 const Expr *origFormatExpr, 7951 const Sema::FormatStringType type, unsigned firstDataArg, 7952 unsigned numDataArgs, bool isObjC, const char *beg, 7953 bool hasVAListArg, ArrayRef<const Expr *> Args, 7954 unsigned formatIdx, bool inFunctionCall, 7955 Sema::VariadicCallType CallType, 7956 llvm::SmallBitVector &CheckedVarArgs, 7957 UncoveredArgHandler &UncoveredArg) 7958 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7959 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7960 inFunctionCall, CallType, CheckedVarArgs, 7961 UncoveredArg) {} 7962 7963 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7964 7965 /// Returns true if '%@' specifiers are allowed in the format string. 7966 bool allowsObjCArg() const { 7967 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7968 FSType == Sema::FST_OSTrace; 7969 } 7970 7971 bool HandleInvalidPrintfConversionSpecifier( 7972 const analyze_printf::PrintfSpecifier &FS, 7973 const char *startSpecifier, 7974 unsigned specifierLen) override; 7975 7976 void handleInvalidMaskType(StringRef MaskType) override; 7977 7978 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7979 const char *startSpecifier, 7980 unsigned specifierLen) override; 7981 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7982 const char *StartSpecifier, 7983 unsigned SpecifierLen, 7984 const Expr *E); 7985 7986 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7987 const char *startSpecifier, unsigned specifierLen); 7988 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7989 const analyze_printf::OptionalAmount &Amt, 7990 unsigned type, 7991 const char *startSpecifier, unsigned specifierLen); 7992 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7993 const analyze_printf::OptionalFlag &flag, 7994 const char *startSpecifier, unsigned specifierLen); 7995 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7996 const analyze_printf::OptionalFlag &ignoredFlag, 7997 const analyze_printf::OptionalFlag &flag, 7998 const char *startSpecifier, unsigned specifierLen); 7999 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8000 const Expr *E); 8001 8002 void HandleEmptyObjCModifierFlag(const char *startFlag, 8003 unsigned flagLen) override; 8004 8005 void HandleInvalidObjCModifierFlag(const char *startFlag, 8006 unsigned flagLen) override; 8007 8008 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8009 const char *flagsEnd, 8010 const char *conversionPosition) 8011 override; 8012 }; 8013 8014 } // namespace 8015 8016 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8017 const analyze_printf::PrintfSpecifier &FS, 8018 const char *startSpecifier, 8019 unsigned specifierLen) { 8020 const analyze_printf::PrintfConversionSpecifier &CS = 8021 FS.getConversionSpecifier(); 8022 8023 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8024 getLocationOfByte(CS.getStart()), 8025 startSpecifier, specifierLen, 8026 CS.getStart(), CS.getLength()); 8027 } 8028 8029 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8030 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8031 } 8032 8033 bool CheckPrintfHandler::HandleAmount( 8034 const analyze_format_string::OptionalAmount &Amt, 8035 unsigned k, const char *startSpecifier, 8036 unsigned specifierLen) { 8037 if (Amt.hasDataArgument()) { 8038 if (!HasVAListArg) { 8039 unsigned argIndex = Amt.getArgIndex(); 8040 if (argIndex >= NumDataArgs) { 8041 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8042 << k, 8043 getLocationOfByte(Amt.getStart()), 8044 /*IsStringLocation*/true, 8045 getSpecifierRange(startSpecifier, specifierLen)); 8046 // Don't do any more checking. We will just emit 8047 // spurious errors. 8048 return false; 8049 } 8050 8051 // Type check the data argument. It should be an 'int'. 8052 // Although not in conformance with C99, we also allow the argument to be 8053 // an 'unsigned int' as that is a reasonably safe case. GCC also 8054 // doesn't emit a warning for that case. 8055 CoveredArgs.set(argIndex); 8056 const Expr *Arg = getDataArg(argIndex); 8057 if (!Arg) 8058 return false; 8059 8060 QualType T = Arg->getType(); 8061 8062 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8063 assert(AT.isValid()); 8064 8065 if (!AT.matchesType(S.Context, T)) { 8066 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8067 << k << AT.getRepresentativeTypeName(S.Context) 8068 << T << Arg->getSourceRange(), 8069 getLocationOfByte(Amt.getStart()), 8070 /*IsStringLocation*/true, 8071 getSpecifierRange(startSpecifier, specifierLen)); 8072 // Don't do any more checking. We will just emit 8073 // spurious errors. 8074 return false; 8075 } 8076 } 8077 } 8078 return true; 8079 } 8080 8081 void CheckPrintfHandler::HandleInvalidAmount( 8082 const analyze_printf::PrintfSpecifier &FS, 8083 const analyze_printf::OptionalAmount &Amt, 8084 unsigned type, 8085 const char *startSpecifier, 8086 unsigned specifierLen) { 8087 const analyze_printf::PrintfConversionSpecifier &CS = 8088 FS.getConversionSpecifier(); 8089 8090 FixItHint fixit = 8091 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8092 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8093 Amt.getConstantLength())) 8094 : FixItHint(); 8095 8096 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8097 << type << CS.toString(), 8098 getLocationOfByte(Amt.getStart()), 8099 /*IsStringLocation*/true, 8100 getSpecifierRange(startSpecifier, specifierLen), 8101 fixit); 8102 } 8103 8104 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8105 const analyze_printf::OptionalFlag &flag, 8106 const char *startSpecifier, 8107 unsigned specifierLen) { 8108 // Warn about pointless flag with a fixit removal. 8109 const analyze_printf::PrintfConversionSpecifier &CS = 8110 FS.getConversionSpecifier(); 8111 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8112 << flag.toString() << CS.toString(), 8113 getLocationOfByte(flag.getPosition()), 8114 /*IsStringLocation*/true, 8115 getSpecifierRange(startSpecifier, specifierLen), 8116 FixItHint::CreateRemoval( 8117 getSpecifierRange(flag.getPosition(), 1))); 8118 } 8119 8120 void CheckPrintfHandler::HandleIgnoredFlag( 8121 const analyze_printf::PrintfSpecifier &FS, 8122 const analyze_printf::OptionalFlag &ignoredFlag, 8123 const analyze_printf::OptionalFlag &flag, 8124 const char *startSpecifier, 8125 unsigned specifierLen) { 8126 // Warn about ignored flag with a fixit removal. 8127 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8128 << ignoredFlag.toString() << flag.toString(), 8129 getLocationOfByte(ignoredFlag.getPosition()), 8130 /*IsStringLocation*/true, 8131 getSpecifierRange(startSpecifier, specifierLen), 8132 FixItHint::CreateRemoval( 8133 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8134 } 8135 8136 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8137 unsigned flagLen) { 8138 // Warn about an empty flag. 8139 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8140 getLocationOfByte(startFlag), 8141 /*IsStringLocation*/true, 8142 getSpecifierRange(startFlag, flagLen)); 8143 } 8144 8145 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8146 unsigned flagLen) { 8147 // Warn about an invalid flag. 8148 auto Range = getSpecifierRange(startFlag, flagLen); 8149 StringRef flag(startFlag, flagLen); 8150 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8151 getLocationOfByte(startFlag), 8152 /*IsStringLocation*/true, 8153 Range, FixItHint::CreateRemoval(Range)); 8154 } 8155 8156 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8157 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8158 // Warn about using '[...]' without a '@' conversion. 8159 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8160 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8161 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8162 getLocationOfByte(conversionPosition), 8163 /*IsStringLocation*/true, 8164 Range, FixItHint::CreateRemoval(Range)); 8165 } 8166 8167 // Determines if the specified is a C++ class or struct containing 8168 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8169 // "c_str()"). 8170 template<typename MemberKind> 8171 static llvm::SmallPtrSet<MemberKind*, 1> 8172 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8173 const RecordType *RT = Ty->getAs<RecordType>(); 8174 llvm::SmallPtrSet<MemberKind*, 1> Results; 8175 8176 if (!RT) 8177 return Results; 8178 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8179 if (!RD || !RD->getDefinition()) 8180 return Results; 8181 8182 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8183 Sema::LookupMemberName); 8184 R.suppressDiagnostics(); 8185 8186 // We just need to include all members of the right kind turned up by the 8187 // filter, at this point. 8188 if (S.LookupQualifiedName(R, RT->getDecl())) 8189 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8190 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8191 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8192 Results.insert(FK); 8193 } 8194 return Results; 8195 } 8196 8197 /// Check if we could call '.c_str()' on an object. 8198 /// 8199 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8200 /// allow the call, or if it would be ambiguous). 8201 bool Sema::hasCStrMethod(const Expr *E) { 8202 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8203 8204 MethodSet Results = 8205 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8206 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8207 MI != ME; ++MI) 8208 if ((*MI)->getMinRequiredArguments() == 0) 8209 return true; 8210 return false; 8211 } 8212 8213 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8214 // better diagnostic if so. AT is assumed to be valid. 8215 // Returns true when a c_str() conversion method is found. 8216 bool CheckPrintfHandler::checkForCStrMembers( 8217 const analyze_printf::ArgType &AT, const Expr *E) { 8218 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8219 8220 MethodSet Results = 8221 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8222 8223 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8224 MI != ME; ++MI) { 8225 const CXXMethodDecl *Method = *MI; 8226 if (Method->getMinRequiredArguments() == 0 && 8227 AT.matchesType(S.Context, Method->getReturnType())) { 8228 // FIXME: Suggest parens if the expression needs them. 8229 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8230 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8231 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8232 return true; 8233 } 8234 } 8235 8236 return false; 8237 } 8238 8239 bool 8240 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8241 &FS, 8242 const char *startSpecifier, 8243 unsigned specifierLen) { 8244 using namespace analyze_format_string; 8245 using namespace analyze_printf; 8246 8247 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8248 8249 if (FS.consumesDataArgument()) { 8250 if (atFirstArg) { 8251 atFirstArg = false; 8252 usesPositionalArgs = FS.usesPositionalArg(); 8253 } 8254 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8255 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8256 startSpecifier, specifierLen); 8257 return false; 8258 } 8259 } 8260 8261 // First check if the field width, precision, and conversion specifier 8262 // have matching data arguments. 8263 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8264 startSpecifier, specifierLen)) { 8265 return false; 8266 } 8267 8268 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8269 startSpecifier, specifierLen)) { 8270 return false; 8271 } 8272 8273 if (!CS.consumesDataArgument()) { 8274 // FIXME: Technically specifying a precision or field width here 8275 // makes no sense. Worth issuing a warning at some point. 8276 return true; 8277 } 8278 8279 // Consume the argument. 8280 unsigned argIndex = FS.getArgIndex(); 8281 if (argIndex < NumDataArgs) { 8282 // The check to see if the argIndex is valid will come later. 8283 // We set the bit here because we may exit early from this 8284 // function if we encounter some other error. 8285 CoveredArgs.set(argIndex); 8286 } 8287 8288 // FreeBSD kernel extensions. 8289 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8290 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8291 // We need at least two arguments. 8292 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8293 return false; 8294 8295 // Claim the second argument. 8296 CoveredArgs.set(argIndex + 1); 8297 8298 // Type check the first argument (int for %b, pointer for %D) 8299 const Expr *Ex = getDataArg(argIndex); 8300 const analyze_printf::ArgType &AT = 8301 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8302 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8303 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8304 EmitFormatDiagnostic( 8305 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8306 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8307 << false << Ex->getSourceRange(), 8308 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8309 getSpecifierRange(startSpecifier, specifierLen)); 8310 8311 // Type check the second argument (char * for both %b and %D) 8312 Ex = getDataArg(argIndex + 1); 8313 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8314 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8315 EmitFormatDiagnostic( 8316 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8317 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8318 << false << Ex->getSourceRange(), 8319 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8320 getSpecifierRange(startSpecifier, specifierLen)); 8321 8322 return true; 8323 } 8324 8325 // Check for using an Objective-C specific conversion specifier 8326 // in a non-ObjC literal. 8327 if (!allowsObjCArg() && CS.isObjCArg()) { 8328 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8329 specifierLen); 8330 } 8331 8332 // %P can only be used with os_log. 8333 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8334 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8335 specifierLen); 8336 } 8337 8338 // %n is not allowed with os_log. 8339 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8340 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8341 getLocationOfByte(CS.getStart()), 8342 /*IsStringLocation*/ false, 8343 getSpecifierRange(startSpecifier, specifierLen)); 8344 8345 return true; 8346 } 8347 8348 // Only scalars are allowed for os_trace. 8349 if (FSType == Sema::FST_OSTrace && 8350 (CS.getKind() == ConversionSpecifier::PArg || 8351 CS.getKind() == ConversionSpecifier::sArg || 8352 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8353 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8354 specifierLen); 8355 } 8356 8357 // Check for use of public/private annotation outside of os_log(). 8358 if (FSType != Sema::FST_OSLog) { 8359 if (FS.isPublic().isSet()) { 8360 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8361 << "public", 8362 getLocationOfByte(FS.isPublic().getPosition()), 8363 /*IsStringLocation*/ false, 8364 getSpecifierRange(startSpecifier, specifierLen)); 8365 } 8366 if (FS.isPrivate().isSet()) { 8367 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8368 << "private", 8369 getLocationOfByte(FS.isPrivate().getPosition()), 8370 /*IsStringLocation*/ false, 8371 getSpecifierRange(startSpecifier, specifierLen)); 8372 } 8373 } 8374 8375 // Check for invalid use of field width 8376 if (!FS.hasValidFieldWidth()) { 8377 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8378 startSpecifier, specifierLen); 8379 } 8380 8381 // Check for invalid use of precision 8382 if (!FS.hasValidPrecision()) { 8383 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8384 startSpecifier, specifierLen); 8385 } 8386 8387 // Precision is mandatory for %P specifier. 8388 if (CS.getKind() == ConversionSpecifier::PArg && 8389 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8390 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8391 getLocationOfByte(startSpecifier), 8392 /*IsStringLocation*/ false, 8393 getSpecifierRange(startSpecifier, specifierLen)); 8394 } 8395 8396 // Check each flag does not conflict with any other component. 8397 if (!FS.hasValidThousandsGroupingPrefix()) 8398 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8399 if (!FS.hasValidLeadingZeros()) 8400 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8401 if (!FS.hasValidPlusPrefix()) 8402 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8403 if (!FS.hasValidSpacePrefix()) 8404 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8405 if (!FS.hasValidAlternativeForm()) 8406 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8407 if (!FS.hasValidLeftJustified()) 8408 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8409 8410 // Check that flags are not ignored by another flag 8411 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8412 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8413 startSpecifier, specifierLen); 8414 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8415 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8416 startSpecifier, specifierLen); 8417 8418 // Check the length modifier is valid with the given conversion specifier. 8419 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8420 S.getLangOpts())) 8421 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8422 diag::warn_format_nonsensical_length); 8423 else if (!FS.hasStandardLengthModifier()) 8424 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8425 else if (!FS.hasStandardLengthConversionCombination()) 8426 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8427 diag::warn_format_non_standard_conversion_spec); 8428 8429 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8430 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8431 8432 // The remaining checks depend on the data arguments. 8433 if (HasVAListArg) 8434 return true; 8435 8436 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8437 return false; 8438 8439 const Expr *Arg = getDataArg(argIndex); 8440 if (!Arg) 8441 return true; 8442 8443 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8444 } 8445 8446 static bool requiresParensToAddCast(const Expr *E) { 8447 // FIXME: We should have a general way to reason about operator 8448 // precedence and whether parens are actually needed here. 8449 // Take care of a few common cases where they aren't. 8450 const Expr *Inside = E->IgnoreImpCasts(); 8451 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8452 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8453 8454 switch (Inside->getStmtClass()) { 8455 case Stmt::ArraySubscriptExprClass: 8456 case Stmt::CallExprClass: 8457 case Stmt::CharacterLiteralClass: 8458 case Stmt::CXXBoolLiteralExprClass: 8459 case Stmt::DeclRefExprClass: 8460 case Stmt::FloatingLiteralClass: 8461 case Stmt::IntegerLiteralClass: 8462 case Stmt::MemberExprClass: 8463 case Stmt::ObjCArrayLiteralClass: 8464 case Stmt::ObjCBoolLiteralExprClass: 8465 case Stmt::ObjCBoxedExprClass: 8466 case Stmt::ObjCDictionaryLiteralClass: 8467 case Stmt::ObjCEncodeExprClass: 8468 case Stmt::ObjCIvarRefExprClass: 8469 case Stmt::ObjCMessageExprClass: 8470 case Stmt::ObjCPropertyRefExprClass: 8471 case Stmt::ObjCStringLiteralClass: 8472 case Stmt::ObjCSubscriptRefExprClass: 8473 case Stmt::ParenExprClass: 8474 case Stmt::StringLiteralClass: 8475 case Stmt::UnaryOperatorClass: 8476 return false; 8477 default: 8478 return true; 8479 } 8480 } 8481 8482 static std::pair<QualType, StringRef> 8483 shouldNotPrintDirectly(const ASTContext &Context, 8484 QualType IntendedTy, 8485 const Expr *E) { 8486 // Use a 'while' to peel off layers of typedefs. 8487 QualType TyTy = IntendedTy; 8488 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8489 StringRef Name = UserTy->getDecl()->getName(); 8490 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8491 .Case("CFIndex", Context.getNSIntegerType()) 8492 .Case("NSInteger", Context.getNSIntegerType()) 8493 .Case("NSUInteger", Context.getNSUIntegerType()) 8494 .Case("SInt32", Context.IntTy) 8495 .Case("UInt32", Context.UnsignedIntTy) 8496 .Default(QualType()); 8497 8498 if (!CastTy.isNull()) 8499 return std::make_pair(CastTy, Name); 8500 8501 TyTy = UserTy->desugar(); 8502 } 8503 8504 // Strip parens if necessary. 8505 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8506 return shouldNotPrintDirectly(Context, 8507 PE->getSubExpr()->getType(), 8508 PE->getSubExpr()); 8509 8510 // If this is a conditional expression, then its result type is constructed 8511 // via usual arithmetic conversions and thus there might be no necessary 8512 // typedef sugar there. Recurse to operands to check for NSInteger & 8513 // Co. usage condition. 8514 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8515 QualType TrueTy, FalseTy; 8516 StringRef TrueName, FalseName; 8517 8518 std::tie(TrueTy, TrueName) = 8519 shouldNotPrintDirectly(Context, 8520 CO->getTrueExpr()->getType(), 8521 CO->getTrueExpr()); 8522 std::tie(FalseTy, FalseName) = 8523 shouldNotPrintDirectly(Context, 8524 CO->getFalseExpr()->getType(), 8525 CO->getFalseExpr()); 8526 8527 if (TrueTy == FalseTy) 8528 return std::make_pair(TrueTy, TrueName); 8529 else if (TrueTy.isNull()) 8530 return std::make_pair(FalseTy, FalseName); 8531 else if (FalseTy.isNull()) 8532 return std::make_pair(TrueTy, TrueName); 8533 } 8534 8535 return std::make_pair(QualType(), StringRef()); 8536 } 8537 8538 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8539 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8540 /// type do not count. 8541 static bool 8542 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8543 QualType From = ICE->getSubExpr()->getType(); 8544 QualType To = ICE->getType(); 8545 // It's an integer promotion if the destination type is the promoted 8546 // source type. 8547 if (ICE->getCastKind() == CK_IntegralCast && 8548 From->isPromotableIntegerType() && 8549 S.Context.getPromotedIntegerType(From) == To) 8550 return true; 8551 // Look through vector types, since we do default argument promotion for 8552 // those in OpenCL. 8553 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8554 From = VecTy->getElementType(); 8555 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8556 To = VecTy->getElementType(); 8557 // It's a floating promotion if the source type is a lower rank. 8558 return ICE->getCastKind() == CK_FloatingCast && 8559 S.Context.getFloatingTypeOrder(From, To) < 0; 8560 } 8561 8562 bool 8563 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8564 const char *StartSpecifier, 8565 unsigned SpecifierLen, 8566 const Expr *E) { 8567 using namespace analyze_format_string; 8568 using namespace analyze_printf; 8569 8570 // Now type check the data expression that matches the 8571 // format specifier. 8572 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8573 if (!AT.isValid()) 8574 return true; 8575 8576 QualType ExprTy = E->getType(); 8577 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8578 ExprTy = TET->getUnderlyingExpr()->getType(); 8579 } 8580 8581 // Diagnose attempts to print a boolean value as a character. Unlike other 8582 // -Wformat diagnostics, this is fine from a type perspective, but it still 8583 // doesn't make sense. 8584 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8585 E->isKnownToHaveBooleanValue()) { 8586 const CharSourceRange &CSR = 8587 getSpecifierRange(StartSpecifier, SpecifierLen); 8588 SmallString<4> FSString; 8589 llvm::raw_svector_ostream os(FSString); 8590 FS.toString(os); 8591 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8592 << FSString, 8593 E->getExprLoc(), false, CSR); 8594 return true; 8595 } 8596 8597 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8598 if (Match == analyze_printf::ArgType::Match) 8599 return true; 8600 8601 // Look through argument promotions for our error message's reported type. 8602 // This includes the integral and floating promotions, but excludes array 8603 // and function pointer decay (seeing that an argument intended to be a 8604 // string has type 'char [6]' is probably more confusing than 'char *') and 8605 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8606 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8607 if (isArithmeticArgumentPromotion(S, ICE)) { 8608 E = ICE->getSubExpr(); 8609 ExprTy = E->getType(); 8610 8611 // Check if we didn't match because of an implicit cast from a 'char' 8612 // or 'short' to an 'int'. This is done because printf is a varargs 8613 // function. 8614 if (ICE->getType() == S.Context.IntTy || 8615 ICE->getType() == S.Context.UnsignedIntTy) { 8616 // All further checking is done on the subexpression 8617 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8618 AT.matchesType(S.Context, ExprTy); 8619 if (ImplicitMatch == analyze_printf::ArgType::Match) 8620 return true; 8621 if (ImplicitMatch == ArgType::NoMatchPedantic || 8622 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8623 Match = ImplicitMatch; 8624 } 8625 } 8626 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8627 // Special case for 'a', which has type 'int' in C. 8628 // Note, however, that we do /not/ want to treat multibyte constants like 8629 // 'MooV' as characters! This form is deprecated but still exists. 8630 if (ExprTy == S.Context.IntTy) 8631 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8632 ExprTy = S.Context.CharTy; 8633 } 8634 8635 // Look through enums to their underlying type. 8636 bool IsEnum = false; 8637 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8638 ExprTy = EnumTy->getDecl()->getIntegerType(); 8639 IsEnum = true; 8640 } 8641 8642 // %C in an Objective-C context prints a unichar, not a wchar_t. 8643 // If the argument is an integer of some kind, believe the %C and suggest 8644 // a cast instead of changing the conversion specifier. 8645 QualType IntendedTy = ExprTy; 8646 if (isObjCContext() && 8647 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8648 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8649 !ExprTy->isCharType()) { 8650 // 'unichar' is defined as a typedef of unsigned short, but we should 8651 // prefer using the typedef if it is visible. 8652 IntendedTy = S.Context.UnsignedShortTy; 8653 8654 // While we are here, check if the value is an IntegerLiteral that happens 8655 // to be within the valid range. 8656 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8657 const llvm::APInt &V = IL->getValue(); 8658 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8659 return true; 8660 } 8661 8662 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8663 Sema::LookupOrdinaryName); 8664 if (S.LookupName(Result, S.getCurScope())) { 8665 NamedDecl *ND = Result.getFoundDecl(); 8666 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8667 if (TD->getUnderlyingType() == IntendedTy) 8668 IntendedTy = S.Context.getTypedefType(TD); 8669 } 8670 } 8671 } 8672 8673 // Special-case some of Darwin's platform-independence types by suggesting 8674 // casts to primitive types that are known to be large enough. 8675 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8676 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8677 QualType CastTy; 8678 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8679 if (!CastTy.isNull()) { 8680 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8681 // (long in ASTContext). Only complain to pedants. 8682 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8683 (AT.isSizeT() || AT.isPtrdiffT()) && 8684 AT.matchesType(S.Context, CastTy)) 8685 Match = ArgType::NoMatchPedantic; 8686 IntendedTy = CastTy; 8687 ShouldNotPrintDirectly = true; 8688 } 8689 } 8690 8691 // We may be able to offer a FixItHint if it is a supported type. 8692 PrintfSpecifier fixedFS = FS; 8693 bool Success = 8694 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8695 8696 if (Success) { 8697 // Get the fix string from the fixed format specifier 8698 SmallString<16> buf; 8699 llvm::raw_svector_ostream os(buf); 8700 fixedFS.toString(os); 8701 8702 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8703 8704 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8705 unsigned Diag; 8706 switch (Match) { 8707 case ArgType::Match: llvm_unreachable("expected non-matching"); 8708 case ArgType::NoMatchPedantic: 8709 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8710 break; 8711 case ArgType::NoMatchTypeConfusion: 8712 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8713 break; 8714 case ArgType::NoMatch: 8715 Diag = diag::warn_format_conversion_argument_type_mismatch; 8716 break; 8717 } 8718 8719 // In this case, the specifier is wrong and should be changed to match 8720 // the argument. 8721 EmitFormatDiagnostic(S.PDiag(Diag) 8722 << AT.getRepresentativeTypeName(S.Context) 8723 << IntendedTy << IsEnum << E->getSourceRange(), 8724 E->getBeginLoc(), 8725 /*IsStringLocation*/ false, SpecRange, 8726 FixItHint::CreateReplacement(SpecRange, os.str())); 8727 } else { 8728 // The canonical type for formatting this value is different from the 8729 // actual type of the expression. (This occurs, for example, with Darwin's 8730 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8731 // should be printed as 'long' for 64-bit compatibility.) 8732 // Rather than emitting a normal format/argument mismatch, we want to 8733 // add a cast to the recommended type (and correct the format string 8734 // if necessary). 8735 SmallString<16> CastBuf; 8736 llvm::raw_svector_ostream CastFix(CastBuf); 8737 CastFix << "("; 8738 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8739 CastFix << ")"; 8740 8741 SmallVector<FixItHint,4> Hints; 8742 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8743 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8744 8745 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8746 // If there's already a cast present, just replace it. 8747 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8748 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8749 8750 } else if (!requiresParensToAddCast(E)) { 8751 // If the expression has high enough precedence, 8752 // just write the C-style cast. 8753 Hints.push_back( 8754 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8755 } else { 8756 // Otherwise, add parens around the expression as well as the cast. 8757 CastFix << "("; 8758 Hints.push_back( 8759 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8760 8761 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8762 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8763 } 8764 8765 if (ShouldNotPrintDirectly) { 8766 // The expression has a type that should not be printed directly. 8767 // We extract the name from the typedef because we don't want to show 8768 // the underlying type in the diagnostic. 8769 StringRef Name; 8770 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8771 Name = TypedefTy->getDecl()->getName(); 8772 else 8773 Name = CastTyName; 8774 unsigned Diag = Match == ArgType::NoMatchPedantic 8775 ? diag::warn_format_argument_needs_cast_pedantic 8776 : diag::warn_format_argument_needs_cast; 8777 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8778 << E->getSourceRange(), 8779 E->getBeginLoc(), /*IsStringLocation=*/false, 8780 SpecRange, Hints); 8781 } else { 8782 // In this case, the expression could be printed using a different 8783 // specifier, but we've decided that the specifier is probably correct 8784 // and we should cast instead. Just use the normal warning message. 8785 EmitFormatDiagnostic( 8786 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8787 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8788 << E->getSourceRange(), 8789 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8790 } 8791 } 8792 } else { 8793 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8794 SpecifierLen); 8795 // Since the warning for passing non-POD types to variadic functions 8796 // was deferred until now, we emit a warning for non-POD 8797 // arguments here. 8798 switch (S.isValidVarArgType(ExprTy)) { 8799 case Sema::VAK_Valid: 8800 case Sema::VAK_ValidInCXX11: { 8801 unsigned Diag; 8802 switch (Match) { 8803 case ArgType::Match: llvm_unreachable("expected non-matching"); 8804 case ArgType::NoMatchPedantic: 8805 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8806 break; 8807 case ArgType::NoMatchTypeConfusion: 8808 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8809 break; 8810 case ArgType::NoMatch: 8811 Diag = diag::warn_format_conversion_argument_type_mismatch; 8812 break; 8813 } 8814 8815 EmitFormatDiagnostic( 8816 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8817 << IsEnum << CSR << E->getSourceRange(), 8818 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8819 break; 8820 } 8821 case Sema::VAK_Undefined: 8822 case Sema::VAK_MSVCUndefined: 8823 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8824 << S.getLangOpts().CPlusPlus11 << ExprTy 8825 << CallType 8826 << AT.getRepresentativeTypeName(S.Context) << CSR 8827 << E->getSourceRange(), 8828 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8829 checkForCStrMembers(AT, E); 8830 break; 8831 8832 case Sema::VAK_Invalid: 8833 if (ExprTy->isObjCObjectType()) 8834 EmitFormatDiagnostic( 8835 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8836 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8837 << AT.getRepresentativeTypeName(S.Context) << CSR 8838 << E->getSourceRange(), 8839 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8840 else 8841 // FIXME: If this is an initializer list, suggest removing the braces 8842 // or inserting a cast to the target type. 8843 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8844 << isa<InitListExpr>(E) << ExprTy << CallType 8845 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8846 break; 8847 } 8848 8849 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8850 "format string specifier index out of range"); 8851 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8852 } 8853 8854 return true; 8855 } 8856 8857 //===--- CHECK: Scanf format string checking ------------------------------===// 8858 8859 namespace { 8860 8861 class CheckScanfHandler : public CheckFormatHandler { 8862 public: 8863 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8864 const Expr *origFormatExpr, Sema::FormatStringType type, 8865 unsigned firstDataArg, unsigned numDataArgs, 8866 const char *beg, bool hasVAListArg, 8867 ArrayRef<const Expr *> Args, unsigned formatIdx, 8868 bool inFunctionCall, Sema::VariadicCallType CallType, 8869 llvm::SmallBitVector &CheckedVarArgs, 8870 UncoveredArgHandler &UncoveredArg) 8871 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8872 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8873 inFunctionCall, CallType, CheckedVarArgs, 8874 UncoveredArg) {} 8875 8876 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8877 const char *startSpecifier, 8878 unsigned specifierLen) override; 8879 8880 bool HandleInvalidScanfConversionSpecifier( 8881 const analyze_scanf::ScanfSpecifier &FS, 8882 const char *startSpecifier, 8883 unsigned specifierLen) override; 8884 8885 void HandleIncompleteScanList(const char *start, const char *end) override; 8886 }; 8887 8888 } // namespace 8889 8890 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8891 const char *end) { 8892 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8893 getLocationOfByte(end), /*IsStringLocation*/true, 8894 getSpecifierRange(start, end - start)); 8895 } 8896 8897 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8898 const analyze_scanf::ScanfSpecifier &FS, 8899 const char *startSpecifier, 8900 unsigned specifierLen) { 8901 const analyze_scanf::ScanfConversionSpecifier &CS = 8902 FS.getConversionSpecifier(); 8903 8904 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8905 getLocationOfByte(CS.getStart()), 8906 startSpecifier, specifierLen, 8907 CS.getStart(), CS.getLength()); 8908 } 8909 8910 bool CheckScanfHandler::HandleScanfSpecifier( 8911 const analyze_scanf::ScanfSpecifier &FS, 8912 const char *startSpecifier, 8913 unsigned specifierLen) { 8914 using namespace analyze_scanf; 8915 using namespace analyze_format_string; 8916 8917 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8918 8919 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8920 // be used to decide if we are using positional arguments consistently. 8921 if (FS.consumesDataArgument()) { 8922 if (atFirstArg) { 8923 atFirstArg = false; 8924 usesPositionalArgs = FS.usesPositionalArg(); 8925 } 8926 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8927 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8928 startSpecifier, specifierLen); 8929 return false; 8930 } 8931 } 8932 8933 // Check if the field with is non-zero. 8934 const OptionalAmount &Amt = FS.getFieldWidth(); 8935 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8936 if (Amt.getConstantAmount() == 0) { 8937 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8938 Amt.getConstantLength()); 8939 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8940 getLocationOfByte(Amt.getStart()), 8941 /*IsStringLocation*/true, R, 8942 FixItHint::CreateRemoval(R)); 8943 } 8944 } 8945 8946 if (!FS.consumesDataArgument()) { 8947 // FIXME: Technically specifying a precision or field width here 8948 // makes no sense. Worth issuing a warning at some point. 8949 return true; 8950 } 8951 8952 // Consume the argument. 8953 unsigned argIndex = FS.getArgIndex(); 8954 if (argIndex < NumDataArgs) { 8955 // The check to see if the argIndex is valid will come later. 8956 // We set the bit here because we may exit early from this 8957 // function if we encounter some other error. 8958 CoveredArgs.set(argIndex); 8959 } 8960 8961 // Check the length modifier is valid with the given conversion specifier. 8962 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8963 S.getLangOpts())) 8964 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8965 diag::warn_format_nonsensical_length); 8966 else if (!FS.hasStandardLengthModifier()) 8967 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8968 else if (!FS.hasStandardLengthConversionCombination()) 8969 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8970 diag::warn_format_non_standard_conversion_spec); 8971 8972 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8973 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8974 8975 // The remaining checks depend on the data arguments. 8976 if (HasVAListArg) 8977 return true; 8978 8979 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8980 return false; 8981 8982 // Check that the argument type matches the format specifier. 8983 const Expr *Ex = getDataArg(argIndex); 8984 if (!Ex) 8985 return true; 8986 8987 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8988 8989 if (!AT.isValid()) { 8990 return true; 8991 } 8992 8993 analyze_format_string::ArgType::MatchKind Match = 8994 AT.matchesType(S.Context, Ex->getType()); 8995 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8996 if (Match == analyze_format_string::ArgType::Match) 8997 return true; 8998 8999 ScanfSpecifier fixedFS = FS; 9000 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9001 S.getLangOpts(), S.Context); 9002 9003 unsigned Diag = 9004 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9005 : diag::warn_format_conversion_argument_type_mismatch; 9006 9007 if (Success) { 9008 // Get the fix string from the fixed format specifier. 9009 SmallString<128> buf; 9010 llvm::raw_svector_ostream os(buf); 9011 fixedFS.toString(os); 9012 9013 EmitFormatDiagnostic( 9014 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9015 << Ex->getType() << false << Ex->getSourceRange(), 9016 Ex->getBeginLoc(), 9017 /*IsStringLocation*/ false, 9018 getSpecifierRange(startSpecifier, specifierLen), 9019 FixItHint::CreateReplacement( 9020 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9021 } else { 9022 EmitFormatDiagnostic(S.PDiag(Diag) 9023 << AT.getRepresentativeTypeName(S.Context) 9024 << Ex->getType() << false << Ex->getSourceRange(), 9025 Ex->getBeginLoc(), 9026 /*IsStringLocation*/ false, 9027 getSpecifierRange(startSpecifier, specifierLen)); 9028 } 9029 9030 return true; 9031 } 9032 9033 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9034 const Expr *OrigFormatExpr, 9035 ArrayRef<const Expr *> Args, 9036 bool HasVAListArg, unsigned format_idx, 9037 unsigned firstDataArg, 9038 Sema::FormatStringType Type, 9039 bool inFunctionCall, 9040 Sema::VariadicCallType CallType, 9041 llvm::SmallBitVector &CheckedVarArgs, 9042 UncoveredArgHandler &UncoveredArg, 9043 bool IgnoreStringsWithoutSpecifiers) { 9044 // CHECK: is the format string a wide literal? 9045 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9046 CheckFormatHandler::EmitFormatDiagnostic( 9047 S, inFunctionCall, Args[format_idx], 9048 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9049 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9050 return; 9051 } 9052 9053 // Str - The format string. NOTE: this is NOT null-terminated! 9054 StringRef StrRef = FExpr->getString(); 9055 const char *Str = StrRef.data(); 9056 // Account for cases where the string literal is truncated in a declaration. 9057 const ConstantArrayType *T = 9058 S.Context.getAsConstantArrayType(FExpr->getType()); 9059 assert(T && "String literal not of constant array type!"); 9060 size_t TypeSize = T->getSize().getZExtValue(); 9061 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9062 const unsigned numDataArgs = Args.size() - firstDataArg; 9063 9064 if (IgnoreStringsWithoutSpecifiers && 9065 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9066 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9067 return; 9068 9069 // Emit a warning if the string literal is truncated and does not contain an 9070 // embedded null character. 9071 if (TypeSize <= StrRef.size() && 9072 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9073 CheckFormatHandler::EmitFormatDiagnostic( 9074 S, inFunctionCall, Args[format_idx], 9075 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9076 FExpr->getBeginLoc(), 9077 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9078 return; 9079 } 9080 9081 // CHECK: empty format string? 9082 if (StrLen == 0 && numDataArgs > 0) { 9083 CheckFormatHandler::EmitFormatDiagnostic( 9084 S, inFunctionCall, Args[format_idx], 9085 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9086 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9087 return; 9088 } 9089 9090 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9091 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9092 Type == Sema::FST_OSTrace) { 9093 CheckPrintfHandler H( 9094 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9095 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9096 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9097 CheckedVarArgs, UncoveredArg); 9098 9099 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9100 S.getLangOpts(), 9101 S.Context.getTargetInfo(), 9102 Type == Sema::FST_FreeBSDKPrintf)) 9103 H.DoneProcessing(); 9104 } else if (Type == Sema::FST_Scanf) { 9105 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9106 numDataArgs, Str, HasVAListArg, Args, format_idx, 9107 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9108 9109 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9110 S.getLangOpts(), 9111 S.Context.getTargetInfo())) 9112 H.DoneProcessing(); 9113 } // TODO: handle other formats 9114 } 9115 9116 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9117 // Str - The format string. NOTE: this is NOT null-terminated! 9118 StringRef StrRef = FExpr->getString(); 9119 const char *Str = StrRef.data(); 9120 // Account for cases where the string literal is truncated in a declaration. 9121 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9122 assert(T && "String literal not of constant array type!"); 9123 size_t TypeSize = T->getSize().getZExtValue(); 9124 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9125 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9126 getLangOpts(), 9127 Context.getTargetInfo()); 9128 } 9129 9130 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9131 9132 // Returns the related absolute value function that is larger, of 0 if one 9133 // does not exist. 9134 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9135 switch (AbsFunction) { 9136 default: 9137 return 0; 9138 9139 case Builtin::BI__builtin_abs: 9140 return Builtin::BI__builtin_labs; 9141 case Builtin::BI__builtin_labs: 9142 return Builtin::BI__builtin_llabs; 9143 case Builtin::BI__builtin_llabs: 9144 return 0; 9145 9146 case Builtin::BI__builtin_fabsf: 9147 return Builtin::BI__builtin_fabs; 9148 case Builtin::BI__builtin_fabs: 9149 return Builtin::BI__builtin_fabsl; 9150 case Builtin::BI__builtin_fabsl: 9151 return 0; 9152 9153 case Builtin::BI__builtin_cabsf: 9154 return Builtin::BI__builtin_cabs; 9155 case Builtin::BI__builtin_cabs: 9156 return Builtin::BI__builtin_cabsl; 9157 case Builtin::BI__builtin_cabsl: 9158 return 0; 9159 9160 case Builtin::BIabs: 9161 return Builtin::BIlabs; 9162 case Builtin::BIlabs: 9163 return Builtin::BIllabs; 9164 case Builtin::BIllabs: 9165 return 0; 9166 9167 case Builtin::BIfabsf: 9168 return Builtin::BIfabs; 9169 case Builtin::BIfabs: 9170 return Builtin::BIfabsl; 9171 case Builtin::BIfabsl: 9172 return 0; 9173 9174 case Builtin::BIcabsf: 9175 return Builtin::BIcabs; 9176 case Builtin::BIcabs: 9177 return Builtin::BIcabsl; 9178 case Builtin::BIcabsl: 9179 return 0; 9180 } 9181 } 9182 9183 // Returns the argument type of the absolute value function. 9184 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9185 unsigned AbsType) { 9186 if (AbsType == 0) 9187 return QualType(); 9188 9189 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9190 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9191 if (Error != ASTContext::GE_None) 9192 return QualType(); 9193 9194 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9195 if (!FT) 9196 return QualType(); 9197 9198 if (FT->getNumParams() != 1) 9199 return QualType(); 9200 9201 return FT->getParamType(0); 9202 } 9203 9204 // Returns the best absolute value function, or zero, based on type and 9205 // current absolute value function. 9206 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9207 unsigned AbsFunctionKind) { 9208 unsigned BestKind = 0; 9209 uint64_t ArgSize = Context.getTypeSize(ArgType); 9210 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9211 Kind = getLargerAbsoluteValueFunction(Kind)) { 9212 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9213 if (Context.getTypeSize(ParamType) >= ArgSize) { 9214 if (BestKind == 0) 9215 BestKind = Kind; 9216 else if (Context.hasSameType(ParamType, ArgType)) { 9217 BestKind = Kind; 9218 break; 9219 } 9220 } 9221 } 9222 return BestKind; 9223 } 9224 9225 enum AbsoluteValueKind { 9226 AVK_Integer, 9227 AVK_Floating, 9228 AVK_Complex 9229 }; 9230 9231 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9232 if (T->isIntegralOrEnumerationType()) 9233 return AVK_Integer; 9234 if (T->isRealFloatingType()) 9235 return AVK_Floating; 9236 if (T->isAnyComplexType()) 9237 return AVK_Complex; 9238 9239 llvm_unreachable("Type not integer, floating, or complex"); 9240 } 9241 9242 // Changes the absolute value function to a different type. Preserves whether 9243 // the function is a builtin. 9244 static unsigned changeAbsFunction(unsigned AbsKind, 9245 AbsoluteValueKind ValueKind) { 9246 switch (ValueKind) { 9247 case AVK_Integer: 9248 switch (AbsKind) { 9249 default: 9250 return 0; 9251 case Builtin::BI__builtin_fabsf: 9252 case Builtin::BI__builtin_fabs: 9253 case Builtin::BI__builtin_fabsl: 9254 case Builtin::BI__builtin_cabsf: 9255 case Builtin::BI__builtin_cabs: 9256 case Builtin::BI__builtin_cabsl: 9257 return Builtin::BI__builtin_abs; 9258 case Builtin::BIfabsf: 9259 case Builtin::BIfabs: 9260 case Builtin::BIfabsl: 9261 case Builtin::BIcabsf: 9262 case Builtin::BIcabs: 9263 case Builtin::BIcabsl: 9264 return Builtin::BIabs; 9265 } 9266 case AVK_Floating: 9267 switch (AbsKind) { 9268 default: 9269 return 0; 9270 case Builtin::BI__builtin_abs: 9271 case Builtin::BI__builtin_labs: 9272 case Builtin::BI__builtin_llabs: 9273 case Builtin::BI__builtin_cabsf: 9274 case Builtin::BI__builtin_cabs: 9275 case Builtin::BI__builtin_cabsl: 9276 return Builtin::BI__builtin_fabsf; 9277 case Builtin::BIabs: 9278 case Builtin::BIlabs: 9279 case Builtin::BIllabs: 9280 case Builtin::BIcabsf: 9281 case Builtin::BIcabs: 9282 case Builtin::BIcabsl: 9283 return Builtin::BIfabsf; 9284 } 9285 case AVK_Complex: 9286 switch (AbsKind) { 9287 default: 9288 return 0; 9289 case Builtin::BI__builtin_abs: 9290 case Builtin::BI__builtin_labs: 9291 case Builtin::BI__builtin_llabs: 9292 case Builtin::BI__builtin_fabsf: 9293 case Builtin::BI__builtin_fabs: 9294 case Builtin::BI__builtin_fabsl: 9295 return Builtin::BI__builtin_cabsf; 9296 case Builtin::BIabs: 9297 case Builtin::BIlabs: 9298 case Builtin::BIllabs: 9299 case Builtin::BIfabsf: 9300 case Builtin::BIfabs: 9301 case Builtin::BIfabsl: 9302 return Builtin::BIcabsf; 9303 } 9304 } 9305 llvm_unreachable("Unable to convert function"); 9306 } 9307 9308 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9309 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9310 if (!FnInfo) 9311 return 0; 9312 9313 switch (FDecl->getBuiltinID()) { 9314 default: 9315 return 0; 9316 case Builtin::BI__builtin_abs: 9317 case Builtin::BI__builtin_fabs: 9318 case Builtin::BI__builtin_fabsf: 9319 case Builtin::BI__builtin_fabsl: 9320 case Builtin::BI__builtin_labs: 9321 case Builtin::BI__builtin_llabs: 9322 case Builtin::BI__builtin_cabs: 9323 case Builtin::BI__builtin_cabsf: 9324 case Builtin::BI__builtin_cabsl: 9325 case Builtin::BIabs: 9326 case Builtin::BIlabs: 9327 case Builtin::BIllabs: 9328 case Builtin::BIfabs: 9329 case Builtin::BIfabsf: 9330 case Builtin::BIfabsl: 9331 case Builtin::BIcabs: 9332 case Builtin::BIcabsf: 9333 case Builtin::BIcabsl: 9334 return FDecl->getBuiltinID(); 9335 } 9336 llvm_unreachable("Unknown Builtin type"); 9337 } 9338 9339 // If the replacement is valid, emit a note with replacement function. 9340 // Additionally, suggest including the proper header if not already included. 9341 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9342 unsigned AbsKind, QualType ArgType) { 9343 bool EmitHeaderHint = true; 9344 const char *HeaderName = nullptr; 9345 const char *FunctionName = nullptr; 9346 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9347 FunctionName = "std::abs"; 9348 if (ArgType->isIntegralOrEnumerationType()) { 9349 HeaderName = "cstdlib"; 9350 } else if (ArgType->isRealFloatingType()) { 9351 HeaderName = "cmath"; 9352 } else { 9353 llvm_unreachable("Invalid Type"); 9354 } 9355 9356 // Lookup all std::abs 9357 if (NamespaceDecl *Std = S.getStdNamespace()) { 9358 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9359 R.suppressDiagnostics(); 9360 S.LookupQualifiedName(R, Std); 9361 9362 for (const auto *I : R) { 9363 const FunctionDecl *FDecl = nullptr; 9364 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9365 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9366 } else { 9367 FDecl = dyn_cast<FunctionDecl>(I); 9368 } 9369 if (!FDecl) 9370 continue; 9371 9372 // Found std::abs(), check that they are the right ones. 9373 if (FDecl->getNumParams() != 1) 9374 continue; 9375 9376 // Check that the parameter type can handle the argument. 9377 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9378 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9379 S.Context.getTypeSize(ArgType) <= 9380 S.Context.getTypeSize(ParamType)) { 9381 // Found a function, don't need the header hint. 9382 EmitHeaderHint = false; 9383 break; 9384 } 9385 } 9386 } 9387 } else { 9388 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9389 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9390 9391 if (HeaderName) { 9392 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9393 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9394 R.suppressDiagnostics(); 9395 S.LookupName(R, S.getCurScope()); 9396 9397 if (R.isSingleResult()) { 9398 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9399 if (FD && FD->getBuiltinID() == AbsKind) { 9400 EmitHeaderHint = false; 9401 } else { 9402 return; 9403 } 9404 } else if (!R.empty()) { 9405 return; 9406 } 9407 } 9408 } 9409 9410 S.Diag(Loc, diag::note_replace_abs_function) 9411 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9412 9413 if (!HeaderName) 9414 return; 9415 9416 if (!EmitHeaderHint) 9417 return; 9418 9419 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9420 << FunctionName; 9421 } 9422 9423 template <std::size_t StrLen> 9424 static bool IsStdFunction(const FunctionDecl *FDecl, 9425 const char (&Str)[StrLen]) { 9426 if (!FDecl) 9427 return false; 9428 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9429 return false; 9430 if (!FDecl->isInStdNamespace()) 9431 return false; 9432 9433 return true; 9434 } 9435 9436 // Warn when using the wrong abs() function. 9437 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9438 const FunctionDecl *FDecl) { 9439 if (Call->getNumArgs() != 1) 9440 return; 9441 9442 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9443 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9444 if (AbsKind == 0 && !IsStdAbs) 9445 return; 9446 9447 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9448 QualType ParamType = Call->getArg(0)->getType(); 9449 9450 // Unsigned types cannot be negative. Suggest removing the absolute value 9451 // function call. 9452 if (ArgType->isUnsignedIntegerType()) { 9453 const char *FunctionName = 9454 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9455 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9456 Diag(Call->getExprLoc(), diag::note_remove_abs) 9457 << FunctionName 9458 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9459 return; 9460 } 9461 9462 // Taking the absolute value of a pointer is very suspicious, they probably 9463 // wanted to index into an array, dereference a pointer, call a function, etc. 9464 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9465 unsigned DiagType = 0; 9466 if (ArgType->isFunctionType()) 9467 DiagType = 1; 9468 else if (ArgType->isArrayType()) 9469 DiagType = 2; 9470 9471 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9472 return; 9473 } 9474 9475 // std::abs has overloads which prevent most of the absolute value problems 9476 // from occurring. 9477 if (IsStdAbs) 9478 return; 9479 9480 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9481 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9482 9483 // The argument and parameter are the same kind. Check if they are the right 9484 // size. 9485 if (ArgValueKind == ParamValueKind) { 9486 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9487 return; 9488 9489 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9490 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9491 << FDecl << ArgType << ParamType; 9492 9493 if (NewAbsKind == 0) 9494 return; 9495 9496 emitReplacement(*this, Call->getExprLoc(), 9497 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9498 return; 9499 } 9500 9501 // ArgValueKind != ParamValueKind 9502 // The wrong type of absolute value function was used. Attempt to find the 9503 // proper one. 9504 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9505 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9506 if (NewAbsKind == 0) 9507 return; 9508 9509 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9510 << FDecl << ParamValueKind << ArgValueKind; 9511 9512 emitReplacement(*this, Call->getExprLoc(), 9513 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9514 } 9515 9516 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9517 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9518 const FunctionDecl *FDecl) { 9519 if (!Call || !FDecl) return; 9520 9521 // Ignore template specializations and macros. 9522 if (inTemplateInstantiation()) return; 9523 if (Call->getExprLoc().isMacroID()) return; 9524 9525 // Only care about the one template argument, two function parameter std::max 9526 if (Call->getNumArgs() != 2) return; 9527 if (!IsStdFunction(FDecl, "max")) return; 9528 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9529 if (!ArgList) return; 9530 if (ArgList->size() != 1) return; 9531 9532 // Check that template type argument is unsigned integer. 9533 const auto& TA = ArgList->get(0); 9534 if (TA.getKind() != TemplateArgument::Type) return; 9535 QualType ArgType = TA.getAsType(); 9536 if (!ArgType->isUnsignedIntegerType()) return; 9537 9538 // See if either argument is a literal zero. 9539 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9540 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9541 if (!MTE) return false; 9542 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9543 if (!Num) return false; 9544 if (Num->getValue() != 0) return false; 9545 return true; 9546 }; 9547 9548 const Expr *FirstArg = Call->getArg(0); 9549 const Expr *SecondArg = Call->getArg(1); 9550 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9551 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9552 9553 // Only warn when exactly one argument is zero. 9554 if (IsFirstArgZero == IsSecondArgZero) return; 9555 9556 SourceRange FirstRange = FirstArg->getSourceRange(); 9557 SourceRange SecondRange = SecondArg->getSourceRange(); 9558 9559 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9560 9561 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9562 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9563 9564 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9565 SourceRange RemovalRange; 9566 if (IsFirstArgZero) { 9567 RemovalRange = SourceRange(FirstRange.getBegin(), 9568 SecondRange.getBegin().getLocWithOffset(-1)); 9569 } else { 9570 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9571 SecondRange.getEnd()); 9572 } 9573 9574 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9575 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9576 << FixItHint::CreateRemoval(RemovalRange); 9577 } 9578 9579 //===--- CHECK: Standard memory functions ---------------------------------===// 9580 9581 /// Takes the expression passed to the size_t parameter of functions 9582 /// such as memcmp, strncat, etc and warns if it's a comparison. 9583 /// 9584 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9585 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9586 IdentifierInfo *FnName, 9587 SourceLocation FnLoc, 9588 SourceLocation RParenLoc) { 9589 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9590 if (!Size) 9591 return false; 9592 9593 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9594 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9595 return false; 9596 9597 SourceRange SizeRange = Size->getSourceRange(); 9598 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9599 << SizeRange << FnName; 9600 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9601 << FnName 9602 << FixItHint::CreateInsertion( 9603 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9604 << FixItHint::CreateRemoval(RParenLoc); 9605 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9606 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9607 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9608 ")"); 9609 9610 return true; 9611 } 9612 9613 /// Determine whether the given type is or contains a dynamic class type 9614 /// (e.g., whether it has a vtable). 9615 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9616 bool &IsContained) { 9617 // Look through array types while ignoring qualifiers. 9618 const Type *Ty = T->getBaseElementTypeUnsafe(); 9619 IsContained = false; 9620 9621 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9622 RD = RD ? RD->getDefinition() : nullptr; 9623 if (!RD || RD->isInvalidDecl()) 9624 return nullptr; 9625 9626 if (RD->isDynamicClass()) 9627 return RD; 9628 9629 // Check all the fields. If any bases were dynamic, the class is dynamic. 9630 // It's impossible for a class to transitively contain itself by value, so 9631 // infinite recursion is impossible. 9632 for (auto *FD : RD->fields()) { 9633 bool SubContained; 9634 if (const CXXRecordDecl *ContainedRD = 9635 getContainedDynamicClass(FD->getType(), SubContained)) { 9636 IsContained = true; 9637 return ContainedRD; 9638 } 9639 } 9640 9641 return nullptr; 9642 } 9643 9644 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9645 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9646 if (Unary->getKind() == UETT_SizeOf) 9647 return Unary; 9648 return nullptr; 9649 } 9650 9651 /// If E is a sizeof expression, returns its argument expression, 9652 /// otherwise returns NULL. 9653 static const Expr *getSizeOfExprArg(const Expr *E) { 9654 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9655 if (!SizeOf->isArgumentType()) 9656 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9657 return nullptr; 9658 } 9659 9660 /// If E is a sizeof expression, returns its argument type. 9661 static QualType getSizeOfArgType(const Expr *E) { 9662 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9663 return SizeOf->getTypeOfArgument(); 9664 return QualType(); 9665 } 9666 9667 namespace { 9668 9669 struct SearchNonTrivialToInitializeField 9670 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9671 using Super = 9672 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9673 9674 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9675 9676 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9677 SourceLocation SL) { 9678 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9679 asDerived().visitArray(PDIK, AT, SL); 9680 return; 9681 } 9682 9683 Super::visitWithKind(PDIK, FT, SL); 9684 } 9685 9686 void visitARCStrong(QualType FT, SourceLocation SL) { 9687 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9688 } 9689 void visitARCWeak(QualType FT, SourceLocation SL) { 9690 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9691 } 9692 void visitStruct(QualType FT, SourceLocation SL) { 9693 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9694 visit(FD->getType(), FD->getLocation()); 9695 } 9696 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9697 const ArrayType *AT, SourceLocation SL) { 9698 visit(getContext().getBaseElementType(AT), SL); 9699 } 9700 void visitTrivial(QualType FT, SourceLocation SL) {} 9701 9702 static void diag(QualType RT, const Expr *E, Sema &S) { 9703 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9704 } 9705 9706 ASTContext &getContext() { return S.getASTContext(); } 9707 9708 const Expr *E; 9709 Sema &S; 9710 }; 9711 9712 struct SearchNonTrivialToCopyField 9713 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9714 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9715 9716 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9717 9718 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9719 SourceLocation SL) { 9720 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9721 asDerived().visitArray(PCK, AT, SL); 9722 return; 9723 } 9724 9725 Super::visitWithKind(PCK, FT, SL); 9726 } 9727 9728 void visitARCStrong(QualType FT, SourceLocation SL) { 9729 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9730 } 9731 void visitARCWeak(QualType FT, SourceLocation SL) { 9732 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9733 } 9734 void visitStruct(QualType FT, SourceLocation SL) { 9735 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9736 visit(FD->getType(), FD->getLocation()); 9737 } 9738 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9739 SourceLocation SL) { 9740 visit(getContext().getBaseElementType(AT), SL); 9741 } 9742 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9743 SourceLocation SL) {} 9744 void visitTrivial(QualType FT, SourceLocation SL) {} 9745 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9746 9747 static void diag(QualType RT, const Expr *E, Sema &S) { 9748 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9749 } 9750 9751 ASTContext &getContext() { return S.getASTContext(); } 9752 9753 const Expr *E; 9754 Sema &S; 9755 }; 9756 9757 } 9758 9759 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9760 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9761 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9762 9763 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9764 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9765 return false; 9766 9767 return doesExprLikelyComputeSize(BO->getLHS()) || 9768 doesExprLikelyComputeSize(BO->getRHS()); 9769 } 9770 9771 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9772 } 9773 9774 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9775 /// 9776 /// \code 9777 /// #define MACRO 0 9778 /// foo(MACRO); 9779 /// foo(0); 9780 /// \endcode 9781 /// 9782 /// This should return true for the first call to foo, but not for the second 9783 /// (regardless of whether foo is a macro or function). 9784 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9785 SourceLocation CallLoc, 9786 SourceLocation ArgLoc) { 9787 if (!CallLoc.isMacroID()) 9788 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9789 9790 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9791 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9792 } 9793 9794 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9795 /// last two arguments transposed. 9796 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9797 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9798 return; 9799 9800 const Expr *SizeArg = 9801 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9802 9803 auto isLiteralZero = [](const Expr *E) { 9804 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9805 }; 9806 9807 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9808 SourceLocation CallLoc = Call->getRParenLoc(); 9809 SourceManager &SM = S.getSourceManager(); 9810 if (isLiteralZero(SizeArg) && 9811 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9812 9813 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9814 9815 // Some platforms #define bzero to __builtin_memset. See if this is the 9816 // case, and if so, emit a better diagnostic. 9817 if (BId == Builtin::BIbzero || 9818 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9819 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9820 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9821 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9822 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9823 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9824 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9825 } 9826 return; 9827 } 9828 9829 // If the second argument to a memset is a sizeof expression and the third 9830 // isn't, this is also likely an error. This should catch 9831 // 'memset(buf, sizeof(buf), 0xff)'. 9832 if (BId == Builtin::BImemset && 9833 doesExprLikelyComputeSize(Call->getArg(1)) && 9834 !doesExprLikelyComputeSize(Call->getArg(2))) { 9835 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9836 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9837 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9838 return; 9839 } 9840 } 9841 9842 /// Check for dangerous or invalid arguments to memset(). 9843 /// 9844 /// This issues warnings on known problematic, dangerous or unspecified 9845 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9846 /// function calls. 9847 /// 9848 /// \param Call The call expression to diagnose. 9849 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9850 unsigned BId, 9851 IdentifierInfo *FnName) { 9852 assert(BId != 0); 9853 9854 // It is possible to have a non-standard definition of memset. Validate 9855 // we have enough arguments, and if not, abort further checking. 9856 unsigned ExpectedNumArgs = 9857 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9858 if (Call->getNumArgs() < ExpectedNumArgs) 9859 return; 9860 9861 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9862 BId == Builtin::BIstrndup ? 1 : 2); 9863 unsigned LenArg = 9864 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9865 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9866 9867 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9868 Call->getBeginLoc(), Call->getRParenLoc())) 9869 return; 9870 9871 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9872 CheckMemaccessSize(*this, BId, Call); 9873 9874 // We have special checking when the length is a sizeof expression. 9875 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9876 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9877 llvm::FoldingSetNodeID SizeOfArgID; 9878 9879 // Although widely used, 'bzero' is not a standard function. Be more strict 9880 // with the argument types before allowing diagnostics and only allow the 9881 // form bzero(ptr, sizeof(...)). 9882 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9883 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9884 return; 9885 9886 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9887 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9888 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9889 9890 QualType DestTy = Dest->getType(); 9891 QualType PointeeTy; 9892 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9893 PointeeTy = DestPtrTy->getPointeeType(); 9894 9895 // Never warn about void type pointers. This can be used to suppress 9896 // false positives. 9897 if (PointeeTy->isVoidType()) 9898 continue; 9899 9900 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9901 // actually comparing the expressions for equality. Because computing the 9902 // expression IDs can be expensive, we only do this if the diagnostic is 9903 // enabled. 9904 if (SizeOfArg && 9905 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9906 SizeOfArg->getExprLoc())) { 9907 // We only compute IDs for expressions if the warning is enabled, and 9908 // cache the sizeof arg's ID. 9909 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9910 SizeOfArg->Profile(SizeOfArgID, Context, true); 9911 llvm::FoldingSetNodeID DestID; 9912 Dest->Profile(DestID, Context, true); 9913 if (DestID == SizeOfArgID) { 9914 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9915 // over sizeof(src) as well. 9916 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9917 StringRef ReadableName = FnName->getName(); 9918 9919 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9920 if (UnaryOp->getOpcode() == UO_AddrOf) 9921 ActionIdx = 1; // If its an address-of operator, just remove it. 9922 if (!PointeeTy->isIncompleteType() && 9923 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9924 ActionIdx = 2; // If the pointee's size is sizeof(char), 9925 // suggest an explicit length. 9926 9927 // If the function is defined as a builtin macro, do not show macro 9928 // expansion. 9929 SourceLocation SL = SizeOfArg->getExprLoc(); 9930 SourceRange DSR = Dest->getSourceRange(); 9931 SourceRange SSR = SizeOfArg->getSourceRange(); 9932 SourceManager &SM = getSourceManager(); 9933 9934 if (SM.isMacroArgExpansion(SL)) { 9935 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9936 SL = SM.getSpellingLoc(SL); 9937 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9938 SM.getSpellingLoc(DSR.getEnd())); 9939 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9940 SM.getSpellingLoc(SSR.getEnd())); 9941 } 9942 9943 DiagRuntimeBehavior(SL, SizeOfArg, 9944 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9945 << ReadableName 9946 << PointeeTy 9947 << DestTy 9948 << DSR 9949 << SSR); 9950 DiagRuntimeBehavior(SL, SizeOfArg, 9951 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9952 << ActionIdx 9953 << SSR); 9954 9955 break; 9956 } 9957 } 9958 9959 // Also check for cases where the sizeof argument is the exact same 9960 // type as the memory argument, and where it points to a user-defined 9961 // record type. 9962 if (SizeOfArgTy != QualType()) { 9963 if (PointeeTy->isRecordType() && 9964 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9965 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9966 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9967 << FnName << SizeOfArgTy << ArgIdx 9968 << PointeeTy << Dest->getSourceRange() 9969 << LenExpr->getSourceRange()); 9970 break; 9971 } 9972 } 9973 } else if (DestTy->isArrayType()) { 9974 PointeeTy = DestTy; 9975 } 9976 9977 if (PointeeTy == QualType()) 9978 continue; 9979 9980 // Always complain about dynamic classes. 9981 bool IsContained; 9982 if (const CXXRecordDecl *ContainedRD = 9983 getContainedDynamicClass(PointeeTy, IsContained)) { 9984 9985 unsigned OperationType = 0; 9986 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9987 // "overwritten" if we're warning about the destination for any call 9988 // but memcmp; otherwise a verb appropriate to the call. 9989 if (ArgIdx != 0 || IsCmp) { 9990 if (BId == Builtin::BImemcpy) 9991 OperationType = 1; 9992 else if(BId == Builtin::BImemmove) 9993 OperationType = 2; 9994 else if (IsCmp) 9995 OperationType = 3; 9996 } 9997 9998 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9999 PDiag(diag::warn_dyn_class_memaccess) 10000 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10001 << IsContained << ContainedRD << OperationType 10002 << Call->getCallee()->getSourceRange()); 10003 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10004 BId != Builtin::BImemset) 10005 DiagRuntimeBehavior( 10006 Dest->getExprLoc(), Dest, 10007 PDiag(diag::warn_arc_object_memaccess) 10008 << ArgIdx << FnName << PointeeTy 10009 << Call->getCallee()->getSourceRange()); 10010 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10011 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10012 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10013 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10014 PDiag(diag::warn_cstruct_memaccess) 10015 << ArgIdx << FnName << PointeeTy << 0); 10016 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10017 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10018 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10019 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10020 PDiag(diag::warn_cstruct_memaccess) 10021 << ArgIdx << FnName << PointeeTy << 1); 10022 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10023 } else { 10024 continue; 10025 } 10026 } else 10027 continue; 10028 10029 DiagRuntimeBehavior( 10030 Dest->getExprLoc(), Dest, 10031 PDiag(diag::note_bad_memaccess_silence) 10032 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10033 break; 10034 } 10035 } 10036 10037 // A little helper routine: ignore addition and subtraction of integer literals. 10038 // This intentionally does not ignore all integer constant expressions because 10039 // we don't want to remove sizeof(). 10040 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10041 Ex = Ex->IgnoreParenCasts(); 10042 10043 while (true) { 10044 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10045 if (!BO || !BO->isAdditiveOp()) 10046 break; 10047 10048 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10049 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10050 10051 if (isa<IntegerLiteral>(RHS)) 10052 Ex = LHS; 10053 else if (isa<IntegerLiteral>(LHS)) 10054 Ex = RHS; 10055 else 10056 break; 10057 } 10058 10059 return Ex; 10060 } 10061 10062 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10063 ASTContext &Context) { 10064 // Only handle constant-sized or VLAs, but not flexible members. 10065 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10066 // Only issue the FIXIT for arrays of size > 1. 10067 if (CAT->getSize().getSExtValue() <= 1) 10068 return false; 10069 } else if (!Ty->isVariableArrayType()) { 10070 return false; 10071 } 10072 return true; 10073 } 10074 10075 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10076 // be the size of the source, instead of the destination. 10077 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10078 IdentifierInfo *FnName) { 10079 10080 // Don't crash if the user has the wrong number of arguments 10081 unsigned NumArgs = Call->getNumArgs(); 10082 if ((NumArgs != 3) && (NumArgs != 4)) 10083 return; 10084 10085 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10086 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10087 const Expr *CompareWithSrc = nullptr; 10088 10089 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10090 Call->getBeginLoc(), Call->getRParenLoc())) 10091 return; 10092 10093 // Look for 'strlcpy(dst, x, sizeof(x))' 10094 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10095 CompareWithSrc = Ex; 10096 else { 10097 // Look for 'strlcpy(dst, x, strlen(x))' 10098 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10099 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10100 SizeCall->getNumArgs() == 1) 10101 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10102 } 10103 } 10104 10105 if (!CompareWithSrc) 10106 return; 10107 10108 // Determine if the argument to sizeof/strlen is equal to the source 10109 // argument. In principle there's all kinds of things you could do 10110 // here, for instance creating an == expression and evaluating it with 10111 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10112 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10113 if (!SrcArgDRE) 10114 return; 10115 10116 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10117 if (!CompareWithSrcDRE || 10118 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10119 return; 10120 10121 const Expr *OriginalSizeArg = Call->getArg(2); 10122 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10123 << OriginalSizeArg->getSourceRange() << FnName; 10124 10125 // Output a FIXIT hint if the destination is an array (rather than a 10126 // pointer to an array). This could be enhanced to handle some 10127 // pointers if we know the actual size, like if DstArg is 'array+2' 10128 // we could say 'sizeof(array)-2'. 10129 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10130 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10131 return; 10132 10133 SmallString<128> sizeString; 10134 llvm::raw_svector_ostream OS(sizeString); 10135 OS << "sizeof("; 10136 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10137 OS << ")"; 10138 10139 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10140 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10141 OS.str()); 10142 } 10143 10144 /// Check if two expressions refer to the same declaration. 10145 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10146 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10147 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10148 return D1->getDecl() == D2->getDecl(); 10149 return false; 10150 } 10151 10152 static const Expr *getStrlenExprArg(const Expr *E) { 10153 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10154 const FunctionDecl *FD = CE->getDirectCallee(); 10155 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10156 return nullptr; 10157 return CE->getArg(0)->IgnoreParenCasts(); 10158 } 10159 return nullptr; 10160 } 10161 10162 // Warn on anti-patterns as the 'size' argument to strncat. 10163 // The correct size argument should look like following: 10164 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10165 void Sema::CheckStrncatArguments(const CallExpr *CE, 10166 IdentifierInfo *FnName) { 10167 // Don't crash if the user has the wrong number of arguments. 10168 if (CE->getNumArgs() < 3) 10169 return; 10170 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10171 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10172 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10173 10174 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10175 CE->getRParenLoc())) 10176 return; 10177 10178 // Identify common expressions, which are wrongly used as the size argument 10179 // to strncat and may lead to buffer overflows. 10180 unsigned PatternType = 0; 10181 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10182 // - sizeof(dst) 10183 if (referToTheSameDecl(SizeOfArg, DstArg)) 10184 PatternType = 1; 10185 // - sizeof(src) 10186 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10187 PatternType = 2; 10188 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10189 if (BE->getOpcode() == BO_Sub) { 10190 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10191 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10192 // - sizeof(dst) - strlen(dst) 10193 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10194 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10195 PatternType = 1; 10196 // - sizeof(src) - (anything) 10197 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10198 PatternType = 2; 10199 } 10200 } 10201 10202 if (PatternType == 0) 10203 return; 10204 10205 // Generate the diagnostic. 10206 SourceLocation SL = LenArg->getBeginLoc(); 10207 SourceRange SR = LenArg->getSourceRange(); 10208 SourceManager &SM = getSourceManager(); 10209 10210 // If the function is defined as a builtin macro, do not show macro expansion. 10211 if (SM.isMacroArgExpansion(SL)) { 10212 SL = SM.getSpellingLoc(SL); 10213 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10214 SM.getSpellingLoc(SR.getEnd())); 10215 } 10216 10217 // Check if the destination is an array (rather than a pointer to an array). 10218 QualType DstTy = DstArg->getType(); 10219 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10220 Context); 10221 if (!isKnownSizeArray) { 10222 if (PatternType == 1) 10223 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10224 else 10225 Diag(SL, diag::warn_strncat_src_size) << SR; 10226 return; 10227 } 10228 10229 if (PatternType == 1) 10230 Diag(SL, diag::warn_strncat_large_size) << SR; 10231 else 10232 Diag(SL, diag::warn_strncat_src_size) << SR; 10233 10234 SmallString<128> sizeString; 10235 llvm::raw_svector_ostream OS(sizeString); 10236 OS << "sizeof("; 10237 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10238 OS << ") - "; 10239 OS << "strlen("; 10240 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10241 OS << ") - 1"; 10242 10243 Diag(SL, diag::note_strncat_wrong_size) 10244 << FixItHint::CreateReplacement(SR, OS.str()); 10245 } 10246 10247 namespace { 10248 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10249 const UnaryOperator *UnaryExpr, 10250 const VarDecl *Var) { 10251 StorageClass Class = Var->getStorageClass(); 10252 if (Class == StorageClass::SC_Extern || 10253 Class == StorageClass::SC_PrivateExtern || 10254 Var->getType()->isReferenceType()) 10255 return; 10256 10257 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10258 << CalleeName << Var; 10259 } 10260 10261 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10262 const UnaryOperator *UnaryExpr, const Decl *D) { 10263 if (const auto *Field = dyn_cast<FieldDecl>(D)) 10264 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10265 << CalleeName << Field; 10266 } 10267 10268 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10269 const UnaryOperator *UnaryExpr) { 10270 if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf) 10271 return; 10272 10273 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) 10274 if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl())) 10275 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var); 10276 10277 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10278 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10279 Lvalue->getMemberDecl()); 10280 } 10281 10282 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10283 const DeclRefExpr *Lvalue) { 10284 if (!Lvalue->getType()->isArrayType()) 10285 return; 10286 10287 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10288 if (Var == nullptr) 10289 return; 10290 10291 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10292 << CalleeName << Var; 10293 } 10294 } // namespace 10295 10296 /// Alerts the user that they are attempting to free a non-malloc'd object. 10297 void Sema::CheckFreeArguments(const CallExpr *E) { 10298 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10299 const std::string CalleeName = 10300 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10301 10302 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10303 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10304 10305 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10306 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10307 } 10308 10309 void 10310 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10311 SourceLocation ReturnLoc, 10312 bool isObjCMethod, 10313 const AttrVec *Attrs, 10314 const FunctionDecl *FD) { 10315 // Check if the return value is null but should not be. 10316 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10317 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10318 CheckNonNullExpr(*this, RetValExp)) 10319 Diag(ReturnLoc, diag::warn_null_ret) 10320 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10321 10322 // C++11 [basic.stc.dynamic.allocation]p4: 10323 // If an allocation function declared with a non-throwing 10324 // exception-specification fails to allocate storage, it shall return 10325 // a null pointer. Any other allocation function that fails to allocate 10326 // storage shall indicate failure only by throwing an exception [...] 10327 if (FD) { 10328 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10329 if (Op == OO_New || Op == OO_Array_New) { 10330 const FunctionProtoType *Proto 10331 = FD->getType()->castAs<FunctionProtoType>(); 10332 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10333 CheckNonNullExpr(*this, RetValExp)) 10334 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10335 << FD << getLangOpts().CPlusPlus11; 10336 } 10337 } 10338 10339 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10340 // here prevent the user from using a PPC MMA type as trailing return type. 10341 if (Context.getTargetInfo().getTriple().isPPC64()) 10342 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10343 } 10344 10345 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10346 10347 /// Check for comparisons of floating point operands using != and ==. 10348 /// Issue a warning if these are no self-comparisons, as they are not likely 10349 /// to do what the programmer intended. 10350 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10351 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10352 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10353 10354 // Special case: check for x == x (which is OK). 10355 // Do not emit warnings for such cases. 10356 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10357 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10358 if (DRL->getDecl() == DRR->getDecl()) 10359 return; 10360 10361 // Special case: check for comparisons against literals that can be exactly 10362 // represented by APFloat. In such cases, do not emit a warning. This 10363 // is a heuristic: often comparison against such literals are used to 10364 // detect if a value in a variable has not changed. This clearly can 10365 // lead to false negatives. 10366 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10367 if (FLL->isExact()) 10368 return; 10369 } else 10370 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10371 if (FLR->isExact()) 10372 return; 10373 10374 // Check for comparisons with builtin types. 10375 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10376 if (CL->getBuiltinCallee()) 10377 return; 10378 10379 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10380 if (CR->getBuiltinCallee()) 10381 return; 10382 10383 // Emit the diagnostic. 10384 Diag(Loc, diag::warn_floatingpoint_eq) 10385 << LHS->getSourceRange() << RHS->getSourceRange(); 10386 } 10387 10388 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10389 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10390 10391 namespace { 10392 10393 /// Structure recording the 'active' range of an integer-valued 10394 /// expression. 10395 struct IntRange { 10396 /// The number of bits active in the int. Note that this includes exactly one 10397 /// sign bit if !NonNegative. 10398 unsigned Width; 10399 10400 /// True if the int is known not to have negative values. If so, all leading 10401 /// bits before Width are known zero, otherwise they are known to be the 10402 /// same as the MSB within Width. 10403 bool NonNegative; 10404 10405 IntRange(unsigned Width, bool NonNegative) 10406 : Width(Width), NonNegative(NonNegative) {} 10407 10408 /// Number of bits excluding the sign bit. 10409 unsigned valueBits() const { 10410 return NonNegative ? Width : Width - 1; 10411 } 10412 10413 /// Returns the range of the bool type. 10414 static IntRange forBoolType() { 10415 return IntRange(1, true); 10416 } 10417 10418 /// Returns the range of an opaque value of the given integral type. 10419 static IntRange forValueOfType(ASTContext &C, QualType T) { 10420 return forValueOfCanonicalType(C, 10421 T->getCanonicalTypeInternal().getTypePtr()); 10422 } 10423 10424 /// Returns the range of an opaque value of a canonical integral type. 10425 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10426 assert(T->isCanonicalUnqualified()); 10427 10428 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10429 T = VT->getElementType().getTypePtr(); 10430 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10431 T = CT->getElementType().getTypePtr(); 10432 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10433 T = AT->getValueType().getTypePtr(); 10434 10435 if (!C.getLangOpts().CPlusPlus) { 10436 // For enum types in C code, use the underlying datatype. 10437 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10438 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10439 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10440 // For enum types in C++, use the known bit width of the enumerators. 10441 EnumDecl *Enum = ET->getDecl(); 10442 // In C++11, enums can have a fixed underlying type. Use this type to 10443 // compute the range. 10444 if (Enum->isFixed()) { 10445 return IntRange(C.getIntWidth(QualType(T, 0)), 10446 !ET->isSignedIntegerOrEnumerationType()); 10447 } 10448 10449 unsigned NumPositive = Enum->getNumPositiveBits(); 10450 unsigned NumNegative = Enum->getNumNegativeBits(); 10451 10452 if (NumNegative == 0) 10453 return IntRange(NumPositive, true/*NonNegative*/); 10454 else 10455 return IntRange(std::max(NumPositive + 1, NumNegative), 10456 false/*NonNegative*/); 10457 } 10458 10459 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10460 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10461 10462 const BuiltinType *BT = cast<BuiltinType>(T); 10463 assert(BT->isInteger()); 10464 10465 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10466 } 10467 10468 /// Returns the "target" range of a canonical integral type, i.e. 10469 /// the range of values expressible in the type. 10470 /// 10471 /// This matches forValueOfCanonicalType except that enums have the 10472 /// full range of their type, not the range of their enumerators. 10473 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10474 assert(T->isCanonicalUnqualified()); 10475 10476 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10477 T = VT->getElementType().getTypePtr(); 10478 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10479 T = CT->getElementType().getTypePtr(); 10480 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10481 T = AT->getValueType().getTypePtr(); 10482 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10483 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10484 10485 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10486 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10487 10488 const BuiltinType *BT = cast<BuiltinType>(T); 10489 assert(BT->isInteger()); 10490 10491 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10492 } 10493 10494 /// Returns the supremum of two ranges: i.e. their conservative merge. 10495 static IntRange join(IntRange L, IntRange R) { 10496 bool Unsigned = L.NonNegative && R.NonNegative; 10497 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10498 L.NonNegative && R.NonNegative); 10499 } 10500 10501 /// Return the range of a bitwise-AND of the two ranges. 10502 static IntRange bit_and(IntRange L, IntRange R) { 10503 unsigned Bits = std::max(L.Width, R.Width); 10504 bool NonNegative = false; 10505 if (L.NonNegative) { 10506 Bits = std::min(Bits, L.Width); 10507 NonNegative = true; 10508 } 10509 if (R.NonNegative) { 10510 Bits = std::min(Bits, R.Width); 10511 NonNegative = true; 10512 } 10513 return IntRange(Bits, NonNegative); 10514 } 10515 10516 /// Return the range of a sum of the two ranges. 10517 static IntRange sum(IntRange L, IntRange R) { 10518 bool Unsigned = L.NonNegative && R.NonNegative; 10519 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10520 Unsigned); 10521 } 10522 10523 /// Return the range of a difference of the two ranges. 10524 static IntRange difference(IntRange L, IntRange R) { 10525 // We need a 1-bit-wider range if: 10526 // 1) LHS can be negative: least value can be reduced. 10527 // 2) RHS can be negative: greatest value can be increased. 10528 bool CanWiden = !L.NonNegative || !R.NonNegative; 10529 bool Unsigned = L.NonNegative && R.Width == 0; 10530 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10531 !Unsigned, 10532 Unsigned); 10533 } 10534 10535 /// Return the range of a product of the two ranges. 10536 static IntRange product(IntRange L, IntRange R) { 10537 // If both LHS and RHS can be negative, we can form 10538 // -2^L * -2^R = 2^(L + R) 10539 // which requires L + R + 1 value bits to represent. 10540 bool CanWiden = !L.NonNegative && !R.NonNegative; 10541 bool Unsigned = L.NonNegative && R.NonNegative; 10542 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10543 Unsigned); 10544 } 10545 10546 /// Return the range of a remainder operation between the two ranges. 10547 static IntRange rem(IntRange L, IntRange R) { 10548 // The result of a remainder can't be larger than the result of 10549 // either side. The sign of the result is the sign of the LHS. 10550 bool Unsigned = L.NonNegative; 10551 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10552 Unsigned); 10553 } 10554 }; 10555 10556 } // namespace 10557 10558 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10559 unsigned MaxWidth) { 10560 if (value.isSigned() && value.isNegative()) 10561 return IntRange(value.getMinSignedBits(), false); 10562 10563 if (value.getBitWidth() > MaxWidth) 10564 value = value.trunc(MaxWidth); 10565 10566 // isNonNegative() just checks the sign bit without considering 10567 // signedness. 10568 return IntRange(value.getActiveBits(), true); 10569 } 10570 10571 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10572 unsigned MaxWidth) { 10573 if (result.isInt()) 10574 return GetValueRange(C, result.getInt(), MaxWidth); 10575 10576 if (result.isVector()) { 10577 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10578 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10579 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10580 R = IntRange::join(R, El); 10581 } 10582 return R; 10583 } 10584 10585 if (result.isComplexInt()) { 10586 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10587 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10588 return IntRange::join(R, I); 10589 } 10590 10591 // This can happen with lossless casts to intptr_t of "based" lvalues. 10592 // Assume it might use arbitrary bits. 10593 // FIXME: The only reason we need to pass the type in here is to get 10594 // the sign right on this one case. It would be nice if APValue 10595 // preserved this. 10596 assert(result.isLValue() || result.isAddrLabelDiff()); 10597 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10598 } 10599 10600 static QualType GetExprType(const Expr *E) { 10601 QualType Ty = E->getType(); 10602 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10603 Ty = AtomicRHS->getValueType(); 10604 return Ty; 10605 } 10606 10607 /// Pseudo-evaluate the given integer expression, estimating the 10608 /// range of values it might take. 10609 /// 10610 /// \param MaxWidth The width to which the value will be truncated. 10611 /// \param Approximate If \c true, return a likely range for the result: in 10612 /// particular, assume that aritmetic on narrower types doesn't leave 10613 /// those types. If \c false, return a range including all possible 10614 /// result values. 10615 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10616 bool InConstantContext, bool Approximate) { 10617 E = E->IgnoreParens(); 10618 10619 // Try a full evaluation first. 10620 Expr::EvalResult result; 10621 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10622 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10623 10624 // I think we only want to look through implicit casts here; if the 10625 // user has an explicit widening cast, we should treat the value as 10626 // being of the new, wider type. 10627 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10628 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10629 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10630 Approximate); 10631 10632 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10633 10634 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10635 CE->getCastKind() == CK_BooleanToSignedIntegral; 10636 10637 // Assume that non-integer casts can span the full range of the type. 10638 if (!isIntegerCast) 10639 return OutputTypeRange; 10640 10641 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10642 std::min(MaxWidth, OutputTypeRange.Width), 10643 InConstantContext, Approximate); 10644 10645 // Bail out if the subexpr's range is as wide as the cast type. 10646 if (SubRange.Width >= OutputTypeRange.Width) 10647 return OutputTypeRange; 10648 10649 // Otherwise, we take the smaller width, and we're non-negative if 10650 // either the output type or the subexpr is. 10651 return IntRange(SubRange.Width, 10652 SubRange.NonNegative || OutputTypeRange.NonNegative); 10653 } 10654 10655 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10656 // If we can fold the condition, just take that operand. 10657 bool CondResult; 10658 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10659 return GetExprRange(C, 10660 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10661 MaxWidth, InConstantContext, Approximate); 10662 10663 // Otherwise, conservatively merge. 10664 // GetExprRange requires an integer expression, but a throw expression 10665 // results in a void type. 10666 Expr *E = CO->getTrueExpr(); 10667 IntRange L = E->getType()->isVoidType() 10668 ? IntRange{0, true} 10669 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10670 E = CO->getFalseExpr(); 10671 IntRange R = E->getType()->isVoidType() 10672 ? IntRange{0, true} 10673 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10674 return IntRange::join(L, R); 10675 } 10676 10677 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10678 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10679 10680 switch (BO->getOpcode()) { 10681 case BO_Cmp: 10682 llvm_unreachable("builtin <=> should have class type"); 10683 10684 // Boolean-valued operations are single-bit and positive. 10685 case BO_LAnd: 10686 case BO_LOr: 10687 case BO_LT: 10688 case BO_GT: 10689 case BO_LE: 10690 case BO_GE: 10691 case BO_EQ: 10692 case BO_NE: 10693 return IntRange::forBoolType(); 10694 10695 // The type of the assignments is the type of the LHS, so the RHS 10696 // is not necessarily the same type. 10697 case BO_MulAssign: 10698 case BO_DivAssign: 10699 case BO_RemAssign: 10700 case BO_AddAssign: 10701 case BO_SubAssign: 10702 case BO_XorAssign: 10703 case BO_OrAssign: 10704 // TODO: bitfields? 10705 return IntRange::forValueOfType(C, GetExprType(E)); 10706 10707 // Simple assignments just pass through the RHS, which will have 10708 // been coerced to the LHS type. 10709 case BO_Assign: 10710 // TODO: bitfields? 10711 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10712 Approximate); 10713 10714 // Operations with opaque sources are black-listed. 10715 case BO_PtrMemD: 10716 case BO_PtrMemI: 10717 return IntRange::forValueOfType(C, GetExprType(E)); 10718 10719 // Bitwise-and uses the *infinum* of the two source ranges. 10720 case BO_And: 10721 case BO_AndAssign: 10722 Combine = IntRange::bit_and; 10723 break; 10724 10725 // Left shift gets black-listed based on a judgement call. 10726 case BO_Shl: 10727 // ...except that we want to treat '1 << (blah)' as logically 10728 // positive. It's an important idiom. 10729 if (IntegerLiteral *I 10730 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10731 if (I->getValue() == 1) { 10732 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10733 return IntRange(R.Width, /*NonNegative*/ true); 10734 } 10735 } 10736 LLVM_FALLTHROUGH; 10737 10738 case BO_ShlAssign: 10739 return IntRange::forValueOfType(C, GetExprType(E)); 10740 10741 // Right shift by a constant can narrow its left argument. 10742 case BO_Shr: 10743 case BO_ShrAssign: { 10744 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10745 Approximate); 10746 10747 // If the shift amount is a positive constant, drop the width by 10748 // that much. 10749 if (Optional<llvm::APSInt> shift = 10750 BO->getRHS()->getIntegerConstantExpr(C)) { 10751 if (shift->isNonNegative()) { 10752 unsigned zext = shift->getZExtValue(); 10753 if (zext >= L.Width) 10754 L.Width = (L.NonNegative ? 0 : 1); 10755 else 10756 L.Width -= zext; 10757 } 10758 } 10759 10760 return L; 10761 } 10762 10763 // Comma acts as its right operand. 10764 case BO_Comma: 10765 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10766 Approximate); 10767 10768 case BO_Add: 10769 if (!Approximate) 10770 Combine = IntRange::sum; 10771 break; 10772 10773 case BO_Sub: 10774 if (BO->getLHS()->getType()->isPointerType()) 10775 return IntRange::forValueOfType(C, GetExprType(E)); 10776 if (!Approximate) 10777 Combine = IntRange::difference; 10778 break; 10779 10780 case BO_Mul: 10781 if (!Approximate) 10782 Combine = IntRange::product; 10783 break; 10784 10785 // The width of a division result is mostly determined by the size 10786 // of the LHS. 10787 case BO_Div: { 10788 // Don't 'pre-truncate' the operands. 10789 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10790 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 10791 Approximate); 10792 10793 // If the divisor is constant, use that. 10794 if (Optional<llvm::APSInt> divisor = 10795 BO->getRHS()->getIntegerConstantExpr(C)) { 10796 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10797 if (log2 >= L.Width) 10798 L.Width = (L.NonNegative ? 0 : 1); 10799 else 10800 L.Width = std::min(L.Width - log2, MaxWidth); 10801 return L; 10802 } 10803 10804 // Otherwise, just use the LHS's width. 10805 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10806 // could be -1. 10807 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 10808 Approximate); 10809 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10810 } 10811 10812 case BO_Rem: 10813 Combine = IntRange::rem; 10814 break; 10815 10816 // The default behavior is okay for these. 10817 case BO_Xor: 10818 case BO_Or: 10819 break; 10820 } 10821 10822 // Combine the two ranges, but limit the result to the type in which we 10823 // performed the computation. 10824 QualType T = GetExprType(E); 10825 unsigned opWidth = C.getIntWidth(T); 10826 IntRange L = 10827 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10828 IntRange R = 10829 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10830 IntRange C = Combine(L, R); 10831 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10832 C.Width = std::min(C.Width, MaxWidth); 10833 return C; 10834 } 10835 10836 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10837 switch (UO->getOpcode()) { 10838 // Boolean-valued operations are white-listed. 10839 case UO_LNot: 10840 return IntRange::forBoolType(); 10841 10842 // Operations with opaque sources are black-listed. 10843 case UO_Deref: 10844 case UO_AddrOf: // should be impossible 10845 return IntRange::forValueOfType(C, GetExprType(E)); 10846 10847 default: 10848 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 10849 Approximate); 10850 } 10851 } 10852 10853 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10854 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 10855 Approximate); 10856 10857 if (const auto *BitField = E->getSourceBitField()) 10858 return IntRange(BitField->getBitWidthValue(C), 10859 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10860 10861 return IntRange::forValueOfType(C, GetExprType(E)); 10862 } 10863 10864 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10865 bool InConstantContext, bool Approximate) { 10866 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 10867 Approximate); 10868 } 10869 10870 /// Checks whether the given value, which currently has the given 10871 /// source semantics, has the same value when coerced through the 10872 /// target semantics. 10873 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10874 const llvm::fltSemantics &Src, 10875 const llvm::fltSemantics &Tgt) { 10876 llvm::APFloat truncated = value; 10877 10878 bool ignored; 10879 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10880 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10881 10882 return truncated.bitwiseIsEqual(value); 10883 } 10884 10885 /// Checks whether the given value, which currently has the given 10886 /// source semantics, has the same value when coerced through the 10887 /// target semantics. 10888 /// 10889 /// The value might be a vector of floats (or a complex number). 10890 static bool IsSameFloatAfterCast(const APValue &value, 10891 const llvm::fltSemantics &Src, 10892 const llvm::fltSemantics &Tgt) { 10893 if (value.isFloat()) 10894 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10895 10896 if (value.isVector()) { 10897 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10898 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10899 return false; 10900 return true; 10901 } 10902 10903 assert(value.isComplexFloat()); 10904 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10905 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10906 } 10907 10908 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10909 bool IsListInit = false); 10910 10911 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10912 // Suppress cases where we are comparing against an enum constant. 10913 if (const DeclRefExpr *DR = 10914 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10915 if (isa<EnumConstantDecl>(DR->getDecl())) 10916 return true; 10917 10918 // Suppress cases where the value is expanded from a macro, unless that macro 10919 // is how a language represents a boolean literal. This is the case in both C 10920 // and Objective-C. 10921 SourceLocation BeginLoc = E->getBeginLoc(); 10922 if (BeginLoc.isMacroID()) { 10923 StringRef MacroName = Lexer::getImmediateMacroName( 10924 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10925 return MacroName != "YES" && MacroName != "NO" && 10926 MacroName != "true" && MacroName != "false"; 10927 } 10928 10929 return false; 10930 } 10931 10932 static bool isKnownToHaveUnsignedValue(Expr *E) { 10933 return E->getType()->isIntegerType() && 10934 (!E->getType()->isSignedIntegerType() || 10935 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10936 } 10937 10938 namespace { 10939 /// The promoted range of values of a type. In general this has the 10940 /// following structure: 10941 /// 10942 /// |-----------| . . . |-----------| 10943 /// ^ ^ ^ ^ 10944 /// Min HoleMin HoleMax Max 10945 /// 10946 /// ... where there is only a hole if a signed type is promoted to unsigned 10947 /// (in which case Min and Max are the smallest and largest representable 10948 /// values). 10949 struct PromotedRange { 10950 // Min, or HoleMax if there is a hole. 10951 llvm::APSInt PromotedMin; 10952 // Max, or HoleMin if there is a hole. 10953 llvm::APSInt PromotedMax; 10954 10955 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10956 if (R.Width == 0) 10957 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10958 else if (R.Width >= BitWidth && !Unsigned) { 10959 // Promotion made the type *narrower*. This happens when promoting 10960 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10961 // Treat all values of 'signed int' as being in range for now. 10962 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10963 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10964 } else { 10965 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10966 .extOrTrunc(BitWidth); 10967 PromotedMin.setIsUnsigned(Unsigned); 10968 10969 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10970 .extOrTrunc(BitWidth); 10971 PromotedMax.setIsUnsigned(Unsigned); 10972 } 10973 } 10974 10975 // Determine whether this range is contiguous (has no hole). 10976 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10977 10978 // Where a constant value is within the range. 10979 enum ComparisonResult { 10980 LT = 0x1, 10981 LE = 0x2, 10982 GT = 0x4, 10983 GE = 0x8, 10984 EQ = 0x10, 10985 NE = 0x20, 10986 InRangeFlag = 0x40, 10987 10988 Less = LE | LT | NE, 10989 Min = LE | InRangeFlag, 10990 InRange = InRangeFlag, 10991 Max = GE | InRangeFlag, 10992 Greater = GE | GT | NE, 10993 10994 OnlyValue = LE | GE | EQ | InRangeFlag, 10995 InHole = NE 10996 }; 10997 10998 ComparisonResult compare(const llvm::APSInt &Value) const { 10999 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11000 Value.isUnsigned() == PromotedMin.isUnsigned()); 11001 if (!isContiguous()) { 11002 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11003 if (Value.isMinValue()) return Min; 11004 if (Value.isMaxValue()) return Max; 11005 if (Value >= PromotedMin) return InRange; 11006 if (Value <= PromotedMax) return InRange; 11007 return InHole; 11008 } 11009 11010 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11011 case -1: return Less; 11012 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11013 case 1: 11014 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11015 case -1: return InRange; 11016 case 0: return Max; 11017 case 1: return Greater; 11018 } 11019 } 11020 11021 llvm_unreachable("impossible compare result"); 11022 } 11023 11024 static llvm::Optional<StringRef> 11025 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11026 if (Op == BO_Cmp) { 11027 ComparisonResult LTFlag = LT, GTFlag = GT; 11028 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11029 11030 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11031 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11032 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11033 return llvm::None; 11034 } 11035 11036 ComparisonResult TrueFlag, FalseFlag; 11037 if (Op == BO_EQ) { 11038 TrueFlag = EQ; 11039 FalseFlag = NE; 11040 } else if (Op == BO_NE) { 11041 TrueFlag = NE; 11042 FalseFlag = EQ; 11043 } else { 11044 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11045 TrueFlag = LT; 11046 FalseFlag = GE; 11047 } else { 11048 TrueFlag = GT; 11049 FalseFlag = LE; 11050 } 11051 if (Op == BO_GE || Op == BO_LE) 11052 std::swap(TrueFlag, FalseFlag); 11053 } 11054 if (R & TrueFlag) 11055 return StringRef("true"); 11056 if (R & FalseFlag) 11057 return StringRef("false"); 11058 return llvm::None; 11059 } 11060 }; 11061 } 11062 11063 static bool HasEnumType(Expr *E) { 11064 // Strip off implicit integral promotions. 11065 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11066 if (ICE->getCastKind() != CK_IntegralCast && 11067 ICE->getCastKind() != CK_NoOp) 11068 break; 11069 E = ICE->getSubExpr(); 11070 } 11071 11072 return E->getType()->isEnumeralType(); 11073 } 11074 11075 static int classifyConstantValue(Expr *Constant) { 11076 // The values of this enumeration are used in the diagnostics 11077 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11078 enum ConstantValueKind { 11079 Miscellaneous = 0, 11080 LiteralTrue, 11081 LiteralFalse 11082 }; 11083 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11084 return BL->getValue() ? ConstantValueKind::LiteralTrue 11085 : ConstantValueKind::LiteralFalse; 11086 return ConstantValueKind::Miscellaneous; 11087 } 11088 11089 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11090 Expr *Constant, Expr *Other, 11091 const llvm::APSInt &Value, 11092 bool RhsConstant) { 11093 if (S.inTemplateInstantiation()) 11094 return false; 11095 11096 Expr *OriginalOther = Other; 11097 11098 Constant = Constant->IgnoreParenImpCasts(); 11099 Other = Other->IgnoreParenImpCasts(); 11100 11101 // Suppress warnings on tautological comparisons between values of the same 11102 // enumeration type. There are only two ways we could warn on this: 11103 // - If the constant is outside the range of representable values of 11104 // the enumeration. In such a case, we should warn about the cast 11105 // to enumeration type, not about the comparison. 11106 // - If the constant is the maximum / minimum in-range value. For an 11107 // enumeratin type, such comparisons can be meaningful and useful. 11108 if (Constant->getType()->isEnumeralType() && 11109 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11110 return false; 11111 11112 IntRange OtherValueRange = GetExprRange( 11113 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11114 11115 QualType OtherT = Other->getType(); 11116 if (const auto *AT = OtherT->getAs<AtomicType>()) 11117 OtherT = AT->getValueType(); 11118 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11119 11120 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11121 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11122 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11123 S.NSAPIObj->isObjCBOOLType(OtherT) && 11124 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11125 11126 // Whether we're treating Other as being a bool because of the form of 11127 // expression despite it having another type (typically 'int' in C). 11128 bool OtherIsBooleanDespiteType = 11129 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11130 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11131 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11132 11133 // Check if all values in the range of possible values of this expression 11134 // lead to the same comparison outcome. 11135 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11136 Value.isUnsigned()); 11137 auto Cmp = OtherPromotedValueRange.compare(Value); 11138 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11139 if (!Result) 11140 return false; 11141 11142 // Also consider the range determined by the type alone. This allows us to 11143 // classify the warning under the proper diagnostic group. 11144 bool TautologicalTypeCompare = false; 11145 { 11146 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11147 Value.isUnsigned()); 11148 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11149 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11150 RhsConstant)) { 11151 TautologicalTypeCompare = true; 11152 Cmp = TypeCmp; 11153 Result = TypeResult; 11154 } 11155 } 11156 11157 // Don't warn if the non-constant operand actually always evaluates to the 11158 // same value. 11159 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11160 return false; 11161 11162 // Suppress the diagnostic for an in-range comparison if the constant comes 11163 // from a macro or enumerator. We don't want to diagnose 11164 // 11165 // some_long_value <= INT_MAX 11166 // 11167 // when sizeof(int) == sizeof(long). 11168 bool InRange = Cmp & PromotedRange::InRangeFlag; 11169 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11170 return false; 11171 11172 // A comparison of an unsigned bit-field against 0 is really a type problem, 11173 // even though at the type level the bit-field might promote to 'signed int'. 11174 if (Other->refersToBitField() && InRange && Value == 0 && 11175 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11176 TautologicalTypeCompare = true; 11177 11178 // If this is a comparison to an enum constant, include that 11179 // constant in the diagnostic. 11180 const EnumConstantDecl *ED = nullptr; 11181 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11182 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11183 11184 // Should be enough for uint128 (39 decimal digits) 11185 SmallString<64> PrettySourceValue; 11186 llvm::raw_svector_ostream OS(PrettySourceValue); 11187 if (ED) { 11188 OS << '\'' << *ED << "' (" << Value << ")"; 11189 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11190 Constant->IgnoreParenImpCasts())) { 11191 OS << (BL->getValue() ? "YES" : "NO"); 11192 } else { 11193 OS << Value; 11194 } 11195 11196 if (!TautologicalTypeCompare) { 11197 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11198 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11199 << E->getOpcodeStr() << OS.str() << *Result 11200 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11201 return true; 11202 } 11203 11204 if (IsObjCSignedCharBool) { 11205 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11206 S.PDiag(diag::warn_tautological_compare_objc_bool) 11207 << OS.str() << *Result); 11208 return true; 11209 } 11210 11211 // FIXME: We use a somewhat different formatting for the in-range cases and 11212 // cases involving boolean values for historical reasons. We should pick a 11213 // consistent way of presenting these diagnostics. 11214 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11215 11216 S.DiagRuntimeBehavior( 11217 E->getOperatorLoc(), E, 11218 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11219 : diag::warn_tautological_bool_compare) 11220 << OS.str() << classifyConstantValue(Constant) << OtherT 11221 << OtherIsBooleanDespiteType << *Result 11222 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11223 } else { 11224 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11225 ? (HasEnumType(OriginalOther) 11226 ? diag::warn_unsigned_enum_always_true_comparison 11227 : diag::warn_unsigned_always_true_comparison) 11228 : diag::warn_tautological_constant_compare; 11229 11230 S.Diag(E->getOperatorLoc(), Diag) 11231 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11232 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11233 } 11234 11235 return true; 11236 } 11237 11238 /// Analyze the operands of the given comparison. Implements the 11239 /// fallback case from AnalyzeComparison. 11240 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11241 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11242 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11243 } 11244 11245 /// Implements -Wsign-compare. 11246 /// 11247 /// \param E the binary operator to check for warnings 11248 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11249 // The type the comparison is being performed in. 11250 QualType T = E->getLHS()->getType(); 11251 11252 // Only analyze comparison operators where both sides have been converted to 11253 // the same type. 11254 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11255 return AnalyzeImpConvsInComparison(S, E); 11256 11257 // Don't analyze value-dependent comparisons directly. 11258 if (E->isValueDependent()) 11259 return AnalyzeImpConvsInComparison(S, E); 11260 11261 Expr *LHS = E->getLHS(); 11262 Expr *RHS = E->getRHS(); 11263 11264 if (T->isIntegralType(S.Context)) { 11265 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11266 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11267 11268 // We don't care about expressions whose result is a constant. 11269 if (RHSValue && LHSValue) 11270 return AnalyzeImpConvsInComparison(S, E); 11271 11272 // We only care about expressions where just one side is literal 11273 if ((bool)RHSValue ^ (bool)LHSValue) { 11274 // Is the constant on the RHS or LHS? 11275 const bool RhsConstant = (bool)RHSValue; 11276 Expr *Const = RhsConstant ? RHS : LHS; 11277 Expr *Other = RhsConstant ? LHS : RHS; 11278 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11279 11280 // Check whether an integer constant comparison results in a value 11281 // of 'true' or 'false'. 11282 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11283 return AnalyzeImpConvsInComparison(S, E); 11284 } 11285 } 11286 11287 if (!T->hasUnsignedIntegerRepresentation()) { 11288 // We don't do anything special if this isn't an unsigned integral 11289 // comparison: we're only interested in integral comparisons, and 11290 // signed comparisons only happen in cases we don't care to warn about. 11291 return AnalyzeImpConvsInComparison(S, E); 11292 } 11293 11294 LHS = LHS->IgnoreParenImpCasts(); 11295 RHS = RHS->IgnoreParenImpCasts(); 11296 11297 if (!S.getLangOpts().CPlusPlus) { 11298 // Avoid warning about comparison of integers with different signs when 11299 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11300 // the type of `E`. 11301 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11302 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11303 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11304 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11305 } 11306 11307 // Check to see if one of the (unmodified) operands is of different 11308 // signedness. 11309 Expr *signedOperand, *unsignedOperand; 11310 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11311 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11312 "unsigned comparison between two signed integer expressions?"); 11313 signedOperand = LHS; 11314 unsignedOperand = RHS; 11315 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11316 signedOperand = RHS; 11317 unsignedOperand = LHS; 11318 } else { 11319 return AnalyzeImpConvsInComparison(S, E); 11320 } 11321 11322 // Otherwise, calculate the effective range of the signed operand. 11323 IntRange signedRange = GetExprRange( 11324 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11325 11326 // Go ahead and analyze implicit conversions in the operands. Note 11327 // that we skip the implicit conversions on both sides. 11328 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11329 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11330 11331 // If the signed range is non-negative, -Wsign-compare won't fire. 11332 if (signedRange.NonNegative) 11333 return; 11334 11335 // For (in)equality comparisons, if the unsigned operand is a 11336 // constant which cannot collide with a overflowed signed operand, 11337 // then reinterpreting the signed operand as unsigned will not 11338 // change the result of the comparison. 11339 if (E->isEqualityOp()) { 11340 unsigned comparisonWidth = S.Context.getIntWidth(T); 11341 IntRange unsignedRange = 11342 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11343 /*Approximate*/ true); 11344 11345 // We should never be unable to prove that the unsigned operand is 11346 // non-negative. 11347 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11348 11349 if (unsignedRange.Width < comparisonWidth) 11350 return; 11351 } 11352 11353 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11354 S.PDiag(diag::warn_mixed_sign_comparison) 11355 << LHS->getType() << RHS->getType() 11356 << LHS->getSourceRange() << RHS->getSourceRange()); 11357 } 11358 11359 /// Analyzes an attempt to assign the given value to a bitfield. 11360 /// 11361 /// Returns true if there was something fishy about the attempt. 11362 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11363 SourceLocation InitLoc) { 11364 assert(Bitfield->isBitField()); 11365 if (Bitfield->isInvalidDecl()) 11366 return false; 11367 11368 // White-list bool bitfields. 11369 QualType BitfieldType = Bitfield->getType(); 11370 if (BitfieldType->isBooleanType()) 11371 return false; 11372 11373 if (BitfieldType->isEnumeralType()) { 11374 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11375 // If the underlying enum type was not explicitly specified as an unsigned 11376 // type and the enum contain only positive values, MSVC++ will cause an 11377 // inconsistency by storing this as a signed type. 11378 if (S.getLangOpts().CPlusPlus11 && 11379 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11380 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11381 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11382 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11383 << BitfieldEnumDecl; 11384 } 11385 } 11386 11387 if (Bitfield->getType()->isBooleanType()) 11388 return false; 11389 11390 // Ignore value- or type-dependent expressions. 11391 if (Bitfield->getBitWidth()->isValueDependent() || 11392 Bitfield->getBitWidth()->isTypeDependent() || 11393 Init->isValueDependent() || 11394 Init->isTypeDependent()) 11395 return false; 11396 11397 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11398 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11399 11400 Expr::EvalResult Result; 11401 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11402 Expr::SE_AllowSideEffects)) { 11403 // The RHS is not constant. If the RHS has an enum type, make sure the 11404 // bitfield is wide enough to hold all the values of the enum without 11405 // truncation. 11406 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11407 EnumDecl *ED = EnumTy->getDecl(); 11408 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11409 11410 // Enum types are implicitly signed on Windows, so check if there are any 11411 // negative enumerators to see if the enum was intended to be signed or 11412 // not. 11413 bool SignedEnum = ED->getNumNegativeBits() > 0; 11414 11415 // Check for surprising sign changes when assigning enum values to a 11416 // bitfield of different signedness. If the bitfield is signed and we 11417 // have exactly the right number of bits to store this unsigned enum, 11418 // suggest changing the enum to an unsigned type. This typically happens 11419 // on Windows where unfixed enums always use an underlying type of 'int'. 11420 unsigned DiagID = 0; 11421 if (SignedEnum && !SignedBitfield) { 11422 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11423 } else if (SignedBitfield && !SignedEnum && 11424 ED->getNumPositiveBits() == FieldWidth) { 11425 DiagID = diag::warn_signed_bitfield_enum_conversion; 11426 } 11427 11428 if (DiagID) { 11429 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11430 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11431 SourceRange TypeRange = 11432 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11433 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11434 << SignedEnum << TypeRange; 11435 } 11436 11437 // Compute the required bitwidth. If the enum has negative values, we need 11438 // one more bit than the normal number of positive bits to represent the 11439 // sign bit. 11440 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11441 ED->getNumNegativeBits()) 11442 : ED->getNumPositiveBits(); 11443 11444 // Check the bitwidth. 11445 if (BitsNeeded > FieldWidth) { 11446 Expr *WidthExpr = Bitfield->getBitWidth(); 11447 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11448 << Bitfield << ED; 11449 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11450 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11451 } 11452 } 11453 11454 return false; 11455 } 11456 11457 llvm::APSInt Value = Result.Val.getInt(); 11458 11459 unsigned OriginalWidth = Value.getBitWidth(); 11460 11461 if (!Value.isSigned() || Value.isNegative()) 11462 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11463 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11464 OriginalWidth = Value.getMinSignedBits(); 11465 11466 if (OriginalWidth <= FieldWidth) 11467 return false; 11468 11469 // Compute the value which the bitfield will contain. 11470 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11471 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11472 11473 // Check whether the stored value is equal to the original value. 11474 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11475 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11476 return false; 11477 11478 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11479 // therefore don't strictly fit into a signed bitfield of width 1. 11480 if (FieldWidth == 1 && Value == 1) 11481 return false; 11482 11483 std::string PrettyValue = Value.toString(10); 11484 std::string PrettyTrunc = TruncatedValue.toString(10); 11485 11486 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11487 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11488 << Init->getSourceRange(); 11489 11490 return true; 11491 } 11492 11493 /// Analyze the given simple or compound assignment for warning-worthy 11494 /// operations. 11495 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11496 // Just recurse on the LHS. 11497 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11498 11499 // We want to recurse on the RHS as normal unless we're assigning to 11500 // a bitfield. 11501 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11502 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11503 E->getOperatorLoc())) { 11504 // Recurse, ignoring any implicit conversions on the RHS. 11505 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11506 E->getOperatorLoc()); 11507 } 11508 } 11509 11510 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11511 11512 // Diagnose implicitly sequentially-consistent atomic assignment. 11513 if (E->getLHS()->getType()->isAtomicType()) 11514 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11515 } 11516 11517 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11518 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11519 SourceLocation CContext, unsigned diag, 11520 bool pruneControlFlow = false) { 11521 if (pruneControlFlow) { 11522 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11523 S.PDiag(diag) 11524 << SourceType << T << E->getSourceRange() 11525 << SourceRange(CContext)); 11526 return; 11527 } 11528 S.Diag(E->getExprLoc(), diag) 11529 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11530 } 11531 11532 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11533 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11534 SourceLocation CContext, 11535 unsigned diag, bool pruneControlFlow = false) { 11536 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11537 } 11538 11539 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11540 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11541 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11542 } 11543 11544 static void adornObjCBoolConversionDiagWithTernaryFixit( 11545 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11546 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11547 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11548 Ignored = OVE->getSourceExpr(); 11549 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11550 isa<BinaryOperator>(Ignored) || 11551 isa<CXXOperatorCallExpr>(Ignored); 11552 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11553 if (NeedsParens) 11554 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11555 << FixItHint::CreateInsertion(EndLoc, ")"); 11556 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11557 } 11558 11559 /// Diagnose an implicit cast from a floating point value to an integer value. 11560 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11561 SourceLocation CContext) { 11562 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11563 const bool PruneWarnings = S.inTemplateInstantiation(); 11564 11565 Expr *InnerE = E->IgnoreParenImpCasts(); 11566 // We also want to warn on, e.g., "int i = -1.234" 11567 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11568 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11569 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11570 11571 const bool IsLiteral = 11572 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11573 11574 llvm::APFloat Value(0.0); 11575 bool IsConstant = 11576 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11577 if (!IsConstant) { 11578 if (isObjCSignedCharBool(S, T)) { 11579 return adornObjCBoolConversionDiagWithTernaryFixit( 11580 S, E, 11581 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11582 << E->getType()); 11583 } 11584 11585 return DiagnoseImpCast(S, E, T, CContext, 11586 diag::warn_impcast_float_integer, PruneWarnings); 11587 } 11588 11589 bool isExact = false; 11590 11591 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11592 T->hasUnsignedIntegerRepresentation()); 11593 llvm::APFloat::opStatus Result = Value.convertToInteger( 11594 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11595 11596 // FIXME: Force the precision of the source value down so we don't print 11597 // digits which are usually useless (we don't really care here if we 11598 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11599 // would automatically print the shortest representation, but it's a bit 11600 // tricky to implement. 11601 SmallString<16> PrettySourceValue; 11602 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11603 precision = (precision * 59 + 195) / 196; 11604 Value.toString(PrettySourceValue, precision); 11605 11606 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11607 return adornObjCBoolConversionDiagWithTernaryFixit( 11608 S, E, 11609 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11610 << PrettySourceValue); 11611 } 11612 11613 if (Result == llvm::APFloat::opOK && isExact) { 11614 if (IsLiteral) return; 11615 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11616 PruneWarnings); 11617 } 11618 11619 // Conversion of a floating-point value to a non-bool integer where the 11620 // integral part cannot be represented by the integer type is undefined. 11621 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11622 return DiagnoseImpCast( 11623 S, E, T, CContext, 11624 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11625 : diag::warn_impcast_float_to_integer_out_of_range, 11626 PruneWarnings); 11627 11628 unsigned DiagID = 0; 11629 if (IsLiteral) { 11630 // Warn on floating point literal to integer. 11631 DiagID = diag::warn_impcast_literal_float_to_integer; 11632 } else if (IntegerValue == 0) { 11633 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11634 return DiagnoseImpCast(S, E, T, CContext, 11635 diag::warn_impcast_float_integer, PruneWarnings); 11636 } 11637 // Warn on non-zero to zero conversion. 11638 DiagID = diag::warn_impcast_float_to_integer_zero; 11639 } else { 11640 if (IntegerValue.isUnsigned()) { 11641 if (!IntegerValue.isMaxValue()) { 11642 return DiagnoseImpCast(S, E, T, CContext, 11643 diag::warn_impcast_float_integer, PruneWarnings); 11644 } 11645 } else { // IntegerValue.isSigned() 11646 if (!IntegerValue.isMaxSignedValue() && 11647 !IntegerValue.isMinSignedValue()) { 11648 return DiagnoseImpCast(S, E, T, CContext, 11649 diag::warn_impcast_float_integer, PruneWarnings); 11650 } 11651 } 11652 // Warn on evaluatable floating point expression to integer conversion. 11653 DiagID = diag::warn_impcast_float_to_integer; 11654 } 11655 11656 SmallString<16> PrettyTargetValue; 11657 if (IsBool) 11658 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11659 else 11660 IntegerValue.toString(PrettyTargetValue); 11661 11662 if (PruneWarnings) { 11663 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11664 S.PDiag(DiagID) 11665 << E->getType() << T.getUnqualifiedType() 11666 << PrettySourceValue << PrettyTargetValue 11667 << E->getSourceRange() << SourceRange(CContext)); 11668 } else { 11669 S.Diag(E->getExprLoc(), DiagID) 11670 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11671 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11672 } 11673 } 11674 11675 /// Analyze the given compound assignment for the possible losing of 11676 /// floating-point precision. 11677 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11678 assert(isa<CompoundAssignOperator>(E) && 11679 "Must be compound assignment operation"); 11680 // Recurse on the LHS and RHS in here 11681 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11682 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11683 11684 if (E->getLHS()->getType()->isAtomicType()) 11685 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11686 11687 // Now check the outermost expression 11688 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11689 const auto *RBT = cast<CompoundAssignOperator>(E) 11690 ->getComputationResultType() 11691 ->getAs<BuiltinType>(); 11692 11693 // The below checks assume source is floating point. 11694 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11695 11696 // If source is floating point but target is an integer. 11697 if (ResultBT->isInteger()) 11698 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11699 E->getExprLoc(), diag::warn_impcast_float_integer); 11700 11701 if (!ResultBT->isFloatingPoint()) 11702 return; 11703 11704 // If both source and target are floating points, warn about losing precision. 11705 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11706 QualType(ResultBT, 0), QualType(RBT, 0)); 11707 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11708 // warn about dropping FP rank. 11709 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11710 diag::warn_impcast_float_result_precision); 11711 } 11712 11713 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11714 IntRange Range) { 11715 if (!Range.Width) return "0"; 11716 11717 llvm::APSInt ValueInRange = Value; 11718 ValueInRange.setIsSigned(!Range.NonNegative); 11719 ValueInRange = ValueInRange.trunc(Range.Width); 11720 return ValueInRange.toString(10); 11721 } 11722 11723 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11724 if (!isa<ImplicitCastExpr>(Ex)) 11725 return false; 11726 11727 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11728 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11729 const Type *Source = 11730 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11731 if (Target->isDependentType()) 11732 return false; 11733 11734 const BuiltinType *FloatCandidateBT = 11735 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11736 const Type *BoolCandidateType = ToBool ? Target : Source; 11737 11738 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11739 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11740 } 11741 11742 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11743 SourceLocation CC) { 11744 unsigned NumArgs = TheCall->getNumArgs(); 11745 for (unsigned i = 0; i < NumArgs; ++i) { 11746 Expr *CurrA = TheCall->getArg(i); 11747 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11748 continue; 11749 11750 bool IsSwapped = ((i > 0) && 11751 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11752 IsSwapped |= ((i < (NumArgs - 1)) && 11753 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11754 if (IsSwapped) { 11755 // Warn on this floating-point to bool conversion. 11756 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11757 CurrA->getType(), CC, 11758 diag::warn_impcast_floating_point_to_bool); 11759 } 11760 } 11761 } 11762 11763 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11764 SourceLocation CC) { 11765 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11766 E->getExprLoc())) 11767 return; 11768 11769 // Don't warn on functions which have return type nullptr_t. 11770 if (isa<CallExpr>(E)) 11771 return; 11772 11773 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11774 const Expr::NullPointerConstantKind NullKind = 11775 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11776 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11777 return; 11778 11779 // Return if target type is a safe conversion. 11780 if (T->isAnyPointerType() || T->isBlockPointerType() || 11781 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11782 return; 11783 11784 SourceLocation Loc = E->getSourceRange().getBegin(); 11785 11786 // Venture through the macro stacks to get to the source of macro arguments. 11787 // The new location is a better location than the complete location that was 11788 // passed in. 11789 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11790 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11791 11792 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11793 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11794 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11795 Loc, S.SourceMgr, S.getLangOpts()); 11796 if (MacroName == "NULL") 11797 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11798 } 11799 11800 // Only warn if the null and context location are in the same macro expansion. 11801 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11802 return; 11803 11804 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11805 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11806 << FixItHint::CreateReplacement(Loc, 11807 S.getFixItZeroLiteralForType(T, Loc)); 11808 } 11809 11810 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11811 ObjCArrayLiteral *ArrayLiteral); 11812 11813 static void 11814 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11815 ObjCDictionaryLiteral *DictionaryLiteral); 11816 11817 /// Check a single element within a collection literal against the 11818 /// target element type. 11819 static void checkObjCCollectionLiteralElement(Sema &S, 11820 QualType TargetElementType, 11821 Expr *Element, 11822 unsigned ElementKind) { 11823 // Skip a bitcast to 'id' or qualified 'id'. 11824 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11825 if (ICE->getCastKind() == CK_BitCast && 11826 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11827 Element = ICE->getSubExpr(); 11828 } 11829 11830 QualType ElementType = Element->getType(); 11831 ExprResult ElementResult(Element); 11832 if (ElementType->getAs<ObjCObjectPointerType>() && 11833 S.CheckSingleAssignmentConstraints(TargetElementType, 11834 ElementResult, 11835 false, false) 11836 != Sema::Compatible) { 11837 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11838 << ElementType << ElementKind << TargetElementType 11839 << Element->getSourceRange(); 11840 } 11841 11842 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11843 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11844 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11845 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11846 } 11847 11848 /// Check an Objective-C array literal being converted to the given 11849 /// target type. 11850 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11851 ObjCArrayLiteral *ArrayLiteral) { 11852 if (!S.NSArrayDecl) 11853 return; 11854 11855 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11856 if (!TargetObjCPtr) 11857 return; 11858 11859 if (TargetObjCPtr->isUnspecialized() || 11860 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11861 != S.NSArrayDecl->getCanonicalDecl()) 11862 return; 11863 11864 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11865 if (TypeArgs.size() != 1) 11866 return; 11867 11868 QualType TargetElementType = TypeArgs[0]; 11869 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11870 checkObjCCollectionLiteralElement(S, TargetElementType, 11871 ArrayLiteral->getElement(I), 11872 0); 11873 } 11874 } 11875 11876 /// Check an Objective-C dictionary literal being converted to the given 11877 /// target type. 11878 static void 11879 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11880 ObjCDictionaryLiteral *DictionaryLiteral) { 11881 if (!S.NSDictionaryDecl) 11882 return; 11883 11884 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11885 if (!TargetObjCPtr) 11886 return; 11887 11888 if (TargetObjCPtr->isUnspecialized() || 11889 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11890 != S.NSDictionaryDecl->getCanonicalDecl()) 11891 return; 11892 11893 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11894 if (TypeArgs.size() != 2) 11895 return; 11896 11897 QualType TargetKeyType = TypeArgs[0]; 11898 QualType TargetObjectType = TypeArgs[1]; 11899 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11900 auto Element = DictionaryLiteral->getKeyValueElement(I); 11901 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11902 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11903 } 11904 } 11905 11906 // Helper function to filter out cases for constant width constant conversion. 11907 // Don't warn on char array initialization or for non-decimal values. 11908 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11909 SourceLocation CC) { 11910 // If initializing from a constant, and the constant starts with '0', 11911 // then it is a binary, octal, or hexadecimal. Allow these constants 11912 // to fill all the bits, even if there is a sign change. 11913 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11914 const char FirstLiteralCharacter = 11915 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11916 if (FirstLiteralCharacter == '0') 11917 return false; 11918 } 11919 11920 // If the CC location points to a '{', and the type is char, then assume 11921 // assume it is an array initialization. 11922 if (CC.isValid() && T->isCharType()) { 11923 const char FirstContextCharacter = 11924 S.getSourceManager().getCharacterData(CC)[0]; 11925 if (FirstContextCharacter == '{') 11926 return false; 11927 } 11928 11929 return true; 11930 } 11931 11932 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11933 const auto *IL = dyn_cast<IntegerLiteral>(E); 11934 if (!IL) { 11935 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11936 if (UO->getOpcode() == UO_Minus) 11937 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11938 } 11939 } 11940 11941 return IL; 11942 } 11943 11944 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11945 E = E->IgnoreParenImpCasts(); 11946 SourceLocation ExprLoc = E->getExprLoc(); 11947 11948 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11949 BinaryOperator::Opcode Opc = BO->getOpcode(); 11950 Expr::EvalResult Result; 11951 // Do not diagnose unsigned shifts. 11952 if (Opc == BO_Shl) { 11953 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11954 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11955 if (LHS && LHS->getValue() == 0) 11956 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11957 else if (!E->isValueDependent() && LHS && RHS && 11958 RHS->getValue().isNonNegative() && 11959 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11960 S.Diag(ExprLoc, diag::warn_left_shift_always) 11961 << (Result.Val.getInt() != 0); 11962 else if (E->getType()->isSignedIntegerType()) 11963 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11964 } 11965 } 11966 11967 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11968 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11969 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11970 if (!LHS || !RHS) 11971 return; 11972 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11973 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11974 // Do not diagnose common idioms. 11975 return; 11976 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11977 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11978 } 11979 } 11980 11981 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11982 SourceLocation CC, 11983 bool *ICContext = nullptr, 11984 bool IsListInit = false) { 11985 if (E->isTypeDependent() || E->isValueDependent()) return; 11986 11987 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11988 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11989 if (Source == Target) return; 11990 if (Target->isDependentType()) return; 11991 11992 // If the conversion context location is invalid don't complain. We also 11993 // don't want to emit a warning if the issue occurs from the expansion of 11994 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11995 // delay this check as long as possible. Once we detect we are in that 11996 // scenario, we just return. 11997 if (CC.isInvalid()) 11998 return; 11999 12000 if (Source->isAtomicType()) 12001 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12002 12003 // Diagnose implicit casts to bool. 12004 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12005 if (isa<StringLiteral>(E)) 12006 // Warn on string literal to bool. Checks for string literals in logical 12007 // and expressions, for instance, assert(0 && "error here"), are 12008 // prevented by a check in AnalyzeImplicitConversions(). 12009 return DiagnoseImpCast(S, E, T, CC, 12010 diag::warn_impcast_string_literal_to_bool); 12011 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12012 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12013 // This covers the literal expressions that evaluate to Objective-C 12014 // objects. 12015 return DiagnoseImpCast(S, E, T, CC, 12016 diag::warn_impcast_objective_c_literal_to_bool); 12017 } 12018 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12019 // Warn on pointer to bool conversion that is always true. 12020 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12021 SourceRange(CC)); 12022 } 12023 } 12024 12025 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12026 // is a typedef for signed char (macOS), then that constant value has to be 1 12027 // or 0. 12028 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12029 Expr::EvalResult Result; 12030 if (E->EvaluateAsInt(Result, S.getASTContext(), 12031 Expr::SE_AllowSideEffects)) { 12032 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12033 adornObjCBoolConversionDiagWithTernaryFixit( 12034 S, E, 12035 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12036 << Result.Val.getInt().toString(10)); 12037 } 12038 return; 12039 } 12040 } 12041 12042 // Check implicit casts from Objective-C collection literals to specialized 12043 // collection types, e.g., NSArray<NSString *> *. 12044 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12045 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12046 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12047 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12048 12049 // Strip vector types. 12050 if (isa<VectorType>(Source)) { 12051 if (!isa<VectorType>(Target)) { 12052 if (S.SourceMgr.isInSystemMacro(CC)) 12053 return; 12054 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12055 } 12056 12057 // If the vector cast is cast between two vectors of the same size, it is 12058 // a bitcast, not a conversion. 12059 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12060 return; 12061 12062 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12063 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12064 } 12065 if (auto VecTy = dyn_cast<VectorType>(Target)) 12066 Target = VecTy->getElementType().getTypePtr(); 12067 12068 // Strip complex types. 12069 if (isa<ComplexType>(Source)) { 12070 if (!isa<ComplexType>(Target)) { 12071 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12072 return; 12073 12074 return DiagnoseImpCast(S, E, T, CC, 12075 S.getLangOpts().CPlusPlus 12076 ? diag::err_impcast_complex_scalar 12077 : diag::warn_impcast_complex_scalar); 12078 } 12079 12080 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12081 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12082 } 12083 12084 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12085 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12086 12087 // If the source is floating point... 12088 if (SourceBT && SourceBT->isFloatingPoint()) { 12089 // ...and the target is floating point... 12090 if (TargetBT && TargetBT->isFloatingPoint()) { 12091 // ...then warn if we're dropping FP rank. 12092 12093 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12094 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12095 if (Order > 0) { 12096 // Don't warn about float constants that are precisely 12097 // representable in the target type. 12098 Expr::EvalResult result; 12099 if (E->EvaluateAsRValue(result, S.Context)) { 12100 // Value might be a float, a float vector, or a float complex. 12101 if (IsSameFloatAfterCast(result.Val, 12102 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12103 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12104 return; 12105 } 12106 12107 if (S.SourceMgr.isInSystemMacro(CC)) 12108 return; 12109 12110 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12111 } 12112 // ... or possibly if we're increasing rank, too 12113 else if (Order < 0) { 12114 if (S.SourceMgr.isInSystemMacro(CC)) 12115 return; 12116 12117 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12118 } 12119 return; 12120 } 12121 12122 // If the target is integral, always warn. 12123 if (TargetBT && TargetBT->isInteger()) { 12124 if (S.SourceMgr.isInSystemMacro(CC)) 12125 return; 12126 12127 DiagnoseFloatingImpCast(S, E, T, CC); 12128 } 12129 12130 // Detect the case where a call result is converted from floating-point to 12131 // to bool, and the final argument to the call is converted from bool, to 12132 // discover this typo: 12133 // 12134 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12135 // 12136 // FIXME: This is an incredibly special case; is there some more general 12137 // way to detect this class of misplaced-parentheses bug? 12138 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12139 // Check last argument of function call to see if it is an 12140 // implicit cast from a type matching the type the result 12141 // is being cast to. 12142 CallExpr *CEx = cast<CallExpr>(E); 12143 if (unsigned NumArgs = CEx->getNumArgs()) { 12144 Expr *LastA = CEx->getArg(NumArgs - 1); 12145 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12146 if (isa<ImplicitCastExpr>(LastA) && 12147 InnerE->getType()->isBooleanType()) { 12148 // Warn on this floating-point to bool conversion 12149 DiagnoseImpCast(S, E, T, CC, 12150 diag::warn_impcast_floating_point_to_bool); 12151 } 12152 } 12153 } 12154 return; 12155 } 12156 12157 // Valid casts involving fixed point types should be accounted for here. 12158 if (Source->isFixedPointType()) { 12159 if (Target->isUnsaturatedFixedPointType()) { 12160 Expr::EvalResult Result; 12161 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12162 S.isConstantEvaluated())) { 12163 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12164 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12165 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12166 if (Value > MaxVal || Value < MinVal) { 12167 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12168 S.PDiag(diag::warn_impcast_fixed_point_range) 12169 << Value.toString() << T 12170 << E->getSourceRange() 12171 << clang::SourceRange(CC)); 12172 return; 12173 } 12174 } 12175 } else if (Target->isIntegerType()) { 12176 Expr::EvalResult Result; 12177 if (!S.isConstantEvaluated() && 12178 E->EvaluateAsFixedPoint(Result, S.Context, 12179 Expr::SE_AllowSideEffects)) { 12180 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12181 12182 bool Overflowed; 12183 llvm::APSInt IntResult = FXResult.convertToInt( 12184 S.Context.getIntWidth(T), 12185 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12186 12187 if (Overflowed) { 12188 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12189 S.PDiag(diag::warn_impcast_fixed_point_range) 12190 << FXResult.toString() << T 12191 << E->getSourceRange() 12192 << clang::SourceRange(CC)); 12193 return; 12194 } 12195 } 12196 } 12197 } else if (Target->isUnsaturatedFixedPointType()) { 12198 if (Source->isIntegerType()) { 12199 Expr::EvalResult Result; 12200 if (!S.isConstantEvaluated() && 12201 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12202 llvm::APSInt Value = Result.Val.getInt(); 12203 12204 bool Overflowed; 12205 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12206 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12207 12208 if (Overflowed) { 12209 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12210 S.PDiag(diag::warn_impcast_fixed_point_range) 12211 << Value.toString(/*Radix=*/10) << T 12212 << E->getSourceRange() 12213 << clang::SourceRange(CC)); 12214 return; 12215 } 12216 } 12217 } 12218 } 12219 12220 // If we are casting an integer type to a floating point type without 12221 // initialization-list syntax, we might lose accuracy if the floating 12222 // point type has a narrower significand than the integer type. 12223 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12224 TargetBT->isFloatingType() && !IsListInit) { 12225 // Determine the number of precision bits in the source integer type. 12226 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12227 /*Approximate*/ true); 12228 unsigned int SourcePrecision = SourceRange.Width; 12229 12230 // Determine the number of precision bits in the 12231 // target floating point type. 12232 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12233 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12234 12235 if (SourcePrecision > 0 && TargetPrecision > 0 && 12236 SourcePrecision > TargetPrecision) { 12237 12238 if (Optional<llvm::APSInt> SourceInt = 12239 E->getIntegerConstantExpr(S.Context)) { 12240 // If the source integer is a constant, convert it to the target 12241 // floating point type. Issue a warning if the value changes 12242 // during the whole conversion. 12243 llvm::APFloat TargetFloatValue( 12244 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12245 llvm::APFloat::opStatus ConversionStatus = 12246 TargetFloatValue.convertFromAPInt( 12247 *SourceInt, SourceBT->isSignedInteger(), 12248 llvm::APFloat::rmNearestTiesToEven); 12249 12250 if (ConversionStatus != llvm::APFloat::opOK) { 12251 std::string PrettySourceValue = SourceInt->toString(10); 12252 SmallString<32> PrettyTargetValue; 12253 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12254 12255 S.DiagRuntimeBehavior( 12256 E->getExprLoc(), E, 12257 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12258 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12259 << E->getSourceRange() << clang::SourceRange(CC)); 12260 } 12261 } else { 12262 // Otherwise, the implicit conversion may lose precision. 12263 DiagnoseImpCast(S, E, T, CC, 12264 diag::warn_impcast_integer_float_precision); 12265 } 12266 } 12267 } 12268 12269 DiagnoseNullConversion(S, E, T, CC); 12270 12271 S.DiscardMisalignedMemberAddress(Target, E); 12272 12273 if (Target->isBooleanType()) 12274 DiagnoseIntInBoolContext(S, E); 12275 12276 if (!Source->isIntegerType() || !Target->isIntegerType()) 12277 return; 12278 12279 // TODO: remove this early return once the false positives for constant->bool 12280 // in templates, macros, etc, are reduced or removed. 12281 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12282 return; 12283 12284 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12285 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12286 return adornObjCBoolConversionDiagWithTernaryFixit( 12287 S, E, 12288 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12289 << E->getType()); 12290 } 12291 12292 IntRange SourceTypeRange = 12293 IntRange::forTargetOfCanonicalType(S.Context, Source); 12294 IntRange LikelySourceRange = 12295 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12296 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12297 12298 if (LikelySourceRange.Width > TargetRange.Width) { 12299 // If the source is a constant, use a default-on diagnostic. 12300 // TODO: this should happen for bitfield stores, too. 12301 Expr::EvalResult Result; 12302 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12303 S.isConstantEvaluated())) { 12304 llvm::APSInt Value(32); 12305 Value = Result.Val.getInt(); 12306 12307 if (S.SourceMgr.isInSystemMacro(CC)) 12308 return; 12309 12310 std::string PrettySourceValue = Value.toString(10); 12311 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12312 12313 S.DiagRuntimeBehavior( 12314 E->getExprLoc(), E, 12315 S.PDiag(diag::warn_impcast_integer_precision_constant) 12316 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12317 << E->getSourceRange() << SourceRange(CC)); 12318 return; 12319 } 12320 12321 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12322 if (S.SourceMgr.isInSystemMacro(CC)) 12323 return; 12324 12325 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12326 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12327 /* pruneControlFlow */ true); 12328 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12329 } 12330 12331 if (TargetRange.Width > SourceTypeRange.Width) { 12332 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12333 if (UO->getOpcode() == UO_Minus) 12334 if (Source->isUnsignedIntegerType()) { 12335 if (Target->isUnsignedIntegerType()) 12336 return DiagnoseImpCast(S, E, T, CC, 12337 diag::warn_impcast_high_order_zero_bits); 12338 if (Target->isSignedIntegerType()) 12339 return DiagnoseImpCast(S, E, T, CC, 12340 diag::warn_impcast_nonnegative_result); 12341 } 12342 } 12343 12344 if (TargetRange.Width == LikelySourceRange.Width && 12345 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12346 Source->isSignedIntegerType()) { 12347 // Warn when doing a signed to signed conversion, warn if the positive 12348 // source value is exactly the width of the target type, which will 12349 // cause a negative value to be stored. 12350 12351 Expr::EvalResult Result; 12352 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12353 !S.SourceMgr.isInSystemMacro(CC)) { 12354 llvm::APSInt Value = Result.Val.getInt(); 12355 if (isSameWidthConstantConversion(S, E, T, CC)) { 12356 std::string PrettySourceValue = Value.toString(10); 12357 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12358 12359 S.DiagRuntimeBehavior( 12360 E->getExprLoc(), E, 12361 S.PDiag(diag::warn_impcast_integer_precision_constant) 12362 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12363 << E->getSourceRange() << SourceRange(CC)); 12364 return; 12365 } 12366 } 12367 12368 // Fall through for non-constants to give a sign conversion warning. 12369 } 12370 12371 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12372 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12373 LikelySourceRange.Width == TargetRange.Width)) { 12374 if (S.SourceMgr.isInSystemMacro(CC)) 12375 return; 12376 12377 unsigned DiagID = diag::warn_impcast_integer_sign; 12378 12379 // Traditionally, gcc has warned about this under -Wsign-compare. 12380 // We also want to warn about it in -Wconversion. 12381 // So if -Wconversion is off, use a completely identical diagnostic 12382 // in the sign-compare group. 12383 // The conditional-checking code will 12384 if (ICContext) { 12385 DiagID = diag::warn_impcast_integer_sign_conditional; 12386 *ICContext = true; 12387 } 12388 12389 return DiagnoseImpCast(S, E, T, CC, DiagID); 12390 } 12391 12392 // Diagnose conversions between different enumeration types. 12393 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12394 // type, to give us better diagnostics. 12395 QualType SourceType = E->getType(); 12396 if (!S.getLangOpts().CPlusPlus) { 12397 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12398 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12399 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12400 SourceType = S.Context.getTypeDeclType(Enum); 12401 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12402 } 12403 } 12404 12405 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12406 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12407 if (SourceEnum->getDecl()->hasNameForLinkage() && 12408 TargetEnum->getDecl()->hasNameForLinkage() && 12409 SourceEnum != TargetEnum) { 12410 if (S.SourceMgr.isInSystemMacro(CC)) 12411 return; 12412 12413 return DiagnoseImpCast(S, E, SourceType, T, CC, 12414 diag::warn_impcast_different_enum_types); 12415 } 12416 } 12417 12418 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12419 SourceLocation CC, QualType T); 12420 12421 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12422 SourceLocation CC, bool &ICContext) { 12423 E = E->IgnoreParenImpCasts(); 12424 12425 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12426 return CheckConditionalOperator(S, CO, CC, T); 12427 12428 AnalyzeImplicitConversions(S, E, CC); 12429 if (E->getType() != T) 12430 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12431 } 12432 12433 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12434 SourceLocation CC, QualType T) { 12435 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12436 12437 Expr *TrueExpr = E->getTrueExpr(); 12438 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12439 TrueExpr = BCO->getCommon(); 12440 12441 bool Suspicious = false; 12442 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12443 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12444 12445 if (T->isBooleanType()) 12446 DiagnoseIntInBoolContext(S, E); 12447 12448 // If -Wconversion would have warned about either of the candidates 12449 // for a signedness conversion to the context type... 12450 if (!Suspicious) return; 12451 12452 // ...but it's currently ignored... 12453 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12454 return; 12455 12456 // ...then check whether it would have warned about either of the 12457 // candidates for a signedness conversion to the condition type. 12458 if (E->getType() == T) return; 12459 12460 Suspicious = false; 12461 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12462 E->getType(), CC, &Suspicious); 12463 if (!Suspicious) 12464 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12465 E->getType(), CC, &Suspicious); 12466 } 12467 12468 /// Check conversion of given expression to boolean. 12469 /// Input argument E is a logical expression. 12470 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12471 if (S.getLangOpts().Bool) 12472 return; 12473 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12474 return; 12475 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12476 } 12477 12478 namespace { 12479 struct AnalyzeImplicitConversionsWorkItem { 12480 Expr *E; 12481 SourceLocation CC; 12482 bool IsListInit; 12483 }; 12484 } 12485 12486 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12487 /// that should be visited are added to WorkList. 12488 static void AnalyzeImplicitConversions( 12489 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12490 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12491 Expr *OrigE = Item.E; 12492 SourceLocation CC = Item.CC; 12493 12494 QualType T = OrigE->getType(); 12495 Expr *E = OrigE->IgnoreParenImpCasts(); 12496 12497 // Propagate whether we are in a C++ list initialization expression. 12498 // If so, we do not issue warnings for implicit int-float conversion 12499 // precision loss, because C++11 narrowing already handles it. 12500 bool IsListInit = Item.IsListInit || 12501 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12502 12503 if (E->isTypeDependent() || E->isValueDependent()) 12504 return; 12505 12506 Expr *SourceExpr = E; 12507 // Examine, but don't traverse into the source expression of an 12508 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12509 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12510 // evaluate it in the context of checking the specific conversion to T though. 12511 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12512 if (auto *Src = OVE->getSourceExpr()) 12513 SourceExpr = Src; 12514 12515 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12516 if (UO->getOpcode() == UO_Not && 12517 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12518 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12519 << OrigE->getSourceRange() << T->isBooleanType() 12520 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12521 12522 // For conditional operators, we analyze the arguments as if they 12523 // were being fed directly into the output. 12524 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12525 CheckConditionalOperator(S, CO, CC, T); 12526 return; 12527 } 12528 12529 // Check implicit argument conversions for function calls. 12530 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12531 CheckImplicitArgumentConversions(S, Call, CC); 12532 12533 // Go ahead and check any implicit conversions we might have skipped. 12534 // The non-canonical typecheck is just an optimization; 12535 // CheckImplicitConversion will filter out dead implicit conversions. 12536 if (SourceExpr->getType() != T) 12537 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12538 12539 // Now continue drilling into this expression. 12540 12541 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12542 // The bound subexpressions in a PseudoObjectExpr are not reachable 12543 // as transitive children. 12544 // FIXME: Use a more uniform representation for this. 12545 for (auto *SE : POE->semantics()) 12546 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12547 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12548 } 12549 12550 // Skip past explicit casts. 12551 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12552 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12553 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12554 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12555 WorkList.push_back({E, CC, IsListInit}); 12556 return; 12557 } 12558 12559 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12560 // Do a somewhat different check with comparison operators. 12561 if (BO->isComparisonOp()) 12562 return AnalyzeComparison(S, BO); 12563 12564 // And with simple assignments. 12565 if (BO->getOpcode() == BO_Assign) 12566 return AnalyzeAssignment(S, BO); 12567 // And with compound assignments. 12568 if (BO->isAssignmentOp()) 12569 return AnalyzeCompoundAssignment(S, BO); 12570 } 12571 12572 // These break the otherwise-useful invariant below. Fortunately, 12573 // we don't really need to recurse into them, because any internal 12574 // expressions should have been analyzed already when they were 12575 // built into statements. 12576 if (isa<StmtExpr>(E)) return; 12577 12578 // Don't descend into unevaluated contexts. 12579 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12580 12581 // Now just recurse over the expression's children. 12582 CC = E->getExprLoc(); 12583 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12584 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12585 for (Stmt *SubStmt : E->children()) { 12586 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12587 if (!ChildExpr) 12588 continue; 12589 12590 if (IsLogicalAndOperator && 12591 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12592 // Ignore checking string literals that are in logical and operators. 12593 // This is a common pattern for asserts. 12594 continue; 12595 WorkList.push_back({ChildExpr, CC, IsListInit}); 12596 } 12597 12598 if (BO && BO->isLogicalOp()) { 12599 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12600 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12601 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12602 12603 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12604 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12605 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12606 } 12607 12608 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12609 if (U->getOpcode() == UO_LNot) { 12610 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12611 } else if (U->getOpcode() != UO_AddrOf) { 12612 if (U->getSubExpr()->getType()->isAtomicType()) 12613 S.Diag(U->getSubExpr()->getBeginLoc(), 12614 diag::warn_atomic_implicit_seq_cst); 12615 } 12616 } 12617 } 12618 12619 /// AnalyzeImplicitConversions - Find and report any interesting 12620 /// implicit conversions in the given expression. There are a couple 12621 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12622 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12623 bool IsListInit/*= false*/) { 12624 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12625 WorkList.push_back({OrigE, CC, IsListInit}); 12626 while (!WorkList.empty()) 12627 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12628 } 12629 12630 /// Diagnose integer type and any valid implicit conversion to it. 12631 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12632 // Taking into account implicit conversions, 12633 // allow any integer. 12634 if (!E->getType()->isIntegerType()) { 12635 S.Diag(E->getBeginLoc(), 12636 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12637 return true; 12638 } 12639 // Potentially emit standard warnings for implicit conversions if enabled 12640 // using -Wconversion. 12641 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12642 return false; 12643 } 12644 12645 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12646 // Returns true when emitting a warning about taking the address of a reference. 12647 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12648 const PartialDiagnostic &PD) { 12649 E = E->IgnoreParenImpCasts(); 12650 12651 const FunctionDecl *FD = nullptr; 12652 12653 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12654 if (!DRE->getDecl()->getType()->isReferenceType()) 12655 return false; 12656 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12657 if (!M->getMemberDecl()->getType()->isReferenceType()) 12658 return false; 12659 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12660 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12661 return false; 12662 FD = Call->getDirectCallee(); 12663 } else { 12664 return false; 12665 } 12666 12667 SemaRef.Diag(E->getExprLoc(), PD); 12668 12669 // If possible, point to location of function. 12670 if (FD) { 12671 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12672 } 12673 12674 return true; 12675 } 12676 12677 // Returns true if the SourceLocation is expanded from any macro body. 12678 // Returns false if the SourceLocation is invalid, is from not in a macro 12679 // expansion, or is from expanded from a top-level macro argument. 12680 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12681 if (Loc.isInvalid()) 12682 return false; 12683 12684 while (Loc.isMacroID()) { 12685 if (SM.isMacroBodyExpansion(Loc)) 12686 return true; 12687 Loc = SM.getImmediateMacroCallerLoc(Loc); 12688 } 12689 12690 return false; 12691 } 12692 12693 /// Diagnose pointers that are always non-null. 12694 /// \param E the expression containing the pointer 12695 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12696 /// compared to a null pointer 12697 /// \param IsEqual True when the comparison is equal to a null pointer 12698 /// \param Range Extra SourceRange to highlight in the diagnostic 12699 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12700 Expr::NullPointerConstantKind NullKind, 12701 bool IsEqual, SourceRange Range) { 12702 if (!E) 12703 return; 12704 12705 // Don't warn inside macros. 12706 if (E->getExprLoc().isMacroID()) { 12707 const SourceManager &SM = getSourceManager(); 12708 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12709 IsInAnyMacroBody(SM, Range.getBegin())) 12710 return; 12711 } 12712 E = E->IgnoreImpCasts(); 12713 12714 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12715 12716 if (isa<CXXThisExpr>(E)) { 12717 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12718 : diag::warn_this_bool_conversion; 12719 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12720 return; 12721 } 12722 12723 bool IsAddressOf = false; 12724 12725 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12726 if (UO->getOpcode() != UO_AddrOf) 12727 return; 12728 IsAddressOf = true; 12729 E = UO->getSubExpr(); 12730 } 12731 12732 if (IsAddressOf) { 12733 unsigned DiagID = IsCompare 12734 ? diag::warn_address_of_reference_null_compare 12735 : diag::warn_address_of_reference_bool_conversion; 12736 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12737 << IsEqual; 12738 if (CheckForReference(*this, E, PD)) { 12739 return; 12740 } 12741 } 12742 12743 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12744 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12745 std::string Str; 12746 llvm::raw_string_ostream S(Str); 12747 E->printPretty(S, nullptr, getPrintingPolicy()); 12748 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12749 : diag::warn_cast_nonnull_to_bool; 12750 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12751 << E->getSourceRange() << Range << IsEqual; 12752 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12753 }; 12754 12755 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12756 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12757 if (auto *Callee = Call->getDirectCallee()) { 12758 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12759 ComplainAboutNonnullParamOrCall(A); 12760 return; 12761 } 12762 } 12763 } 12764 12765 // Expect to find a single Decl. Skip anything more complicated. 12766 ValueDecl *D = nullptr; 12767 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12768 D = R->getDecl(); 12769 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12770 D = M->getMemberDecl(); 12771 } 12772 12773 // Weak Decls can be null. 12774 if (!D || D->isWeak()) 12775 return; 12776 12777 // Check for parameter decl with nonnull attribute 12778 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12779 if (getCurFunction() && 12780 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12781 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12782 ComplainAboutNonnullParamOrCall(A); 12783 return; 12784 } 12785 12786 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12787 // Skip function template not specialized yet. 12788 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12789 return; 12790 auto ParamIter = llvm::find(FD->parameters(), PV); 12791 assert(ParamIter != FD->param_end()); 12792 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12793 12794 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12795 if (!NonNull->args_size()) { 12796 ComplainAboutNonnullParamOrCall(NonNull); 12797 return; 12798 } 12799 12800 for (const ParamIdx &ArgNo : NonNull->args()) { 12801 if (ArgNo.getASTIndex() == ParamNo) { 12802 ComplainAboutNonnullParamOrCall(NonNull); 12803 return; 12804 } 12805 } 12806 } 12807 } 12808 } 12809 } 12810 12811 QualType T = D->getType(); 12812 const bool IsArray = T->isArrayType(); 12813 const bool IsFunction = T->isFunctionType(); 12814 12815 // Address of function is used to silence the function warning. 12816 if (IsAddressOf && IsFunction) { 12817 return; 12818 } 12819 12820 // Found nothing. 12821 if (!IsAddressOf && !IsFunction && !IsArray) 12822 return; 12823 12824 // Pretty print the expression for the diagnostic. 12825 std::string Str; 12826 llvm::raw_string_ostream S(Str); 12827 E->printPretty(S, nullptr, getPrintingPolicy()); 12828 12829 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12830 : diag::warn_impcast_pointer_to_bool; 12831 enum { 12832 AddressOf, 12833 FunctionPointer, 12834 ArrayPointer 12835 } DiagType; 12836 if (IsAddressOf) 12837 DiagType = AddressOf; 12838 else if (IsFunction) 12839 DiagType = FunctionPointer; 12840 else if (IsArray) 12841 DiagType = ArrayPointer; 12842 else 12843 llvm_unreachable("Could not determine diagnostic."); 12844 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12845 << Range << IsEqual; 12846 12847 if (!IsFunction) 12848 return; 12849 12850 // Suggest '&' to silence the function warning. 12851 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12852 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12853 12854 // Check to see if '()' fixit should be emitted. 12855 QualType ReturnType; 12856 UnresolvedSet<4> NonTemplateOverloads; 12857 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12858 if (ReturnType.isNull()) 12859 return; 12860 12861 if (IsCompare) { 12862 // There are two cases here. If there is null constant, the only suggest 12863 // for a pointer return type. If the null is 0, then suggest if the return 12864 // type is a pointer or an integer type. 12865 if (!ReturnType->isPointerType()) { 12866 if (NullKind == Expr::NPCK_ZeroExpression || 12867 NullKind == Expr::NPCK_ZeroLiteral) { 12868 if (!ReturnType->isIntegerType()) 12869 return; 12870 } else { 12871 return; 12872 } 12873 } 12874 } else { // !IsCompare 12875 // For function to bool, only suggest if the function pointer has bool 12876 // return type. 12877 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12878 return; 12879 } 12880 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12881 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12882 } 12883 12884 /// Diagnoses "dangerous" implicit conversions within the given 12885 /// expression (which is a full expression). Implements -Wconversion 12886 /// and -Wsign-compare. 12887 /// 12888 /// \param CC the "context" location of the implicit conversion, i.e. 12889 /// the most location of the syntactic entity requiring the implicit 12890 /// conversion 12891 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12892 // Don't diagnose in unevaluated contexts. 12893 if (isUnevaluatedContext()) 12894 return; 12895 12896 // Don't diagnose for value- or type-dependent expressions. 12897 if (E->isTypeDependent() || E->isValueDependent()) 12898 return; 12899 12900 // Check for array bounds violations in cases where the check isn't triggered 12901 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12902 // ArraySubscriptExpr is on the RHS of a variable initialization. 12903 CheckArrayAccess(E); 12904 12905 // This is not the right CC for (e.g.) a variable initialization. 12906 AnalyzeImplicitConversions(*this, E, CC); 12907 } 12908 12909 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12910 /// Input argument E is a logical expression. 12911 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12912 ::CheckBoolLikeConversion(*this, E, CC); 12913 } 12914 12915 /// Diagnose when expression is an integer constant expression and its evaluation 12916 /// results in integer overflow 12917 void Sema::CheckForIntOverflow (Expr *E) { 12918 // Use a work list to deal with nested struct initializers. 12919 SmallVector<Expr *, 2> Exprs(1, E); 12920 12921 do { 12922 Expr *OriginalE = Exprs.pop_back_val(); 12923 Expr *E = OriginalE->IgnoreParenCasts(); 12924 12925 if (isa<BinaryOperator>(E)) { 12926 E->EvaluateForOverflow(Context); 12927 continue; 12928 } 12929 12930 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12931 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12932 else if (isa<ObjCBoxedExpr>(OriginalE)) 12933 E->EvaluateForOverflow(Context); 12934 else if (auto Call = dyn_cast<CallExpr>(E)) 12935 Exprs.append(Call->arg_begin(), Call->arg_end()); 12936 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12937 Exprs.append(Message->arg_begin(), Message->arg_end()); 12938 } while (!Exprs.empty()); 12939 } 12940 12941 namespace { 12942 12943 /// Visitor for expressions which looks for unsequenced operations on the 12944 /// same object. 12945 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12946 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12947 12948 /// A tree of sequenced regions within an expression. Two regions are 12949 /// unsequenced if one is an ancestor or a descendent of the other. When we 12950 /// finish processing an expression with sequencing, such as a comma 12951 /// expression, we fold its tree nodes into its parent, since they are 12952 /// unsequenced with respect to nodes we will visit later. 12953 class SequenceTree { 12954 struct Value { 12955 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12956 unsigned Parent : 31; 12957 unsigned Merged : 1; 12958 }; 12959 SmallVector<Value, 8> Values; 12960 12961 public: 12962 /// A region within an expression which may be sequenced with respect 12963 /// to some other region. 12964 class Seq { 12965 friend class SequenceTree; 12966 12967 unsigned Index; 12968 12969 explicit Seq(unsigned N) : Index(N) {} 12970 12971 public: 12972 Seq() : Index(0) {} 12973 }; 12974 12975 SequenceTree() { Values.push_back(Value(0)); } 12976 Seq root() const { return Seq(0); } 12977 12978 /// Create a new sequence of operations, which is an unsequenced 12979 /// subset of \p Parent. This sequence of operations is sequenced with 12980 /// respect to other children of \p Parent. 12981 Seq allocate(Seq Parent) { 12982 Values.push_back(Value(Parent.Index)); 12983 return Seq(Values.size() - 1); 12984 } 12985 12986 /// Merge a sequence of operations into its parent. 12987 void merge(Seq S) { 12988 Values[S.Index].Merged = true; 12989 } 12990 12991 /// Determine whether two operations are unsequenced. This operation 12992 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12993 /// should have been merged into its parent as appropriate. 12994 bool isUnsequenced(Seq Cur, Seq Old) { 12995 unsigned C = representative(Cur.Index); 12996 unsigned Target = representative(Old.Index); 12997 while (C >= Target) { 12998 if (C == Target) 12999 return true; 13000 C = Values[C].Parent; 13001 } 13002 return false; 13003 } 13004 13005 private: 13006 /// Pick a representative for a sequence. 13007 unsigned representative(unsigned K) { 13008 if (Values[K].Merged) 13009 // Perform path compression as we go. 13010 return Values[K].Parent = representative(Values[K].Parent); 13011 return K; 13012 } 13013 }; 13014 13015 /// An object for which we can track unsequenced uses. 13016 using Object = const NamedDecl *; 13017 13018 /// Different flavors of object usage which we track. We only track the 13019 /// least-sequenced usage of each kind. 13020 enum UsageKind { 13021 /// A read of an object. Multiple unsequenced reads are OK. 13022 UK_Use, 13023 13024 /// A modification of an object which is sequenced before the value 13025 /// computation of the expression, such as ++n in C++. 13026 UK_ModAsValue, 13027 13028 /// A modification of an object which is not sequenced before the value 13029 /// computation of the expression, such as n++. 13030 UK_ModAsSideEffect, 13031 13032 UK_Count = UK_ModAsSideEffect + 1 13033 }; 13034 13035 /// Bundle together a sequencing region and the expression corresponding 13036 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13037 struct Usage { 13038 const Expr *UsageExpr; 13039 SequenceTree::Seq Seq; 13040 13041 Usage() : UsageExpr(nullptr), Seq() {} 13042 }; 13043 13044 struct UsageInfo { 13045 Usage Uses[UK_Count]; 13046 13047 /// Have we issued a diagnostic for this object already? 13048 bool Diagnosed; 13049 13050 UsageInfo() : Uses(), Diagnosed(false) {} 13051 }; 13052 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13053 13054 Sema &SemaRef; 13055 13056 /// Sequenced regions within the expression. 13057 SequenceTree Tree; 13058 13059 /// Declaration modifications and references which we have seen. 13060 UsageInfoMap UsageMap; 13061 13062 /// The region we are currently within. 13063 SequenceTree::Seq Region; 13064 13065 /// Filled in with declarations which were modified as a side-effect 13066 /// (that is, post-increment operations). 13067 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13068 13069 /// Expressions to check later. We defer checking these to reduce 13070 /// stack usage. 13071 SmallVectorImpl<const Expr *> &WorkList; 13072 13073 /// RAII object wrapping the visitation of a sequenced subexpression of an 13074 /// expression. At the end of this process, the side-effects of the evaluation 13075 /// become sequenced with respect to the value computation of the result, so 13076 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13077 /// UK_ModAsValue. 13078 struct SequencedSubexpression { 13079 SequencedSubexpression(SequenceChecker &Self) 13080 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13081 Self.ModAsSideEffect = &ModAsSideEffect; 13082 } 13083 13084 ~SequencedSubexpression() { 13085 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13086 // Add a new usage with usage kind UK_ModAsValue, and then restore 13087 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13088 // the previous one was empty). 13089 UsageInfo &UI = Self.UsageMap[M.first]; 13090 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13091 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13092 SideEffectUsage = M.second; 13093 } 13094 Self.ModAsSideEffect = OldModAsSideEffect; 13095 } 13096 13097 SequenceChecker &Self; 13098 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13099 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13100 }; 13101 13102 /// RAII object wrapping the visitation of a subexpression which we might 13103 /// choose to evaluate as a constant. If any subexpression is evaluated and 13104 /// found to be non-constant, this allows us to suppress the evaluation of 13105 /// the outer expression. 13106 class EvaluationTracker { 13107 public: 13108 EvaluationTracker(SequenceChecker &Self) 13109 : Self(Self), Prev(Self.EvalTracker) { 13110 Self.EvalTracker = this; 13111 } 13112 13113 ~EvaluationTracker() { 13114 Self.EvalTracker = Prev; 13115 if (Prev) 13116 Prev->EvalOK &= EvalOK; 13117 } 13118 13119 bool evaluate(const Expr *E, bool &Result) { 13120 if (!EvalOK || E->isValueDependent()) 13121 return false; 13122 EvalOK = E->EvaluateAsBooleanCondition( 13123 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13124 return EvalOK; 13125 } 13126 13127 private: 13128 SequenceChecker &Self; 13129 EvaluationTracker *Prev; 13130 bool EvalOK = true; 13131 } *EvalTracker = nullptr; 13132 13133 /// Find the object which is produced by the specified expression, 13134 /// if any. 13135 Object getObject(const Expr *E, bool Mod) const { 13136 E = E->IgnoreParenCasts(); 13137 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13138 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13139 return getObject(UO->getSubExpr(), Mod); 13140 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13141 if (BO->getOpcode() == BO_Comma) 13142 return getObject(BO->getRHS(), Mod); 13143 if (Mod && BO->isAssignmentOp()) 13144 return getObject(BO->getLHS(), Mod); 13145 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13146 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13147 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13148 return ME->getMemberDecl(); 13149 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13150 // FIXME: If this is a reference, map through to its value. 13151 return DRE->getDecl(); 13152 return nullptr; 13153 } 13154 13155 /// Note that an object \p O was modified or used by an expression 13156 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13157 /// the object \p O as obtained via the \p UsageMap. 13158 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13159 // Get the old usage for the given object and usage kind. 13160 Usage &U = UI.Uses[UK]; 13161 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13162 // If we have a modification as side effect and are in a sequenced 13163 // subexpression, save the old Usage so that we can restore it later 13164 // in SequencedSubexpression::~SequencedSubexpression. 13165 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13166 ModAsSideEffect->push_back(std::make_pair(O, U)); 13167 // Then record the new usage with the current sequencing region. 13168 U.UsageExpr = UsageExpr; 13169 U.Seq = Region; 13170 } 13171 } 13172 13173 /// Check whether a modification or use of an object \p O in an expression 13174 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13175 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13176 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13177 /// usage and false we are checking for a mod-use unsequenced usage. 13178 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13179 UsageKind OtherKind, bool IsModMod) { 13180 if (UI.Diagnosed) 13181 return; 13182 13183 const Usage &U = UI.Uses[OtherKind]; 13184 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13185 return; 13186 13187 const Expr *Mod = U.UsageExpr; 13188 const Expr *ModOrUse = UsageExpr; 13189 if (OtherKind == UK_Use) 13190 std::swap(Mod, ModOrUse); 13191 13192 SemaRef.DiagRuntimeBehavior( 13193 Mod->getExprLoc(), {Mod, ModOrUse}, 13194 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13195 : diag::warn_unsequenced_mod_use) 13196 << O << SourceRange(ModOrUse->getExprLoc())); 13197 UI.Diagnosed = true; 13198 } 13199 13200 // A note on note{Pre, Post}{Use, Mod}: 13201 // 13202 // (It helps to follow the algorithm with an expression such as 13203 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13204 // operations before C++17 and both are well-defined in C++17). 13205 // 13206 // When visiting a node which uses/modify an object we first call notePreUse 13207 // or notePreMod before visiting its sub-expression(s). At this point the 13208 // children of the current node have not yet been visited and so the eventual 13209 // uses/modifications resulting from the children of the current node have not 13210 // been recorded yet. 13211 // 13212 // We then visit the children of the current node. After that notePostUse or 13213 // notePostMod is called. These will 1) detect an unsequenced modification 13214 // as side effect (as in "k++ + k") and 2) add a new usage with the 13215 // appropriate usage kind. 13216 // 13217 // We also have to be careful that some operation sequences modification as 13218 // side effect as well (for example: || or ,). To account for this we wrap 13219 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13220 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13221 // which record usages which are modifications as side effect, and then 13222 // downgrade them (or more accurately restore the previous usage which was a 13223 // modification as side effect) when exiting the scope of the sequenced 13224 // subexpression. 13225 13226 void notePreUse(Object O, const Expr *UseExpr) { 13227 UsageInfo &UI = UsageMap[O]; 13228 // Uses conflict with other modifications. 13229 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13230 } 13231 13232 void notePostUse(Object O, const Expr *UseExpr) { 13233 UsageInfo &UI = UsageMap[O]; 13234 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13235 /*IsModMod=*/false); 13236 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13237 } 13238 13239 void notePreMod(Object O, const Expr *ModExpr) { 13240 UsageInfo &UI = UsageMap[O]; 13241 // Modifications conflict with other modifications and with uses. 13242 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13243 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13244 } 13245 13246 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13247 UsageInfo &UI = UsageMap[O]; 13248 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13249 /*IsModMod=*/true); 13250 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13251 } 13252 13253 public: 13254 SequenceChecker(Sema &S, const Expr *E, 13255 SmallVectorImpl<const Expr *> &WorkList) 13256 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13257 Visit(E); 13258 // Silence a -Wunused-private-field since WorkList is now unused. 13259 // TODO: Evaluate if it can be used, and if not remove it. 13260 (void)this->WorkList; 13261 } 13262 13263 void VisitStmt(const Stmt *S) { 13264 // Skip all statements which aren't expressions for now. 13265 } 13266 13267 void VisitExpr(const Expr *E) { 13268 // By default, just recurse to evaluated subexpressions. 13269 Base::VisitStmt(E); 13270 } 13271 13272 void VisitCastExpr(const CastExpr *E) { 13273 Object O = Object(); 13274 if (E->getCastKind() == CK_LValueToRValue) 13275 O = getObject(E->getSubExpr(), false); 13276 13277 if (O) 13278 notePreUse(O, E); 13279 VisitExpr(E); 13280 if (O) 13281 notePostUse(O, E); 13282 } 13283 13284 void VisitSequencedExpressions(const Expr *SequencedBefore, 13285 const Expr *SequencedAfter) { 13286 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13287 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13288 SequenceTree::Seq OldRegion = Region; 13289 13290 { 13291 SequencedSubexpression SeqBefore(*this); 13292 Region = BeforeRegion; 13293 Visit(SequencedBefore); 13294 } 13295 13296 Region = AfterRegion; 13297 Visit(SequencedAfter); 13298 13299 Region = OldRegion; 13300 13301 Tree.merge(BeforeRegion); 13302 Tree.merge(AfterRegion); 13303 } 13304 13305 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13306 // C++17 [expr.sub]p1: 13307 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13308 // expression E1 is sequenced before the expression E2. 13309 if (SemaRef.getLangOpts().CPlusPlus17) 13310 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13311 else { 13312 Visit(ASE->getLHS()); 13313 Visit(ASE->getRHS()); 13314 } 13315 } 13316 13317 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13318 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13319 void VisitBinPtrMem(const BinaryOperator *BO) { 13320 // C++17 [expr.mptr.oper]p4: 13321 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13322 // the expression E1 is sequenced before the expression E2. 13323 if (SemaRef.getLangOpts().CPlusPlus17) 13324 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13325 else { 13326 Visit(BO->getLHS()); 13327 Visit(BO->getRHS()); 13328 } 13329 } 13330 13331 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13332 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13333 void VisitBinShlShr(const BinaryOperator *BO) { 13334 // C++17 [expr.shift]p4: 13335 // The expression E1 is sequenced before the expression E2. 13336 if (SemaRef.getLangOpts().CPlusPlus17) 13337 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13338 else { 13339 Visit(BO->getLHS()); 13340 Visit(BO->getRHS()); 13341 } 13342 } 13343 13344 void VisitBinComma(const BinaryOperator *BO) { 13345 // C++11 [expr.comma]p1: 13346 // Every value computation and side effect associated with the left 13347 // expression is sequenced before every value computation and side 13348 // effect associated with the right expression. 13349 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13350 } 13351 13352 void VisitBinAssign(const BinaryOperator *BO) { 13353 SequenceTree::Seq RHSRegion; 13354 SequenceTree::Seq LHSRegion; 13355 if (SemaRef.getLangOpts().CPlusPlus17) { 13356 RHSRegion = Tree.allocate(Region); 13357 LHSRegion = Tree.allocate(Region); 13358 } else { 13359 RHSRegion = Region; 13360 LHSRegion = Region; 13361 } 13362 SequenceTree::Seq OldRegion = Region; 13363 13364 // C++11 [expr.ass]p1: 13365 // [...] the assignment is sequenced after the value computation 13366 // of the right and left operands, [...] 13367 // 13368 // so check it before inspecting the operands and update the 13369 // map afterwards. 13370 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13371 if (O) 13372 notePreMod(O, BO); 13373 13374 if (SemaRef.getLangOpts().CPlusPlus17) { 13375 // C++17 [expr.ass]p1: 13376 // [...] The right operand is sequenced before the left operand. [...] 13377 { 13378 SequencedSubexpression SeqBefore(*this); 13379 Region = RHSRegion; 13380 Visit(BO->getRHS()); 13381 } 13382 13383 Region = LHSRegion; 13384 Visit(BO->getLHS()); 13385 13386 if (O && isa<CompoundAssignOperator>(BO)) 13387 notePostUse(O, BO); 13388 13389 } else { 13390 // C++11 does not specify any sequencing between the LHS and RHS. 13391 Region = LHSRegion; 13392 Visit(BO->getLHS()); 13393 13394 if (O && isa<CompoundAssignOperator>(BO)) 13395 notePostUse(O, BO); 13396 13397 Region = RHSRegion; 13398 Visit(BO->getRHS()); 13399 } 13400 13401 // C++11 [expr.ass]p1: 13402 // the assignment is sequenced [...] before the value computation of the 13403 // assignment expression. 13404 // C11 6.5.16/3 has no such rule. 13405 Region = OldRegion; 13406 if (O) 13407 notePostMod(O, BO, 13408 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13409 : UK_ModAsSideEffect); 13410 if (SemaRef.getLangOpts().CPlusPlus17) { 13411 Tree.merge(RHSRegion); 13412 Tree.merge(LHSRegion); 13413 } 13414 } 13415 13416 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13417 VisitBinAssign(CAO); 13418 } 13419 13420 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13421 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13422 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13423 Object O = getObject(UO->getSubExpr(), true); 13424 if (!O) 13425 return VisitExpr(UO); 13426 13427 notePreMod(O, UO); 13428 Visit(UO->getSubExpr()); 13429 // C++11 [expr.pre.incr]p1: 13430 // the expression ++x is equivalent to x+=1 13431 notePostMod(O, UO, 13432 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13433 : UK_ModAsSideEffect); 13434 } 13435 13436 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13437 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13438 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13439 Object O = getObject(UO->getSubExpr(), true); 13440 if (!O) 13441 return VisitExpr(UO); 13442 13443 notePreMod(O, UO); 13444 Visit(UO->getSubExpr()); 13445 notePostMod(O, UO, UK_ModAsSideEffect); 13446 } 13447 13448 void VisitBinLOr(const BinaryOperator *BO) { 13449 // C++11 [expr.log.or]p2: 13450 // If the second expression is evaluated, every value computation and 13451 // side effect associated with the first expression is sequenced before 13452 // every value computation and side effect associated with the 13453 // second expression. 13454 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13455 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13456 SequenceTree::Seq OldRegion = Region; 13457 13458 EvaluationTracker Eval(*this); 13459 { 13460 SequencedSubexpression Sequenced(*this); 13461 Region = LHSRegion; 13462 Visit(BO->getLHS()); 13463 } 13464 13465 // C++11 [expr.log.or]p1: 13466 // [...] the second operand is not evaluated if the first operand 13467 // evaluates to true. 13468 bool EvalResult = false; 13469 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13470 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13471 if (ShouldVisitRHS) { 13472 Region = RHSRegion; 13473 Visit(BO->getRHS()); 13474 } 13475 13476 Region = OldRegion; 13477 Tree.merge(LHSRegion); 13478 Tree.merge(RHSRegion); 13479 } 13480 13481 void VisitBinLAnd(const BinaryOperator *BO) { 13482 // C++11 [expr.log.and]p2: 13483 // If the second expression is evaluated, every value computation and 13484 // side effect associated with the first expression is sequenced before 13485 // every value computation and side effect associated with the 13486 // second expression. 13487 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13488 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13489 SequenceTree::Seq OldRegion = Region; 13490 13491 EvaluationTracker Eval(*this); 13492 { 13493 SequencedSubexpression Sequenced(*this); 13494 Region = LHSRegion; 13495 Visit(BO->getLHS()); 13496 } 13497 13498 // C++11 [expr.log.and]p1: 13499 // [...] the second operand is not evaluated if the first operand is false. 13500 bool EvalResult = false; 13501 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13502 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13503 if (ShouldVisitRHS) { 13504 Region = RHSRegion; 13505 Visit(BO->getRHS()); 13506 } 13507 13508 Region = OldRegion; 13509 Tree.merge(LHSRegion); 13510 Tree.merge(RHSRegion); 13511 } 13512 13513 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13514 // C++11 [expr.cond]p1: 13515 // [...] Every value computation and side effect associated with the first 13516 // expression is sequenced before every value computation and side effect 13517 // associated with the second or third expression. 13518 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13519 13520 // No sequencing is specified between the true and false expression. 13521 // However since exactly one of both is going to be evaluated we can 13522 // consider them to be sequenced. This is needed to avoid warning on 13523 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13524 // both the true and false expressions because we can't evaluate x. 13525 // This will still allow us to detect an expression like (pre C++17) 13526 // "(x ? y += 1 : y += 2) = y". 13527 // 13528 // We don't wrap the visitation of the true and false expression with 13529 // SequencedSubexpression because we don't want to downgrade modifications 13530 // as side effect in the true and false expressions after the visition 13531 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13532 // not warn between the two "y++", but we should warn between the "y++" 13533 // and the "y". 13534 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13535 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13536 SequenceTree::Seq OldRegion = Region; 13537 13538 EvaluationTracker Eval(*this); 13539 { 13540 SequencedSubexpression Sequenced(*this); 13541 Region = ConditionRegion; 13542 Visit(CO->getCond()); 13543 } 13544 13545 // C++11 [expr.cond]p1: 13546 // [...] The first expression is contextually converted to bool (Clause 4). 13547 // It is evaluated and if it is true, the result of the conditional 13548 // expression is the value of the second expression, otherwise that of the 13549 // third expression. Only one of the second and third expressions is 13550 // evaluated. [...] 13551 bool EvalResult = false; 13552 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13553 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13554 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13555 if (ShouldVisitTrueExpr) { 13556 Region = TrueRegion; 13557 Visit(CO->getTrueExpr()); 13558 } 13559 if (ShouldVisitFalseExpr) { 13560 Region = FalseRegion; 13561 Visit(CO->getFalseExpr()); 13562 } 13563 13564 Region = OldRegion; 13565 Tree.merge(ConditionRegion); 13566 Tree.merge(TrueRegion); 13567 Tree.merge(FalseRegion); 13568 } 13569 13570 void VisitCallExpr(const CallExpr *CE) { 13571 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13572 13573 if (CE->isUnevaluatedBuiltinCall(Context)) 13574 return; 13575 13576 // C++11 [intro.execution]p15: 13577 // When calling a function [...], every value computation and side effect 13578 // associated with any argument expression, or with the postfix expression 13579 // designating the called function, is sequenced before execution of every 13580 // expression or statement in the body of the function [and thus before 13581 // the value computation of its result]. 13582 SequencedSubexpression Sequenced(*this); 13583 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13584 // C++17 [expr.call]p5 13585 // The postfix-expression is sequenced before each expression in the 13586 // expression-list and any default argument. [...] 13587 SequenceTree::Seq CalleeRegion; 13588 SequenceTree::Seq OtherRegion; 13589 if (SemaRef.getLangOpts().CPlusPlus17) { 13590 CalleeRegion = Tree.allocate(Region); 13591 OtherRegion = Tree.allocate(Region); 13592 } else { 13593 CalleeRegion = Region; 13594 OtherRegion = Region; 13595 } 13596 SequenceTree::Seq OldRegion = Region; 13597 13598 // Visit the callee expression first. 13599 Region = CalleeRegion; 13600 if (SemaRef.getLangOpts().CPlusPlus17) { 13601 SequencedSubexpression Sequenced(*this); 13602 Visit(CE->getCallee()); 13603 } else { 13604 Visit(CE->getCallee()); 13605 } 13606 13607 // Then visit the argument expressions. 13608 Region = OtherRegion; 13609 for (const Expr *Argument : CE->arguments()) 13610 Visit(Argument); 13611 13612 Region = OldRegion; 13613 if (SemaRef.getLangOpts().CPlusPlus17) { 13614 Tree.merge(CalleeRegion); 13615 Tree.merge(OtherRegion); 13616 } 13617 }); 13618 } 13619 13620 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13621 // C++17 [over.match.oper]p2: 13622 // [...] the operator notation is first transformed to the equivalent 13623 // function-call notation as summarized in Table 12 (where @ denotes one 13624 // of the operators covered in the specified subclause). However, the 13625 // operands are sequenced in the order prescribed for the built-in 13626 // operator (Clause 8). 13627 // 13628 // From the above only overloaded binary operators and overloaded call 13629 // operators have sequencing rules in C++17 that we need to handle 13630 // separately. 13631 if (!SemaRef.getLangOpts().CPlusPlus17 || 13632 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13633 return VisitCallExpr(CXXOCE); 13634 13635 enum { 13636 NoSequencing, 13637 LHSBeforeRHS, 13638 RHSBeforeLHS, 13639 LHSBeforeRest 13640 } SequencingKind; 13641 switch (CXXOCE->getOperator()) { 13642 case OO_Equal: 13643 case OO_PlusEqual: 13644 case OO_MinusEqual: 13645 case OO_StarEqual: 13646 case OO_SlashEqual: 13647 case OO_PercentEqual: 13648 case OO_CaretEqual: 13649 case OO_AmpEqual: 13650 case OO_PipeEqual: 13651 case OO_LessLessEqual: 13652 case OO_GreaterGreaterEqual: 13653 SequencingKind = RHSBeforeLHS; 13654 break; 13655 13656 case OO_LessLess: 13657 case OO_GreaterGreater: 13658 case OO_AmpAmp: 13659 case OO_PipePipe: 13660 case OO_Comma: 13661 case OO_ArrowStar: 13662 case OO_Subscript: 13663 SequencingKind = LHSBeforeRHS; 13664 break; 13665 13666 case OO_Call: 13667 SequencingKind = LHSBeforeRest; 13668 break; 13669 13670 default: 13671 SequencingKind = NoSequencing; 13672 break; 13673 } 13674 13675 if (SequencingKind == NoSequencing) 13676 return VisitCallExpr(CXXOCE); 13677 13678 // This is a call, so all subexpressions are sequenced before the result. 13679 SequencedSubexpression Sequenced(*this); 13680 13681 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13682 assert(SemaRef.getLangOpts().CPlusPlus17 && 13683 "Should only get there with C++17 and above!"); 13684 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13685 "Should only get there with an overloaded binary operator" 13686 " or an overloaded call operator!"); 13687 13688 if (SequencingKind == LHSBeforeRest) { 13689 assert(CXXOCE->getOperator() == OO_Call && 13690 "We should only have an overloaded call operator here!"); 13691 13692 // This is very similar to VisitCallExpr, except that we only have the 13693 // C++17 case. The postfix-expression is the first argument of the 13694 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13695 // are in the following arguments. 13696 // 13697 // Note that we intentionally do not visit the callee expression since 13698 // it is just a decayed reference to a function. 13699 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13700 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13701 SequenceTree::Seq OldRegion = Region; 13702 13703 assert(CXXOCE->getNumArgs() >= 1 && 13704 "An overloaded call operator must have at least one argument" 13705 " for the postfix-expression!"); 13706 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13707 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13708 CXXOCE->getNumArgs() - 1); 13709 13710 // Visit the postfix-expression first. 13711 { 13712 Region = PostfixExprRegion; 13713 SequencedSubexpression Sequenced(*this); 13714 Visit(PostfixExpr); 13715 } 13716 13717 // Then visit the argument expressions. 13718 Region = ArgsRegion; 13719 for (const Expr *Arg : Args) 13720 Visit(Arg); 13721 13722 Region = OldRegion; 13723 Tree.merge(PostfixExprRegion); 13724 Tree.merge(ArgsRegion); 13725 } else { 13726 assert(CXXOCE->getNumArgs() == 2 && 13727 "Should only have two arguments here!"); 13728 assert((SequencingKind == LHSBeforeRHS || 13729 SequencingKind == RHSBeforeLHS) && 13730 "Unexpected sequencing kind!"); 13731 13732 // We do not visit the callee expression since it is just a decayed 13733 // reference to a function. 13734 const Expr *E1 = CXXOCE->getArg(0); 13735 const Expr *E2 = CXXOCE->getArg(1); 13736 if (SequencingKind == RHSBeforeLHS) 13737 std::swap(E1, E2); 13738 13739 return VisitSequencedExpressions(E1, E2); 13740 } 13741 }); 13742 } 13743 13744 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13745 // This is a call, so all subexpressions are sequenced before the result. 13746 SequencedSubexpression Sequenced(*this); 13747 13748 if (!CCE->isListInitialization()) 13749 return VisitExpr(CCE); 13750 13751 // In C++11, list initializations are sequenced. 13752 SmallVector<SequenceTree::Seq, 32> Elts; 13753 SequenceTree::Seq Parent = Region; 13754 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13755 E = CCE->arg_end(); 13756 I != E; ++I) { 13757 Region = Tree.allocate(Parent); 13758 Elts.push_back(Region); 13759 Visit(*I); 13760 } 13761 13762 // Forget that the initializers are sequenced. 13763 Region = Parent; 13764 for (unsigned I = 0; I < Elts.size(); ++I) 13765 Tree.merge(Elts[I]); 13766 } 13767 13768 void VisitInitListExpr(const InitListExpr *ILE) { 13769 if (!SemaRef.getLangOpts().CPlusPlus11) 13770 return VisitExpr(ILE); 13771 13772 // In C++11, list initializations are sequenced. 13773 SmallVector<SequenceTree::Seq, 32> Elts; 13774 SequenceTree::Seq Parent = Region; 13775 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13776 const Expr *E = ILE->getInit(I); 13777 if (!E) 13778 continue; 13779 Region = Tree.allocate(Parent); 13780 Elts.push_back(Region); 13781 Visit(E); 13782 } 13783 13784 // Forget that the initializers are sequenced. 13785 Region = Parent; 13786 for (unsigned I = 0; I < Elts.size(); ++I) 13787 Tree.merge(Elts[I]); 13788 } 13789 }; 13790 13791 } // namespace 13792 13793 void Sema::CheckUnsequencedOperations(const Expr *E) { 13794 SmallVector<const Expr *, 8> WorkList; 13795 WorkList.push_back(E); 13796 while (!WorkList.empty()) { 13797 const Expr *Item = WorkList.pop_back_val(); 13798 SequenceChecker(*this, Item, WorkList); 13799 } 13800 } 13801 13802 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13803 bool IsConstexpr) { 13804 llvm::SaveAndRestore<bool> ConstantContext( 13805 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13806 CheckImplicitConversions(E, CheckLoc); 13807 if (!E->isInstantiationDependent()) 13808 CheckUnsequencedOperations(E); 13809 if (!IsConstexpr && !E->isValueDependent()) 13810 CheckForIntOverflow(E); 13811 DiagnoseMisalignedMembers(); 13812 } 13813 13814 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13815 FieldDecl *BitField, 13816 Expr *Init) { 13817 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13818 } 13819 13820 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13821 SourceLocation Loc) { 13822 if (!PType->isVariablyModifiedType()) 13823 return; 13824 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13825 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13826 return; 13827 } 13828 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13829 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13830 return; 13831 } 13832 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13833 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13834 return; 13835 } 13836 13837 const ArrayType *AT = S.Context.getAsArrayType(PType); 13838 if (!AT) 13839 return; 13840 13841 if (AT->getSizeModifier() != ArrayType::Star) { 13842 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13843 return; 13844 } 13845 13846 S.Diag(Loc, diag::err_array_star_in_function_definition); 13847 } 13848 13849 /// CheckParmsForFunctionDef - Check that the parameters of the given 13850 /// function are appropriate for the definition of a function. This 13851 /// takes care of any checks that cannot be performed on the 13852 /// declaration itself, e.g., that the types of each of the function 13853 /// parameters are complete. 13854 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13855 bool CheckParameterNames) { 13856 bool HasInvalidParm = false; 13857 for (ParmVarDecl *Param : Parameters) { 13858 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13859 // function declarator that is part of a function definition of 13860 // that function shall not have incomplete type. 13861 // 13862 // This is also C++ [dcl.fct]p6. 13863 if (!Param->isInvalidDecl() && 13864 RequireCompleteType(Param->getLocation(), Param->getType(), 13865 diag::err_typecheck_decl_incomplete_type)) { 13866 Param->setInvalidDecl(); 13867 HasInvalidParm = true; 13868 } 13869 13870 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13871 // declaration of each parameter shall include an identifier. 13872 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13873 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13874 // Diagnose this as an extension in C17 and earlier. 13875 if (!getLangOpts().C2x) 13876 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13877 } 13878 13879 // C99 6.7.5.3p12: 13880 // If the function declarator is not part of a definition of that 13881 // function, parameters may have incomplete type and may use the [*] 13882 // notation in their sequences of declarator specifiers to specify 13883 // variable length array types. 13884 QualType PType = Param->getOriginalType(); 13885 // FIXME: This diagnostic should point the '[*]' if source-location 13886 // information is added for it. 13887 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13888 13889 // If the parameter is a c++ class type and it has to be destructed in the 13890 // callee function, declare the destructor so that it can be called by the 13891 // callee function. Do not perform any direct access check on the dtor here. 13892 if (!Param->isInvalidDecl()) { 13893 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13894 if (!ClassDecl->isInvalidDecl() && 13895 !ClassDecl->hasIrrelevantDestructor() && 13896 !ClassDecl->isDependentContext() && 13897 ClassDecl->isParamDestroyedInCallee()) { 13898 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13899 MarkFunctionReferenced(Param->getLocation(), Destructor); 13900 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13901 } 13902 } 13903 } 13904 13905 // Parameters with the pass_object_size attribute only need to be marked 13906 // constant at function definitions. Because we lack information about 13907 // whether we're on a declaration or definition when we're instantiating the 13908 // attribute, we need to check for constness here. 13909 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13910 if (!Param->getType().isConstQualified()) 13911 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13912 << Attr->getSpelling() << 1; 13913 13914 // Check for parameter names shadowing fields from the class. 13915 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13916 // The owning context for the parameter should be the function, but we 13917 // want to see if this function's declaration context is a record. 13918 DeclContext *DC = Param->getDeclContext(); 13919 if (DC && DC->isFunctionOrMethod()) { 13920 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13921 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13922 RD, /*DeclIsField*/ false); 13923 } 13924 } 13925 } 13926 13927 return HasInvalidParm; 13928 } 13929 13930 Optional<std::pair<CharUnits, CharUnits>> 13931 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13932 13933 /// Compute the alignment and offset of the base class object given the 13934 /// derived-to-base cast expression and the alignment and offset of the derived 13935 /// class object. 13936 static std::pair<CharUnits, CharUnits> 13937 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13938 CharUnits BaseAlignment, CharUnits Offset, 13939 ASTContext &Ctx) { 13940 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13941 ++PathI) { 13942 const CXXBaseSpecifier *Base = *PathI; 13943 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13944 if (Base->isVirtual()) { 13945 // The complete object may have a lower alignment than the non-virtual 13946 // alignment of the base, in which case the base may be misaligned. Choose 13947 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13948 // conservative lower bound of the complete object alignment. 13949 CharUnits NonVirtualAlignment = 13950 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13951 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13952 Offset = CharUnits::Zero(); 13953 } else { 13954 const ASTRecordLayout &RL = 13955 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13956 Offset += RL.getBaseClassOffset(BaseDecl); 13957 } 13958 DerivedType = Base->getType(); 13959 } 13960 13961 return std::make_pair(BaseAlignment, Offset); 13962 } 13963 13964 /// Compute the alignment and offset of a binary additive operator. 13965 static Optional<std::pair<CharUnits, CharUnits>> 13966 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13967 bool IsSub, ASTContext &Ctx) { 13968 QualType PointeeType = PtrE->getType()->getPointeeType(); 13969 13970 if (!PointeeType->isConstantSizeType()) 13971 return llvm::None; 13972 13973 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13974 13975 if (!P) 13976 return llvm::None; 13977 13978 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13979 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13980 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13981 if (IsSub) 13982 Offset = -Offset; 13983 return std::make_pair(P->first, P->second + Offset); 13984 } 13985 13986 // If the integer expression isn't a constant expression, compute the lower 13987 // bound of the alignment using the alignment and offset of the pointer 13988 // expression and the element size. 13989 return std::make_pair( 13990 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13991 CharUnits::Zero()); 13992 } 13993 13994 /// This helper function takes an lvalue expression and returns the alignment of 13995 /// a VarDecl and a constant offset from the VarDecl. 13996 Optional<std::pair<CharUnits, CharUnits>> 13997 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13998 E = E->IgnoreParens(); 13999 switch (E->getStmtClass()) { 14000 default: 14001 break; 14002 case Stmt::CStyleCastExprClass: 14003 case Stmt::CXXStaticCastExprClass: 14004 case Stmt::ImplicitCastExprClass: { 14005 auto *CE = cast<CastExpr>(E); 14006 const Expr *From = CE->getSubExpr(); 14007 switch (CE->getCastKind()) { 14008 default: 14009 break; 14010 case CK_NoOp: 14011 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14012 case CK_UncheckedDerivedToBase: 14013 case CK_DerivedToBase: { 14014 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14015 if (!P) 14016 break; 14017 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14018 P->second, Ctx); 14019 } 14020 } 14021 break; 14022 } 14023 case Stmt::ArraySubscriptExprClass: { 14024 auto *ASE = cast<ArraySubscriptExpr>(E); 14025 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14026 false, Ctx); 14027 } 14028 case Stmt::DeclRefExprClass: { 14029 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14030 // FIXME: If VD is captured by copy or is an escaping __block variable, 14031 // use the alignment of VD's type. 14032 if (!VD->getType()->isReferenceType()) 14033 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14034 if (VD->hasInit()) 14035 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14036 } 14037 break; 14038 } 14039 case Stmt::MemberExprClass: { 14040 auto *ME = cast<MemberExpr>(E); 14041 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14042 if (!FD || FD->getType()->isReferenceType()) 14043 break; 14044 Optional<std::pair<CharUnits, CharUnits>> P; 14045 if (ME->isArrow()) 14046 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14047 else 14048 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14049 if (!P) 14050 break; 14051 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14052 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14053 return std::make_pair(P->first, 14054 P->second + CharUnits::fromQuantity(Offset)); 14055 } 14056 case Stmt::UnaryOperatorClass: { 14057 auto *UO = cast<UnaryOperator>(E); 14058 switch (UO->getOpcode()) { 14059 default: 14060 break; 14061 case UO_Deref: 14062 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14063 } 14064 break; 14065 } 14066 case Stmt::BinaryOperatorClass: { 14067 auto *BO = cast<BinaryOperator>(E); 14068 auto Opcode = BO->getOpcode(); 14069 switch (Opcode) { 14070 default: 14071 break; 14072 case BO_Comma: 14073 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14074 } 14075 break; 14076 } 14077 } 14078 return llvm::None; 14079 } 14080 14081 /// This helper function takes a pointer expression and returns the alignment of 14082 /// a VarDecl and a constant offset from the VarDecl. 14083 Optional<std::pair<CharUnits, CharUnits>> 14084 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14085 E = E->IgnoreParens(); 14086 switch (E->getStmtClass()) { 14087 default: 14088 break; 14089 case Stmt::CStyleCastExprClass: 14090 case Stmt::CXXStaticCastExprClass: 14091 case Stmt::ImplicitCastExprClass: { 14092 auto *CE = cast<CastExpr>(E); 14093 const Expr *From = CE->getSubExpr(); 14094 switch (CE->getCastKind()) { 14095 default: 14096 break; 14097 case CK_NoOp: 14098 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14099 case CK_ArrayToPointerDecay: 14100 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14101 case CK_UncheckedDerivedToBase: 14102 case CK_DerivedToBase: { 14103 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14104 if (!P) 14105 break; 14106 return getDerivedToBaseAlignmentAndOffset( 14107 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14108 } 14109 } 14110 break; 14111 } 14112 case Stmt::CXXThisExprClass: { 14113 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14114 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14115 return std::make_pair(Alignment, CharUnits::Zero()); 14116 } 14117 case Stmt::UnaryOperatorClass: { 14118 auto *UO = cast<UnaryOperator>(E); 14119 if (UO->getOpcode() == UO_AddrOf) 14120 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14121 break; 14122 } 14123 case Stmt::BinaryOperatorClass: { 14124 auto *BO = cast<BinaryOperator>(E); 14125 auto Opcode = BO->getOpcode(); 14126 switch (Opcode) { 14127 default: 14128 break; 14129 case BO_Add: 14130 case BO_Sub: { 14131 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14132 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14133 std::swap(LHS, RHS); 14134 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14135 Ctx); 14136 } 14137 case BO_Comma: 14138 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14139 } 14140 break; 14141 } 14142 } 14143 return llvm::None; 14144 } 14145 14146 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14147 // See if we can compute the alignment of a VarDecl and an offset from it. 14148 Optional<std::pair<CharUnits, CharUnits>> P = 14149 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14150 14151 if (P) 14152 return P->first.alignmentAtOffset(P->second); 14153 14154 // If that failed, return the type's alignment. 14155 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14156 } 14157 14158 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14159 /// pointer cast increases the alignment requirements. 14160 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14161 // This is actually a lot of work to potentially be doing on every 14162 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14163 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14164 return; 14165 14166 // Ignore dependent types. 14167 if (T->isDependentType() || Op->getType()->isDependentType()) 14168 return; 14169 14170 // Require that the destination be a pointer type. 14171 const PointerType *DestPtr = T->getAs<PointerType>(); 14172 if (!DestPtr) return; 14173 14174 // If the destination has alignment 1, we're done. 14175 QualType DestPointee = DestPtr->getPointeeType(); 14176 if (DestPointee->isIncompleteType()) return; 14177 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14178 if (DestAlign.isOne()) return; 14179 14180 // Require that the source be a pointer type. 14181 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14182 if (!SrcPtr) return; 14183 QualType SrcPointee = SrcPtr->getPointeeType(); 14184 14185 // Explicitly allow casts from cv void*. We already implicitly 14186 // allowed casts to cv void*, since they have alignment 1. 14187 // Also allow casts involving incomplete types, which implicitly 14188 // includes 'void'. 14189 if (SrcPointee->isIncompleteType()) return; 14190 14191 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14192 14193 if (SrcAlign >= DestAlign) return; 14194 14195 Diag(TRange.getBegin(), diag::warn_cast_align) 14196 << Op->getType() << T 14197 << static_cast<unsigned>(SrcAlign.getQuantity()) 14198 << static_cast<unsigned>(DestAlign.getQuantity()) 14199 << TRange << Op->getSourceRange(); 14200 } 14201 14202 /// Check whether this array fits the idiom of a size-one tail padded 14203 /// array member of a struct. 14204 /// 14205 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14206 /// commonly used to emulate flexible arrays in C89 code. 14207 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14208 const NamedDecl *ND) { 14209 if (Size != 1 || !ND) return false; 14210 14211 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14212 if (!FD) return false; 14213 14214 // Don't consider sizes resulting from macro expansions or template argument 14215 // substitution to form C89 tail-padded arrays. 14216 14217 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14218 while (TInfo) { 14219 TypeLoc TL = TInfo->getTypeLoc(); 14220 // Look through typedefs. 14221 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14222 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14223 TInfo = TDL->getTypeSourceInfo(); 14224 continue; 14225 } 14226 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14227 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14228 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14229 return false; 14230 } 14231 break; 14232 } 14233 14234 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14235 if (!RD) return false; 14236 if (RD->isUnion()) return false; 14237 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14238 if (!CRD->isStandardLayout()) return false; 14239 } 14240 14241 // See if this is the last field decl in the record. 14242 const Decl *D = FD; 14243 while ((D = D->getNextDeclInContext())) 14244 if (isa<FieldDecl>(D)) 14245 return false; 14246 return true; 14247 } 14248 14249 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14250 const ArraySubscriptExpr *ASE, 14251 bool AllowOnePastEnd, bool IndexNegated) { 14252 // Already diagnosed by the constant evaluator. 14253 if (isConstantEvaluated()) 14254 return; 14255 14256 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14257 if (IndexExpr->isValueDependent()) 14258 return; 14259 14260 const Type *EffectiveType = 14261 BaseExpr->getType()->getPointeeOrArrayElementType(); 14262 BaseExpr = BaseExpr->IgnoreParenCasts(); 14263 const ConstantArrayType *ArrayTy = 14264 Context.getAsConstantArrayType(BaseExpr->getType()); 14265 14266 if (!ArrayTy) 14267 return; 14268 14269 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14270 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14271 return; 14272 14273 Expr::EvalResult Result; 14274 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14275 return; 14276 14277 llvm::APSInt index = Result.Val.getInt(); 14278 if (IndexNegated) 14279 index = -index; 14280 14281 const NamedDecl *ND = nullptr; 14282 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14283 ND = DRE->getDecl(); 14284 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14285 ND = ME->getMemberDecl(); 14286 14287 if (index.isUnsigned() || !index.isNegative()) { 14288 // It is possible that the type of the base expression after 14289 // IgnoreParenCasts is incomplete, even though the type of the base 14290 // expression before IgnoreParenCasts is complete (see PR39746 for an 14291 // example). In this case we have no information about whether the array 14292 // access exceeds the array bounds. However we can still diagnose an array 14293 // access which precedes the array bounds. 14294 if (BaseType->isIncompleteType()) 14295 return; 14296 14297 llvm::APInt size = ArrayTy->getSize(); 14298 if (!size.isStrictlyPositive()) 14299 return; 14300 14301 if (BaseType != EffectiveType) { 14302 // Make sure we're comparing apples to apples when comparing index to size 14303 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14304 uint64_t array_typesize = Context.getTypeSize(BaseType); 14305 // Handle ptrarith_typesize being zero, such as when casting to void* 14306 if (!ptrarith_typesize) ptrarith_typesize = 1; 14307 if (ptrarith_typesize != array_typesize) { 14308 // There's a cast to a different size type involved 14309 uint64_t ratio = array_typesize / ptrarith_typesize; 14310 // TODO: Be smarter about handling cases where array_typesize is not a 14311 // multiple of ptrarith_typesize 14312 if (ptrarith_typesize * ratio == array_typesize) 14313 size *= llvm::APInt(size.getBitWidth(), ratio); 14314 } 14315 } 14316 14317 if (size.getBitWidth() > index.getBitWidth()) 14318 index = index.zext(size.getBitWidth()); 14319 else if (size.getBitWidth() < index.getBitWidth()) 14320 size = size.zext(index.getBitWidth()); 14321 14322 // For array subscripting the index must be less than size, but for pointer 14323 // arithmetic also allow the index (offset) to be equal to size since 14324 // computing the next address after the end of the array is legal and 14325 // commonly done e.g. in C++ iterators and range-based for loops. 14326 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14327 return; 14328 14329 // Also don't warn for arrays of size 1 which are members of some 14330 // structure. These are often used to approximate flexible arrays in C89 14331 // code. 14332 if (IsTailPaddedMemberArray(*this, size, ND)) 14333 return; 14334 14335 // Suppress the warning if the subscript expression (as identified by the 14336 // ']' location) and the index expression are both from macro expansions 14337 // within a system header. 14338 if (ASE) { 14339 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14340 ASE->getRBracketLoc()); 14341 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14342 SourceLocation IndexLoc = 14343 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14344 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14345 return; 14346 } 14347 } 14348 14349 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14350 if (ASE) 14351 DiagID = diag::warn_array_index_exceeds_bounds; 14352 14353 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14354 PDiag(DiagID) << index.toString(10, true) 14355 << size.toString(10, true) 14356 << (unsigned)size.getLimitedValue(~0U) 14357 << IndexExpr->getSourceRange()); 14358 } else { 14359 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14360 if (!ASE) { 14361 DiagID = diag::warn_ptr_arith_precedes_bounds; 14362 if (index.isNegative()) index = -index; 14363 } 14364 14365 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14366 PDiag(DiagID) << index.toString(10, true) 14367 << IndexExpr->getSourceRange()); 14368 } 14369 14370 if (!ND) { 14371 // Try harder to find a NamedDecl to point at in the note. 14372 while (const ArraySubscriptExpr *ASE = 14373 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14374 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14375 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14376 ND = DRE->getDecl(); 14377 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14378 ND = ME->getMemberDecl(); 14379 } 14380 14381 if (ND) 14382 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14383 PDiag(diag::note_array_declared_here) << ND); 14384 } 14385 14386 void Sema::CheckArrayAccess(const Expr *expr) { 14387 int AllowOnePastEnd = 0; 14388 while (expr) { 14389 expr = expr->IgnoreParenImpCasts(); 14390 switch (expr->getStmtClass()) { 14391 case Stmt::ArraySubscriptExprClass: { 14392 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14393 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14394 AllowOnePastEnd > 0); 14395 expr = ASE->getBase(); 14396 break; 14397 } 14398 case Stmt::MemberExprClass: { 14399 expr = cast<MemberExpr>(expr)->getBase(); 14400 break; 14401 } 14402 case Stmt::OMPArraySectionExprClass: { 14403 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14404 if (ASE->getLowerBound()) 14405 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14406 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14407 return; 14408 } 14409 case Stmt::UnaryOperatorClass: { 14410 // Only unwrap the * and & unary operators 14411 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14412 expr = UO->getSubExpr(); 14413 switch (UO->getOpcode()) { 14414 case UO_AddrOf: 14415 AllowOnePastEnd++; 14416 break; 14417 case UO_Deref: 14418 AllowOnePastEnd--; 14419 break; 14420 default: 14421 return; 14422 } 14423 break; 14424 } 14425 case Stmt::ConditionalOperatorClass: { 14426 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14427 if (const Expr *lhs = cond->getLHS()) 14428 CheckArrayAccess(lhs); 14429 if (const Expr *rhs = cond->getRHS()) 14430 CheckArrayAccess(rhs); 14431 return; 14432 } 14433 case Stmt::CXXOperatorCallExprClass: { 14434 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14435 for (const auto *Arg : OCE->arguments()) 14436 CheckArrayAccess(Arg); 14437 return; 14438 } 14439 default: 14440 return; 14441 } 14442 } 14443 } 14444 14445 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14446 14447 namespace { 14448 14449 struct RetainCycleOwner { 14450 VarDecl *Variable = nullptr; 14451 SourceRange Range; 14452 SourceLocation Loc; 14453 bool Indirect = false; 14454 14455 RetainCycleOwner() = default; 14456 14457 void setLocsFrom(Expr *e) { 14458 Loc = e->getExprLoc(); 14459 Range = e->getSourceRange(); 14460 } 14461 }; 14462 14463 } // namespace 14464 14465 /// Consider whether capturing the given variable can possibly lead to 14466 /// a retain cycle. 14467 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14468 // In ARC, it's captured strongly iff the variable has __strong 14469 // lifetime. In MRR, it's captured strongly if the variable is 14470 // __block and has an appropriate type. 14471 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14472 return false; 14473 14474 owner.Variable = var; 14475 if (ref) 14476 owner.setLocsFrom(ref); 14477 return true; 14478 } 14479 14480 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14481 while (true) { 14482 e = e->IgnoreParens(); 14483 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14484 switch (cast->getCastKind()) { 14485 case CK_BitCast: 14486 case CK_LValueBitCast: 14487 case CK_LValueToRValue: 14488 case CK_ARCReclaimReturnedObject: 14489 e = cast->getSubExpr(); 14490 continue; 14491 14492 default: 14493 return false; 14494 } 14495 } 14496 14497 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14498 ObjCIvarDecl *ivar = ref->getDecl(); 14499 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14500 return false; 14501 14502 // Try to find a retain cycle in the base. 14503 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14504 return false; 14505 14506 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14507 owner.Indirect = true; 14508 return true; 14509 } 14510 14511 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14512 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14513 if (!var) return false; 14514 return considerVariable(var, ref, owner); 14515 } 14516 14517 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14518 if (member->isArrow()) return false; 14519 14520 // Don't count this as an indirect ownership. 14521 e = member->getBase(); 14522 continue; 14523 } 14524 14525 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14526 // Only pay attention to pseudo-objects on property references. 14527 ObjCPropertyRefExpr *pre 14528 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14529 ->IgnoreParens()); 14530 if (!pre) return false; 14531 if (pre->isImplicitProperty()) return false; 14532 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14533 if (!property->isRetaining() && 14534 !(property->getPropertyIvarDecl() && 14535 property->getPropertyIvarDecl()->getType() 14536 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14537 return false; 14538 14539 owner.Indirect = true; 14540 if (pre->isSuperReceiver()) { 14541 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14542 if (!owner.Variable) 14543 return false; 14544 owner.Loc = pre->getLocation(); 14545 owner.Range = pre->getSourceRange(); 14546 return true; 14547 } 14548 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14549 ->getSourceExpr()); 14550 continue; 14551 } 14552 14553 // Array ivars? 14554 14555 return false; 14556 } 14557 } 14558 14559 namespace { 14560 14561 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14562 ASTContext &Context; 14563 VarDecl *Variable; 14564 Expr *Capturer = nullptr; 14565 bool VarWillBeReased = false; 14566 14567 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14568 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14569 Context(Context), Variable(variable) {} 14570 14571 void VisitDeclRefExpr(DeclRefExpr *ref) { 14572 if (ref->getDecl() == Variable && !Capturer) 14573 Capturer = ref; 14574 } 14575 14576 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14577 if (Capturer) return; 14578 Visit(ref->getBase()); 14579 if (Capturer && ref->isFreeIvar()) 14580 Capturer = ref; 14581 } 14582 14583 void VisitBlockExpr(BlockExpr *block) { 14584 // Look inside nested blocks 14585 if (block->getBlockDecl()->capturesVariable(Variable)) 14586 Visit(block->getBlockDecl()->getBody()); 14587 } 14588 14589 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14590 if (Capturer) return; 14591 if (OVE->getSourceExpr()) 14592 Visit(OVE->getSourceExpr()); 14593 } 14594 14595 void VisitBinaryOperator(BinaryOperator *BinOp) { 14596 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14597 return; 14598 Expr *LHS = BinOp->getLHS(); 14599 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14600 if (DRE->getDecl() != Variable) 14601 return; 14602 if (Expr *RHS = BinOp->getRHS()) { 14603 RHS = RHS->IgnoreParenCasts(); 14604 Optional<llvm::APSInt> Value; 14605 VarWillBeReased = 14606 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14607 *Value == 0); 14608 } 14609 } 14610 } 14611 }; 14612 14613 } // namespace 14614 14615 /// Check whether the given argument is a block which captures a 14616 /// variable. 14617 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14618 assert(owner.Variable && owner.Loc.isValid()); 14619 14620 e = e->IgnoreParenCasts(); 14621 14622 // Look through [^{...} copy] and Block_copy(^{...}). 14623 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14624 Selector Cmd = ME->getSelector(); 14625 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14626 e = ME->getInstanceReceiver(); 14627 if (!e) 14628 return nullptr; 14629 e = e->IgnoreParenCasts(); 14630 } 14631 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14632 if (CE->getNumArgs() == 1) { 14633 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14634 if (Fn) { 14635 const IdentifierInfo *FnI = Fn->getIdentifier(); 14636 if (FnI && FnI->isStr("_Block_copy")) { 14637 e = CE->getArg(0)->IgnoreParenCasts(); 14638 } 14639 } 14640 } 14641 } 14642 14643 BlockExpr *block = dyn_cast<BlockExpr>(e); 14644 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14645 return nullptr; 14646 14647 FindCaptureVisitor visitor(S.Context, owner.Variable); 14648 visitor.Visit(block->getBlockDecl()->getBody()); 14649 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14650 } 14651 14652 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14653 RetainCycleOwner &owner) { 14654 assert(capturer); 14655 assert(owner.Variable && owner.Loc.isValid()); 14656 14657 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14658 << owner.Variable << capturer->getSourceRange(); 14659 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14660 << owner.Indirect << owner.Range; 14661 } 14662 14663 /// Check for a keyword selector that starts with the word 'add' or 14664 /// 'set'. 14665 static bool isSetterLikeSelector(Selector sel) { 14666 if (sel.isUnarySelector()) return false; 14667 14668 StringRef str = sel.getNameForSlot(0); 14669 while (!str.empty() && str.front() == '_') str = str.substr(1); 14670 if (str.startswith("set")) 14671 str = str.substr(3); 14672 else if (str.startswith("add")) { 14673 // Specially allow 'addOperationWithBlock:'. 14674 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14675 return false; 14676 str = str.substr(3); 14677 } 14678 else 14679 return false; 14680 14681 if (str.empty()) return true; 14682 return !isLowercase(str.front()); 14683 } 14684 14685 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14686 ObjCMessageExpr *Message) { 14687 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14688 Message->getReceiverInterface(), 14689 NSAPI::ClassId_NSMutableArray); 14690 if (!IsMutableArray) { 14691 return None; 14692 } 14693 14694 Selector Sel = Message->getSelector(); 14695 14696 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14697 S.NSAPIObj->getNSArrayMethodKind(Sel); 14698 if (!MKOpt) { 14699 return None; 14700 } 14701 14702 NSAPI::NSArrayMethodKind MK = *MKOpt; 14703 14704 switch (MK) { 14705 case NSAPI::NSMutableArr_addObject: 14706 case NSAPI::NSMutableArr_insertObjectAtIndex: 14707 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14708 return 0; 14709 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14710 return 1; 14711 14712 default: 14713 return None; 14714 } 14715 14716 return None; 14717 } 14718 14719 static 14720 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14721 ObjCMessageExpr *Message) { 14722 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14723 Message->getReceiverInterface(), 14724 NSAPI::ClassId_NSMutableDictionary); 14725 if (!IsMutableDictionary) { 14726 return None; 14727 } 14728 14729 Selector Sel = Message->getSelector(); 14730 14731 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14732 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14733 if (!MKOpt) { 14734 return None; 14735 } 14736 14737 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14738 14739 switch (MK) { 14740 case NSAPI::NSMutableDict_setObjectForKey: 14741 case NSAPI::NSMutableDict_setValueForKey: 14742 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14743 return 0; 14744 14745 default: 14746 return None; 14747 } 14748 14749 return None; 14750 } 14751 14752 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14753 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14754 Message->getReceiverInterface(), 14755 NSAPI::ClassId_NSMutableSet); 14756 14757 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14758 Message->getReceiverInterface(), 14759 NSAPI::ClassId_NSMutableOrderedSet); 14760 if (!IsMutableSet && !IsMutableOrderedSet) { 14761 return None; 14762 } 14763 14764 Selector Sel = Message->getSelector(); 14765 14766 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14767 if (!MKOpt) { 14768 return None; 14769 } 14770 14771 NSAPI::NSSetMethodKind MK = *MKOpt; 14772 14773 switch (MK) { 14774 case NSAPI::NSMutableSet_addObject: 14775 case NSAPI::NSOrderedSet_setObjectAtIndex: 14776 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14777 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14778 return 0; 14779 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14780 return 1; 14781 } 14782 14783 return None; 14784 } 14785 14786 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14787 if (!Message->isInstanceMessage()) { 14788 return; 14789 } 14790 14791 Optional<int> ArgOpt; 14792 14793 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14794 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14795 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14796 return; 14797 } 14798 14799 int ArgIndex = *ArgOpt; 14800 14801 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14802 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14803 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14804 } 14805 14806 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14807 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14808 if (ArgRE->isObjCSelfExpr()) { 14809 Diag(Message->getSourceRange().getBegin(), 14810 diag::warn_objc_circular_container) 14811 << ArgRE->getDecl() << StringRef("'super'"); 14812 } 14813 } 14814 } else { 14815 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14816 14817 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14818 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14819 } 14820 14821 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14822 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14823 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14824 ValueDecl *Decl = ReceiverRE->getDecl(); 14825 Diag(Message->getSourceRange().getBegin(), 14826 diag::warn_objc_circular_container) 14827 << Decl << Decl; 14828 if (!ArgRE->isObjCSelfExpr()) { 14829 Diag(Decl->getLocation(), 14830 diag::note_objc_circular_container_declared_here) 14831 << Decl; 14832 } 14833 } 14834 } 14835 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14836 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14837 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14838 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14839 Diag(Message->getSourceRange().getBegin(), 14840 diag::warn_objc_circular_container) 14841 << Decl << Decl; 14842 Diag(Decl->getLocation(), 14843 diag::note_objc_circular_container_declared_here) 14844 << Decl; 14845 } 14846 } 14847 } 14848 } 14849 } 14850 14851 /// Check a message send to see if it's likely to cause a retain cycle. 14852 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14853 // Only check instance methods whose selector looks like a setter. 14854 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14855 return; 14856 14857 // Try to find a variable that the receiver is strongly owned by. 14858 RetainCycleOwner owner; 14859 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14860 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14861 return; 14862 } else { 14863 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14864 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14865 owner.Loc = msg->getSuperLoc(); 14866 owner.Range = msg->getSuperLoc(); 14867 } 14868 14869 // Check whether the receiver is captured by any of the arguments. 14870 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14871 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14872 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14873 // noescape blocks should not be retained by the method. 14874 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14875 continue; 14876 return diagnoseRetainCycle(*this, capturer, owner); 14877 } 14878 } 14879 } 14880 14881 /// Check a property assign to see if it's likely to cause a retain cycle. 14882 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14883 RetainCycleOwner owner; 14884 if (!findRetainCycleOwner(*this, receiver, owner)) 14885 return; 14886 14887 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14888 diagnoseRetainCycle(*this, capturer, owner); 14889 } 14890 14891 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14892 RetainCycleOwner Owner; 14893 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14894 return; 14895 14896 // Because we don't have an expression for the variable, we have to set the 14897 // location explicitly here. 14898 Owner.Loc = Var->getLocation(); 14899 Owner.Range = Var->getSourceRange(); 14900 14901 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14902 diagnoseRetainCycle(*this, Capturer, Owner); 14903 } 14904 14905 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14906 Expr *RHS, bool isProperty) { 14907 // Check if RHS is an Objective-C object literal, which also can get 14908 // immediately zapped in a weak reference. Note that we explicitly 14909 // allow ObjCStringLiterals, since those are designed to never really die. 14910 RHS = RHS->IgnoreParenImpCasts(); 14911 14912 // This enum needs to match with the 'select' in 14913 // warn_objc_arc_literal_assign (off-by-1). 14914 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14915 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14916 return false; 14917 14918 S.Diag(Loc, diag::warn_arc_literal_assign) 14919 << (unsigned) Kind 14920 << (isProperty ? 0 : 1) 14921 << RHS->getSourceRange(); 14922 14923 return true; 14924 } 14925 14926 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14927 Qualifiers::ObjCLifetime LT, 14928 Expr *RHS, bool isProperty) { 14929 // Strip off any implicit cast added to get to the one ARC-specific. 14930 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14931 if (cast->getCastKind() == CK_ARCConsumeObject) { 14932 S.Diag(Loc, diag::warn_arc_retained_assign) 14933 << (LT == Qualifiers::OCL_ExplicitNone) 14934 << (isProperty ? 0 : 1) 14935 << RHS->getSourceRange(); 14936 return true; 14937 } 14938 RHS = cast->getSubExpr(); 14939 } 14940 14941 if (LT == Qualifiers::OCL_Weak && 14942 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14943 return true; 14944 14945 return false; 14946 } 14947 14948 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14949 QualType LHS, Expr *RHS) { 14950 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14951 14952 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14953 return false; 14954 14955 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14956 return true; 14957 14958 return false; 14959 } 14960 14961 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14962 Expr *LHS, Expr *RHS) { 14963 QualType LHSType; 14964 // PropertyRef on LHS type need be directly obtained from 14965 // its declaration as it has a PseudoType. 14966 ObjCPropertyRefExpr *PRE 14967 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14968 if (PRE && !PRE->isImplicitProperty()) { 14969 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14970 if (PD) 14971 LHSType = PD->getType(); 14972 } 14973 14974 if (LHSType.isNull()) 14975 LHSType = LHS->getType(); 14976 14977 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14978 14979 if (LT == Qualifiers::OCL_Weak) { 14980 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14981 getCurFunction()->markSafeWeakUse(LHS); 14982 } 14983 14984 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14985 return; 14986 14987 // FIXME. Check for other life times. 14988 if (LT != Qualifiers::OCL_None) 14989 return; 14990 14991 if (PRE) { 14992 if (PRE->isImplicitProperty()) 14993 return; 14994 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14995 if (!PD) 14996 return; 14997 14998 unsigned Attributes = PD->getPropertyAttributes(); 14999 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15000 // when 'assign' attribute was not explicitly specified 15001 // by user, ignore it and rely on property type itself 15002 // for lifetime info. 15003 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15004 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15005 LHSType->isObjCRetainableType()) 15006 return; 15007 15008 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15009 if (cast->getCastKind() == CK_ARCConsumeObject) { 15010 Diag(Loc, diag::warn_arc_retained_property_assign) 15011 << RHS->getSourceRange(); 15012 return; 15013 } 15014 RHS = cast->getSubExpr(); 15015 } 15016 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15017 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15018 return; 15019 } 15020 } 15021 } 15022 15023 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15024 15025 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15026 SourceLocation StmtLoc, 15027 const NullStmt *Body) { 15028 // Do not warn if the body is a macro that expands to nothing, e.g: 15029 // 15030 // #define CALL(x) 15031 // if (condition) 15032 // CALL(0); 15033 if (Body->hasLeadingEmptyMacro()) 15034 return false; 15035 15036 // Get line numbers of statement and body. 15037 bool StmtLineInvalid; 15038 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15039 &StmtLineInvalid); 15040 if (StmtLineInvalid) 15041 return false; 15042 15043 bool BodyLineInvalid; 15044 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15045 &BodyLineInvalid); 15046 if (BodyLineInvalid) 15047 return false; 15048 15049 // Warn if null statement and body are on the same line. 15050 if (StmtLine != BodyLine) 15051 return false; 15052 15053 return true; 15054 } 15055 15056 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15057 const Stmt *Body, 15058 unsigned DiagID) { 15059 // Since this is a syntactic check, don't emit diagnostic for template 15060 // instantiations, this just adds noise. 15061 if (CurrentInstantiationScope) 15062 return; 15063 15064 // The body should be a null statement. 15065 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15066 if (!NBody) 15067 return; 15068 15069 // Do the usual checks. 15070 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15071 return; 15072 15073 Diag(NBody->getSemiLoc(), DiagID); 15074 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15075 } 15076 15077 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15078 const Stmt *PossibleBody) { 15079 assert(!CurrentInstantiationScope); // Ensured by caller 15080 15081 SourceLocation StmtLoc; 15082 const Stmt *Body; 15083 unsigned DiagID; 15084 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15085 StmtLoc = FS->getRParenLoc(); 15086 Body = FS->getBody(); 15087 DiagID = diag::warn_empty_for_body; 15088 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15089 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15090 Body = WS->getBody(); 15091 DiagID = diag::warn_empty_while_body; 15092 } else 15093 return; // Neither `for' nor `while'. 15094 15095 // The body should be a null statement. 15096 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15097 if (!NBody) 15098 return; 15099 15100 // Skip expensive checks if diagnostic is disabled. 15101 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15102 return; 15103 15104 // Do the usual checks. 15105 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15106 return; 15107 15108 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15109 // noise level low, emit diagnostics only if for/while is followed by a 15110 // CompoundStmt, e.g.: 15111 // for (int i = 0; i < n; i++); 15112 // { 15113 // a(i); 15114 // } 15115 // or if for/while is followed by a statement with more indentation 15116 // than for/while itself: 15117 // for (int i = 0; i < n; i++); 15118 // a(i); 15119 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15120 if (!ProbableTypo) { 15121 bool BodyColInvalid; 15122 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15123 PossibleBody->getBeginLoc(), &BodyColInvalid); 15124 if (BodyColInvalid) 15125 return; 15126 15127 bool StmtColInvalid; 15128 unsigned StmtCol = 15129 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15130 if (StmtColInvalid) 15131 return; 15132 15133 if (BodyCol > StmtCol) 15134 ProbableTypo = true; 15135 } 15136 15137 if (ProbableTypo) { 15138 Diag(NBody->getSemiLoc(), DiagID); 15139 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15140 } 15141 } 15142 15143 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15144 15145 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15146 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15147 SourceLocation OpLoc) { 15148 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15149 return; 15150 15151 if (inTemplateInstantiation()) 15152 return; 15153 15154 // Strip parens and casts away. 15155 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15156 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15157 15158 // Check for a call expression 15159 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15160 if (!CE || CE->getNumArgs() != 1) 15161 return; 15162 15163 // Check for a call to std::move 15164 if (!CE->isCallToStdMove()) 15165 return; 15166 15167 // Get argument from std::move 15168 RHSExpr = CE->getArg(0); 15169 15170 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15171 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15172 15173 // Two DeclRefExpr's, check that the decls are the same. 15174 if (LHSDeclRef && RHSDeclRef) { 15175 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15176 return; 15177 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15178 RHSDeclRef->getDecl()->getCanonicalDecl()) 15179 return; 15180 15181 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15182 << LHSExpr->getSourceRange() 15183 << RHSExpr->getSourceRange(); 15184 return; 15185 } 15186 15187 // Member variables require a different approach to check for self moves. 15188 // MemberExpr's are the same if every nested MemberExpr refers to the same 15189 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15190 // the base Expr's are CXXThisExpr's. 15191 const Expr *LHSBase = LHSExpr; 15192 const Expr *RHSBase = RHSExpr; 15193 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15194 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15195 if (!LHSME || !RHSME) 15196 return; 15197 15198 while (LHSME && RHSME) { 15199 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15200 RHSME->getMemberDecl()->getCanonicalDecl()) 15201 return; 15202 15203 LHSBase = LHSME->getBase(); 15204 RHSBase = RHSME->getBase(); 15205 LHSME = dyn_cast<MemberExpr>(LHSBase); 15206 RHSME = dyn_cast<MemberExpr>(RHSBase); 15207 } 15208 15209 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15210 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15211 if (LHSDeclRef && RHSDeclRef) { 15212 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15213 return; 15214 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15215 RHSDeclRef->getDecl()->getCanonicalDecl()) 15216 return; 15217 15218 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15219 << LHSExpr->getSourceRange() 15220 << RHSExpr->getSourceRange(); 15221 return; 15222 } 15223 15224 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15225 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15226 << LHSExpr->getSourceRange() 15227 << RHSExpr->getSourceRange(); 15228 } 15229 15230 //===--- Layout compatibility ----------------------------------------------// 15231 15232 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15233 15234 /// Check if two enumeration types are layout-compatible. 15235 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15236 // C++11 [dcl.enum] p8: 15237 // Two enumeration types are layout-compatible if they have the same 15238 // underlying type. 15239 return ED1->isComplete() && ED2->isComplete() && 15240 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15241 } 15242 15243 /// Check if two fields are layout-compatible. 15244 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15245 FieldDecl *Field2) { 15246 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15247 return false; 15248 15249 if (Field1->isBitField() != Field2->isBitField()) 15250 return false; 15251 15252 if (Field1->isBitField()) { 15253 // Make sure that the bit-fields are the same length. 15254 unsigned Bits1 = Field1->getBitWidthValue(C); 15255 unsigned Bits2 = Field2->getBitWidthValue(C); 15256 15257 if (Bits1 != Bits2) 15258 return false; 15259 } 15260 15261 return true; 15262 } 15263 15264 /// Check if two standard-layout structs are layout-compatible. 15265 /// (C++11 [class.mem] p17) 15266 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15267 RecordDecl *RD2) { 15268 // If both records are C++ classes, check that base classes match. 15269 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15270 // If one of records is a CXXRecordDecl we are in C++ mode, 15271 // thus the other one is a CXXRecordDecl, too. 15272 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15273 // Check number of base classes. 15274 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15275 return false; 15276 15277 // Check the base classes. 15278 for (CXXRecordDecl::base_class_const_iterator 15279 Base1 = D1CXX->bases_begin(), 15280 BaseEnd1 = D1CXX->bases_end(), 15281 Base2 = D2CXX->bases_begin(); 15282 Base1 != BaseEnd1; 15283 ++Base1, ++Base2) { 15284 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15285 return false; 15286 } 15287 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15288 // If only RD2 is a C++ class, it should have zero base classes. 15289 if (D2CXX->getNumBases() > 0) 15290 return false; 15291 } 15292 15293 // Check the fields. 15294 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15295 Field2End = RD2->field_end(), 15296 Field1 = RD1->field_begin(), 15297 Field1End = RD1->field_end(); 15298 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15299 if (!isLayoutCompatible(C, *Field1, *Field2)) 15300 return false; 15301 } 15302 if (Field1 != Field1End || Field2 != Field2End) 15303 return false; 15304 15305 return true; 15306 } 15307 15308 /// Check if two standard-layout unions are layout-compatible. 15309 /// (C++11 [class.mem] p18) 15310 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15311 RecordDecl *RD2) { 15312 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15313 for (auto *Field2 : RD2->fields()) 15314 UnmatchedFields.insert(Field2); 15315 15316 for (auto *Field1 : RD1->fields()) { 15317 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15318 I = UnmatchedFields.begin(), 15319 E = UnmatchedFields.end(); 15320 15321 for ( ; I != E; ++I) { 15322 if (isLayoutCompatible(C, Field1, *I)) { 15323 bool Result = UnmatchedFields.erase(*I); 15324 (void) Result; 15325 assert(Result); 15326 break; 15327 } 15328 } 15329 if (I == E) 15330 return false; 15331 } 15332 15333 return UnmatchedFields.empty(); 15334 } 15335 15336 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15337 RecordDecl *RD2) { 15338 if (RD1->isUnion() != RD2->isUnion()) 15339 return false; 15340 15341 if (RD1->isUnion()) 15342 return isLayoutCompatibleUnion(C, RD1, RD2); 15343 else 15344 return isLayoutCompatibleStruct(C, RD1, RD2); 15345 } 15346 15347 /// Check if two types are layout-compatible in C++11 sense. 15348 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15349 if (T1.isNull() || T2.isNull()) 15350 return false; 15351 15352 // C++11 [basic.types] p11: 15353 // If two types T1 and T2 are the same type, then T1 and T2 are 15354 // layout-compatible types. 15355 if (C.hasSameType(T1, T2)) 15356 return true; 15357 15358 T1 = T1.getCanonicalType().getUnqualifiedType(); 15359 T2 = T2.getCanonicalType().getUnqualifiedType(); 15360 15361 const Type::TypeClass TC1 = T1->getTypeClass(); 15362 const Type::TypeClass TC2 = T2->getTypeClass(); 15363 15364 if (TC1 != TC2) 15365 return false; 15366 15367 if (TC1 == Type::Enum) { 15368 return isLayoutCompatible(C, 15369 cast<EnumType>(T1)->getDecl(), 15370 cast<EnumType>(T2)->getDecl()); 15371 } else if (TC1 == Type::Record) { 15372 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15373 return false; 15374 15375 return isLayoutCompatible(C, 15376 cast<RecordType>(T1)->getDecl(), 15377 cast<RecordType>(T2)->getDecl()); 15378 } 15379 15380 return false; 15381 } 15382 15383 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15384 15385 /// Given a type tag expression find the type tag itself. 15386 /// 15387 /// \param TypeExpr Type tag expression, as it appears in user's code. 15388 /// 15389 /// \param VD Declaration of an identifier that appears in a type tag. 15390 /// 15391 /// \param MagicValue Type tag magic value. 15392 /// 15393 /// \param isConstantEvaluated wether the evalaution should be performed in 15394 15395 /// constant context. 15396 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15397 const ValueDecl **VD, uint64_t *MagicValue, 15398 bool isConstantEvaluated) { 15399 while(true) { 15400 if (!TypeExpr) 15401 return false; 15402 15403 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15404 15405 switch (TypeExpr->getStmtClass()) { 15406 case Stmt::UnaryOperatorClass: { 15407 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15408 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15409 TypeExpr = UO->getSubExpr(); 15410 continue; 15411 } 15412 return false; 15413 } 15414 15415 case Stmt::DeclRefExprClass: { 15416 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15417 *VD = DRE->getDecl(); 15418 return true; 15419 } 15420 15421 case Stmt::IntegerLiteralClass: { 15422 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15423 llvm::APInt MagicValueAPInt = IL->getValue(); 15424 if (MagicValueAPInt.getActiveBits() <= 64) { 15425 *MagicValue = MagicValueAPInt.getZExtValue(); 15426 return true; 15427 } else 15428 return false; 15429 } 15430 15431 case Stmt::BinaryConditionalOperatorClass: 15432 case Stmt::ConditionalOperatorClass: { 15433 const AbstractConditionalOperator *ACO = 15434 cast<AbstractConditionalOperator>(TypeExpr); 15435 bool Result; 15436 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15437 isConstantEvaluated)) { 15438 if (Result) 15439 TypeExpr = ACO->getTrueExpr(); 15440 else 15441 TypeExpr = ACO->getFalseExpr(); 15442 continue; 15443 } 15444 return false; 15445 } 15446 15447 case Stmt::BinaryOperatorClass: { 15448 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15449 if (BO->getOpcode() == BO_Comma) { 15450 TypeExpr = BO->getRHS(); 15451 continue; 15452 } 15453 return false; 15454 } 15455 15456 default: 15457 return false; 15458 } 15459 } 15460 } 15461 15462 /// Retrieve the C type corresponding to type tag TypeExpr. 15463 /// 15464 /// \param TypeExpr Expression that specifies a type tag. 15465 /// 15466 /// \param MagicValues Registered magic values. 15467 /// 15468 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15469 /// kind. 15470 /// 15471 /// \param TypeInfo Information about the corresponding C type. 15472 /// 15473 /// \param isConstantEvaluated wether the evalaution should be performed in 15474 /// constant context. 15475 /// 15476 /// \returns true if the corresponding C type was found. 15477 static bool GetMatchingCType( 15478 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15479 const ASTContext &Ctx, 15480 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15481 *MagicValues, 15482 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15483 bool isConstantEvaluated) { 15484 FoundWrongKind = false; 15485 15486 // Variable declaration that has type_tag_for_datatype attribute. 15487 const ValueDecl *VD = nullptr; 15488 15489 uint64_t MagicValue; 15490 15491 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15492 return false; 15493 15494 if (VD) { 15495 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15496 if (I->getArgumentKind() != ArgumentKind) { 15497 FoundWrongKind = true; 15498 return false; 15499 } 15500 TypeInfo.Type = I->getMatchingCType(); 15501 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15502 TypeInfo.MustBeNull = I->getMustBeNull(); 15503 return true; 15504 } 15505 return false; 15506 } 15507 15508 if (!MagicValues) 15509 return false; 15510 15511 llvm::DenseMap<Sema::TypeTagMagicValue, 15512 Sema::TypeTagData>::const_iterator I = 15513 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15514 if (I == MagicValues->end()) 15515 return false; 15516 15517 TypeInfo = I->second; 15518 return true; 15519 } 15520 15521 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15522 uint64_t MagicValue, QualType Type, 15523 bool LayoutCompatible, 15524 bool MustBeNull) { 15525 if (!TypeTagForDatatypeMagicValues) 15526 TypeTagForDatatypeMagicValues.reset( 15527 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15528 15529 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15530 (*TypeTagForDatatypeMagicValues)[Magic] = 15531 TypeTagData(Type, LayoutCompatible, MustBeNull); 15532 } 15533 15534 static bool IsSameCharType(QualType T1, QualType T2) { 15535 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15536 if (!BT1) 15537 return false; 15538 15539 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15540 if (!BT2) 15541 return false; 15542 15543 BuiltinType::Kind T1Kind = BT1->getKind(); 15544 BuiltinType::Kind T2Kind = BT2->getKind(); 15545 15546 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15547 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15548 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15549 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15550 } 15551 15552 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15553 const ArrayRef<const Expr *> ExprArgs, 15554 SourceLocation CallSiteLoc) { 15555 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15556 bool IsPointerAttr = Attr->getIsPointer(); 15557 15558 // Retrieve the argument representing the 'type_tag'. 15559 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15560 if (TypeTagIdxAST >= ExprArgs.size()) { 15561 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15562 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15563 return; 15564 } 15565 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15566 bool FoundWrongKind; 15567 TypeTagData TypeInfo; 15568 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15569 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15570 TypeInfo, isConstantEvaluated())) { 15571 if (FoundWrongKind) 15572 Diag(TypeTagExpr->getExprLoc(), 15573 diag::warn_type_tag_for_datatype_wrong_kind) 15574 << TypeTagExpr->getSourceRange(); 15575 return; 15576 } 15577 15578 // Retrieve the argument representing the 'arg_idx'. 15579 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15580 if (ArgumentIdxAST >= ExprArgs.size()) { 15581 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15582 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15583 return; 15584 } 15585 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15586 if (IsPointerAttr) { 15587 // Skip implicit cast of pointer to `void *' (as a function argument). 15588 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15589 if (ICE->getType()->isVoidPointerType() && 15590 ICE->getCastKind() == CK_BitCast) 15591 ArgumentExpr = ICE->getSubExpr(); 15592 } 15593 QualType ArgumentType = ArgumentExpr->getType(); 15594 15595 // Passing a `void*' pointer shouldn't trigger a warning. 15596 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15597 return; 15598 15599 if (TypeInfo.MustBeNull) { 15600 // Type tag with matching void type requires a null pointer. 15601 if (!ArgumentExpr->isNullPointerConstant(Context, 15602 Expr::NPC_ValueDependentIsNotNull)) { 15603 Diag(ArgumentExpr->getExprLoc(), 15604 diag::warn_type_safety_null_pointer_required) 15605 << ArgumentKind->getName() 15606 << ArgumentExpr->getSourceRange() 15607 << TypeTagExpr->getSourceRange(); 15608 } 15609 return; 15610 } 15611 15612 QualType RequiredType = TypeInfo.Type; 15613 if (IsPointerAttr) 15614 RequiredType = Context.getPointerType(RequiredType); 15615 15616 bool mismatch = false; 15617 if (!TypeInfo.LayoutCompatible) { 15618 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15619 15620 // C++11 [basic.fundamental] p1: 15621 // Plain char, signed char, and unsigned char are three distinct types. 15622 // 15623 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15624 // char' depending on the current char signedness mode. 15625 if (mismatch) 15626 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15627 RequiredType->getPointeeType())) || 15628 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15629 mismatch = false; 15630 } else 15631 if (IsPointerAttr) 15632 mismatch = !isLayoutCompatible(Context, 15633 ArgumentType->getPointeeType(), 15634 RequiredType->getPointeeType()); 15635 else 15636 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15637 15638 if (mismatch) 15639 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15640 << ArgumentType << ArgumentKind 15641 << TypeInfo.LayoutCompatible << RequiredType 15642 << ArgumentExpr->getSourceRange() 15643 << TypeTagExpr->getSourceRange(); 15644 } 15645 15646 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15647 CharUnits Alignment) { 15648 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15649 } 15650 15651 void Sema::DiagnoseMisalignedMembers() { 15652 for (MisalignedMember &m : MisalignedMembers) { 15653 const NamedDecl *ND = m.RD; 15654 if (ND->getName().empty()) { 15655 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15656 ND = TD; 15657 } 15658 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15659 << m.MD << ND << m.E->getSourceRange(); 15660 } 15661 MisalignedMembers.clear(); 15662 } 15663 15664 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15665 E = E->IgnoreParens(); 15666 if (!T->isPointerType() && !T->isIntegerType()) 15667 return; 15668 if (isa<UnaryOperator>(E) && 15669 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15670 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15671 if (isa<MemberExpr>(Op)) { 15672 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15673 if (MA != MisalignedMembers.end() && 15674 (T->isIntegerType() || 15675 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15676 Context.getTypeAlignInChars( 15677 T->getPointeeType()) <= MA->Alignment)))) 15678 MisalignedMembers.erase(MA); 15679 } 15680 } 15681 } 15682 15683 void Sema::RefersToMemberWithReducedAlignment( 15684 Expr *E, 15685 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15686 Action) { 15687 const auto *ME = dyn_cast<MemberExpr>(E); 15688 if (!ME) 15689 return; 15690 15691 // No need to check expressions with an __unaligned-qualified type. 15692 if (E->getType().getQualifiers().hasUnaligned()) 15693 return; 15694 15695 // For a chain of MemberExpr like "a.b.c.d" this list 15696 // will keep FieldDecl's like [d, c, b]. 15697 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15698 const MemberExpr *TopME = nullptr; 15699 bool AnyIsPacked = false; 15700 do { 15701 QualType BaseType = ME->getBase()->getType(); 15702 if (BaseType->isDependentType()) 15703 return; 15704 if (ME->isArrow()) 15705 BaseType = BaseType->getPointeeType(); 15706 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15707 if (RD->isInvalidDecl()) 15708 return; 15709 15710 ValueDecl *MD = ME->getMemberDecl(); 15711 auto *FD = dyn_cast<FieldDecl>(MD); 15712 // We do not care about non-data members. 15713 if (!FD || FD->isInvalidDecl()) 15714 return; 15715 15716 AnyIsPacked = 15717 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15718 ReverseMemberChain.push_back(FD); 15719 15720 TopME = ME; 15721 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15722 } while (ME); 15723 assert(TopME && "We did not compute a topmost MemberExpr!"); 15724 15725 // Not the scope of this diagnostic. 15726 if (!AnyIsPacked) 15727 return; 15728 15729 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15730 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15731 // TODO: The innermost base of the member expression may be too complicated. 15732 // For now, just disregard these cases. This is left for future 15733 // improvement. 15734 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15735 return; 15736 15737 // Alignment expected by the whole expression. 15738 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15739 15740 // No need to do anything else with this case. 15741 if (ExpectedAlignment.isOne()) 15742 return; 15743 15744 // Synthesize offset of the whole access. 15745 CharUnits Offset; 15746 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15747 I++) { 15748 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15749 } 15750 15751 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15752 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15753 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15754 15755 // The base expression of the innermost MemberExpr may give 15756 // stronger guarantees than the class containing the member. 15757 if (DRE && !TopME->isArrow()) { 15758 const ValueDecl *VD = DRE->getDecl(); 15759 if (!VD->getType()->isReferenceType()) 15760 CompleteObjectAlignment = 15761 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15762 } 15763 15764 // Check if the synthesized offset fulfills the alignment. 15765 if (Offset % ExpectedAlignment != 0 || 15766 // It may fulfill the offset it but the effective alignment may still be 15767 // lower than the expected expression alignment. 15768 CompleteObjectAlignment < ExpectedAlignment) { 15769 // If this happens, we want to determine a sensible culprit of this. 15770 // Intuitively, watching the chain of member expressions from right to 15771 // left, we start with the required alignment (as required by the field 15772 // type) but some packed attribute in that chain has reduced the alignment. 15773 // It may happen that another packed structure increases it again. But if 15774 // we are here such increase has not been enough. So pointing the first 15775 // FieldDecl that either is packed or else its RecordDecl is, 15776 // seems reasonable. 15777 FieldDecl *FD = nullptr; 15778 CharUnits Alignment; 15779 for (FieldDecl *FDI : ReverseMemberChain) { 15780 if (FDI->hasAttr<PackedAttr>() || 15781 FDI->getParent()->hasAttr<PackedAttr>()) { 15782 FD = FDI; 15783 Alignment = std::min( 15784 Context.getTypeAlignInChars(FD->getType()), 15785 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15786 break; 15787 } 15788 } 15789 assert(FD && "We did not find a packed FieldDecl!"); 15790 Action(E, FD->getParent(), FD, Alignment); 15791 } 15792 } 15793 15794 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15795 using namespace std::placeholders; 15796 15797 RefersToMemberWithReducedAlignment( 15798 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15799 _2, _3, _4)); 15800 } 15801 15802 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15803 ExprResult CallResult) { 15804 if (checkArgCount(*this, TheCall, 1)) 15805 return ExprError(); 15806 15807 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15808 if (MatrixArg.isInvalid()) 15809 return MatrixArg; 15810 Expr *Matrix = MatrixArg.get(); 15811 15812 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15813 if (!MType) { 15814 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15815 return ExprError(); 15816 } 15817 15818 // Create returned matrix type by swapping rows and columns of the argument 15819 // matrix type. 15820 QualType ResultType = Context.getConstantMatrixType( 15821 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15822 15823 // Change the return type to the type of the returned matrix. 15824 TheCall->setType(ResultType); 15825 15826 // Update call argument to use the possibly converted matrix argument. 15827 TheCall->setArg(0, Matrix); 15828 return CallResult; 15829 } 15830 15831 // Get and verify the matrix dimensions. 15832 static llvm::Optional<unsigned> 15833 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15834 SourceLocation ErrorPos; 15835 Optional<llvm::APSInt> Value = 15836 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15837 if (!Value) { 15838 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15839 << Name; 15840 return {}; 15841 } 15842 uint64_t Dim = Value->getZExtValue(); 15843 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15844 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15845 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15846 return {}; 15847 } 15848 return Dim; 15849 } 15850 15851 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15852 ExprResult CallResult) { 15853 if (!getLangOpts().MatrixTypes) { 15854 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15855 return ExprError(); 15856 } 15857 15858 if (checkArgCount(*this, TheCall, 4)) 15859 return ExprError(); 15860 15861 unsigned PtrArgIdx = 0; 15862 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15863 Expr *RowsExpr = TheCall->getArg(1); 15864 Expr *ColumnsExpr = TheCall->getArg(2); 15865 Expr *StrideExpr = TheCall->getArg(3); 15866 15867 bool ArgError = false; 15868 15869 // Check pointer argument. 15870 { 15871 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15872 if (PtrConv.isInvalid()) 15873 return PtrConv; 15874 PtrExpr = PtrConv.get(); 15875 TheCall->setArg(0, PtrExpr); 15876 if (PtrExpr->isTypeDependent()) { 15877 TheCall->setType(Context.DependentTy); 15878 return TheCall; 15879 } 15880 } 15881 15882 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15883 QualType ElementTy; 15884 if (!PtrTy) { 15885 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15886 << PtrArgIdx + 1; 15887 ArgError = true; 15888 } else { 15889 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15890 15891 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15892 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15893 << PtrArgIdx + 1; 15894 ArgError = true; 15895 } 15896 } 15897 15898 // Apply default Lvalue conversions and convert the expression to size_t. 15899 auto ApplyArgumentConversions = [this](Expr *E) { 15900 ExprResult Conv = DefaultLvalueConversion(E); 15901 if (Conv.isInvalid()) 15902 return Conv; 15903 15904 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15905 }; 15906 15907 // Apply conversion to row and column expressions. 15908 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15909 if (!RowsConv.isInvalid()) { 15910 RowsExpr = RowsConv.get(); 15911 TheCall->setArg(1, RowsExpr); 15912 } else 15913 RowsExpr = nullptr; 15914 15915 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15916 if (!ColumnsConv.isInvalid()) { 15917 ColumnsExpr = ColumnsConv.get(); 15918 TheCall->setArg(2, ColumnsExpr); 15919 } else 15920 ColumnsExpr = nullptr; 15921 15922 // If any any part of the result matrix type is still pending, just use 15923 // Context.DependentTy, until all parts are resolved. 15924 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15925 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15926 TheCall->setType(Context.DependentTy); 15927 return CallResult; 15928 } 15929 15930 // Check row and column dimenions. 15931 llvm::Optional<unsigned> MaybeRows; 15932 if (RowsExpr) 15933 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15934 15935 llvm::Optional<unsigned> MaybeColumns; 15936 if (ColumnsExpr) 15937 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15938 15939 // Check stride argument. 15940 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15941 if (StrideConv.isInvalid()) 15942 return ExprError(); 15943 StrideExpr = StrideConv.get(); 15944 TheCall->setArg(3, StrideExpr); 15945 15946 if (MaybeRows) { 15947 if (Optional<llvm::APSInt> Value = 15948 StrideExpr->getIntegerConstantExpr(Context)) { 15949 uint64_t Stride = Value->getZExtValue(); 15950 if (Stride < *MaybeRows) { 15951 Diag(StrideExpr->getBeginLoc(), 15952 diag::err_builtin_matrix_stride_too_small); 15953 ArgError = true; 15954 } 15955 } 15956 } 15957 15958 if (ArgError || !MaybeRows || !MaybeColumns) 15959 return ExprError(); 15960 15961 TheCall->setType( 15962 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15963 return CallResult; 15964 } 15965 15966 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15967 ExprResult CallResult) { 15968 if (checkArgCount(*this, TheCall, 3)) 15969 return ExprError(); 15970 15971 unsigned PtrArgIdx = 1; 15972 Expr *MatrixExpr = TheCall->getArg(0); 15973 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15974 Expr *StrideExpr = TheCall->getArg(2); 15975 15976 bool ArgError = false; 15977 15978 { 15979 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15980 if (MatrixConv.isInvalid()) 15981 return MatrixConv; 15982 MatrixExpr = MatrixConv.get(); 15983 TheCall->setArg(0, MatrixExpr); 15984 } 15985 if (MatrixExpr->isTypeDependent()) { 15986 TheCall->setType(Context.DependentTy); 15987 return TheCall; 15988 } 15989 15990 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15991 if (!MatrixTy) { 15992 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15993 ArgError = true; 15994 } 15995 15996 { 15997 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15998 if (PtrConv.isInvalid()) 15999 return PtrConv; 16000 PtrExpr = PtrConv.get(); 16001 TheCall->setArg(1, PtrExpr); 16002 if (PtrExpr->isTypeDependent()) { 16003 TheCall->setType(Context.DependentTy); 16004 return TheCall; 16005 } 16006 } 16007 16008 // Check pointer argument. 16009 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16010 if (!PtrTy) { 16011 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16012 << PtrArgIdx + 1; 16013 ArgError = true; 16014 } else { 16015 QualType ElementTy = PtrTy->getPointeeType(); 16016 if (ElementTy.isConstQualified()) { 16017 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16018 ArgError = true; 16019 } 16020 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16021 if (MatrixTy && 16022 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16023 Diag(PtrExpr->getBeginLoc(), 16024 diag::err_builtin_matrix_pointer_arg_mismatch) 16025 << ElementTy << MatrixTy->getElementType(); 16026 ArgError = true; 16027 } 16028 } 16029 16030 // Apply default Lvalue conversions and convert the stride expression to 16031 // size_t. 16032 { 16033 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16034 if (StrideConv.isInvalid()) 16035 return StrideConv; 16036 16037 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16038 if (StrideConv.isInvalid()) 16039 return StrideConv; 16040 StrideExpr = StrideConv.get(); 16041 TheCall->setArg(2, StrideExpr); 16042 } 16043 16044 // Check stride argument. 16045 if (MatrixTy) { 16046 if (Optional<llvm::APSInt> Value = 16047 StrideExpr->getIntegerConstantExpr(Context)) { 16048 uint64_t Stride = Value->getZExtValue(); 16049 if (Stride < MatrixTy->getNumRows()) { 16050 Diag(StrideExpr->getBeginLoc(), 16051 diag::err_builtin_matrix_stride_too_small); 16052 ArgError = true; 16053 } 16054 } 16055 } 16056 16057 if (ArgError) 16058 return ExprError(); 16059 16060 return CallResult; 16061 } 16062