1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 594 isConstantEvaluated()) 595 return; 596 597 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 598 if (!BuiltinID) 599 return; 600 601 const TargetInfo &TI = getASTContext().getTargetInfo(); 602 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 603 604 auto ComputeExplicitObjectSizeArgument = 605 [&](unsigned Index) -> Optional<llvm::APSInt> { 606 Expr::EvalResult Result; 607 Expr *SizeArg = TheCall->getArg(Index); 608 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 609 return llvm::None; 610 return Result.Val.getInt(); 611 }; 612 613 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 614 // If the parameter has a pass_object_size attribute, then we should use its 615 // (potentially) more strict checking mode. Otherwise, conservatively assume 616 // type 0. 617 int BOSType = 0; 618 if (const auto *POS = 619 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 620 BOSType = POS->getType(); 621 622 const Expr *ObjArg = TheCall->getArg(Index); 623 uint64_t Result; 624 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 625 return llvm::None; 626 627 // Get the object size in the target's size_t width. 628 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 629 }; 630 631 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 632 Expr *ObjArg = TheCall->getArg(Index); 633 uint64_t Result; 634 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 635 return llvm::None; 636 // Add 1 for null byte. 637 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 638 }; 639 640 Optional<llvm::APSInt> SourceSize; 641 Optional<llvm::APSInt> DestinationSize; 642 unsigned DiagID = 0; 643 bool IsChkVariant = false; 644 645 switch (BuiltinID) { 646 default: 647 return; 648 case Builtin::BI__builtin_strcpy: 649 case Builtin::BIstrcpy: { 650 DiagID = diag::warn_fortify_strlen_overflow; 651 SourceSize = ComputeStrLenArgument(1); 652 DestinationSize = ComputeSizeArgument(0); 653 break; 654 } 655 656 case Builtin::BI__builtin___strcpy_chk: { 657 DiagID = diag::warn_fortify_strlen_overflow; 658 SourceSize = ComputeStrLenArgument(1); 659 DestinationSize = ComputeExplicitObjectSizeArgument(2); 660 IsChkVariant = true; 661 break; 662 } 663 664 case Builtin::BIsprintf: 665 case Builtin::BI__builtin___sprintf_chk: { 666 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 667 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 668 669 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 670 671 if (!Format->isAscii() && !Format->isUTF8()) 672 return; 673 674 StringRef FormatStrRef = Format->getString(); 675 EstimateSizeFormatHandler H(FormatStrRef); 676 const char *FormatBytes = FormatStrRef.data(); 677 const ConstantArrayType *T = 678 Context.getAsConstantArrayType(Format->getType()); 679 assert(T && "String literal not of constant array type!"); 680 size_t TypeSize = T->getSize().getZExtValue(); 681 682 // In case there's a null byte somewhere. 683 size_t StrLen = 684 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 685 if (!analyze_format_string::ParsePrintfString( 686 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 687 Context.getTargetInfo(), false)) { 688 DiagID = diag::warn_fortify_source_format_overflow; 689 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 690 .extOrTrunc(SizeTypeWidth); 691 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 692 DestinationSize = ComputeExplicitObjectSizeArgument(2); 693 IsChkVariant = true; 694 } else { 695 DestinationSize = ComputeSizeArgument(0); 696 } 697 break; 698 } 699 } 700 return; 701 } 702 case Builtin::BI__builtin___memcpy_chk: 703 case Builtin::BI__builtin___memmove_chk: 704 case Builtin::BI__builtin___memset_chk: 705 case Builtin::BI__builtin___strlcat_chk: 706 case Builtin::BI__builtin___strlcpy_chk: 707 case Builtin::BI__builtin___strncat_chk: 708 case Builtin::BI__builtin___strncpy_chk: 709 case Builtin::BI__builtin___stpncpy_chk: 710 case Builtin::BI__builtin___memccpy_chk: 711 case Builtin::BI__builtin___mempcpy_chk: { 712 DiagID = diag::warn_builtin_chk_overflow; 713 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 714 DestinationSize = 715 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 716 IsChkVariant = true; 717 break; 718 } 719 720 case Builtin::BI__builtin___snprintf_chk: 721 case Builtin::BI__builtin___vsnprintf_chk: { 722 DiagID = diag::warn_builtin_chk_overflow; 723 SourceSize = ComputeExplicitObjectSizeArgument(1); 724 DestinationSize = ComputeExplicitObjectSizeArgument(3); 725 IsChkVariant = true; 726 break; 727 } 728 729 case Builtin::BIstrncat: 730 case Builtin::BI__builtin_strncat: 731 case Builtin::BIstrncpy: 732 case Builtin::BI__builtin_strncpy: 733 case Builtin::BIstpncpy: 734 case Builtin::BI__builtin_stpncpy: { 735 // Whether these functions overflow depends on the runtime strlen of the 736 // string, not just the buffer size, so emitting the "always overflow" 737 // diagnostic isn't quite right. We should still diagnose passing a buffer 738 // size larger than the destination buffer though; this is a runtime abort 739 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 740 DiagID = diag::warn_fortify_source_size_mismatch; 741 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 742 DestinationSize = ComputeSizeArgument(0); 743 break; 744 } 745 746 case Builtin::BImemcpy: 747 case Builtin::BI__builtin_memcpy: 748 case Builtin::BImemmove: 749 case Builtin::BI__builtin_memmove: 750 case Builtin::BImemset: 751 case Builtin::BI__builtin_memset: 752 case Builtin::BImempcpy: 753 case Builtin::BI__builtin_mempcpy: { 754 DiagID = diag::warn_fortify_source_overflow; 755 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 756 DestinationSize = ComputeSizeArgument(0); 757 break; 758 } 759 case Builtin::BIsnprintf: 760 case Builtin::BI__builtin_snprintf: 761 case Builtin::BIvsnprintf: 762 case Builtin::BI__builtin_vsnprintf: { 763 DiagID = diag::warn_fortify_source_size_mismatch; 764 SourceSize = ComputeExplicitObjectSizeArgument(1); 765 DestinationSize = ComputeSizeArgument(0); 766 break; 767 } 768 } 769 770 if (!SourceSize || !DestinationSize || 771 SourceSize.getValue().ule(DestinationSize.getValue())) 772 return; 773 774 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 775 // Skim off the details of whichever builtin was called to produce a better 776 // diagnostic, as it's unlikely that the user wrote the __builtin explicitly. 777 if (IsChkVariant) { 778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 779 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 780 } else if (FunctionName.startswith("__builtin_")) { 781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 782 } 783 784 SmallString<16> DestinationStr; 785 SmallString<16> SourceStr; 786 DestinationSize->toString(DestinationStr, /*Radix=*/10); 787 SourceSize->toString(SourceStr, /*Radix=*/10); 788 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 789 PDiag(DiagID) 790 << FunctionName << DestinationStr << SourceStr); 791 } 792 793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 794 Scope::ScopeFlags NeededScopeFlags, 795 unsigned DiagID) { 796 // Scopes aren't available during instantiation. Fortunately, builtin 797 // functions cannot be template args so they cannot be formed through template 798 // instantiation. Therefore checking once during the parse is sufficient. 799 if (SemaRef.inTemplateInstantiation()) 800 return false; 801 802 Scope *S = SemaRef.getCurScope(); 803 while (S && !S->isSEHExceptScope()) 804 S = S->getParent(); 805 if (!S || !(S->getFlags() & NeededScopeFlags)) { 806 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 807 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 808 << DRE->getDecl()->getIdentifier(); 809 return true; 810 } 811 812 return false; 813 } 814 815 static inline bool isBlockPointer(Expr *Arg) { 816 return Arg->getType()->isBlockPointerType(); 817 } 818 819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 820 /// void*, which is a requirement of device side enqueue. 821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 822 const BlockPointerType *BPT = 823 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 824 ArrayRef<QualType> Params = 825 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 826 unsigned ArgCounter = 0; 827 bool IllegalParams = false; 828 // Iterate through the block parameters until either one is found that is not 829 // a local void*, or the block is valid. 830 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 831 I != E; ++I, ++ArgCounter) { 832 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 833 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 834 LangAS::opencl_local) { 835 // Get the location of the error. If a block literal has been passed 836 // (BlockExpr) then we can point straight to the offending argument, 837 // else we just point to the variable reference. 838 SourceLocation ErrorLoc; 839 if (isa<BlockExpr>(BlockArg)) { 840 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 841 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 842 } else if (isa<DeclRefExpr>(BlockArg)) { 843 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 844 } 845 S.Diag(ErrorLoc, 846 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 847 IllegalParams = true; 848 } 849 } 850 851 return IllegalParams; 852 } 853 854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 855 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 857 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 858 return true; 859 } 860 return false; 861 } 862 863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 864 if (checkArgCount(S, TheCall, 2)) 865 return true; 866 867 if (checkOpenCLSubgroupExt(S, TheCall)) 868 return true; 869 870 // First argument is an ndrange_t type. 871 Expr *NDRangeArg = TheCall->getArg(0); 872 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 873 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 874 << TheCall->getDirectCallee() << "'ndrange_t'"; 875 return true; 876 } 877 878 Expr *BlockArg = TheCall->getArg(1); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 888 /// get_kernel_work_group_size 889 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 891 if (checkArgCount(S, TheCall, 1)) 892 return true; 893 894 Expr *BlockArg = TheCall->getArg(0); 895 if (!isBlockPointer(BlockArg)) { 896 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 897 << TheCall->getDirectCallee() << "block"; 898 return true; 899 } 900 return checkOpenCLBlockArgs(S, BlockArg); 901 } 902 903 /// Diagnose integer type and any valid implicit conversion to it. 904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 905 const QualType &IntType); 906 907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 908 unsigned Start, unsigned End) { 909 bool IllegalParams = false; 910 for (unsigned I = Start; I <= End; ++I) 911 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 912 S.Context.getSizeType()); 913 return IllegalParams; 914 } 915 916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 917 /// 'local void*' parameter of passed block. 918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 919 Expr *BlockArg, 920 unsigned NumNonVarArgs) { 921 const BlockPointerType *BPT = 922 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 923 unsigned NumBlockParams = 924 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 925 unsigned TotalNumArgs = TheCall->getNumArgs(); 926 927 // For each argument passed to the block, a corresponding uint needs to 928 // be passed to describe the size of the local memory. 929 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 930 S.Diag(TheCall->getBeginLoc(), 931 diag::err_opencl_enqueue_kernel_local_size_args); 932 return true; 933 } 934 935 // Check that the sizes of the local memory are specified by integers. 936 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 937 TotalNumArgs - 1); 938 } 939 940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 941 /// overload formats specified in Table 6.13.17.1. 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// void (^block)(void)) 946 /// int enqueue_kernel(queue_t queue, 947 /// kernel_enqueue_flags_t flags, 948 /// const ndrange_t ndrange, 949 /// uint num_events_in_wait_list, 950 /// clk_event_t *event_wait_list, 951 /// clk_event_t *event_ret, 952 /// void (^block)(void)) 953 /// int enqueue_kernel(queue_t queue, 954 /// kernel_enqueue_flags_t flags, 955 /// const ndrange_t ndrange, 956 /// void (^block)(local void*, ...), 957 /// uint size0, ...) 958 /// int enqueue_kernel(queue_t queue, 959 /// kernel_enqueue_flags_t flags, 960 /// const ndrange_t ndrange, 961 /// uint num_events_in_wait_list, 962 /// clk_event_t *event_wait_list, 963 /// clk_event_t *event_ret, 964 /// void (^block)(local void*, ...), 965 /// uint size0, ...) 966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 967 unsigned NumArgs = TheCall->getNumArgs(); 968 969 if (NumArgs < 4) { 970 S.Diag(TheCall->getBeginLoc(), 971 diag::err_typecheck_call_too_few_args_at_least) 972 << 0 << 4 << NumArgs; 973 return true; 974 } 975 976 Expr *Arg0 = TheCall->getArg(0); 977 Expr *Arg1 = TheCall->getArg(1); 978 Expr *Arg2 = TheCall->getArg(2); 979 Expr *Arg3 = TheCall->getArg(3); 980 981 // First argument always needs to be a queue_t type. 982 if (!Arg0->getType()->isQueueT()) { 983 S.Diag(TheCall->getArg(0)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 986 return true; 987 } 988 989 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 990 if (!Arg1->getType()->isIntegerType()) { 991 S.Diag(TheCall->getArg(1)->getBeginLoc(), 992 diag::err_opencl_builtin_expected_type) 993 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 994 return true; 995 } 996 997 // Third argument is always an ndrange_t type. 998 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 999 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1000 diag::err_opencl_builtin_expected_type) 1001 << TheCall->getDirectCallee() << "'ndrange_t'"; 1002 return true; 1003 } 1004 1005 // With four arguments, there is only one form that the function could be 1006 // called in: no events and no variable arguments. 1007 if (NumArgs == 4) { 1008 // check that the last argument is the right block type. 1009 if (!isBlockPointer(Arg3)) { 1010 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1011 << TheCall->getDirectCallee() << "block"; 1012 return true; 1013 } 1014 // we have a block type, check the prototype 1015 const BlockPointerType *BPT = 1016 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1017 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1018 S.Diag(Arg3->getBeginLoc(), 1019 diag::err_opencl_enqueue_kernel_blocks_no_args); 1020 return true; 1021 } 1022 return false; 1023 } 1024 // we can have block + varargs. 1025 if (isBlockPointer(Arg3)) 1026 return (checkOpenCLBlockArgs(S, Arg3) || 1027 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1028 // last two cases with either exactly 7 args or 7 args and varargs. 1029 if (NumArgs >= 7) { 1030 // check common block argument. 1031 Expr *Arg6 = TheCall->getArg(6); 1032 if (!isBlockPointer(Arg6)) { 1033 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1034 << TheCall->getDirectCallee() << "block"; 1035 return true; 1036 } 1037 if (checkOpenCLBlockArgs(S, Arg6)) 1038 return true; 1039 1040 // Forth argument has to be any integer type. 1041 if (!Arg3->getType()->isIntegerType()) { 1042 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1043 diag::err_opencl_builtin_expected_type) 1044 << TheCall->getDirectCallee() << "integer"; 1045 return true; 1046 } 1047 // check remaining common arguments. 1048 Expr *Arg4 = TheCall->getArg(4); 1049 Expr *Arg5 = TheCall->getArg(5); 1050 1051 // Fifth argument is always passed as a pointer to clk_event_t. 1052 if (!Arg4->isNullPointerConstant(S.Context, 1053 Expr::NPC_ValueDependentIsNotNull) && 1054 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1055 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1056 diag::err_opencl_builtin_expected_type) 1057 << TheCall->getDirectCallee() 1058 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1059 return true; 1060 } 1061 1062 // Sixth argument is always passed as a pointer to clk_event_t. 1063 if (!Arg5->isNullPointerConstant(S.Context, 1064 Expr::NPC_ValueDependentIsNotNull) && 1065 !(Arg5->getType()->isPointerType() && 1066 Arg5->getType()->getPointeeType()->isClkEventT())) { 1067 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1068 diag::err_opencl_builtin_expected_type) 1069 << TheCall->getDirectCallee() 1070 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1071 return true; 1072 } 1073 1074 if (NumArgs == 7) 1075 return false; 1076 1077 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1078 } 1079 1080 // None of the specific case has been detected, give generic error 1081 S.Diag(TheCall->getBeginLoc(), 1082 diag::err_opencl_enqueue_kernel_incorrect_args); 1083 return true; 1084 } 1085 1086 /// Returns OpenCL access qual. 1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1088 return D->getAttr<OpenCLAccessAttr>(); 1089 } 1090 1091 /// Returns true if pipe element type is different from the pointer. 1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1093 const Expr *Arg0 = Call->getArg(0); 1094 // First argument type should always be pipe. 1095 if (!Arg0->getType()->isPipeType()) { 1096 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1097 << Call->getDirectCallee() << Arg0->getSourceRange(); 1098 return true; 1099 } 1100 OpenCLAccessAttr *AccessQual = 1101 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1102 // Validates the access qualifier is compatible with the call. 1103 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1104 // read_only and write_only, and assumed to be read_only if no qualifier is 1105 // specified. 1106 switch (Call->getDirectCallee()->getBuiltinID()) { 1107 case Builtin::BIread_pipe: 1108 case Builtin::BIreserve_read_pipe: 1109 case Builtin::BIcommit_read_pipe: 1110 case Builtin::BIwork_group_reserve_read_pipe: 1111 case Builtin::BIsub_group_reserve_read_pipe: 1112 case Builtin::BIwork_group_commit_read_pipe: 1113 case Builtin::BIsub_group_commit_read_pipe: 1114 if (!(!AccessQual || AccessQual->isReadOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "read_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 case Builtin::BIwrite_pipe: 1122 case Builtin::BIreserve_write_pipe: 1123 case Builtin::BIcommit_write_pipe: 1124 case Builtin::BIwork_group_reserve_write_pipe: 1125 case Builtin::BIsub_group_reserve_write_pipe: 1126 case Builtin::BIwork_group_commit_write_pipe: 1127 case Builtin::BIsub_group_commit_write_pipe: 1128 if (!(AccessQual && AccessQual->isWriteOnly())) { 1129 S.Diag(Arg0->getBeginLoc(), 1130 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1131 << "write_only" << Arg0->getSourceRange(); 1132 return true; 1133 } 1134 break; 1135 default: 1136 break; 1137 } 1138 return false; 1139 } 1140 1141 /// Returns true if pipe element type is different from the pointer. 1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1143 const Expr *Arg0 = Call->getArg(0); 1144 const Expr *ArgIdx = Call->getArg(Idx); 1145 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1146 const QualType EltTy = PipeTy->getElementType(); 1147 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1148 // The Idx argument should be a pointer and the type of the pointer and 1149 // the type of pipe element should also be the same. 1150 if (!ArgTy || 1151 !S.Context.hasSameType( 1152 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1153 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1154 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1155 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 // Performs semantic analysis for the read/write_pipe call. 1162 // \param S Reference to the semantic analyzer. 1163 // \param Call A pointer to the builtin call. 1164 // \return True if a semantic error has been found, false otherwise. 1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1166 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1167 // functions have two forms. 1168 switch (Call->getNumArgs()) { 1169 case 2: 1170 if (checkOpenCLPipeArg(S, Call)) 1171 return true; 1172 // The call with 2 arguments should be 1173 // read/write_pipe(pipe T, T*). 1174 // Check packet type T. 1175 if (checkOpenCLPipePacketType(S, Call, 1)) 1176 return true; 1177 break; 1178 1179 case 4: { 1180 if (checkOpenCLPipeArg(S, Call)) 1181 return true; 1182 // The call with 4 arguments should be 1183 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1184 // Check reserve_id_t. 1185 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1186 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1187 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1188 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1189 return true; 1190 } 1191 1192 // Check the index. 1193 const Expr *Arg2 = Call->getArg(2); 1194 if (!Arg2->getType()->isIntegerType() && 1195 !Arg2->getType()->isUnsignedIntegerType()) { 1196 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1197 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1198 << Arg2->getType() << Arg2->getSourceRange(); 1199 return true; 1200 } 1201 1202 // Check packet type T. 1203 if (checkOpenCLPipePacketType(S, Call, 3)) 1204 return true; 1205 } break; 1206 default: 1207 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1208 << Call->getDirectCallee() << Call->getSourceRange(); 1209 return true; 1210 } 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on the {work_group_/sub_group_ 1216 // /_}reserve_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check the reserve size. 1228 if (!Call->getArg(1)->getType()->isIntegerType() && 1229 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1230 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1231 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1232 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1233 return true; 1234 } 1235 1236 // Since return type of reserve_read/write_pipe built-in function is 1237 // reserve_id_t, which is not defined in the builtin def file , we used int 1238 // as return type and need to override the return type of these functions. 1239 Call->setType(S.Context.OCLReserveIDTy); 1240 1241 return false; 1242 } 1243 1244 // Performs a semantic analysis on {work_group_/sub_group_ 1245 // /_}commit_{read/write}_pipe 1246 // \param S Reference to the semantic analyzer. 1247 // \param Call The call to the builtin function to be analyzed. 1248 // \return True if a semantic error was found, false otherwise. 1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1250 if (checkArgCount(S, Call, 2)) 1251 return true; 1252 1253 if (checkOpenCLPipeArg(S, Call)) 1254 return true; 1255 1256 // Check reserve_id_t. 1257 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1258 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1259 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1260 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1261 return true; 1262 } 1263 1264 return false; 1265 } 1266 1267 // Performs a semantic analysis on the call to built-in Pipe 1268 // Query Functions. 1269 // \param S Reference to the semantic analyzer. 1270 // \param Call The call to the builtin function to be analyzed. 1271 // \return True if a semantic error was found, false otherwise. 1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1273 if (checkArgCount(S, Call, 1)) 1274 return true; 1275 1276 if (!Call->getArg(0)->getType()->isPipeType()) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1278 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1279 return true; 1280 } 1281 1282 return false; 1283 } 1284 1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1286 // Performs semantic analysis for the to_global/local/private call. 1287 // \param S Reference to the semantic analyzer. 1288 // \param BuiltinID ID of the builtin function. 1289 // \param Call A pointer to the builtin call. 1290 // \return True if a semantic error has been found, false otherwise. 1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1292 CallExpr *Call) { 1293 if (checkArgCount(S, Call, 1)) 1294 return true; 1295 1296 auto RT = Call->getArg(0)->getType(); 1297 if (!RT->isPointerType() || RT->getPointeeType() 1298 .getAddressSpace() == LangAS::opencl_constant) { 1299 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1300 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1301 return true; 1302 } 1303 1304 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1305 S.Diag(Call->getArg(0)->getBeginLoc(), 1306 diag::warn_opencl_generic_address_space_arg) 1307 << Call->getDirectCallee()->getNameInfo().getAsString() 1308 << Call->getArg(0)->getSourceRange(); 1309 } 1310 1311 RT = RT->getPointeeType(); 1312 auto Qual = RT.getQualifiers(); 1313 switch (BuiltinID) { 1314 case Builtin::BIto_global: 1315 Qual.setAddressSpace(LangAS::opencl_global); 1316 break; 1317 case Builtin::BIto_local: 1318 Qual.setAddressSpace(LangAS::opencl_local); 1319 break; 1320 case Builtin::BIto_private: 1321 Qual.setAddressSpace(LangAS::opencl_private); 1322 break; 1323 default: 1324 llvm_unreachable("Invalid builtin function"); 1325 } 1326 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1327 RT.getUnqualifiedType(), Qual))); 1328 1329 return false; 1330 } 1331 1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1333 if (checkArgCount(S, TheCall, 1)) 1334 return ExprError(); 1335 1336 // Compute __builtin_launder's parameter type from the argument. 1337 // The parameter type is: 1338 // * The type of the argument if it's not an array or function type, 1339 // Otherwise, 1340 // * The decayed argument type. 1341 QualType ParamTy = [&]() { 1342 QualType ArgTy = TheCall->getArg(0)->getType(); 1343 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1344 return S.Context.getPointerType(Ty->getElementType()); 1345 if (ArgTy->isFunctionType()) { 1346 return S.Context.getPointerType(ArgTy); 1347 } 1348 return ArgTy; 1349 }(); 1350 1351 TheCall->setType(ParamTy); 1352 1353 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1354 if (!ParamTy->isPointerType()) 1355 return 0; 1356 if (ParamTy->isFunctionPointerType()) 1357 return 1; 1358 if (ParamTy->isVoidPointerType()) 1359 return 2; 1360 return llvm::Optional<unsigned>{}; 1361 }(); 1362 if (DiagSelect.hasValue()) { 1363 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1364 << DiagSelect.getValue() << TheCall->getSourceRange(); 1365 return ExprError(); 1366 } 1367 1368 // We either have an incomplete class type, or we have a class template 1369 // whose instantiation has not been forced. Example: 1370 // 1371 // template <class T> struct Foo { T value; }; 1372 // Foo<int> *p = nullptr; 1373 // auto *d = __builtin_launder(p); 1374 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1375 diag::err_incomplete_type)) 1376 return ExprError(); 1377 1378 assert(ParamTy->getPointeeType()->isObjectType() && 1379 "Unhandled non-object pointer case"); 1380 1381 InitializedEntity Entity = 1382 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1383 ExprResult Arg = 1384 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1385 if (Arg.isInvalid()) 1386 return ExprError(); 1387 TheCall->setArg(0, Arg.get()); 1388 1389 return TheCall; 1390 } 1391 1392 // Emit an error and return true if the current architecture is not in the list 1393 // of supported architectures. 1394 static bool 1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1396 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1397 llvm::Triple::ArchType CurArch = 1398 S.getASTContext().getTargetInfo().getTriple().getArch(); 1399 if (llvm::is_contained(SupportedArchs, CurArch)) 1400 return false; 1401 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1402 << TheCall->getSourceRange(); 1403 return true; 1404 } 1405 1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1407 SourceLocation CallSiteLoc); 1408 1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1410 CallExpr *TheCall) { 1411 switch (TI.getTriple().getArch()) { 1412 default: 1413 // Some builtins don't require additional checking, so just consider these 1414 // acceptable. 1415 return false; 1416 case llvm::Triple::arm: 1417 case llvm::Triple::armeb: 1418 case llvm::Triple::thumb: 1419 case llvm::Triple::thumbeb: 1420 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::aarch64: 1422 case llvm::Triple::aarch64_32: 1423 case llvm::Triple::aarch64_be: 1424 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::bpfeb: 1426 case llvm::Triple::bpfel: 1427 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1428 case llvm::Triple::hexagon: 1429 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1430 case llvm::Triple::mips: 1431 case llvm::Triple::mipsel: 1432 case llvm::Triple::mips64: 1433 case llvm::Triple::mips64el: 1434 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 case llvm::Triple::systemz: 1436 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1437 case llvm::Triple::x86: 1438 case llvm::Triple::x86_64: 1439 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1440 case llvm::Triple::ppc: 1441 case llvm::Triple::ppcle: 1442 case llvm::Triple::ppc64: 1443 case llvm::Triple::ppc64le: 1444 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1445 case llvm::Triple::amdgcn: 1446 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1447 case llvm::Triple::riscv32: 1448 case llvm::Triple::riscv64: 1449 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1450 } 1451 } 1452 1453 ExprResult 1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1455 CallExpr *TheCall) { 1456 ExprResult TheCallResult(TheCall); 1457 1458 // Find out if any arguments are required to be integer constant expressions. 1459 unsigned ICEArguments = 0; 1460 ASTContext::GetBuiltinTypeError Error; 1461 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1462 if (Error != ASTContext::GE_None) 1463 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1464 1465 // If any arguments are required to be ICE's, check and diagnose. 1466 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1467 // Skip arguments not required to be ICE's. 1468 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1469 1470 llvm::APSInt Result; 1471 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1472 return true; 1473 ICEArguments &= ~(1 << ArgNo); 1474 } 1475 1476 switch (BuiltinID) { 1477 case Builtin::BI__builtin___CFStringMakeConstantString: 1478 assert(TheCall->getNumArgs() == 1 && 1479 "Wrong # arguments to builtin CFStringMakeConstantString"); 1480 if (CheckObjCString(TheCall->getArg(0))) 1481 return ExprError(); 1482 break; 1483 case Builtin::BI__builtin_ms_va_start: 1484 case Builtin::BI__builtin_stdarg_start: 1485 case Builtin::BI__builtin_va_start: 1486 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1487 return ExprError(); 1488 break; 1489 case Builtin::BI__va_start: { 1490 switch (Context.getTargetInfo().getTriple().getArch()) { 1491 case llvm::Triple::aarch64: 1492 case llvm::Triple::arm: 1493 case llvm::Triple::thumb: 1494 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1495 return ExprError(); 1496 break; 1497 default: 1498 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1499 return ExprError(); 1500 break; 1501 } 1502 break; 1503 } 1504 1505 // The acquire, release, and no fence variants are ARM and AArch64 only. 1506 case Builtin::BI_interlockedbittestandset_acq: 1507 case Builtin::BI_interlockedbittestandset_rel: 1508 case Builtin::BI_interlockedbittestandset_nf: 1509 case Builtin::BI_interlockedbittestandreset_acq: 1510 case Builtin::BI_interlockedbittestandreset_rel: 1511 case Builtin::BI_interlockedbittestandreset_nf: 1512 if (CheckBuiltinTargetSupport( 1513 *this, BuiltinID, TheCall, 1514 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1515 return ExprError(); 1516 break; 1517 1518 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1519 case Builtin::BI_bittest64: 1520 case Builtin::BI_bittestandcomplement64: 1521 case Builtin::BI_bittestandreset64: 1522 case Builtin::BI_bittestandset64: 1523 case Builtin::BI_interlockedbittestandreset64: 1524 case Builtin::BI_interlockedbittestandset64: 1525 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1526 {llvm::Triple::x86_64, llvm::Triple::arm, 1527 llvm::Triple::thumb, llvm::Triple::aarch64})) 1528 return ExprError(); 1529 break; 1530 1531 case Builtin::BI__builtin_isgreater: 1532 case Builtin::BI__builtin_isgreaterequal: 1533 case Builtin::BI__builtin_isless: 1534 case Builtin::BI__builtin_islessequal: 1535 case Builtin::BI__builtin_islessgreater: 1536 case Builtin::BI__builtin_isunordered: 1537 if (SemaBuiltinUnorderedCompare(TheCall)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_fpclassify: 1541 if (SemaBuiltinFPClassification(TheCall, 6)) 1542 return ExprError(); 1543 break; 1544 case Builtin::BI__builtin_isfinite: 1545 case Builtin::BI__builtin_isinf: 1546 case Builtin::BI__builtin_isinf_sign: 1547 case Builtin::BI__builtin_isnan: 1548 case Builtin::BI__builtin_isnormal: 1549 case Builtin::BI__builtin_signbit: 1550 case Builtin::BI__builtin_signbitf: 1551 case Builtin::BI__builtin_signbitl: 1552 if (SemaBuiltinFPClassification(TheCall, 1)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_shufflevector: 1556 return SemaBuiltinShuffleVector(TheCall); 1557 // TheCall will be freed by the smart pointer here, but that's fine, since 1558 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1559 case Builtin::BI__builtin_prefetch: 1560 if (SemaBuiltinPrefetch(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_alloca_with_align: 1564 if (SemaBuiltinAllocaWithAlign(TheCall)) 1565 return ExprError(); 1566 LLVM_FALLTHROUGH; 1567 case Builtin::BI__builtin_alloca: 1568 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1569 << TheCall->getDirectCallee(); 1570 break; 1571 case Builtin::BI__arithmetic_fence: 1572 if (SemaBuiltinArithmeticFence(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__assume: 1576 case Builtin::BI__builtin_assume: 1577 if (SemaBuiltinAssume(TheCall)) 1578 return ExprError(); 1579 break; 1580 case Builtin::BI__builtin_assume_aligned: 1581 if (SemaBuiltinAssumeAligned(TheCall)) 1582 return ExprError(); 1583 break; 1584 case Builtin::BI__builtin_dynamic_object_size: 1585 case Builtin::BI__builtin_object_size: 1586 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BI__builtin_longjmp: 1590 if (SemaBuiltinLongjmp(TheCall)) 1591 return ExprError(); 1592 break; 1593 case Builtin::BI__builtin_setjmp: 1594 if (SemaBuiltinSetjmp(TheCall)) 1595 return ExprError(); 1596 break; 1597 case Builtin::BI__builtin_classify_type: 1598 if (checkArgCount(*this, TheCall, 1)) return true; 1599 TheCall->setType(Context.IntTy); 1600 break; 1601 case Builtin::BI__builtin_complex: 1602 if (SemaBuiltinComplex(TheCall)) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_constant_p: { 1606 if (checkArgCount(*this, TheCall, 1)) return true; 1607 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1608 if (Arg.isInvalid()) return true; 1609 TheCall->setArg(0, Arg.get()); 1610 TheCall->setType(Context.IntTy); 1611 break; 1612 } 1613 case Builtin::BI__builtin_launder: 1614 return SemaBuiltinLaunder(*this, TheCall); 1615 case Builtin::BI__sync_fetch_and_add: 1616 case Builtin::BI__sync_fetch_and_add_1: 1617 case Builtin::BI__sync_fetch_and_add_2: 1618 case Builtin::BI__sync_fetch_and_add_4: 1619 case Builtin::BI__sync_fetch_and_add_8: 1620 case Builtin::BI__sync_fetch_and_add_16: 1621 case Builtin::BI__sync_fetch_and_sub: 1622 case Builtin::BI__sync_fetch_and_sub_1: 1623 case Builtin::BI__sync_fetch_and_sub_2: 1624 case Builtin::BI__sync_fetch_and_sub_4: 1625 case Builtin::BI__sync_fetch_and_sub_8: 1626 case Builtin::BI__sync_fetch_and_sub_16: 1627 case Builtin::BI__sync_fetch_and_or: 1628 case Builtin::BI__sync_fetch_and_or_1: 1629 case Builtin::BI__sync_fetch_and_or_2: 1630 case Builtin::BI__sync_fetch_and_or_4: 1631 case Builtin::BI__sync_fetch_and_or_8: 1632 case Builtin::BI__sync_fetch_and_or_16: 1633 case Builtin::BI__sync_fetch_and_and: 1634 case Builtin::BI__sync_fetch_and_and_1: 1635 case Builtin::BI__sync_fetch_and_and_2: 1636 case Builtin::BI__sync_fetch_and_and_4: 1637 case Builtin::BI__sync_fetch_and_and_8: 1638 case Builtin::BI__sync_fetch_and_and_16: 1639 case Builtin::BI__sync_fetch_and_xor: 1640 case Builtin::BI__sync_fetch_and_xor_1: 1641 case Builtin::BI__sync_fetch_and_xor_2: 1642 case Builtin::BI__sync_fetch_and_xor_4: 1643 case Builtin::BI__sync_fetch_and_xor_8: 1644 case Builtin::BI__sync_fetch_and_xor_16: 1645 case Builtin::BI__sync_fetch_and_nand: 1646 case Builtin::BI__sync_fetch_and_nand_1: 1647 case Builtin::BI__sync_fetch_and_nand_2: 1648 case Builtin::BI__sync_fetch_and_nand_4: 1649 case Builtin::BI__sync_fetch_and_nand_8: 1650 case Builtin::BI__sync_fetch_and_nand_16: 1651 case Builtin::BI__sync_add_and_fetch: 1652 case Builtin::BI__sync_add_and_fetch_1: 1653 case Builtin::BI__sync_add_and_fetch_2: 1654 case Builtin::BI__sync_add_and_fetch_4: 1655 case Builtin::BI__sync_add_and_fetch_8: 1656 case Builtin::BI__sync_add_and_fetch_16: 1657 case Builtin::BI__sync_sub_and_fetch: 1658 case Builtin::BI__sync_sub_and_fetch_1: 1659 case Builtin::BI__sync_sub_and_fetch_2: 1660 case Builtin::BI__sync_sub_and_fetch_4: 1661 case Builtin::BI__sync_sub_and_fetch_8: 1662 case Builtin::BI__sync_sub_and_fetch_16: 1663 case Builtin::BI__sync_and_and_fetch: 1664 case Builtin::BI__sync_and_and_fetch_1: 1665 case Builtin::BI__sync_and_and_fetch_2: 1666 case Builtin::BI__sync_and_and_fetch_4: 1667 case Builtin::BI__sync_and_and_fetch_8: 1668 case Builtin::BI__sync_and_and_fetch_16: 1669 case Builtin::BI__sync_or_and_fetch: 1670 case Builtin::BI__sync_or_and_fetch_1: 1671 case Builtin::BI__sync_or_and_fetch_2: 1672 case Builtin::BI__sync_or_and_fetch_4: 1673 case Builtin::BI__sync_or_and_fetch_8: 1674 case Builtin::BI__sync_or_and_fetch_16: 1675 case Builtin::BI__sync_xor_and_fetch: 1676 case Builtin::BI__sync_xor_and_fetch_1: 1677 case Builtin::BI__sync_xor_and_fetch_2: 1678 case Builtin::BI__sync_xor_and_fetch_4: 1679 case Builtin::BI__sync_xor_and_fetch_8: 1680 case Builtin::BI__sync_xor_and_fetch_16: 1681 case Builtin::BI__sync_nand_and_fetch: 1682 case Builtin::BI__sync_nand_and_fetch_1: 1683 case Builtin::BI__sync_nand_and_fetch_2: 1684 case Builtin::BI__sync_nand_and_fetch_4: 1685 case Builtin::BI__sync_nand_and_fetch_8: 1686 case Builtin::BI__sync_nand_and_fetch_16: 1687 case Builtin::BI__sync_val_compare_and_swap: 1688 case Builtin::BI__sync_val_compare_and_swap_1: 1689 case Builtin::BI__sync_val_compare_and_swap_2: 1690 case Builtin::BI__sync_val_compare_and_swap_4: 1691 case Builtin::BI__sync_val_compare_and_swap_8: 1692 case Builtin::BI__sync_val_compare_and_swap_16: 1693 case Builtin::BI__sync_bool_compare_and_swap: 1694 case Builtin::BI__sync_bool_compare_and_swap_1: 1695 case Builtin::BI__sync_bool_compare_and_swap_2: 1696 case Builtin::BI__sync_bool_compare_and_swap_4: 1697 case Builtin::BI__sync_bool_compare_and_swap_8: 1698 case Builtin::BI__sync_bool_compare_and_swap_16: 1699 case Builtin::BI__sync_lock_test_and_set: 1700 case Builtin::BI__sync_lock_test_and_set_1: 1701 case Builtin::BI__sync_lock_test_and_set_2: 1702 case Builtin::BI__sync_lock_test_and_set_4: 1703 case Builtin::BI__sync_lock_test_and_set_8: 1704 case Builtin::BI__sync_lock_test_and_set_16: 1705 case Builtin::BI__sync_lock_release: 1706 case Builtin::BI__sync_lock_release_1: 1707 case Builtin::BI__sync_lock_release_2: 1708 case Builtin::BI__sync_lock_release_4: 1709 case Builtin::BI__sync_lock_release_8: 1710 case Builtin::BI__sync_lock_release_16: 1711 case Builtin::BI__sync_swap: 1712 case Builtin::BI__sync_swap_1: 1713 case Builtin::BI__sync_swap_2: 1714 case Builtin::BI__sync_swap_4: 1715 case Builtin::BI__sync_swap_8: 1716 case Builtin::BI__sync_swap_16: 1717 return SemaBuiltinAtomicOverloaded(TheCallResult); 1718 case Builtin::BI__sync_synchronize: 1719 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1720 << TheCall->getCallee()->getSourceRange(); 1721 break; 1722 case Builtin::BI__builtin_nontemporal_load: 1723 case Builtin::BI__builtin_nontemporal_store: 1724 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1725 case Builtin::BI__builtin_memcpy_inline: { 1726 clang::Expr *SizeOp = TheCall->getArg(2); 1727 // We warn about copying to or from `nullptr` pointers when `size` is 1728 // greater than 0. When `size` is value dependent we cannot evaluate its 1729 // value so we bail out. 1730 if (SizeOp->isValueDependent()) 1731 break; 1732 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1733 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1734 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1735 } 1736 break; 1737 } 1738 #define BUILTIN(ID, TYPE, ATTRS) 1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1740 case Builtin::BI##ID: \ 1741 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1742 #include "clang/Basic/Builtins.def" 1743 case Builtin::BI__annotation: 1744 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_annotation: 1748 if (SemaBuiltinAnnotation(*this, TheCall)) 1749 return ExprError(); 1750 break; 1751 case Builtin::BI__builtin_addressof: 1752 if (SemaBuiltinAddressof(*this, TheCall)) 1753 return ExprError(); 1754 break; 1755 case Builtin::BI__builtin_is_aligned: 1756 case Builtin::BI__builtin_align_up: 1757 case Builtin::BI__builtin_align_down: 1758 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_add_overflow: 1762 case Builtin::BI__builtin_sub_overflow: 1763 case Builtin::BI__builtin_mul_overflow: 1764 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__builtin_operator_new: 1768 case Builtin::BI__builtin_operator_delete: { 1769 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1770 ExprResult Res = 1771 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1772 if (Res.isInvalid()) 1773 CorrectDelayedTyposInExpr(TheCallResult.get()); 1774 return Res; 1775 } 1776 case Builtin::BI__builtin_dump_struct: { 1777 // We first want to ensure we are called with 2 arguments 1778 if (checkArgCount(*this, TheCall, 2)) 1779 return ExprError(); 1780 // Ensure that the first argument is of type 'struct XX *' 1781 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1782 const QualType PtrArgType = PtrArg->getType(); 1783 if (!PtrArgType->isPointerType() || 1784 !PtrArgType->getPointeeType()->isRecordType()) { 1785 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1786 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1787 << "structure pointer"; 1788 return ExprError(); 1789 } 1790 1791 // Ensure that the second argument is of type 'FunctionType' 1792 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1793 const QualType FnPtrArgType = FnPtrArg->getType(); 1794 if (!FnPtrArgType->isPointerType()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1797 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 1801 const auto *FuncType = 1802 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1803 1804 if (!FuncType) { 1805 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1806 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1807 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1808 return ExprError(); 1809 } 1810 1811 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1812 if (!FT->getNumParams()) { 1813 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1814 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1815 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1816 return ExprError(); 1817 } 1818 QualType PT = FT->getParamType(0); 1819 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1820 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1821 !PT->getPointeeType().isConstQualified()) { 1822 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1823 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1824 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1825 return ExprError(); 1826 } 1827 } 1828 1829 TheCall->setType(Context.IntTy); 1830 break; 1831 } 1832 case Builtin::BI__builtin_expect_with_probability: { 1833 // We first want to ensure we are called with 3 arguments 1834 if (checkArgCount(*this, TheCall, 3)) 1835 return ExprError(); 1836 // then check probability is constant float in range [0.0, 1.0] 1837 const Expr *ProbArg = TheCall->getArg(2); 1838 SmallVector<PartialDiagnosticAt, 8> Notes; 1839 Expr::EvalResult Eval; 1840 Eval.Diag = &Notes; 1841 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1842 !Eval.Val.isFloat()) { 1843 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1844 << ProbArg->getSourceRange(); 1845 for (const PartialDiagnosticAt &PDiag : Notes) 1846 Diag(PDiag.first, PDiag.second); 1847 return ExprError(); 1848 } 1849 llvm::APFloat Probability = Eval.Val.getFloat(); 1850 bool LoseInfo = false; 1851 Probability.convert(llvm::APFloat::IEEEdouble(), 1852 llvm::RoundingMode::Dynamic, &LoseInfo); 1853 if (!(Probability >= llvm::APFloat(0.0) && 1854 Probability <= llvm::APFloat(1.0))) { 1855 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1856 << ProbArg->getSourceRange(); 1857 return ExprError(); 1858 } 1859 break; 1860 } 1861 case Builtin::BI__builtin_preserve_access_index: 1862 if (SemaBuiltinPreserveAI(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BI__builtin_call_with_static_chain: 1866 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__exception_code: 1870 case Builtin::BI_exception_code: 1871 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1872 diag::err_seh___except_block)) 1873 return ExprError(); 1874 break; 1875 case Builtin::BI__exception_info: 1876 case Builtin::BI_exception_info: 1877 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1878 diag::err_seh___except_filter)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BI__GetExceptionInfo: 1882 if (checkArgCount(*this, TheCall, 1)) 1883 return ExprError(); 1884 1885 if (CheckCXXThrowOperand( 1886 TheCall->getBeginLoc(), 1887 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1888 TheCall)) 1889 return ExprError(); 1890 1891 TheCall->setType(Context.VoidPtrTy); 1892 break; 1893 // OpenCL v2.0, s6.13.16 - Pipe functions 1894 case Builtin::BIread_pipe: 1895 case Builtin::BIwrite_pipe: 1896 // Since those two functions are declared with var args, we need a semantic 1897 // check for the argument. 1898 if (SemaBuiltinRWPipe(*this, TheCall)) 1899 return ExprError(); 1900 break; 1901 case Builtin::BIreserve_read_pipe: 1902 case Builtin::BIreserve_write_pipe: 1903 case Builtin::BIwork_group_reserve_read_pipe: 1904 case Builtin::BIwork_group_reserve_write_pipe: 1905 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIsub_group_reserve_read_pipe: 1909 case Builtin::BIsub_group_reserve_write_pipe: 1910 if (checkOpenCLSubgroupExt(*this, TheCall) || 1911 SemaBuiltinReserveRWPipe(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIcommit_read_pipe: 1915 case Builtin::BIcommit_write_pipe: 1916 case Builtin::BIwork_group_commit_read_pipe: 1917 case Builtin::BIwork_group_commit_write_pipe: 1918 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1919 return ExprError(); 1920 break; 1921 case Builtin::BIsub_group_commit_read_pipe: 1922 case Builtin::BIsub_group_commit_write_pipe: 1923 if (checkOpenCLSubgroupExt(*this, TheCall) || 1924 SemaBuiltinCommitRWPipe(*this, TheCall)) 1925 return ExprError(); 1926 break; 1927 case Builtin::BIget_pipe_num_packets: 1928 case Builtin::BIget_pipe_max_packets: 1929 if (SemaBuiltinPipePackets(*this, TheCall)) 1930 return ExprError(); 1931 break; 1932 case Builtin::BIto_global: 1933 case Builtin::BIto_local: 1934 case Builtin::BIto_private: 1935 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1936 return ExprError(); 1937 break; 1938 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1939 case Builtin::BIenqueue_kernel: 1940 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1941 return ExprError(); 1942 break; 1943 case Builtin::BIget_kernel_work_group_size: 1944 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1945 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1946 return ExprError(); 1947 break; 1948 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1949 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1950 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1951 return ExprError(); 1952 break; 1953 case Builtin::BI__builtin_os_log_format: 1954 Cleanup.setExprNeedsCleanups(true); 1955 LLVM_FALLTHROUGH; 1956 case Builtin::BI__builtin_os_log_format_buffer_size: 1957 if (SemaBuiltinOSLogFormat(TheCall)) 1958 return ExprError(); 1959 break; 1960 case Builtin::BI__builtin_frame_address: 1961 case Builtin::BI__builtin_return_address: { 1962 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1963 return ExprError(); 1964 1965 // -Wframe-address warning if non-zero passed to builtin 1966 // return/frame address. 1967 Expr::EvalResult Result; 1968 if (!TheCall->getArg(0)->isValueDependent() && 1969 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1970 Result.Val.getInt() != 0) 1971 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1972 << ((BuiltinID == Builtin::BI__builtin_return_address) 1973 ? "__builtin_return_address" 1974 : "__builtin_frame_address") 1975 << TheCall->getSourceRange(); 1976 break; 1977 } 1978 1979 case Builtin::BI__builtin_elementwise_abs: 1980 if (SemaBuiltinElementwiseMathOneArg(TheCall)) 1981 return ExprError(); 1982 break; 1983 case Builtin::BI__builtin_elementwise_min: 1984 case Builtin::BI__builtin_elementwise_max: 1985 if (SemaBuiltinElementwiseMath(TheCall)) 1986 return ExprError(); 1987 break; 1988 case Builtin::BI__builtin_matrix_transpose: 1989 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1990 1991 case Builtin::BI__builtin_matrix_column_major_load: 1992 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1993 1994 case Builtin::BI__builtin_matrix_column_major_store: 1995 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1996 1997 case Builtin::BI__builtin_get_device_side_mangled_name: { 1998 auto Check = [](CallExpr *TheCall) { 1999 if (TheCall->getNumArgs() != 1) 2000 return false; 2001 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2002 if (!DRE) 2003 return false; 2004 auto *D = DRE->getDecl(); 2005 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2006 return false; 2007 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2008 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2009 }; 2010 if (!Check(TheCall)) { 2011 Diag(TheCall->getBeginLoc(), 2012 diag::err_hip_invalid_args_builtin_mangled_name); 2013 return ExprError(); 2014 } 2015 } 2016 } 2017 2018 // Since the target specific builtins for each arch overlap, only check those 2019 // of the arch we are compiling for. 2020 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2021 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2022 assert(Context.getAuxTargetInfo() && 2023 "Aux Target Builtin, but not an aux target?"); 2024 2025 if (CheckTSBuiltinFunctionCall( 2026 *Context.getAuxTargetInfo(), 2027 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2028 return ExprError(); 2029 } else { 2030 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2031 TheCall)) 2032 return ExprError(); 2033 } 2034 } 2035 2036 return TheCallResult; 2037 } 2038 2039 // Get the valid immediate range for the specified NEON type code. 2040 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2041 NeonTypeFlags Type(t); 2042 int IsQuad = ForceQuad ? true : Type.isQuad(); 2043 switch (Type.getEltType()) { 2044 case NeonTypeFlags::Int8: 2045 case NeonTypeFlags::Poly8: 2046 return shift ? 7 : (8 << IsQuad) - 1; 2047 case NeonTypeFlags::Int16: 2048 case NeonTypeFlags::Poly16: 2049 return shift ? 15 : (4 << IsQuad) - 1; 2050 case NeonTypeFlags::Int32: 2051 return shift ? 31 : (2 << IsQuad) - 1; 2052 case NeonTypeFlags::Int64: 2053 case NeonTypeFlags::Poly64: 2054 return shift ? 63 : (1 << IsQuad) - 1; 2055 case NeonTypeFlags::Poly128: 2056 return shift ? 127 : (1 << IsQuad) - 1; 2057 case NeonTypeFlags::Float16: 2058 assert(!shift && "cannot shift float types!"); 2059 return (4 << IsQuad) - 1; 2060 case NeonTypeFlags::Float32: 2061 assert(!shift && "cannot shift float types!"); 2062 return (2 << IsQuad) - 1; 2063 case NeonTypeFlags::Float64: 2064 assert(!shift && "cannot shift float types!"); 2065 return (1 << IsQuad) - 1; 2066 case NeonTypeFlags::BFloat16: 2067 assert(!shift && "cannot shift float types!"); 2068 return (4 << IsQuad) - 1; 2069 } 2070 llvm_unreachable("Invalid NeonTypeFlag!"); 2071 } 2072 2073 /// getNeonEltType - Return the QualType corresponding to the elements of 2074 /// the vector type specified by the NeonTypeFlags. This is used to check 2075 /// the pointer arguments for Neon load/store intrinsics. 2076 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2077 bool IsPolyUnsigned, bool IsInt64Long) { 2078 switch (Flags.getEltType()) { 2079 case NeonTypeFlags::Int8: 2080 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2081 case NeonTypeFlags::Int16: 2082 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2083 case NeonTypeFlags::Int32: 2084 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2085 case NeonTypeFlags::Int64: 2086 if (IsInt64Long) 2087 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2088 else 2089 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2090 : Context.LongLongTy; 2091 case NeonTypeFlags::Poly8: 2092 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2093 case NeonTypeFlags::Poly16: 2094 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2095 case NeonTypeFlags::Poly64: 2096 if (IsInt64Long) 2097 return Context.UnsignedLongTy; 2098 else 2099 return Context.UnsignedLongLongTy; 2100 case NeonTypeFlags::Poly128: 2101 break; 2102 case NeonTypeFlags::Float16: 2103 return Context.HalfTy; 2104 case NeonTypeFlags::Float32: 2105 return Context.FloatTy; 2106 case NeonTypeFlags::Float64: 2107 return Context.DoubleTy; 2108 case NeonTypeFlags::BFloat16: 2109 return Context.BFloat16Ty; 2110 } 2111 llvm_unreachable("Invalid NeonTypeFlag!"); 2112 } 2113 2114 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2115 // Range check SVE intrinsics that take immediate values. 2116 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2117 2118 switch (BuiltinID) { 2119 default: 2120 return false; 2121 #define GET_SVE_IMMEDIATE_CHECK 2122 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2123 #undef GET_SVE_IMMEDIATE_CHECK 2124 } 2125 2126 // Perform all the immediate checks for this builtin call. 2127 bool HasError = false; 2128 for (auto &I : ImmChecks) { 2129 int ArgNum, CheckTy, ElementSizeInBits; 2130 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2131 2132 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2133 2134 // Function that checks whether the operand (ArgNum) is an immediate 2135 // that is one of the predefined values. 2136 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2137 int ErrDiag) -> bool { 2138 // We can't check the value of a dependent argument. 2139 Expr *Arg = TheCall->getArg(ArgNum); 2140 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2141 return false; 2142 2143 // Check constant-ness first. 2144 llvm::APSInt Imm; 2145 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2146 return true; 2147 2148 if (!CheckImm(Imm.getSExtValue())) 2149 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2150 return false; 2151 }; 2152 2153 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2154 case SVETypeFlags::ImmCheck0_31: 2155 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2156 HasError = true; 2157 break; 2158 case SVETypeFlags::ImmCheck0_13: 2159 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2160 HasError = true; 2161 break; 2162 case SVETypeFlags::ImmCheck1_16: 2163 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheck0_7: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2168 HasError = true; 2169 break; 2170 case SVETypeFlags::ImmCheckExtract: 2171 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2172 (2048 / ElementSizeInBits) - 1)) 2173 HasError = true; 2174 break; 2175 case SVETypeFlags::ImmCheckShiftRight: 2176 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2177 HasError = true; 2178 break; 2179 case SVETypeFlags::ImmCheckShiftRightNarrow: 2180 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2181 ElementSizeInBits / 2)) 2182 HasError = true; 2183 break; 2184 case SVETypeFlags::ImmCheckShiftLeft: 2185 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2186 ElementSizeInBits - 1)) 2187 HasError = true; 2188 break; 2189 case SVETypeFlags::ImmCheckLaneIndex: 2190 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2191 (128 / (1 * ElementSizeInBits)) - 1)) 2192 HasError = true; 2193 break; 2194 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2195 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2196 (128 / (2 * ElementSizeInBits)) - 1)) 2197 HasError = true; 2198 break; 2199 case SVETypeFlags::ImmCheckLaneIndexDot: 2200 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2201 (128 / (4 * ElementSizeInBits)) - 1)) 2202 HasError = true; 2203 break; 2204 case SVETypeFlags::ImmCheckComplexRot90_270: 2205 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2206 diag::err_rotation_argument_to_cadd)) 2207 HasError = true; 2208 break; 2209 case SVETypeFlags::ImmCheckComplexRotAll90: 2210 if (CheckImmediateInSet( 2211 [](int64_t V) { 2212 return V == 0 || V == 90 || V == 180 || V == 270; 2213 }, 2214 diag::err_rotation_argument_to_cmla)) 2215 HasError = true; 2216 break; 2217 case SVETypeFlags::ImmCheck0_1: 2218 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2219 HasError = true; 2220 break; 2221 case SVETypeFlags::ImmCheck0_2: 2222 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2223 HasError = true; 2224 break; 2225 case SVETypeFlags::ImmCheck0_3: 2226 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2227 HasError = true; 2228 break; 2229 } 2230 } 2231 2232 return HasError; 2233 } 2234 2235 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2236 unsigned BuiltinID, CallExpr *TheCall) { 2237 llvm::APSInt Result; 2238 uint64_t mask = 0; 2239 unsigned TV = 0; 2240 int PtrArgNum = -1; 2241 bool HasConstPtr = false; 2242 switch (BuiltinID) { 2243 #define GET_NEON_OVERLOAD_CHECK 2244 #include "clang/Basic/arm_neon.inc" 2245 #include "clang/Basic/arm_fp16.inc" 2246 #undef GET_NEON_OVERLOAD_CHECK 2247 } 2248 2249 // For NEON intrinsics which are overloaded on vector element type, validate 2250 // the immediate which specifies which variant to emit. 2251 unsigned ImmArg = TheCall->getNumArgs()-1; 2252 if (mask) { 2253 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2254 return true; 2255 2256 TV = Result.getLimitedValue(64); 2257 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2258 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2259 << TheCall->getArg(ImmArg)->getSourceRange(); 2260 } 2261 2262 if (PtrArgNum >= 0) { 2263 // Check that pointer arguments have the specified type. 2264 Expr *Arg = TheCall->getArg(PtrArgNum); 2265 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2266 Arg = ICE->getSubExpr(); 2267 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2268 QualType RHSTy = RHS.get()->getType(); 2269 2270 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2271 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2272 Arch == llvm::Triple::aarch64_32 || 2273 Arch == llvm::Triple::aarch64_be; 2274 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2275 QualType EltTy = 2276 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2277 if (HasConstPtr) 2278 EltTy = EltTy.withConst(); 2279 QualType LHSTy = Context.getPointerType(EltTy); 2280 AssignConvertType ConvTy; 2281 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2282 if (RHS.isInvalid()) 2283 return true; 2284 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2285 RHS.get(), AA_Assigning)) 2286 return true; 2287 } 2288 2289 // For NEON intrinsics which take an immediate value as part of the 2290 // instruction, range check them here. 2291 unsigned i = 0, l = 0, u = 0; 2292 switch (BuiltinID) { 2293 default: 2294 return false; 2295 #define GET_NEON_IMMEDIATE_CHECK 2296 #include "clang/Basic/arm_neon.inc" 2297 #include "clang/Basic/arm_fp16.inc" 2298 #undef GET_NEON_IMMEDIATE_CHECK 2299 } 2300 2301 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2302 } 2303 2304 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2305 switch (BuiltinID) { 2306 default: 2307 return false; 2308 #include "clang/Basic/arm_mve_builtin_sema.inc" 2309 } 2310 } 2311 2312 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2313 CallExpr *TheCall) { 2314 bool Err = false; 2315 switch (BuiltinID) { 2316 default: 2317 return false; 2318 #include "clang/Basic/arm_cde_builtin_sema.inc" 2319 } 2320 2321 if (Err) 2322 return true; 2323 2324 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2325 } 2326 2327 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2328 const Expr *CoprocArg, bool WantCDE) { 2329 if (isConstantEvaluated()) 2330 return false; 2331 2332 // We can't check the value of a dependent argument. 2333 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2334 return false; 2335 2336 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2337 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2338 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2339 2340 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2341 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2342 2343 if (IsCDECoproc != WantCDE) 2344 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2345 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2346 2347 return false; 2348 } 2349 2350 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2351 unsigned MaxWidth) { 2352 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2353 BuiltinID == ARM::BI__builtin_arm_ldaex || 2354 BuiltinID == ARM::BI__builtin_arm_strex || 2355 BuiltinID == ARM::BI__builtin_arm_stlex || 2356 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2357 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2358 BuiltinID == AArch64::BI__builtin_arm_strex || 2359 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2360 "unexpected ARM builtin"); 2361 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2362 BuiltinID == ARM::BI__builtin_arm_ldaex || 2363 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2364 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2365 2366 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2367 2368 // Ensure that we have the proper number of arguments. 2369 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2370 return true; 2371 2372 // Inspect the pointer argument of the atomic builtin. This should always be 2373 // a pointer type, whose element is an integral scalar or pointer type. 2374 // Because it is a pointer type, we don't have to worry about any implicit 2375 // casts here. 2376 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2377 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2378 if (PointerArgRes.isInvalid()) 2379 return true; 2380 PointerArg = PointerArgRes.get(); 2381 2382 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2383 if (!pointerType) { 2384 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2385 << PointerArg->getType() << PointerArg->getSourceRange(); 2386 return true; 2387 } 2388 2389 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2390 // task is to insert the appropriate casts into the AST. First work out just 2391 // what the appropriate type is. 2392 QualType ValType = pointerType->getPointeeType(); 2393 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2394 if (IsLdrex) 2395 AddrType.addConst(); 2396 2397 // Issue a warning if the cast is dodgy. 2398 CastKind CastNeeded = CK_NoOp; 2399 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2400 CastNeeded = CK_BitCast; 2401 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2402 << PointerArg->getType() << Context.getPointerType(AddrType) 2403 << AA_Passing << PointerArg->getSourceRange(); 2404 } 2405 2406 // Finally, do the cast and replace the argument with the corrected version. 2407 AddrType = Context.getPointerType(AddrType); 2408 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2409 if (PointerArgRes.isInvalid()) 2410 return true; 2411 PointerArg = PointerArgRes.get(); 2412 2413 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2414 2415 // In general, we allow ints, floats and pointers to be loaded and stored. 2416 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2417 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2418 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2419 << PointerArg->getType() << PointerArg->getSourceRange(); 2420 return true; 2421 } 2422 2423 // But ARM doesn't have instructions to deal with 128-bit versions. 2424 if (Context.getTypeSize(ValType) > MaxWidth) { 2425 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2426 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2427 << PointerArg->getType() << PointerArg->getSourceRange(); 2428 return true; 2429 } 2430 2431 switch (ValType.getObjCLifetime()) { 2432 case Qualifiers::OCL_None: 2433 case Qualifiers::OCL_ExplicitNone: 2434 // okay 2435 break; 2436 2437 case Qualifiers::OCL_Weak: 2438 case Qualifiers::OCL_Strong: 2439 case Qualifiers::OCL_Autoreleasing: 2440 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2441 << ValType << PointerArg->getSourceRange(); 2442 return true; 2443 } 2444 2445 if (IsLdrex) { 2446 TheCall->setType(ValType); 2447 return false; 2448 } 2449 2450 // Initialize the argument to be stored. 2451 ExprResult ValArg = TheCall->getArg(0); 2452 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2453 Context, ValType, /*consume*/ false); 2454 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2455 if (ValArg.isInvalid()) 2456 return true; 2457 TheCall->setArg(0, ValArg.get()); 2458 2459 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2460 // but the custom checker bypasses all default analysis. 2461 TheCall->setType(Context.IntTy); 2462 return false; 2463 } 2464 2465 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2466 CallExpr *TheCall) { 2467 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2468 BuiltinID == ARM::BI__builtin_arm_ldaex || 2469 BuiltinID == ARM::BI__builtin_arm_strex || 2470 BuiltinID == ARM::BI__builtin_arm_stlex) { 2471 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2472 } 2473 2474 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2475 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2476 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2477 } 2478 2479 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2480 BuiltinID == ARM::BI__builtin_arm_wsr64) 2481 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2482 2483 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2484 BuiltinID == ARM::BI__builtin_arm_rsrp || 2485 BuiltinID == ARM::BI__builtin_arm_wsr || 2486 BuiltinID == ARM::BI__builtin_arm_wsrp) 2487 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2488 2489 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2490 return true; 2491 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2492 return true; 2493 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2494 return true; 2495 2496 // For intrinsics which take an immediate value as part of the instruction, 2497 // range check them here. 2498 // FIXME: VFP Intrinsics should error if VFP not present. 2499 switch (BuiltinID) { 2500 default: return false; 2501 case ARM::BI__builtin_arm_ssat: 2502 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2503 case ARM::BI__builtin_arm_usat: 2504 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2505 case ARM::BI__builtin_arm_ssat16: 2506 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2507 case ARM::BI__builtin_arm_usat16: 2508 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2509 case ARM::BI__builtin_arm_vcvtr_f: 2510 case ARM::BI__builtin_arm_vcvtr_d: 2511 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2512 case ARM::BI__builtin_arm_dmb: 2513 case ARM::BI__builtin_arm_dsb: 2514 case ARM::BI__builtin_arm_isb: 2515 case ARM::BI__builtin_arm_dbg: 2516 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2517 case ARM::BI__builtin_arm_cdp: 2518 case ARM::BI__builtin_arm_cdp2: 2519 case ARM::BI__builtin_arm_mcr: 2520 case ARM::BI__builtin_arm_mcr2: 2521 case ARM::BI__builtin_arm_mrc: 2522 case ARM::BI__builtin_arm_mrc2: 2523 case ARM::BI__builtin_arm_mcrr: 2524 case ARM::BI__builtin_arm_mcrr2: 2525 case ARM::BI__builtin_arm_mrrc: 2526 case ARM::BI__builtin_arm_mrrc2: 2527 case ARM::BI__builtin_arm_ldc: 2528 case ARM::BI__builtin_arm_ldcl: 2529 case ARM::BI__builtin_arm_ldc2: 2530 case ARM::BI__builtin_arm_ldc2l: 2531 case ARM::BI__builtin_arm_stc: 2532 case ARM::BI__builtin_arm_stcl: 2533 case ARM::BI__builtin_arm_stc2: 2534 case ARM::BI__builtin_arm_stc2l: 2535 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2536 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2537 /*WantCDE*/ false); 2538 } 2539 } 2540 2541 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2542 unsigned BuiltinID, 2543 CallExpr *TheCall) { 2544 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2545 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2546 BuiltinID == AArch64::BI__builtin_arm_strex || 2547 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2548 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2549 } 2550 2551 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2552 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2553 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2554 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2555 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2556 } 2557 2558 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2559 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2560 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2561 2562 // Memory Tagging Extensions (MTE) Intrinsics 2563 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2564 BuiltinID == AArch64::BI__builtin_arm_addg || 2565 BuiltinID == AArch64::BI__builtin_arm_gmi || 2566 BuiltinID == AArch64::BI__builtin_arm_ldg || 2567 BuiltinID == AArch64::BI__builtin_arm_stg || 2568 BuiltinID == AArch64::BI__builtin_arm_subp) { 2569 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2570 } 2571 2572 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2573 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2574 BuiltinID == AArch64::BI__builtin_arm_wsr || 2575 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2576 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2577 2578 // Only check the valid encoding range. Any constant in this range would be 2579 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2580 // an exception for incorrect registers. This matches MSVC behavior. 2581 if (BuiltinID == AArch64::BI_ReadStatusReg || 2582 BuiltinID == AArch64::BI_WriteStatusReg) 2583 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2584 2585 if (BuiltinID == AArch64::BI__getReg) 2586 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2587 2588 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2589 return true; 2590 2591 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2592 return true; 2593 2594 // For intrinsics which take an immediate value as part of the instruction, 2595 // range check them here. 2596 unsigned i = 0, l = 0, u = 0; 2597 switch (BuiltinID) { 2598 default: return false; 2599 case AArch64::BI__builtin_arm_dmb: 2600 case AArch64::BI__builtin_arm_dsb: 2601 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2602 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2603 } 2604 2605 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2606 } 2607 2608 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2609 if (Arg->getType()->getAsPlaceholderType()) 2610 return false; 2611 2612 // The first argument needs to be a record field access. 2613 // If it is an array element access, we delay decision 2614 // to BPF backend to check whether the access is a 2615 // field access or not. 2616 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2617 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2618 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2619 } 2620 2621 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2622 QualType VectorTy, QualType EltTy) { 2623 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2624 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2625 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2626 << Call->getSourceRange() << VectorEltTy << EltTy; 2627 return false; 2628 } 2629 return true; 2630 } 2631 2632 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2633 QualType ArgType = Arg->getType(); 2634 if (ArgType->getAsPlaceholderType()) 2635 return false; 2636 2637 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2638 // format: 2639 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2640 // 2. <type> var; 2641 // __builtin_preserve_type_info(var, flag); 2642 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2643 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2644 return false; 2645 2646 // Typedef type. 2647 if (ArgType->getAs<TypedefType>()) 2648 return true; 2649 2650 // Record type or Enum type. 2651 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2652 if (const auto *RT = Ty->getAs<RecordType>()) { 2653 if (!RT->getDecl()->getDeclName().isEmpty()) 2654 return true; 2655 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2656 if (!ET->getDecl()->getDeclName().isEmpty()) 2657 return true; 2658 } 2659 2660 return false; 2661 } 2662 2663 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2664 QualType ArgType = Arg->getType(); 2665 if (ArgType->getAsPlaceholderType()) 2666 return false; 2667 2668 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2669 // format: 2670 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2671 // flag); 2672 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2673 if (!UO) 2674 return false; 2675 2676 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2677 if (!CE) 2678 return false; 2679 if (CE->getCastKind() != CK_IntegralToPointer && 2680 CE->getCastKind() != CK_NullToPointer) 2681 return false; 2682 2683 // The integer must be from an EnumConstantDecl. 2684 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2685 if (!DR) 2686 return false; 2687 2688 const EnumConstantDecl *Enumerator = 2689 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2690 if (!Enumerator) 2691 return false; 2692 2693 // The type must be EnumType. 2694 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2695 const auto *ET = Ty->getAs<EnumType>(); 2696 if (!ET) 2697 return false; 2698 2699 // The enum value must be supported. 2700 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 2701 } 2702 2703 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2704 CallExpr *TheCall) { 2705 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2706 BuiltinID == BPF::BI__builtin_btf_type_id || 2707 BuiltinID == BPF::BI__builtin_preserve_type_info || 2708 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2709 "unexpected BPF builtin"); 2710 2711 if (checkArgCount(*this, TheCall, 2)) 2712 return true; 2713 2714 // The second argument needs to be a constant int 2715 Expr *Arg = TheCall->getArg(1); 2716 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2717 diag::kind kind; 2718 if (!Value) { 2719 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2720 kind = diag::err_preserve_field_info_not_const; 2721 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2722 kind = diag::err_btf_type_id_not_const; 2723 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2724 kind = diag::err_preserve_type_info_not_const; 2725 else 2726 kind = diag::err_preserve_enum_value_not_const; 2727 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2728 return true; 2729 } 2730 2731 // The first argument 2732 Arg = TheCall->getArg(0); 2733 bool InvalidArg = false; 2734 bool ReturnUnsignedInt = true; 2735 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2736 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2737 InvalidArg = true; 2738 kind = diag::err_preserve_field_info_not_field; 2739 } 2740 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2741 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2742 InvalidArg = true; 2743 kind = diag::err_preserve_type_info_invalid; 2744 } 2745 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2746 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2747 InvalidArg = true; 2748 kind = diag::err_preserve_enum_value_invalid; 2749 } 2750 ReturnUnsignedInt = false; 2751 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2752 ReturnUnsignedInt = false; 2753 } 2754 2755 if (InvalidArg) { 2756 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2757 return true; 2758 } 2759 2760 if (ReturnUnsignedInt) 2761 TheCall->setType(Context.UnsignedIntTy); 2762 else 2763 TheCall->setType(Context.UnsignedLongTy); 2764 return false; 2765 } 2766 2767 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2768 struct ArgInfo { 2769 uint8_t OpNum; 2770 bool IsSigned; 2771 uint8_t BitWidth; 2772 uint8_t Align; 2773 }; 2774 struct BuiltinInfo { 2775 unsigned BuiltinID; 2776 ArgInfo Infos[2]; 2777 }; 2778 2779 static BuiltinInfo Infos[] = { 2780 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2781 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2782 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2783 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2784 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2785 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2786 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2787 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2788 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2789 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2790 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2791 2792 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2803 2804 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2856 {{ 1, false, 6, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2864 {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2871 { 2, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2873 { 2, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2875 { 3, false, 5, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2877 { 3, false, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2894 {{ 2, false, 4, 0 }, 2895 { 3, false, 5, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2897 {{ 2, false, 4, 0 }, 2898 { 3, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2900 {{ 2, false, 4, 0 }, 2901 { 3, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2903 {{ 2, false, 4, 0 }, 2904 { 3, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2916 { 2, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2918 { 2, false, 6, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2928 {{ 1, false, 4, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2931 {{ 1, false, 4, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2948 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2952 {{ 3, false, 1, 0 }} }, 2953 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2957 {{ 3, false, 1, 0 }} }, 2958 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2959 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2960 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2961 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2962 {{ 3, false, 1, 0 }} }, 2963 }; 2964 2965 // Use a dynamically initialized static to sort the table exactly once on 2966 // first run. 2967 static const bool SortOnce = 2968 (llvm::sort(Infos, 2969 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2970 return LHS.BuiltinID < RHS.BuiltinID; 2971 }), 2972 true); 2973 (void)SortOnce; 2974 2975 const BuiltinInfo *F = llvm::partition_point( 2976 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2977 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2978 return false; 2979 2980 bool Error = false; 2981 2982 for (const ArgInfo &A : F->Infos) { 2983 // Ignore empty ArgInfo elements. 2984 if (A.BitWidth == 0) 2985 continue; 2986 2987 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2988 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2989 if (!A.Align) { 2990 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2991 } else { 2992 unsigned M = 1 << A.Align; 2993 Min *= M; 2994 Max *= M; 2995 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2996 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2997 } 2998 } 2999 return Error; 3000 } 3001 3002 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3003 CallExpr *TheCall) { 3004 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3005 } 3006 3007 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3008 unsigned BuiltinID, CallExpr *TheCall) { 3009 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3010 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3011 } 3012 3013 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3014 CallExpr *TheCall) { 3015 3016 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3017 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3018 if (!TI.hasFeature("dsp")) 3019 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3020 } 3021 3022 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3023 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3024 if (!TI.hasFeature("dspr2")) 3025 return Diag(TheCall->getBeginLoc(), 3026 diag::err_mips_builtin_requires_dspr2); 3027 } 3028 3029 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3030 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3031 if (!TI.hasFeature("msa")) 3032 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3033 } 3034 3035 return false; 3036 } 3037 3038 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3039 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3040 // ordering for DSP is unspecified. MSA is ordered by the data format used 3041 // by the underlying instruction i.e., df/m, df/n and then by size. 3042 // 3043 // FIXME: The size tests here should instead be tablegen'd along with the 3044 // definitions from include/clang/Basic/BuiltinsMips.def. 3045 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3046 // be too. 3047 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3048 unsigned i = 0, l = 0, u = 0, m = 0; 3049 switch (BuiltinID) { 3050 default: return false; 3051 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3052 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3053 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3054 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3055 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3056 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3057 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3058 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3059 // df/m field. 3060 // These intrinsics take an unsigned 3 bit immediate. 3061 case Mips::BI__builtin_msa_bclri_b: 3062 case Mips::BI__builtin_msa_bnegi_b: 3063 case Mips::BI__builtin_msa_bseti_b: 3064 case Mips::BI__builtin_msa_sat_s_b: 3065 case Mips::BI__builtin_msa_sat_u_b: 3066 case Mips::BI__builtin_msa_slli_b: 3067 case Mips::BI__builtin_msa_srai_b: 3068 case Mips::BI__builtin_msa_srari_b: 3069 case Mips::BI__builtin_msa_srli_b: 3070 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3071 case Mips::BI__builtin_msa_binsli_b: 3072 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3073 // These intrinsics take an unsigned 4 bit immediate. 3074 case Mips::BI__builtin_msa_bclri_h: 3075 case Mips::BI__builtin_msa_bnegi_h: 3076 case Mips::BI__builtin_msa_bseti_h: 3077 case Mips::BI__builtin_msa_sat_s_h: 3078 case Mips::BI__builtin_msa_sat_u_h: 3079 case Mips::BI__builtin_msa_slli_h: 3080 case Mips::BI__builtin_msa_srai_h: 3081 case Mips::BI__builtin_msa_srari_h: 3082 case Mips::BI__builtin_msa_srli_h: 3083 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3084 case Mips::BI__builtin_msa_binsli_h: 3085 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3086 // These intrinsics take an unsigned 5 bit immediate. 3087 // The first block of intrinsics actually have an unsigned 5 bit field, 3088 // not a df/n field. 3089 case Mips::BI__builtin_msa_cfcmsa: 3090 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3091 case Mips::BI__builtin_msa_clei_u_b: 3092 case Mips::BI__builtin_msa_clei_u_h: 3093 case Mips::BI__builtin_msa_clei_u_w: 3094 case Mips::BI__builtin_msa_clei_u_d: 3095 case Mips::BI__builtin_msa_clti_u_b: 3096 case Mips::BI__builtin_msa_clti_u_h: 3097 case Mips::BI__builtin_msa_clti_u_w: 3098 case Mips::BI__builtin_msa_clti_u_d: 3099 case Mips::BI__builtin_msa_maxi_u_b: 3100 case Mips::BI__builtin_msa_maxi_u_h: 3101 case Mips::BI__builtin_msa_maxi_u_w: 3102 case Mips::BI__builtin_msa_maxi_u_d: 3103 case Mips::BI__builtin_msa_mini_u_b: 3104 case Mips::BI__builtin_msa_mini_u_h: 3105 case Mips::BI__builtin_msa_mini_u_w: 3106 case Mips::BI__builtin_msa_mini_u_d: 3107 case Mips::BI__builtin_msa_addvi_b: 3108 case Mips::BI__builtin_msa_addvi_h: 3109 case Mips::BI__builtin_msa_addvi_w: 3110 case Mips::BI__builtin_msa_addvi_d: 3111 case Mips::BI__builtin_msa_bclri_w: 3112 case Mips::BI__builtin_msa_bnegi_w: 3113 case Mips::BI__builtin_msa_bseti_w: 3114 case Mips::BI__builtin_msa_sat_s_w: 3115 case Mips::BI__builtin_msa_sat_u_w: 3116 case Mips::BI__builtin_msa_slli_w: 3117 case Mips::BI__builtin_msa_srai_w: 3118 case Mips::BI__builtin_msa_srari_w: 3119 case Mips::BI__builtin_msa_srli_w: 3120 case Mips::BI__builtin_msa_srlri_w: 3121 case Mips::BI__builtin_msa_subvi_b: 3122 case Mips::BI__builtin_msa_subvi_h: 3123 case Mips::BI__builtin_msa_subvi_w: 3124 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3125 case Mips::BI__builtin_msa_binsli_w: 3126 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3127 // These intrinsics take an unsigned 6 bit immediate. 3128 case Mips::BI__builtin_msa_bclri_d: 3129 case Mips::BI__builtin_msa_bnegi_d: 3130 case Mips::BI__builtin_msa_bseti_d: 3131 case Mips::BI__builtin_msa_sat_s_d: 3132 case Mips::BI__builtin_msa_sat_u_d: 3133 case Mips::BI__builtin_msa_slli_d: 3134 case Mips::BI__builtin_msa_srai_d: 3135 case Mips::BI__builtin_msa_srari_d: 3136 case Mips::BI__builtin_msa_srli_d: 3137 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3138 case Mips::BI__builtin_msa_binsli_d: 3139 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3140 // These intrinsics take a signed 5 bit immediate. 3141 case Mips::BI__builtin_msa_ceqi_b: 3142 case Mips::BI__builtin_msa_ceqi_h: 3143 case Mips::BI__builtin_msa_ceqi_w: 3144 case Mips::BI__builtin_msa_ceqi_d: 3145 case Mips::BI__builtin_msa_clti_s_b: 3146 case Mips::BI__builtin_msa_clti_s_h: 3147 case Mips::BI__builtin_msa_clti_s_w: 3148 case Mips::BI__builtin_msa_clti_s_d: 3149 case Mips::BI__builtin_msa_clei_s_b: 3150 case Mips::BI__builtin_msa_clei_s_h: 3151 case Mips::BI__builtin_msa_clei_s_w: 3152 case Mips::BI__builtin_msa_clei_s_d: 3153 case Mips::BI__builtin_msa_maxi_s_b: 3154 case Mips::BI__builtin_msa_maxi_s_h: 3155 case Mips::BI__builtin_msa_maxi_s_w: 3156 case Mips::BI__builtin_msa_maxi_s_d: 3157 case Mips::BI__builtin_msa_mini_s_b: 3158 case Mips::BI__builtin_msa_mini_s_h: 3159 case Mips::BI__builtin_msa_mini_s_w: 3160 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3161 // These intrinsics take an unsigned 8 bit immediate. 3162 case Mips::BI__builtin_msa_andi_b: 3163 case Mips::BI__builtin_msa_nori_b: 3164 case Mips::BI__builtin_msa_ori_b: 3165 case Mips::BI__builtin_msa_shf_b: 3166 case Mips::BI__builtin_msa_shf_h: 3167 case Mips::BI__builtin_msa_shf_w: 3168 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3169 case Mips::BI__builtin_msa_bseli_b: 3170 case Mips::BI__builtin_msa_bmnzi_b: 3171 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3172 // df/n format 3173 // These intrinsics take an unsigned 4 bit immediate. 3174 case Mips::BI__builtin_msa_copy_s_b: 3175 case Mips::BI__builtin_msa_copy_u_b: 3176 case Mips::BI__builtin_msa_insve_b: 3177 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3178 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3179 // These intrinsics take an unsigned 3 bit immediate. 3180 case Mips::BI__builtin_msa_copy_s_h: 3181 case Mips::BI__builtin_msa_copy_u_h: 3182 case Mips::BI__builtin_msa_insve_h: 3183 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3184 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3185 // These intrinsics take an unsigned 2 bit immediate. 3186 case Mips::BI__builtin_msa_copy_s_w: 3187 case Mips::BI__builtin_msa_copy_u_w: 3188 case Mips::BI__builtin_msa_insve_w: 3189 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3190 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3191 // These intrinsics take an unsigned 1 bit immediate. 3192 case Mips::BI__builtin_msa_copy_s_d: 3193 case Mips::BI__builtin_msa_copy_u_d: 3194 case Mips::BI__builtin_msa_insve_d: 3195 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3196 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3197 // Memory offsets and immediate loads. 3198 // These intrinsics take a signed 10 bit immediate. 3199 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3200 case Mips::BI__builtin_msa_ldi_h: 3201 case Mips::BI__builtin_msa_ldi_w: 3202 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3203 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3204 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3205 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3206 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3207 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3208 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3209 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3210 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3211 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3212 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3213 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3214 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3215 } 3216 3217 if (!m) 3218 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3219 3220 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3221 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3222 } 3223 3224 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3225 /// advancing the pointer over the consumed characters. The decoded type is 3226 /// returned. If the decoded type represents a constant integer with a 3227 /// constraint on its value then Mask is set to that value. The type descriptors 3228 /// used in Str are specific to PPC MMA builtins and are documented in the file 3229 /// defining the PPC builtins. 3230 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3231 unsigned &Mask) { 3232 bool RequireICE = false; 3233 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3234 switch (*Str++) { 3235 case 'V': 3236 return Context.getVectorType(Context.UnsignedCharTy, 16, 3237 VectorType::VectorKind::AltiVecVector); 3238 case 'i': { 3239 char *End; 3240 unsigned size = strtoul(Str, &End, 10); 3241 assert(End != Str && "Missing constant parameter constraint"); 3242 Str = End; 3243 Mask = size; 3244 return Context.IntTy; 3245 } 3246 case 'W': { 3247 char *End; 3248 unsigned size = strtoul(Str, &End, 10); 3249 assert(End != Str && "Missing PowerPC MMA type size"); 3250 Str = End; 3251 QualType Type; 3252 switch (size) { 3253 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3254 case size: Type = Context.Id##Ty; break; 3255 #include "clang/Basic/PPCTypes.def" 3256 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3257 } 3258 bool CheckVectorArgs = false; 3259 while (!CheckVectorArgs) { 3260 switch (*Str++) { 3261 case '*': 3262 Type = Context.getPointerType(Type); 3263 break; 3264 case 'C': 3265 Type = Type.withConst(); 3266 break; 3267 default: 3268 CheckVectorArgs = true; 3269 --Str; 3270 break; 3271 } 3272 } 3273 return Type; 3274 } 3275 default: 3276 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3277 } 3278 } 3279 3280 static bool isPPC_64Builtin(unsigned BuiltinID) { 3281 // These builtins only work on PPC 64bit targets. 3282 switch (BuiltinID) { 3283 case PPC::BI__builtin_divde: 3284 case PPC::BI__builtin_divdeu: 3285 case PPC::BI__builtin_bpermd: 3286 case PPC::BI__builtin_ppc_ldarx: 3287 case PPC::BI__builtin_ppc_stdcx: 3288 case PPC::BI__builtin_ppc_tdw: 3289 case PPC::BI__builtin_ppc_trapd: 3290 case PPC::BI__builtin_ppc_cmpeqb: 3291 case PPC::BI__builtin_ppc_setb: 3292 case PPC::BI__builtin_ppc_mulhd: 3293 case PPC::BI__builtin_ppc_mulhdu: 3294 case PPC::BI__builtin_ppc_maddhd: 3295 case PPC::BI__builtin_ppc_maddhdu: 3296 case PPC::BI__builtin_ppc_maddld: 3297 case PPC::BI__builtin_ppc_load8r: 3298 case PPC::BI__builtin_ppc_store8r: 3299 case PPC::BI__builtin_ppc_insert_exp: 3300 case PPC::BI__builtin_ppc_extract_sig: 3301 case PPC::BI__builtin_ppc_addex: 3302 case PPC::BI__builtin_darn: 3303 case PPC::BI__builtin_darn_raw: 3304 case PPC::BI__builtin_ppc_compare_and_swaplp: 3305 case PPC::BI__builtin_ppc_fetch_and_addlp: 3306 case PPC::BI__builtin_ppc_fetch_and_andlp: 3307 case PPC::BI__builtin_ppc_fetch_and_orlp: 3308 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3309 return true; 3310 } 3311 return false; 3312 } 3313 3314 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3315 StringRef FeatureToCheck, unsigned DiagID, 3316 StringRef DiagArg = "") { 3317 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3318 return false; 3319 3320 if (DiagArg.empty()) 3321 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3322 else 3323 S.Diag(TheCall->getBeginLoc(), DiagID) 3324 << DiagArg << TheCall->getSourceRange(); 3325 3326 return true; 3327 } 3328 3329 /// Returns true if the argument consists of one contiguous run of 1s with any 3330 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3331 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3332 /// since all 1s are not contiguous. 3333 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3334 llvm::APSInt Result; 3335 // We can't check the value of a dependent argument. 3336 Expr *Arg = TheCall->getArg(ArgNum); 3337 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3338 return false; 3339 3340 // Check constant-ness first. 3341 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3342 return true; 3343 3344 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3345 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3346 return false; 3347 3348 return Diag(TheCall->getBeginLoc(), 3349 diag::err_argument_not_contiguous_bit_field) 3350 << ArgNum << Arg->getSourceRange(); 3351 } 3352 3353 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3354 CallExpr *TheCall) { 3355 unsigned i = 0, l = 0, u = 0; 3356 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3357 llvm::APSInt Result; 3358 3359 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3360 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3361 << TheCall->getSourceRange(); 3362 3363 switch (BuiltinID) { 3364 default: return false; 3365 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3366 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3367 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3368 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3369 case PPC::BI__builtin_altivec_dss: 3370 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3371 case PPC::BI__builtin_tbegin: 3372 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3373 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3374 case PPC::BI__builtin_tabortwc: 3375 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3376 case PPC::BI__builtin_tabortwci: 3377 case PPC::BI__builtin_tabortdci: 3378 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3379 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3380 case PPC::BI__builtin_altivec_dst: 3381 case PPC::BI__builtin_altivec_dstt: 3382 case PPC::BI__builtin_altivec_dstst: 3383 case PPC::BI__builtin_altivec_dststt: 3384 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3385 case PPC::BI__builtin_vsx_xxpermdi: 3386 case PPC::BI__builtin_vsx_xxsldwi: 3387 return SemaBuiltinVSX(TheCall); 3388 case PPC::BI__builtin_divwe: 3389 case PPC::BI__builtin_divweu: 3390 case PPC::BI__builtin_divde: 3391 case PPC::BI__builtin_divdeu: 3392 return SemaFeatureCheck(*this, TheCall, "extdiv", 3393 diag::err_ppc_builtin_only_on_arch, "7"); 3394 case PPC::BI__builtin_bpermd: 3395 return SemaFeatureCheck(*this, TheCall, "bpermd", 3396 diag::err_ppc_builtin_only_on_arch, "7"); 3397 case PPC::BI__builtin_unpack_vector_int128: 3398 return SemaFeatureCheck(*this, TheCall, "vsx", 3399 diag::err_ppc_builtin_only_on_arch, "7") || 3400 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3401 case PPC::BI__builtin_pack_vector_int128: 3402 return SemaFeatureCheck(*this, TheCall, "vsx", 3403 diag::err_ppc_builtin_only_on_arch, "7"); 3404 case PPC::BI__builtin_altivec_vgnb: 3405 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3406 case PPC::BI__builtin_altivec_vec_replace_elt: 3407 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3408 QualType VecTy = TheCall->getArg(0)->getType(); 3409 QualType EltTy = TheCall->getArg(1)->getType(); 3410 unsigned Width = Context.getIntWidth(EltTy); 3411 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3412 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3413 } 3414 case PPC::BI__builtin_vsx_xxeval: 3415 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3416 case PPC::BI__builtin_altivec_vsldbi: 3417 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3418 case PPC::BI__builtin_altivec_vsrdbi: 3419 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3420 case PPC::BI__builtin_vsx_xxpermx: 3421 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3422 case PPC::BI__builtin_ppc_tw: 3423 case PPC::BI__builtin_ppc_tdw: 3424 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3425 case PPC::BI__builtin_ppc_cmpeqb: 3426 case PPC::BI__builtin_ppc_setb: 3427 case PPC::BI__builtin_ppc_maddhd: 3428 case PPC::BI__builtin_ppc_maddhdu: 3429 case PPC::BI__builtin_ppc_maddld: 3430 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3431 diag::err_ppc_builtin_only_on_arch, "9"); 3432 case PPC::BI__builtin_ppc_cmprb: 3433 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3434 diag::err_ppc_builtin_only_on_arch, "9") || 3435 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3436 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3437 // be a constant that represents a contiguous bit field. 3438 case PPC::BI__builtin_ppc_rlwnm: 3439 return SemaValueIsRunOfOnes(TheCall, 2); 3440 case PPC::BI__builtin_ppc_rlwimi: 3441 case PPC::BI__builtin_ppc_rldimi: 3442 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3443 SemaValueIsRunOfOnes(TheCall, 3); 3444 case PPC::BI__builtin_ppc_extract_exp: 3445 case PPC::BI__builtin_ppc_extract_sig: 3446 case PPC::BI__builtin_ppc_insert_exp: 3447 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3448 diag::err_ppc_builtin_only_on_arch, "9"); 3449 case PPC::BI__builtin_ppc_addex: { 3450 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3451 diag::err_ppc_builtin_only_on_arch, "9") || 3452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3453 return true; 3454 // Output warning for reserved values 1 to 3. 3455 int ArgValue = 3456 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3457 if (ArgValue != 0) 3458 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3459 << ArgValue; 3460 return false; 3461 } 3462 case PPC::BI__builtin_ppc_mtfsb0: 3463 case PPC::BI__builtin_ppc_mtfsb1: 3464 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3465 case PPC::BI__builtin_ppc_mtfsf: 3466 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3467 case PPC::BI__builtin_ppc_mtfsfi: 3468 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3469 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3470 case PPC::BI__builtin_ppc_alignx: 3471 return SemaBuiltinConstantArgPower2(TheCall, 0); 3472 case PPC::BI__builtin_ppc_rdlam: 3473 return SemaValueIsRunOfOnes(TheCall, 2); 3474 case PPC::BI__builtin_ppc_icbt: 3475 case PPC::BI__builtin_ppc_sthcx: 3476 case PPC::BI__builtin_ppc_stbcx: 3477 case PPC::BI__builtin_ppc_lharx: 3478 case PPC::BI__builtin_ppc_lbarx: 3479 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3480 diag::err_ppc_builtin_only_on_arch, "8"); 3481 case PPC::BI__builtin_vsx_ldrmb: 3482 case PPC::BI__builtin_vsx_strmb: 3483 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3484 diag::err_ppc_builtin_only_on_arch, "8") || 3485 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3486 case PPC::BI__builtin_altivec_vcntmbb: 3487 case PPC::BI__builtin_altivec_vcntmbh: 3488 case PPC::BI__builtin_altivec_vcntmbw: 3489 case PPC::BI__builtin_altivec_vcntmbd: 3490 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3491 case PPC::BI__builtin_darn: 3492 case PPC::BI__builtin_darn_raw: 3493 case PPC::BI__builtin_darn_32: 3494 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3495 diag::err_ppc_builtin_only_on_arch, "9"); 3496 case PPC::BI__builtin_vsx_xxgenpcvbm: 3497 case PPC::BI__builtin_vsx_xxgenpcvhm: 3498 case PPC::BI__builtin_vsx_xxgenpcvwm: 3499 case PPC::BI__builtin_vsx_xxgenpcvdm: 3500 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3501 case PPC::BI__builtin_ppc_compare_exp_uo: 3502 case PPC::BI__builtin_ppc_compare_exp_lt: 3503 case PPC::BI__builtin_ppc_compare_exp_gt: 3504 case PPC::BI__builtin_ppc_compare_exp_eq: 3505 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3506 diag::err_ppc_builtin_only_on_arch, "9") || 3507 SemaFeatureCheck(*this, TheCall, "vsx", 3508 diag::err_ppc_builtin_requires_vsx); 3509 case PPC::BI__builtin_ppc_test_data_class: { 3510 // Check if the first argument of the __builtin_ppc_test_data_class call is 3511 // valid. The argument must be either a 'float' or a 'double'. 3512 QualType ArgType = TheCall->getArg(0)->getType(); 3513 if (ArgType != QualType(Context.FloatTy) && 3514 ArgType != QualType(Context.DoubleTy)) 3515 return Diag(TheCall->getBeginLoc(), 3516 diag::err_ppc_invalid_test_data_class_type); 3517 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3518 diag::err_ppc_builtin_only_on_arch, "9") || 3519 SemaFeatureCheck(*this, TheCall, "vsx", 3520 diag::err_ppc_builtin_requires_vsx) || 3521 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3522 } 3523 case PPC::BI__builtin_ppc_load8r: 3524 case PPC::BI__builtin_ppc_store8r: 3525 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3526 diag::err_ppc_builtin_only_on_arch, "7"); 3527 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3528 case PPC::BI__builtin_##Name: \ 3529 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3530 #include "clang/Basic/BuiltinsPPC.def" 3531 } 3532 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3533 } 3534 3535 // Check if the given type is a non-pointer PPC MMA type. This function is used 3536 // in Sema to prevent invalid uses of restricted PPC MMA types. 3537 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3538 if (Type->isPointerType() || Type->isArrayType()) 3539 return false; 3540 3541 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3542 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3543 if (false 3544 #include "clang/Basic/PPCTypes.def" 3545 ) { 3546 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3547 return true; 3548 } 3549 return false; 3550 } 3551 3552 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3553 CallExpr *TheCall) { 3554 // position of memory order and scope arguments in the builtin 3555 unsigned OrderIndex, ScopeIndex; 3556 switch (BuiltinID) { 3557 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3558 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3559 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3560 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3561 OrderIndex = 2; 3562 ScopeIndex = 3; 3563 break; 3564 case AMDGPU::BI__builtin_amdgcn_fence: 3565 OrderIndex = 0; 3566 ScopeIndex = 1; 3567 break; 3568 default: 3569 return false; 3570 } 3571 3572 ExprResult Arg = TheCall->getArg(OrderIndex); 3573 auto ArgExpr = Arg.get(); 3574 Expr::EvalResult ArgResult; 3575 3576 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3577 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3578 << ArgExpr->getType(); 3579 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3580 3581 // Check validity of memory ordering as per C11 / C++11's memody model. 3582 // Only fence needs check. Atomic dec/inc allow all memory orders. 3583 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3584 return Diag(ArgExpr->getBeginLoc(), 3585 diag::warn_atomic_op_has_invalid_memory_order) 3586 << ArgExpr->getSourceRange(); 3587 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3588 case llvm::AtomicOrderingCABI::relaxed: 3589 case llvm::AtomicOrderingCABI::consume: 3590 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3591 return Diag(ArgExpr->getBeginLoc(), 3592 diag::warn_atomic_op_has_invalid_memory_order) 3593 << ArgExpr->getSourceRange(); 3594 break; 3595 case llvm::AtomicOrderingCABI::acquire: 3596 case llvm::AtomicOrderingCABI::release: 3597 case llvm::AtomicOrderingCABI::acq_rel: 3598 case llvm::AtomicOrderingCABI::seq_cst: 3599 break; 3600 } 3601 3602 Arg = TheCall->getArg(ScopeIndex); 3603 ArgExpr = Arg.get(); 3604 Expr::EvalResult ArgResult1; 3605 // Check that sync scope is a constant literal 3606 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3607 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3608 << ArgExpr->getType(); 3609 3610 return false; 3611 } 3612 3613 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3614 llvm::APSInt Result; 3615 3616 // We can't check the value of a dependent argument. 3617 Expr *Arg = TheCall->getArg(ArgNum); 3618 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3619 return false; 3620 3621 // Check constant-ness first. 3622 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3623 return true; 3624 3625 int64_t Val = Result.getSExtValue(); 3626 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3627 return false; 3628 3629 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3630 << Arg->getSourceRange(); 3631 } 3632 3633 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3634 unsigned BuiltinID, 3635 CallExpr *TheCall) { 3636 // CodeGenFunction can also detect this, but this gives a better error 3637 // message. 3638 bool FeatureMissing = false; 3639 SmallVector<StringRef> ReqFeatures; 3640 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3641 Features.split(ReqFeatures, ','); 3642 3643 // Check if each required feature is included 3644 for (StringRef F : ReqFeatures) { 3645 if (TI.hasFeature(F)) 3646 continue; 3647 3648 // If the feature is 64bit, alter the string so it will print better in 3649 // the diagnostic. 3650 if (F == "64bit") 3651 F = "RV64"; 3652 3653 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3654 F.consume_front("experimental-"); 3655 std::string FeatureStr = F.str(); 3656 FeatureStr[0] = std::toupper(FeatureStr[0]); 3657 3658 // Error message 3659 FeatureMissing = true; 3660 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3661 << TheCall->getSourceRange() << StringRef(FeatureStr); 3662 } 3663 3664 if (FeatureMissing) 3665 return true; 3666 3667 switch (BuiltinID) { 3668 case RISCVVector::BI__builtin_rvv_vsetvli: 3669 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3670 CheckRISCVLMUL(TheCall, 2); 3671 case RISCVVector::BI__builtin_rvv_vsetvlimax: 3672 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3673 CheckRISCVLMUL(TheCall, 1); 3674 } 3675 3676 return false; 3677 } 3678 3679 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3680 CallExpr *TheCall) { 3681 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3682 Expr *Arg = TheCall->getArg(0); 3683 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3684 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3685 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3686 << Arg->getSourceRange(); 3687 } 3688 3689 // For intrinsics which take an immediate value as part of the instruction, 3690 // range check them here. 3691 unsigned i = 0, l = 0, u = 0; 3692 switch (BuiltinID) { 3693 default: return false; 3694 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3695 case SystemZ::BI__builtin_s390_verimb: 3696 case SystemZ::BI__builtin_s390_verimh: 3697 case SystemZ::BI__builtin_s390_verimf: 3698 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3699 case SystemZ::BI__builtin_s390_vfaeb: 3700 case SystemZ::BI__builtin_s390_vfaeh: 3701 case SystemZ::BI__builtin_s390_vfaef: 3702 case SystemZ::BI__builtin_s390_vfaebs: 3703 case SystemZ::BI__builtin_s390_vfaehs: 3704 case SystemZ::BI__builtin_s390_vfaefs: 3705 case SystemZ::BI__builtin_s390_vfaezb: 3706 case SystemZ::BI__builtin_s390_vfaezh: 3707 case SystemZ::BI__builtin_s390_vfaezf: 3708 case SystemZ::BI__builtin_s390_vfaezbs: 3709 case SystemZ::BI__builtin_s390_vfaezhs: 3710 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3711 case SystemZ::BI__builtin_s390_vfisb: 3712 case SystemZ::BI__builtin_s390_vfidb: 3713 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3714 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3715 case SystemZ::BI__builtin_s390_vftcisb: 3716 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3717 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3718 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3719 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3720 case SystemZ::BI__builtin_s390_vstrcb: 3721 case SystemZ::BI__builtin_s390_vstrch: 3722 case SystemZ::BI__builtin_s390_vstrcf: 3723 case SystemZ::BI__builtin_s390_vstrczb: 3724 case SystemZ::BI__builtin_s390_vstrczh: 3725 case SystemZ::BI__builtin_s390_vstrczf: 3726 case SystemZ::BI__builtin_s390_vstrcbs: 3727 case SystemZ::BI__builtin_s390_vstrchs: 3728 case SystemZ::BI__builtin_s390_vstrcfs: 3729 case SystemZ::BI__builtin_s390_vstrczbs: 3730 case SystemZ::BI__builtin_s390_vstrczhs: 3731 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3732 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3733 case SystemZ::BI__builtin_s390_vfminsb: 3734 case SystemZ::BI__builtin_s390_vfmaxsb: 3735 case SystemZ::BI__builtin_s390_vfmindb: 3736 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3737 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3738 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3739 case SystemZ::BI__builtin_s390_vclfnhs: 3740 case SystemZ::BI__builtin_s390_vclfnls: 3741 case SystemZ::BI__builtin_s390_vcfn: 3742 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3743 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3744 } 3745 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3746 } 3747 3748 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3749 /// This checks that the target supports __builtin_cpu_supports and 3750 /// that the string argument is constant and valid. 3751 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3752 CallExpr *TheCall) { 3753 Expr *Arg = TheCall->getArg(0); 3754 3755 // Check if the argument is a string literal. 3756 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3757 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3758 << Arg->getSourceRange(); 3759 3760 // Check the contents of the string. 3761 StringRef Feature = 3762 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3763 if (!TI.validateCpuSupports(Feature)) 3764 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3765 << Arg->getSourceRange(); 3766 return false; 3767 } 3768 3769 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3770 /// This checks that the target supports __builtin_cpu_is and 3771 /// that the string argument is constant and valid. 3772 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3773 Expr *Arg = TheCall->getArg(0); 3774 3775 // Check if the argument is a string literal. 3776 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3777 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3778 << Arg->getSourceRange(); 3779 3780 // Check the contents of the string. 3781 StringRef Feature = 3782 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3783 if (!TI.validateCpuIs(Feature)) 3784 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3785 << Arg->getSourceRange(); 3786 return false; 3787 } 3788 3789 // Check if the rounding mode is legal. 3790 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3791 // Indicates if this instruction has rounding control or just SAE. 3792 bool HasRC = false; 3793 3794 unsigned ArgNum = 0; 3795 switch (BuiltinID) { 3796 default: 3797 return false; 3798 case X86::BI__builtin_ia32_vcvttsd2si32: 3799 case X86::BI__builtin_ia32_vcvttsd2si64: 3800 case X86::BI__builtin_ia32_vcvttsd2usi32: 3801 case X86::BI__builtin_ia32_vcvttsd2usi64: 3802 case X86::BI__builtin_ia32_vcvttss2si32: 3803 case X86::BI__builtin_ia32_vcvttss2si64: 3804 case X86::BI__builtin_ia32_vcvttss2usi32: 3805 case X86::BI__builtin_ia32_vcvttss2usi64: 3806 case X86::BI__builtin_ia32_vcvttsh2si32: 3807 case X86::BI__builtin_ia32_vcvttsh2si64: 3808 case X86::BI__builtin_ia32_vcvttsh2usi32: 3809 case X86::BI__builtin_ia32_vcvttsh2usi64: 3810 ArgNum = 1; 3811 break; 3812 case X86::BI__builtin_ia32_maxpd512: 3813 case X86::BI__builtin_ia32_maxps512: 3814 case X86::BI__builtin_ia32_minpd512: 3815 case X86::BI__builtin_ia32_minps512: 3816 case X86::BI__builtin_ia32_maxph512: 3817 case X86::BI__builtin_ia32_minph512: 3818 ArgNum = 2; 3819 break; 3820 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3821 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3822 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3823 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3824 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3825 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3826 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3827 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3828 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3829 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3830 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3831 case X86::BI__builtin_ia32_vcvttph2w512_mask: 3832 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 3833 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 3834 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 3835 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 3836 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 3837 case X86::BI__builtin_ia32_exp2pd_mask: 3838 case X86::BI__builtin_ia32_exp2ps_mask: 3839 case X86::BI__builtin_ia32_getexppd512_mask: 3840 case X86::BI__builtin_ia32_getexpps512_mask: 3841 case X86::BI__builtin_ia32_getexpph512_mask: 3842 case X86::BI__builtin_ia32_rcp28pd_mask: 3843 case X86::BI__builtin_ia32_rcp28ps_mask: 3844 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3845 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3846 case X86::BI__builtin_ia32_vcomisd: 3847 case X86::BI__builtin_ia32_vcomiss: 3848 case X86::BI__builtin_ia32_vcomish: 3849 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3850 ArgNum = 3; 3851 break; 3852 case X86::BI__builtin_ia32_cmppd512_mask: 3853 case X86::BI__builtin_ia32_cmpps512_mask: 3854 case X86::BI__builtin_ia32_cmpsd_mask: 3855 case X86::BI__builtin_ia32_cmpss_mask: 3856 case X86::BI__builtin_ia32_cmpsh_mask: 3857 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 3858 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 3859 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3860 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3861 case X86::BI__builtin_ia32_getexpss128_round_mask: 3862 case X86::BI__builtin_ia32_getexpsh128_round_mask: 3863 case X86::BI__builtin_ia32_getmantpd512_mask: 3864 case X86::BI__builtin_ia32_getmantps512_mask: 3865 case X86::BI__builtin_ia32_getmantph512_mask: 3866 case X86::BI__builtin_ia32_maxsd_round_mask: 3867 case X86::BI__builtin_ia32_maxss_round_mask: 3868 case X86::BI__builtin_ia32_maxsh_round_mask: 3869 case X86::BI__builtin_ia32_minsd_round_mask: 3870 case X86::BI__builtin_ia32_minss_round_mask: 3871 case X86::BI__builtin_ia32_minsh_round_mask: 3872 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3873 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3874 case X86::BI__builtin_ia32_reducepd512_mask: 3875 case X86::BI__builtin_ia32_reduceps512_mask: 3876 case X86::BI__builtin_ia32_reduceph512_mask: 3877 case X86::BI__builtin_ia32_rndscalepd_mask: 3878 case X86::BI__builtin_ia32_rndscaleps_mask: 3879 case X86::BI__builtin_ia32_rndscaleph_mask: 3880 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3881 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3882 ArgNum = 4; 3883 break; 3884 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3885 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3886 case X86::BI__builtin_ia32_fixupimmps512_mask: 3887 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3888 case X86::BI__builtin_ia32_fixupimmsd_mask: 3889 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3890 case X86::BI__builtin_ia32_fixupimmss_mask: 3891 case X86::BI__builtin_ia32_fixupimmss_maskz: 3892 case X86::BI__builtin_ia32_getmantsd_round_mask: 3893 case X86::BI__builtin_ia32_getmantss_round_mask: 3894 case X86::BI__builtin_ia32_getmantsh_round_mask: 3895 case X86::BI__builtin_ia32_rangepd512_mask: 3896 case X86::BI__builtin_ia32_rangeps512_mask: 3897 case X86::BI__builtin_ia32_rangesd128_round_mask: 3898 case X86::BI__builtin_ia32_rangess128_round_mask: 3899 case X86::BI__builtin_ia32_reducesd_mask: 3900 case X86::BI__builtin_ia32_reducess_mask: 3901 case X86::BI__builtin_ia32_reducesh_mask: 3902 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3903 case X86::BI__builtin_ia32_rndscaless_round_mask: 3904 case X86::BI__builtin_ia32_rndscalesh_round_mask: 3905 ArgNum = 5; 3906 break; 3907 case X86::BI__builtin_ia32_vcvtsd2si64: 3908 case X86::BI__builtin_ia32_vcvtsd2si32: 3909 case X86::BI__builtin_ia32_vcvtsd2usi32: 3910 case X86::BI__builtin_ia32_vcvtsd2usi64: 3911 case X86::BI__builtin_ia32_vcvtss2si32: 3912 case X86::BI__builtin_ia32_vcvtss2si64: 3913 case X86::BI__builtin_ia32_vcvtss2usi32: 3914 case X86::BI__builtin_ia32_vcvtss2usi64: 3915 case X86::BI__builtin_ia32_vcvtsh2si32: 3916 case X86::BI__builtin_ia32_vcvtsh2si64: 3917 case X86::BI__builtin_ia32_vcvtsh2usi32: 3918 case X86::BI__builtin_ia32_vcvtsh2usi64: 3919 case X86::BI__builtin_ia32_sqrtpd512: 3920 case X86::BI__builtin_ia32_sqrtps512: 3921 case X86::BI__builtin_ia32_sqrtph512: 3922 ArgNum = 1; 3923 HasRC = true; 3924 break; 3925 case X86::BI__builtin_ia32_addph512: 3926 case X86::BI__builtin_ia32_divph512: 3927 case X86::BI__builtin_ia32_mulph512: 3928 case X86::BI__builtin_ia32_subph512: 3929 case X86::BI__builtin_ia32_addpd512: 3930 case X86::BI__builtin_ia32_addps512: 3931 case X86::BI__builtin_ia32_divpd512: 3932 case X86::BI__builtin_ia32_divps512: 3933 case X86::BI__builtin_ia32_mulpd512: 3934 case X86::BI__builtin_ia32_mulps512: 3935 case X86::BI__builtin_ia32_subpd512: 3936 case X86::BI__builtin_ia32_subps512: 3937 case X86::BI__builtin_ia32_cvtsi2sd64: 3938 case X86::BI__builtin_ia32_cvtsi2ss32: 3939 case X86::BI__builtin_ia32_cvtsi2ss64: 3940 case X86::BI__builtin_ia32_cvtusi2sd64: 3941 case X86::BI__builtin_ia32_cvtusi2ss32: 3942 case X86::BI__builtin_ia32_cvtusi2ss64: 3943 case X86::BI__builtin_ia32_vcvtusi2sh: 3944 case X86::BI__builtin_ia32_vcvtusi642sh: 3945 case X86::BI__builtin_ia32_vcvtsi2sh: 3946 case X86::BI__builtin_ia32_vcvtsi642sh: 3947 ArgNum = 2; 3948 HasRC = true; 3949 break; 3950 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3951 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3952 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 3953 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 3954 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3955 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3956 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3957 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3958 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3959 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3960 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3961 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3962 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3963 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3964 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3965 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3966 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3967 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 3968 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 3969 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 3970 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 3971 case X86::BI__builtin_ia32_vcvtph2w512_mask: 3972 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 3973 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 3974 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 3975 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 3976 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 3977 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 3978 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 3979 ArgNum = 3; 3980 HasRC = true; 3981 break; 3982 case X86::BI__builtin_ia32_addsh_round_mask: 3983 case X86::BI__builtin_ia32_addss_round_mask: 3984 case X86::BI__builtin_ia32_addsd_round_mask: 3985 case X86::BI__builtin_ia32_divsh_round_mask: 3986 case X86::BI__builtin_ia32_divss_round_mask: 3987 case X86::BI__builtin_ia32_divsd_round_mask: 3988 case X86::BI__builtin_ia32_mulsh_round_mask: 3989 case X86::BI__builtin_ia32_mulss_round_mask: 3990 case X86::BI__builtin_ia32_mulsd_round_mask: 3991 case X86::BI__builtin_ia32_subsh_round_mask: 3992 case X86::BI__builtin_ia32_subss_round_mask: 3993 case X86::BI__builtin_ia32_subsd_round_mask: 3994 case X86::BI__builtin_ia32_scalefph512_mask: 3995 case X86::BI__builtin_ia32_scalefpd512_mask: 3996 case X86::BI__builtin_ia32_scalefps512_mask: 3997 case X86::BI__builtin_ia32_scalefsd_round_mask: 3998 case X86::BI__builtin_ia32_scalefss_round_mask: 3999 case X86::BI__builtin_ia32_scalefsh_round_mask: 4000 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4001 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4002 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4003 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4004 case X86::BI__builtin_ia32_sqrtss_round_mask: 4005 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4006 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4007 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4008 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4009 case X86::BI__builtin_ia32_vfmaddss3_mask: 4010 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4011 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4012 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4013 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4014 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4015 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4016 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4017 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4018 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4019 case X86::BI__builtin_ia32_vfmaddps512_mask: 4020 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4021 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4022 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4023 case X86::BI__builtin_ia32_vfmaddph512_mask: 4024 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4025 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4026 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4027 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4028 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4029 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4030 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4031 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4032 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4033 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4034 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4035 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4036 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4037 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4038 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4039 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4040 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4041 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4042 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4043 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4044 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4045 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4046 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4047 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4048 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4049 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4050 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4051 case X86::BI__builtin_ia32_vfmulcsh_mask: 4052 case X86::BI__builtin_ia32_vfmulcph512_mask: 4053 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4054 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4055 ArgNum = 4; 4056 HasRC = true; 4057 break; 4058 } 4059 4060 llvm::APSInt Result; 4061 4062 // We can't check the value of a dependent argument. 4063 Expr *Arg = TheCall->getArg(ArgNum); 4064 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4065 return false; 4066 4067 // Check constant-ness first. 4068 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4069 return true; 4070 4071 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4072 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4073 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4074 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4075 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4076 Result == 8/*ROUND_NO_EXC*/ || 4077 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4078 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4079 return false; 4080 4081 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4082 << Arg->getSourceRange(); 4083 } 4084 4085 // Check if the gather/scatter scale is legal. 4086 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4087 CallExpr *TheCall) { 4088 unsigned ArgNum = 0; 4089 switch (BuiltinID) { 4090 default: 4091 return false; 4092 case X86::BI__builtin_ia32_gatherpfdpd: 4093 case X86::BI__builtin_ia32_gatherpfdps: 4094 case X86::BI__builtin_ia32_gatherpfqpd: 4095 case X86::BI__builtin_ia32_gatherpfqps: 4096 case X86::BI__builtin_ia32_scatterpfdpd: 4097 case X86::BI__builtin_ia32_scatterpfdps: 4098 case X86::BI__builtin_ia32_scatterpfqpd: 4099 case X86::BI__builtin_ia32_scatterpfqps: 4100 ArgNum = 3; 4101 break; 4102 case X86::BI__builtin_ia32_gatherd_pd: 4103 case X86::BI__builtin_ia32_gatherd_pd256: 4104 case X86::BI__builtin_ia32_gatherq_pd: 4105 case X86::BI__builtin_ia32_gatherq_pd256: 4106 case X86::BI__builtin_ia32_gatherd_ps: 4107 case X86::BI__builtin_ia32_gatherd_ps256: 4108 case X86::BI__builtin_ia32_gatherq_ps: 4109 case X86::BI__builtin_ia32_gatherq_ps256: 4110 case X86::BI__builtin_ia32_gatherd_q: 4111 case X86::BI__builtin_ia32_gatherd_q256: 4112 case X86::BI__builtin_ia32_gatherq_q: 4113 case X86::BI__builtin_ia32_gatherq_q256: 4114 case X86::BI__builtin_ia32_gatherd_d: 4115 case X86::BI__builtin_ia32_gatherd_d256: 4116 case X86::BI__builtin_ia32_gatherq_d: 4117 case X86::BI__builtin_ia32_gatherq_d256: 4118 case X86::BI__builtin_ia32_gather3div2df: 4119 case X86::BI__builtin_ia32_gather3div2di: 4120 case X86::BI__builtin_ia32_gather3div4df: 4121 case X86::BI__builtin_ia32_gather3div4di: 4122 case X86::BI__builtin_ia32_gather3div4sf: 4123 case X86::BI__builtin_ia32_gather3div4si: 4124 case X86::BI__builtin_ia32_gather3div8sf: 4125 case X86::BI__builtin_ia32_gather3div8si: 4126 case X86::BI__builtin_ia32_gather3siv2df: 4127 case X86::BI__builtin_ia32_gather3siv2di: 4128 case X86::BI__builtin_ia32_gather3siv4df: 4129 case X86::BI__builtin_ia32_gather3siv4di: 4130 case X86::BI__builtin_ia32_gather3siv4sf: 4131 case X86::BI__builtin_ia32_gather3siv4si: 4132 case X86::BI__builtin_ia32_gather3siv8sf: 4133 case X86::BI__builtin_ia32_gather3siv8si: 4134 case X86::BI__builtin_ia32_gathersiv8df: 4135 case X86::BI__builtin_ia32_gathersiv16sf: 4136 case X86::BI__builtin_ia32_gatherdiv8df: 4137 case X86::BI__builtin_ia32_gatherdiv16sf: 4138 case X86::BI__builtin_ia32_gathersiv8di: 4139 case X86::BI__builtin_ia32_gathersiv16si: 4140 case X86::BI__builtin_ia32_gatherdiv8di: 4141 case X86::BI__builtin_ia32_gatherdiv16si: 4142 case X86::BI__builtin_ia32_scatterdiv2df: 4143 case X86::BI__builtin_ia32_scatterdiv2di: 4144 case X86::BI__builtin_ia32_scatterdiv4df: 4145 case X86::BI__builtin_ia32_scatterdiv4di: 4146 case X86::BI__builtin_ia32_scatterdiv4sf: 4147 case X86::BI__builtin_ia32_scatterdiv4si: 4148 case X86::BI__builtin_ia32_scatterdiv8sf: 4149 case X86::BI__builtin_ia32_scatterdiv8si: 4150 case X86::BI__builtin_ia32_scattersiv2df: 4151 case X86::BI__builtin_ia32_scattersiv2di: 4152 case X86::BI__builtin_ia32_scattersiv4df: 4153 case X86::BI__builtin_ia32_scattersiv4di: 4154 case X86::BI__builtin_ia32_scattersiv4sf: 4155 case X86::BI__builtin_ia32_scattersiv4si: 4156 case X86::BI__builtin_ia32_scattersiv8sf: 4157 case X86::BI__builtin_ia32_scattersiv8si: 4158 case X86::BI__builtin_ia32_scattersiv8df: 4159 case X86::BI__builtin_ia32_scattersiv16sf: 4160 case X86::BI__builtin_ia32_scatterdiv8df: 4161 case X86::BI__builtin_ia32_scatterdiv16sf: 4162 case X86::BI__builtin_ia32_scattersiv8di: 4163 case X86::BI__builtin_ia32_scattersiv16si: 4164 case X86::BI__builtin_ia32_scatterdiv8di: 4165 case X86::BI__builtin_ia32_scatterdiv16si: 4166 ArgNum = 4; 4167 break; 4168 } 4169 4170 llvm::APSInt Result; 4171 4172 // We can't check the value of a dependent argument. 4173 Expr *Arg = TheCall->getArg(ArgNum); 4174 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4175 return false; 4176 4177 // Check constant-ness first. 4178 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4179 return true; 4180 4181 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4182 return false; 4183 4184 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4185 << Arg->getSourceRange(); 4186 } 4187 4188 enum { TileRegLow = 0, TileRegHigh = 7 }; 4189 4190 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4191 ArrayRef<int> ArgNums) { 4192 for (int ArgNum : ArgNums) { 4193 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4194 return true; 4195 } 4196 return false; 4197 } 4198 4199 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4200 ArrayRef<int> ArgNums) { 4201 // Because the max number of tile register is TileRegHigh + 1, so here we use 4202 // each bit to represent the usage of them in bitset. 4203 std::bitset<TileRegHigh + 1> ArgValues; 4204 for (int ArgNum : ArgNums) { 4205 Expr *Arg = TheCall->getArg(ArgNum); 4206 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4207 continue; 4208 4209 llvm::APSInt Result; 4210 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4211 return true; 4212 int ArgExtValue = Result.getExtValue(); 4213 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4214 "Incorrect tile register num."); 4215 if (ArgValues.test(ArgExtValue)) 4216 return Diag(TheCall->getBeginLoc(), 4217 diag::err_x86_builtin_tile_arg_duplicate) 4218 << TheCall->getArg(ArgNum)->getSourceRange(); 4219 ArgValues.set(ArgExtValue); 4220 } 4221 return false; 4222 } 4223 4224 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4225 ArrayRef<int> ArgNums) { 4226 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4227 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4228 } 4229 4230 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4231 switch (BuiltinID) { 4232 default: 4233 return false; 4234 case X86::BI__builtin_ia32_tileloadd64: 4235 case X86::BI__builtin_ia32_tileloaddt164: 4236 case X86::BI__builtin_ia32_tilestored64: 4237 case X86::BI__builtin_ia32_tilezero: 4238 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4239 case X86::BI__builtin_ia32_tdpbssd: 4240 case X86::BI__builtin_ia32_tdpbsud: 4241 case X86::BI__builtin_ia32_tdpbusd: 4242 case X86::BI__builtin_ia32_tdpbuud: 4243 case X86::BI__builtin_ia32_tdpbf16ps: 4244 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4245 } 4246 } 4247 static bool isX86_32Builtin(unsigned BuiltinID) { 4248 // These builtins only work on x86-32 targets. 4249 switch (BuiltinID) { 4250 case X86::BI__builtin_ia32_readeflags_u32: 4251 case X86::BI__builtin_ia32_writeeflags_u32: 4252 return true; 4253 } 4254 4255 return false; 4256 } 4257 4258 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4259 CallExpr *TheCall) { 4260 if (BuiltinID == X86::BI__builtin_cpu_supports) 4261 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4262 4263 if (BuiltinID == X86::BI__builtin_cpu_is) 4264 return SemaBuiltinCpuIs(*this, TI, TheCall); 4265 4266 // Check for 32-bit only builtins on a 64-bit target. 4267 const llvm::Triple &TT = TI.getTriple(); 4268 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4269 return Diag(TheCall->getCallee()->getBeginLoc(), 4270 diag::err_32_bit_builtin_64_bit_tgt); 4271 4272 // If the intrinsic has rounding or SAE make sure its valid. 4273 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4274 return true; 4275 4276 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4277 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4278 return true; 4279 4280 // If the intrinsic has a tile arguments, make sure they are valid. 4281 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4282 return true; 4283 4284 // For intrinsics which take an immediate value as part of the instruction, 4285 // range check them here. 4286 int i = 0, l = 0, u = 0; 4287 switch (BuiltinID) { 4288 default: 4289 return false; 4290 case X86::BI__builtin_ia32_vec_ext_v2si: 4291 case X86::BI__builtin_ia32_vec_ext_v2di: 4292 case X86::BI__builtin_ia32_vextractf128_pd256: 4293 case X86::BI__builtin_ia32_vextractf128_ps256: 4294 case X86::BI__builtin_ia32_vextractf128_si256: 4295 case X86::BI__builtin_ia32_extract128i256: 4296 case X86::BI__builtin_ia32_extractf64x4_mask: 4297 case X86::BI__builtin_ia32_extracti64x4_mask: 4298 case X86::BI__builtin_ia32_extractf32x8_mask: 4299 case X86::BI__builtin_ia32_extracti32x8_mask: 4300 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4301 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4302 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4303 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4304 i = 1; l = 0; u = 1; 4305 break; 4306 case X86::BI__builtin_ia32_vec_set_v2di: 4307 case X86::BI__builtin_ia32_vinsertf128_pd256: 4308 case X86::BI__builtin_ia32_vinsertf128_ps256: 4309 case X86::BI__builtin_ia32_vinsertf128_si256: 4310 case X86::BI__builtin_ia32_insert128i256: 4311 case X86::BI__builtin_ia32_insertf32x8: 4312 case X86::BI__builtin_ia32_inserti32x8: 4313 case X86::BI__builtin_ia32_insertf64x4: 4314 case X86::BI__builtin_ia32_inserti64x4: 4315 case X86::BI__builtin_ia32_insertf64x2_256: 4316 case X86::BI__builtin_ia32_inserti64x2_256: 4317 case X86::BI__builtin_ia32_insertf32x4_256: 4318 case X86::BI__builtin_ia32_inserti32x4_256: 4319 i = 2; l = 0; u = 1; 4320 break; 4321 case X86::BI__builtin_ia32_vpermilpd: 4322 case X86::BI__builtin_ia32_vec_ext_v4hi: 4323 case X86::BI__builtin_ia32_vec_ext_v4si: 4324 case X86::BI__builtin_ia32_vec_ext_v4sf: 4325 case X86::BI__builtin_ia32_vec_ext_v4di: 4326 case X86::BI__builtin_ia32_extractf32x4_mask: 4327 case X86::BI__builtin_ia32_extracti32x4_mask: 4328 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4329 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4330 i = 1; l = 0; u = 3; 4331 break; 4332 case X86::BI_mm_prefetch: 4333 case X86::BI__builtin_ia32_vec_ext_v8hi: 4334 case X86::BI__builtin_ia32_vec_ext_v8si: 4335 i = 1; l = 0; u = 7; 4336 break; 4337 case X86::BI__builtin_ia32_sha1rnds4: 4338 case X86::BI__builtin_ia32_blendpd: 4339 case X86::BI__builtin_ia32_shufpd: 4340 case X86::BI__builtin_ia32_vec_set_v4hi: 4341 case X86::BI__builtin_ia32_vec_set_v4si: 4342 case X86::BI__builtin_ia32_vec_set_v4di: 4343 case X86::BI__builtin_ia32_shuf_f32x4_256: 4344 case X86::BI__builtin_ia32_shuf_f64x2_256: 4345 case X86::BI__builtin_ia32_shuf_i32x4_256: 4346 case X86::BI__builtin_ia32_shuf_i64x2_256: 4347 case X86::BI__builtin_ia32_insertf64x2_512: 4348 case X86::BI__builtin_ia32_inserti64x2_512: 4349 case X86::BI__builtin_ia32_insertf32x4: 4350 case X86::BI__builtin_ia32_inserti32x4: 4351 i = 2; l = 0; u = 3; 4352 break; 4353 case X86::BI__builtin_ia32_vpermil2pd: 4354 case X86::BI__builtin_ia32_vpermil2pd256: 4355 case X86::BI__builtin_ia32_vpermil2ps: 4356 case X86::BI__builtin_ia32_vpermil2ps256: 4357 i = 3; l = 0; u = 3; 4358 break; 4359 case X86::BI__builtin_ia32_cmpb128_mask: 4360 case X86::BI__builtin_ia32_cmpw128_mask: 4361 case X86::BI__builtin_ia32_cmpd128_mask: 4362 case X86::BI__builtin_ia32_cmpq128_mask: 4363 case X86::BI__builtin_ia32_cmpb256_mask: 4364 case X86::BI__builtin_ia32_cmpw256_mask: 4365 case X86::BI__builtin_ia32_cmpd256_mask: 4366 case X86::BI__builtin_ia32_cmpq256_mask: 4367 case X86::BI__builtin_ia32_cmpb512_mask: 4368 case X86::BI__builtin_ia32_cmpw512_mask: 4369 case X86::BI__builtin_ia32_cmpd512_mask: 4370 case X86::BI__builtin_ia32_cmpq512_mask: 4371 case X86::BI__builtin_ia32_ucmpb128_mask: 4372 case X86::BI__builtin_ia32_ucmpw128_mask: 4373 case X86::BI__builtin_ia32_ucmpd128_mask: 4374 case X86::BI__builtin_ia32_ucmpq128_mask: 4375 case X86::BI__builtin_ia32_ucmpb256_mask: 4376 case X86::BI__builtin_ia32_ucmpw256_mask: 4377 case X86::BI__builtin_ia32_ucmpd256_mask: 4378 case X86::BI__builtin_ia32_ucmpq256_mask: 4379 case X86::BI__builtin_ia32_ucmpb512_mask: 4380 case X86::BI__builtin_ia32_ucmpw512_mask: 4381 case X86::BI__builtin_ia32_ucmpd512_mask: 4382 case X86::BI__builtin_ia32_ucmpq512_mask: 4383 case X86::BI__builtin_ia32_vpcomub: 4384 case X86::BI__builtin_ia32_vpcomuw: 4385 case X86::BI__builtin_ia32_vpcomud: 4386 case X86::BI__builtin_ia32_vpcomuq: 4387 case X86::BI__builtin_ia32_vpcomb: 4388 case X86::BI__builtin_ia32_vpcomw: 4389 case X86::BI__builtin_ia32_vpcomd: 4390 case X86::BI__builtin_ia32_vpcomq: 4391 case X86::BI__builtin_ia32_vec_set_v8hi: 4392 case X86::BI__builtin_ia32_vec_set_v8si: 4393 i = 2; l = 0; u = 7; 4394 break; 4395 case X86::BI__builtin_ia32_vpermilpd256: 4396 case X86::BI__builtin_ia32_roundps: 4397 case X86::BI__builtin_ia32_roundpd: 4398 case X86::BI__builtin_ia32_roundps256: 4399 case X86::BI__builtin_ia32_roundpd256: 4400 case X86::BI__builtin_ia32_getmantpd128_mask: 4401 case X86::BI__builtin_ia32_getmantpd256_mask: 4402 case X86::BI__builtin_ia32_getmantps128_mask: 4403 case X86::BI__builtin_ia32_getmantps256_mask: 4404 case X86::BI__builtin_ia32_getmantpd512_mask: 4405 case X86::BI__builtin_ia32_getmantps512_mask: 4406 case X86::BI__builtin_ia32_getmantph128_mask: 4407 case X86::BI__builtin_ia32_getmantph256_mask: 4408 case X86::BI__builtin_ia32_getmantph512_mask: 4409 case X86::BI__builtin_ia32_vec_ext_v16qi: 4410 case X86::BI__builtin_ia32_vec_ext_v16hi: 4411 i = 1; l = 0; u = 15; 4412 break; 4413 case X86::BI__builtin_ia32_pblendd128: 4414 case X86::BI__builtin_ia32_blendps: 4415 case X86::BI__builtin_ia32_blendpd256: 4416 case X86::BI__builtin_ia32_shufpd256: 4417 case X86::BI__builtin_ia32_roundss: 4418 case X86::BI__builtin_ia32_roundsd: 4419 case X86::BI__builtin_ia32_rangepd128_mask: 4420 case X86::BI__builtin_ia32_rangepd256_mask: 4421 case X86::BI__builtin_ia32_rangepd512_mask: 4422 case X86::BI__builtin_ia32_rangeps128_mask: 4423 case X86::BI__builtin_ia32_rangeps256_mask: 4424 case X86::BI__builtin_ia32_rangeps512_mask: 4425 case X86::BI__builtin_ia32_getmantsd_round_mask: 4426 case X86::BI__builtin_ia32_getmantss_round_mask: 4427 case X86::BI__builtin_ia32_getmantsh_round_mask: 4428 case X86::BI__builtin_ia32_vec_set_v16qi: 4429 case X86::BI__builtin_ia32_vec_set_v16hi: 4430 i = 2; l = 0; u = 15; 4431 break; 4432 case X86::BI__builtin_ia32_vec_ext_v32qi: 4433 i = 1; l = 0; u = 31; 4434 break; 4435 case X86::BI__builtin_ia32_cmpps: 4436 case X86::BI__builtin_ia32_cmpss: 4437 case X86::BI__builtin_ia32_cmppd: 4438 case X86::BI__builtin_ia32_cmpsd: 4439 case X86::BI__builtin_ia32_cmpps256: 4440 case X86::BI__builtin_ia32_cmppd256: 4441 case X86::BI__builtin_ia32_cmpps128_mask: 4442 case X86::BI__builtin_ia32_cmppd128_mask: 4443 case X86::BI__builtin_ia32_cmpps256_mask: 4444 case X86::BI__builtin_ia32_cmppd256_mask: 4445 case X86::BI__builtin_ia32_cmpps512_mask: 4446 case X86::BI__builtin_ia32_cmppd512_mask: 4447 case X86::BI__builtin_ia32_cmpsd_mask: 4448 case X86::BI__builtin_ia32_cmpss_mask: 4449 case X86::BI__builtin_ia32_vec_set_v32qi: 4450 i = 2; l = 0; u = 31; 4451 break; 4452 case X86::BI__builtin_ia32_permdf256: 4453 case X86::BI__builtin_ia32_permdi256: 4454 case X86::BI__builtin_ia32_permdf512: 4455 case X86::BI__builtin_ia32_permdi512: 4456 case X86::BI__builtin_ia32_vpermilps: 4457 case X86::BI__builtin_ia32_vpermilps256: 4458 case X86::BI__builtin_ia32_vpermilpd512: 4459 case X86::BI__builtin_ia32_vpermilps512: 4460 case X86::BI__builtin_ia32_pshufd: 4461 case X86::BI__builtin_ia32_pshufd256: 4462 case X86::BI__builtin_ia32_pshufd512: 4463 case X86::BI__builtin_ia32_pshufhw: 4464 case X86::BI__builtin_ia32_pshufhw256: 4465 case X86::BI__builtin_ia32_pshufhw512: 4466 case X86::BI__builtin_ia32_pshuflw: 4467 case X86::BI__builtin_ia32_pshuflw256: 4468 case X86::BI__builtin_ia32_pshuflw512: 4469 case X86::BI__builtin_ia32_vcvtps2ph: 4470 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4471 case X86::BI__builtin_ia32_vcvtps2ph256: 4472 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4473 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4474 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4475 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4476 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4477 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4478 case X86::BI__builtin_ia32_rndscaleps_mask: 4479 case X86::BI__builtin_ia32_rndscalepd_mask: 4480 case X86::BI__builtin_ia32_rndscaleph_mask: 4481 case X86::BI__builtin_ia32_reducepd128_mask: 4482 case X86::BI__builtin_ia32_reducepd256_mask: 4483 case X86::BI__builtin_ia32_reducepd512_mask: 4484 case X86::BI__builtin_ia32_reduceps128_mask: 4485 case X86::BI__builtin_ia32_reduceps256_mask: 4486 case X86::BI__builtin_ia32_reduceps512_mask: 4487 case X86::BI__builtin_ia32_reduceph128_mask: 4488 case X86::BI__builtin_ia32_reduceph256_mask: 4489 case X86::BI__builtin_ia32_reduceph512_mask: 4490 case X86::BI__builtin_ia32_prold512: 4491 case X86::BI__builtin_ia32_prolq512: 4492 case X86::BI__builtin_ia32_prold128: 4493 case X86::BI__builtin_ia32_prold256: 4494 case X86::BI__builtin_ia32_prolq128: 4495 case X86::BI__builtin_ia32_prolq256: 4496 case X86::BI__builtin_ia32_prord512: 4497 case X86::BI__builtin_ia32_prorq512: 4498 case X86::BI__builtin_ia32_prord128: 4499 case X86::BI__builtin_ia32_prord256: 4500 case X86::BI__builtin_ia32_prorq128: 4501 case X86::BI__builtin_ia32_prorq256: 4502 case X86::BI__builtin_ia32_fpclasspd128_mask: 4503 case X86::BI__builtin_ia32_fpclasspd256_mask: 4504 case X86::BI__builtin_ia32_fpclassps128_mask: 4505 case X86::BI__builtin_ia32_fpclassps256_mask: 4506 case X86::BI__builtin_ia32_fpclassps512_mask: 4507 case X86::BI__builtin_ia32_fpclasspd512_mask: 4508 case X86::BI__builtin_ia32_fpclassph128_mask: 4509 case X86::BI__builtin_ia32_fpclassph256_mask: 4510 case X86::BI__builtin_ia32_fpclassph512_mask: 4511 case X86::BI__builtin_ia32_fpclasssd_mask: 4512 case X86::BI__builtin_ia32_fpclassss_mask: 4513 case X86::BI__builtin_ia32_fpclasssh_mask: 4514 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4515 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4516 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4517 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4518 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4519 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4520 case X86::BI__builtin_ia32_kshiftliqi: 4521 case X86::BI__builtin_ia32_kshiftlihi: 4522 case X86::BI__builtin_ia32_kshiftlisi: 4523 case X86::BI__builtin_ia32_kshiftlidi: 4524 case X86::BI__builtin_ia32_kshiftriqi: 4525 case X86::BI__builtin_ia32_kshiftrihi: 4526 case X86::BI__builtin_ia32_kshiftrisi: 4527 case X86::BI__builtin_ia32_kshiftridi: 4528 i = 1; l = 0; u = 255; 4529 break; 4530 case X86::BI__builtin_ia32_vperm2f128_pd256: 4531 case X86::BI__builtin_ia32_vperm2f128_ps256: 4532 case X86::BI__builtin_ia32_vperm2f128_si256: 4533 case X86::BI__builtin_ia32_permti256: 4534 case X86::BI__builtin_ia32_pblendw128: 4535 case X86::BI__builtin_ia32_pblendw256: 4536 case X86::BI__builtin_ia32_blendps256: 4537 case X86::BI__builtin_ia32_pblendd256: 4538 case X86::BI__builtin_ia32_palignr128: 4539 case X86::BI__builtin_ia32_palignr256: 4540 case X86::BI__builtin_ia32_palignr512: 4541 case X86::BI__builtin_ia32_alignq512: 4542 case X86::BI__builtin_ia32_alignd512: 4543 case X86::BI__builtin_ia32_alignd128: 4544 case X86::BI__builtin_ia32_alignd256: 4545 case X86::BI__builtin_ia32_alignq128: 4546 case X86::BI__builtin_ia32_alignq256: 4547 case X86::BI__builtin_ia32_vcomisd: 4548 case X86::BI__builtin_ia32_vcomiss: 4549 case X86::BI__builtin_ia32_shuf_f32x4: 4550 case X86::BI__builtin_ia32_shuf_f64x2: 4551 case X86::BI__builtin_ia32_shuf_i32x4: 4552 case X86::BI__builtin_ia32_shuf_i64x2: 4553 case X86::BI__builtin_ia32_shufpd512: 4554 case X86::BI__builtin_ia32_shufps: 4555 case X86::BI__builtin_ia32_shufps256: 4556 case X86::BI__builtin_ia32_shufps512: 4557 case X86::BI__builtin_ia32_dbpsadbw128: 4558 case X86::BI__builtin_ia32_dbpsadbw256: 4559 case X86::BI__builtin_ia32_dbpsadbw512: 4560 case X86::BI__builtin_ia32_vpshldd128: 4561 case X86::BI__builtin_ia32_vpshldd256: 4562 case X86::BI__builtin_ia32_vpshldd512: 4563 case X86::BI__builtin_ia32_vpshldq128: 4564 case X86::BI__builtin_ia32_vpshldq256: 4565 case X86::BI__builtin_ia32_vpshldq512: 4566 case X86::BI__builtin_ia32_vpshldw128: 4567 case X86::BI__builtin_ia32_vpshldw256: 4568 case X86::BI__builtin_ia32_vpshldw512: 4569 case X86::BI__builtin_ia32_vpshrdd128: 4570 case X86::BI__builtin_ia32_vpshrdd256: 4571 case X86::BI__builtin_ia32_vpshrdd512: 4572 case X86::BI__builtin_ia32_vpshrdq128: 4573 case X86::BI__builtin_ia32_vpshrdq256: 4574 case X86::BI__builtin_ia32_vpshrdq512: 4575 case X86::BI__builtin_ia32_vpshrdw128: 4576 case X86::BI__builtin_ia32_vpshrdw256: 4577 case X86::BI__builtin_ia32_vpshrdw512: 4578 i = 2; l = 0; u = 255; 4579 break; 4580 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4581 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4582 case X86::BI__builtin_ia32_fixupimmps512_mask: 4583 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4584 case X86::BI__builtin_ia32_fixupimmsd_mask: 4585 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4586 case X86::BI__builtin_ia32_fixupimmss_mask: 4587 case X86::BI__builtin_ia32_fixupimmss_maskz: 4588 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4589 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4590 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4591 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4592 case X86::BI__builtin_ia32_fixupimmps128_mask: 4593 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4594 case X86::BI__builtin_ia32_fixupimmps256_mask: 4595 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4596 case X86::BI__builtin_ia32_pternlogd512_mask: 4597 case X86::BI__builtin_ia32_pternlogd512_maskz: 4598 case X86::BI__builtin_ia32_pternlogq512_mask: 4599 case X86::BI__builtin_ia32_pternlogq512_maskz: 4600 case X86::BI__builtin_ia32_pternlogd128_mask: 4601 case X86::BI__builtin_ia32_pternlogd128_maskz: 4602 case X86::BI__builtin_ia32_pternlogd256_mask: 4603 case X86::BI__builtin_ia32_pternlogd256_maskz: 4604 case X86::BI__builtin_ia32_pternlogq128_mask: 4605 case X86::BI__builtin_ia32_pternlogq128_maskz: 4606 case X86::BI__builtin_ia32_pternlogq256_mask: 4607 case X86::BI__builtin_ia32_pternlogq256_maskz: 4608 i = 3; l = 0; u = 255; 4609 break; 4610 case X86::BI__builtin_ia32_gatherpfdpd: 4611 case X86::BI__builtin_ia32_gatherpfdps: 4612 case X86::BI__builtin_ia32_gatherpfqpd: 4613 case X86::BI__builtin_ia32_gatherpfqps: 4614 case X86::BI__builtin_ia32_scatterpfdpd: 4615 case X86::BI__builtin_ia32_scatterpfdps: 4616 case X86::BI__builtin_ia32_scatterpfqpd: 4617 case X86::BI__builtin_ia32_scatterpfqps: 4618 i = 4; l = 2; u = 3; 4619 break; 4620 case X86::BI__builtin_ia32_reducesd_mask: 4621 case X86::BI__builtin_ia32_reducess_mask: 4622 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4623 case X86::BI__builtin_ia32_rndscaless_round_mask: 4624 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4625 case X86::BI__builtin_ia32_reducesh_mask: 4626 i = 4; l = 0; u = 255; 4627 break; 4628 } 4629 4630 // Note that we don't force a hard error on the range check here, allowing 4631 // template-generated or macro-generated dead code to potentially have out-of- 4632 // range values. These need to code generate, but don't need to necessarily 4633 // make any sense. We use a warning that defaults to an error. 4634 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4635 } 4636 4637 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4638 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4639 /// Returns true when the format fits the function and the FormatStringInfo has 4640 /// been populated. 4641 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4642 FormatStringInfo *FSI) { 4643 FSI->HasVAListArg = Format->getFirstArg() == 0; 4644 FSI->FormatIdx = Format->getFormatIdx() - 1; 4645 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4646 4647 // The way the format attribute works in GCC, the implicit this argument 4648 // of member functions is counted. However, it doesn't appear in our own 4649 // lists, so decrement format_idx in that case. 4650 if (IsCXXMember) { 4651 if(FSI->FormatIdx == 0) 4652 return false; 4653 --FSI->FormatIdx; 4654 if (FSI->FirstDataArg != 0) 4655 --FSI->FirstDataArg; 4656 } 4657 return true; 4658 } 4659 4660 /// Checks if a the given expression evaluates to null. 4661 /// 4662 /// Returns true if the value evaluates to null. 4663 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4664 // If the expression has non-null type, it doesn't evaluate to null. 4665 if (auto nullability 4666 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4667 if (*nullability == NullabilityKind::NonNull) 4668 return false; 4669 } 4670 4671 // As a special case, transparent unions initialized with zero are 4672 // considered null for the purposes of the nonnull attribute. 4673 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4674 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4675 if (const CompoundLiteralExpr *CLE = 4676 dyn_cast<CompoundLiteralExpr>(Expr)) 4677 if (const InitListExpr *ILE = 4678 dyn_cast<InitListExpr>(CLE->getInitializer())) 4679 Expr = ILE->getInit(0); 4680 } 4681 4682 bool Result; 4683 return (!Expr->isValueDependent() && 4684 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4685 !Result); 4686 } 4687 4688 static void CheckNonNullArgument(Sema &S, 4689 const Expr *ArgExpr, 4690 SourceLocation CallSiteLoc) { 4691 if (CheckNonNullExpr(S, ArgExpr)) 4692 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4693 S.PDiag(diag::warn_null_arg) 4694 << ArgExpr->getSourceRange()); 4695 } 4696 4697 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4698 FormatStringInfo FSI; 4699 if ((GetFormatStringType(Format) == FST_NSString) && 4700 getFormatStringInfo(Format, false, &FSI)) { 4701 Idx = FSI.FormatIdx; 4702 return true; 4703 } 4704 return false; 4705 } 4706 4707 /// Diagnose use of %s directive in an NSString which is being passed 4708 /// as formatting string to formatting method. 4709 static void 4710 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4711 const NamedDecl *FDecl, 4712 Expr **Args, 4713 unsigned NumArgs) { 4714 unsigned Idx = 0; 4715 bool Format = false; 4716 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4717 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4718 Idx = 2; 4719 Format = true; 4720 } 4721 else 4722 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4723 if (S.GetFormatNSStringIdx(I, Idx)) { 4724 Format = true; 4725 break; 4726 } 4727 } 4728 if (!Format || NumArgs <= Idx) 4729 return; 4730 const Expr *FormatExpr = Args[Idx]; 4731 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4732 FormatExpr = CSCE->getSubExpr(); 4733 const StringLiteral *FormatString; 4734 if (const ObjCStringLiteral *OSL = 4735 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4736 FormatString = OSL->getString(); 4737 else 4738 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4739 if (!FormatString) 4740 return; 4741 if (S.FormatStringHasSArg(FormatString)) { 4742 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4743 << "%s" << 1 << 1; 4744 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4745 << FDecl->getDeclName(); 4746 } 4747 } 4748 4749 /// Determine whether the given type has a non-null nullability annotation. 4750 static bool isNonNullType(ASTContext &ctx, QualType type) { 4751 if (auto nullability = type->getNullability(ctx)) 4752 return *nullability == NullabilityKind::NonNull; 4753 4754 return false; 4755 } 4756 4757 static void CheckNonNullArguments(Sema &S, 4758 const NamedDecl *FDecl, 4759 const FunctionProtoType *Proto, 4760 ArrayRef<const Expr *> Args, 4761 SourceLocation CallSiteLoc) { 4762 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4763 4764 // Already checked by by constant evaluator. 4765 if (S.isConstantEvaluated()) 4766 return; 4767 // Check the attributes attached to the method/function itself. 4768 llvm::SmallBitVector NonNullArgs; 4769 if (FDecl) { 4770 // Handle the nonnull attribute on the function/method declaration itself. 4771 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4772 if (!NonNull->args_size()) { 4773 // Easy case: all pointer arguments are nonnull. 4774 for (const auto *Arg : Args) 4775 if (S.isValidPointerAttrType(Arg->getType())) 4776 CheckNonNullArgument(S, Arg, CallSiteLoc); 4777 return; 4778 } 4779 4780 for (const ParamIdx &Idx : NonNull->args()) { 4781 unsigned IdxAST = Idx.getASTIndex(); 4782 if (IdxAST >= Args.size()) 4783 continue; 4784 if (NonNullArgs.empty()) 4785 NonNullArgs.resize(Args.size()); 4786 NonNullArgs.set(IdxAST); 4787 } 4788 } 4789 } 4790 4791 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4792 // Handle the nonnull attribute on the parameters of the 4793 // function/method. 4794 ArrayRef<ParmVarDecl*> parms; 4795 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4796 parms = FD->parameters(); 4797 else 4798 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4799 4800 unsigned ParamIndex = 0; 4801 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4802 I != E; ++I, ++ParamIndex) { 4803 const ParmVarDecl *PVD = *I; 4804 if (PVD->hasAttr<NonNullAttr>() || 4805 isNonNullType(S.Context, PVD->getType())) { 4806 if (NonNullArgs.empty()) 4807 NonNullArgs.resize(Args.size()); 4808 4809 NonNullArgs.set(ParamIndex); 4810 } 4811 } 4812 } else { 4813 // If we have a non-function, non-method declaration but no 4814 // function prototype, try to dig out the function prototype. 4815 if (!Proto) { 4816 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4817 QualType type = VD->getType().getNonReferenceType(); 4818 if (auto pointerType = type->getAs<PointerType>()) 4819 type = pointerType->getPointeeType(); 4820 else if (auto blockType = type->getAs<BlockPointerType>()) 4821 type = blockType->getPointeeType(); 4822 // FIXME: data member pointers? 4823 4824 // Dig out the function prototype, if there is one. 4825 Proto = type->getAs<FunctionProtoType>(); 4826 } 4827 } 4828 4829 // Fill in non-null argument information from the nullability 4830 // information on the parameter types (if we have them). 4831 if (Proto) { 4832 unsigned Index = 0; 4833 for (auto paramType : Proto->getParamTypes()) { 4834 if (isNonNullType(S.Context, paramType)) { 4835 if (NonNullArgs.empty()) 4836 NonNullArgs.resize(Args.size()); 4837 4838 NonNullArgs.set(Index); 4839 } 4840 4841 ++Index; 4842 } 4843 } 4844 } 4845 4846 // Check for non-null arguments. 4847 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4848 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4849 if (NonNullArgs[ArgIndex]) 4850 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4851 } 4852 } 4853 4854 /// Warn if a pointer or reference argument passed to a function points to an 4855 /// object that is less aligned than the parameter. This can happen when 4856 /// creating a typedef with a lower alignment than the original type and then 4857 /// calling functions defined in terms of the original type. 4858 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4859 StringRef ParamName, QualType ArgTy, 4860 QualType ParamTy) { 4861 4862 // If a function accepts a pointer or reference type 4863 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4864 return; 4865 4866 // If the parameter is a pointer type, get the pointee type for the 4867 // argument too. If the parameter is a reference type, don't try to get 4868 // the pointee type for the argument. 4869 if (ParamTy->isPointerType()) 4870 ArgTy = ArgTy->getPointeeType(); 4871 4872 // Remove reference or pointer 4873 ParamTy = ParamTy->getPointeeType(); 4874 4875 // Find expected alignment, and the actual alignment of the passed object. 4876 // getTypeAlignInChars requires complete types 4877 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4878 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4879 ArgTy->isUndeducedType()) 4880 return; 4881 4882 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4883 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4884 4885 // If the argument is less aligned than the parameter, there is a 4886 // potential alignment issue. 4887 if (ArgAlign < ParamAlign) 4888 Diag(Loc, diag::warn_param_mismatched_alignment) 4889 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4890 << ParamName << (FDecl != nullptr) << FDecl; 4891 } 4892 4893 /// Handles the checks for format strings, non-POD arguments to vararg 4894 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4895 /// attributes. 4896 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4897 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4898 bool IsMemberFunction, SourceLocation Loc, 4899 SourceRange Range, VariadicCallType CallType) { 4900 // FIXME: We should check as much as we can in the template definition. 4901 if (CurContext->isDependentContext()) 4902 return; 4903 4904 // Printf and scanf checking. 4905 llvm::SmallBitVector CheckedVarArgs; 4906 if (FDecl) { 4907 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4908 // Only create vector if there are format attributes. 4909 CheckedVarArgs.resize(Args.size()); 4910 4911 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4912 CheckedVarArgs); 4913 } 4914 } 4915 4916 // Refuse POD arguments that weren't caught by the format string 4917 // checks above. 4918 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4919 if (CallType != VariadicDoesNotApply && 4920 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4921 unsigned NumParams = Proto ? Proto->getNumParams() 4922 : FDecl && isa<FunctionDecl>(FDecl) 4923 ? cast<FunctionDecl>(FDecl)->getNumParams() 4924 : FDecl && isa<ObjCMethodDecl>(FDecl) 4925 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4926 : 0; 4927 4928 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4929 // Args[ArgIdx] can be null in malformed code. 4930 if (const Expr *Arg = Args[ArgIdx]) { 4931 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4932 checkVariadicArgument(Arg, CallType); 4933 } 4934 } 4935 } 4936 4937 if (FDecl || Proto) { 4938 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4939 4940 // Type safety checking. 4941 if (FDecl) { 4942 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4943 CheckArgumentWithTypeTag(I, Args, Loc); 4944 } 4945 } 4946 4947 // Check that passed arguments match the alignment of original arguments. 4948 // Try to get the missing prototype from the declaration. 4949 if (!Proto && FDecl) { 4950 const auto *FT = FDecl->getFunctionType(); 4951 if (isa_and_nonnull<FunctionProtoType>(FT)) 4952 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4953 } 4954 if (Proto) { 4955 // For variadic functions, we may have more args than parameters. 4956 // For some K&R functions, we may have less args than parameters. 4957 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4958 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4959 // Args[ArgIdx] can be null in malformed code. 4960 if (const Expr *Arg = Args[ArgIdx]) { 4961 if (Arg->containsErrors()) 4962 continue; 4963 4964 QualType ParamTy = Proto->getParamType(ArgIdx); 4965 QualType ArgTy = Arg->getType(); 4966 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4967 ArgTy, ParamTy); 4968 } 4969 } 4970 } 4971 4972 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4973 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4974 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4975 if (!Arg->isValueDependent()) { 4976 Expr::EvalResult Align; 4977 if (Arg->EvaluateAsInt(Align, Context)) { 4978 const llvm::APSInt &I = Align.Val.getInt(); 4979 if (!I.isPowerOf2()) 4980 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4981 << Arg->getSourceRange(); 4982 4983 if (I > Sema::MaximumAlignment) 4984 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4985 << Arg->getSourceRange() << Sema::MaximumAlignment; 4986 } 4987 } 4988 } 4989 4990 if (FD) 4991 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4992 } 4993 4994 /// CheckConstructorCall - Check a constructor call for correctness and safety 4995 /// properties not enforced by the C type system. 4996 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4997 ArrayRef<const Expr *> Args, 4998 const FunctionProtoType *Proto, 4999 SourceLocation Loc) { 5000 VariadicCallType CallType = 5001 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5002 5003 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5004 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5005 Context.getPointerType(Ctor->getThisObjectType())); 5006 5007 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5008 Loc, SourceRange(), CallType); 5009 } 5010 5011 /// CheckFunctionCall - Check a direct function call for various correctness 5012 /// and safety properties not strictly enforced by the C type system. 5013 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5014 const FunctionProtoType *Proto) { 5015 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5016 isa<CXXMethodDecl>(FDecl); 5017 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5018 IsMemberOperatorCall; 5019 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5020 TheCall->getCallee()); 5021 Expr** Args = TheCall->getArgs(); 5022 unsigned NumArgs = TheCall->getNumArgs(); 5023 5024 Expr *ImplicitThis = nullptr; 5025 if (IsMemberOperatorCall) { 5026 // If this is a call to a member operator, hide the first argument 5027 // from checkCall. 5028 // FIXME: Our choice of AST representation here is less than ideal. 5029 ImplicitThis = Args[0]; 5030 ++Args; 5031 --NumArgs; 5032 } else if (IsMemberFunction) 5033 ImplicitThis = 5034 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5035 5036 if (ImplicitThis) { 5037 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5038 // used. 5039 QualType ThisType = ImplicitThis->getType(); 5040 if (!ThisType->isPointerType()) { 5041 assert(!ThisType->isReferenceType()); 5042 ThisType = Context.getPointerType(ThisType); 5043 } 5044 5045 QualType ThisTypeFromDecl = 5046 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5047 5048 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5049 ThisTypeFromDecl); 5050 } 5051 5052 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5053 IsMemberFunction, TheCall->getRParenLoc(), 5054 TheCall->getCallee()->getSourceRange(), CallType); 5055 5056 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5057 // None of the checks below are needed for functions that don't have 5058 // simple names (e.g., C++ conversion functions). 5059 if (!FnInfo) 5060 return false; 5061 5062 CheckTCBEnforcement(TheCall, FDecl); 5063 5064 CheckAbsoluteValueFunction(TheCall, FDecl); 5065 CheckMaxUnsignedZero(TheCall, FDecl); 5066 5067 if (getLangOpts().ObjC) 5068 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5069 5070 unsigned CMId = FDecl->getMemoryFunctionKind(); 5071 5072 // Handle memory setting and copying functions. 5073 switch (CMId) { 5074 case 0: 5075 return false; 5076 case Builtin::BIstrlcpy: // fallthrough 5077 case Builtin::BIstrlcat: 5078 CheckStrlcpycatArguments(TheCall, FnInfo); 5079 break; 5080 case Builtin::BIstrncat: 5081 CheckStrncatArguments(TheCall, FnInfo); 5082 break; 5083 case Builtin::BIfree: 5084 CheckFreeArguments(TheCall); 5085 break; 5086 default: 5087 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5088 } 5089 5090 return false; 5091 } 5092 5093 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5094 ArrayRef<const Expr *> Args) { 5095 VariadicCallType CallType = 5096 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5097 5098 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5099 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5100 CallType); 5101 5102 return false; 5103 } 5104 5105 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5106 const FunctionProtoType *Proto) { 5107 QualType Ty; 5108 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5109 Ty = V->getType().getNonReferenceType(); 5110 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5111 Ty = F->getType().getNonReferenceType(); 5112 else 5113 return false; 5114 5115 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5116 !Ty->isFunctionProtoType()) 5117 return false; 5118 5119 VariadicCallType CallType; 5120 if (!Proto || !Proto->isVariadic()) { 5121 CallType = VariadicDoesNotApply; 5122 } else if (Ty->isBlockPointerType()) { 5123 CallType = VariadicBlock; 5124 } else { // Ty->isFunctionPointerType() 5125 CallType = VariadicFunction; 5126 } 5127 5128 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5129 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5130 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5131 TheCall->getCallee()->getSourceRange(), CallType); 5132 5133 return false; 5134 } 5135 5136 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5137 /// such as function pointers returned from functions. 5138 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5139 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5140 TheCall->getCallee()); 5141 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5142 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5143 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5144 TheCall->getCallee()->getSourceRange(), CallType); 5145 5146 return false; 5147 } 5148 5149 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5150 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5151 return false; 5152 5153 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5154 switch (Op) { 5155 case AtomicExpr::AO__c11_atomic_init: 5156 case AtomicExpr::AO__opencl_atomic_init: 5157 llvm_unreachable("There is no ordering argument for an init"); 5158 5159 case AtomicExpr::AO__c11_atomic_load: 5160 case AtomicExpr::AO__opencl_atomic_load: 5161 case AtomicExpr::AO__atomic_load_n: 5162 case AtomicExpr::AO__atomic_load: 5163 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5164 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5165 5166 case AtomicExpr::AO__c11_atomic_store: 5167 case AtomicExpr::AO__opencl_atomic_store: 5168 case AtomicExpr::AO__atomic_store: 5169 case AtomicExpr::AO__atomic_store_n: 5170 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5171 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5172 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5173 5174 default: 5175 return true; 5176 } 5177 } 5178 5179 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5180 AtomicExpr::AtomicOp Op) { 5181 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5182 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5183 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5184 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5185 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5186 Op); 5187 } 5188 5189 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5190 SourceLocation RParenLoc, MultiExprArg Args, 5191 AtomicExpr::AtomicOp Op, 5192 AtomicArgumentOrder ArgOrder) { 5193 // All the non-OpenCL operations take one of the following forms. 5194 // The OpenCL operations take the __c11 forms with one extra argument for 5195 // synchronization scope. 5196 enum { 5197 // C __c11_atomic_init(A *, C) 5198 Init, 5199 5200 // C __c11_atomic_load(A *, int) 5201 Load, 5202 5203 // void __atomic_load(A *, CP, int) 5204 LoadCopy, 5205 5206 // void __atomic_store(A *, CP, int) 5207 Copy, 5208 5209 // C __c11_atomic_add(A *, M, int) 5210 Arithmetic, 5211 5212 // C __atomic_exchange_n(A *, CP, int) 5213 Xchg, 5214 5215 // void __atomic_exchange(A *, C *, CP, int) 5216 GNUXchg, 5217 5218 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5219 C11CmpXchg, 5220 5221 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5222 GNUCmpXchg 5223 } Form = Init; 5224 5225 const unsigned NumForm = GNUCmpXchg + 1; 5226 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5227 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5228 // where: 5229 // C is an appropriate type, 5230 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5231 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5232 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5233 // the int parameters are for orderings. 5234 5235 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5236 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5237 "need to update code for modified forms"); 5238 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5239 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5240 AtomicExpr::AO__atomic_load, 5241 "need to update code for modified C11 atomics"); 5242 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5243 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5244 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5245 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5246 IsOpenCL; 5247 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5248 Op == AtomicExpr::AO__atomic_store_n || 5249 Op == AtomicExpr::AO__atomic_exchange_n || 5250 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5251 bool IsAddSub = false; 5252 5253 switch (Op) { 5254 case AtomicExpr::AO__c11_atomic_init: 5255 case AtomicExpr::AO__opencl_atomic_init: 5256 Form = Init; 5257 break; 5258 5259 case AtomicExpr::AO__c11_atomic_load: 5260 case AtomicExpr::AO__opencl_atomic_load: 5261 case AtomicExpr::AO__atomic_load_n: 5262 Form = Load; 5263 break; 5264 5265 case AtomicExpr::AO__atomic_load: 5266 Form = LoadCopy; 5267 break; 5268 5269 case AtomicExpr::AO__c11_atomic_store: 5270 case AtomicExpr::AO__opencl_atomic_store: 5271 case AtomicExpr::AO__atomic_store: 5272 case AtomicExpr::AO__atomic_store_n: 5273 Form = Copy; 5274 break; 5275 5276 case AtomicExpr::AO__c11_atomic_fetch_add: 5277 case AtomicExpr::AO__c11_atomic_fetch_sub: 5278 case AtomicExpr::AO__opencl_atomic_fetch_add: 5279 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5280 case AtomicExpr::AO__atomic_fetch_add: 5281 case AtomicExpr::AO__atomic_fetch_sub: 5282 case AtomicExpr::AO__atomic_add_fetch: 5283 case AtomicExpr::AO__atomic_sub_fetch: 5284 IsAddSub = true; 5285 Form = Arithmetic; 5286 break; 5287 case AtomicExpr::AO__c11_atomic_fetch_and: 5288 case AtomicExpr::AO__c11_atomic_fetch_or: 5289 case AtomicExpr::AO__c11_atomic_fetch_xor: 5290 case AtomicExpr::AO__c11_atomic_fetch_nand: 5291 case AtomicExpr::AO__opencl_atomic_fetch_and: 5292 case AtomicExpr::AO__opencl_atomic_fetch_or: 5293 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5294 case AtomicExpr::AO__atomic_fetch_and: 5295 case AtomicExpr::AO__atomic_fetch_or: 5296 case AtomicExpr::AO__atomic_fetch_xor: 5297 case AtomicExpr::AO__atomic_fetch_nand: 5298 case AtomicExpr::AO__atomic_and_fetch: 5299 case AtomicExpr::AO__atomic_or_fetch: 5300 case AtomicExpr::AO__atomic_xor_fetch: 5301 case AtomicExpr::AO__atomic_nand_fetch: 5302 Form = Arithmetic; 5303 break; 5304 case AtomicExpr::AO__c11_atomic_fetch_min: 5305 case AtomicExpr::AO__c11_atomic_fetch_max: 5306 case AtomicExpr::AO__opencl_atomic_fetch_min: 5307 case AtomicExpr::AO__opencl_atomic_fetch_max: 5308 case AtomicExpr::AO__atomic_min_fetch: 5309 case AtomicExpr::AO__atomic_max_fetch: 5310 case AtomicExpr::AO__atomic_fetch_min: 5311 case AtomicExpr::AO__atomic_fetch_max: 5312 Form = Arithmetic; 5313 break; 5314 5315 case AtomicExpr::AO__c11_atomic_exchange: 5316 case AtomicExpr::AO__opencl_atomic_exchange: 5317 case AtomicExpr::AO__atomic_exchange_n: 5318 Form = Xchg; 5319 break; 5320 5321 case AtomicExpr::AO__atomic_exchange: 5322 Form = GNUXchg; 5323 break; 5324 5325 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5326 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5327 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5328 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5329 Form = C11CmpXchg; 5330 break; 5331 5332 case AtomicExpr::AO__atomic_compare_exchange: 5333 case AtomicExpr::AO__atomic_compare_exchange_n: 5334 Form = GNUCmpXchg; 5335 break; 5336 } 5337 5338 unsigned AdjustedNumArgs = NumArgs[Form]; 5339 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5340 ++AdjustedNumArgs; 5341 // Check we have the right number of arguments. 5342 if (Args.size() < AdjustedNumArgs) { 5343 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5344 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5345 << ExprRange; 5346 return ExprError(); 5347 } else if (Args.size() > AdjustedNumArgs) { 5348 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5349 diag::err_typecheck_call_too_many_args) 5350 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5351 << ExprRange; 5352 return ExprError(); 5353 } 5354 5355 // Inspect the first argument of the atomic operation. 5356 Expr *Ptr = Args[0]; 5357 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5358 if (ConvertedPtr.isInvalid()) 5359 return ExprError(); 5360 5361 Ptr = ConvertedPtr.get(); 5362 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5363 if (!pointerType) { 5364 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5365 << Ptr->getType() << Ptr->getSourceRange(); 5366 return ExprError(); 5367 } 5368 5369 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5370 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5371 QualType ValType = AtomTy; // 'C' 5372 if (IsC11) { 5373 if (!AtomTy->isAtomicType()) { 5374 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5375 << Ptr->getType() << Ptr->getSourceRange(); 5376 return ExprError(); 5377 } 5378 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5379 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5380 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5381 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5382 << Ptr->getSourceRange(); 5383 return ExprError(); 5384 } 5385 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5386 } else if (Form != Load && Form != LoadCopy) { 5387 if (ValType.isConstQualified()) { 5388 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5389 << Ptr->getType() << Ptr->getSourceRange(); 5390 return ExprError(); 5391 } 5392 } 5393 5394 // For an arithmetic operation, the implied arithmetic must be well-formed. 5395 if (Form == Arithmetic) { 5396 // gcc does not enforce these rules for GNU atomics, but we do so for 5397 // sanity. 5398 auto IsAllowedValueType = [&](QualType ValType) { 5399 if (ValType->isIntegerType()) 5400 return true; 5401 if (ValType->isPointerType()) 5402 return true; 5403 if (!ValType->isFloatingType()) 5404 return false; 5405 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5406 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5407 &Context.getTargetInfo().getLongDoubleFormat() == 5408 &llvm::APFloat::x87DoubleExtended()) 5409 return false; 5410 return true; 5411 }; 5412 if (IsAddSub && !IsAllowedValueType(ValType)) { 5413 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5414 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5415 return ExprError(); 5416 } 5417 if (!IsAddSub && !ValType->isIntegerType()) { 5418 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5419 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5420 return ExprError(); 5421 } 5422 if (IsC11 && ValType->isPointerType() && 5423 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5424 diag::err_incomplete_type)) { 5425 return ExprError(); 5426 } 5427 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5428 // For __atomic_*_n operations, the value type must be a scalar integral or 5429 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5430 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5431 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5432 return ExprError(); 5433 } 5434 5435 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5436 !AtomTy->isScalarType()) { 5437 // For GNU atomics, require a trivially-copyable type. This is not part of 5438 // the GNU atomics specification, but we enforce it for sanity. 5439 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5440 << Ptr->getType() << Ptr->getSourceRange(); 5441 return ExprError(); 5442 } 5443 5444 switch (ValType.getObjCLifetime()) { 5445 case Qualifiers::OCL_None: 5446 case Qualifiers::OCL_ExplicitNone: 5447 // okay 5448 break; 5449 5450 case Qualifiers::OCL_Weak: 5451 case Qualifiers::OCL_Strong: 5452 case Qualifiers::OCL_Autoreleasing: 5453 // FIXME: Can this happen? By this point, ValType should be known 5454 // to be trivially copyable. 5455 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5456 << ValType << Ptr->getSourceRange(); 5457 return ExprError(); 5458 } 5459 5460 // All atomic operations have an overload which takes a pointer to a volatile 5461 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5462 // into the result or the other operands. Similarly atomic_load takes a 5463 // pointer to a const 'A'. 5464 ValType.removeLocalVolatile(); 5465 ValType.removeLocalConst(); 5466 QualType ResultType = ValType; 5467 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5468 Form == Init) 5469 ResultType = Context.VoidTy; 5470 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5471 ResultType = Context.BoolTy; 5472 5473 // The type of a parameter passed 'by value'. In the GNU atomics, such 5474 // arguments are actually passed as pointers. 5475 QualType ByValType = ValType; // 'CP' 5476 bool IsPassedByAddress = false; 5477 if (!IsC11 && !IsN) { 5478 ByValType = Ptr->getType(); 5479 IsPassedByAddress = true; 5480 } 5481 5482 SmallVector<Expr *, 5> APIOrderedArgs; 5483 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5484 APIOrderedArgs.push_back(Args[0]); 5485 switch (Form) { 5486 case Init: 5487 case Load: 5488 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5489 break; 5490 case LoadCopy: 5491 case Copy: 5492 case Arithmetic: 5493 case Xchg: 5494 APIOrderedArgs.push_back(Args[2]); // Val1 5495 APIOrderedArgs.push_back(Args[1]); // Order 5496 break; 5497 case GNUXchg: 5498 APIOrderedArgs.push_back(Args[2]); // Val1 5499 APIOrderedArgs.push_back(Args[3]); // Val2 5500 APIOrderedArgs.push_back(Args[1]); // Order 5501 break; 5502 case C11CmpXchg: 5503 APIOrderedArgs.push_back(Args[2]); // Val1 5504 APIOrderedArgs.push_back(Args[4]); // Val2 5505 APIOrderedArgs.push_back(Args[1]); // Order 5506 APIOrderedArgs.push_back(Args[3]); // OrderFail 5507 break; 5508 case GNUCmpXchg: 5509 APIOrderedArgs.push_back(Args[2]); // Val1 5510 APIOrderedArgs.push_back(Args[4]); // Val2 5511 APIOrderedArgs.push_back(Args[5]); // Weak 5512 APIOrderedArgs.push_back(Args[1]); // Order 5513 APIOrderedArgs.push_back(Args[3]); // OrderFail 5514 break; 5515 } 5516 } else 5517 APIOrderedArgs.append(Args.begin(), Args.end()); 5518 5519 // The first argument's non-CV pointer type is used to deduce the type of 5520 // subsequent arguments, except for: 5521 // - weak flag (always converted to bool) 5522 // - memory order (always converted to int) 5523 // - scope (always converted to int) 5524 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5525 QualType Ty; 5526 if (i < NumVals[Form] + 1) { 5527 switch (i) { 5528 case 0: 5529 // The first argument is always a pointer. It has a fixed type. 5530 // It is always dereferenced, a nullptr is undefined. 5531 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5532 // Nothing else to do: we already know all we want about this pointer. 5533 continue; 5534 case 1: 5535 // The second argument is the non-atomic operand. For arithmetic, this 5536 // is always passed by value, and for a compare_exchange it is always 5537 // passed by address. For the rest, GNU uses by-address and C11 uses 5538 // by-value. 5539 assert(Form != Load); 5540 if (Form == Arithmetic && ValType->isPointerType()) 5541 Ty = Context.getPointerDiffType(); 5542 else if (Form == Init || Form == Arithmetic) 5543 Ty = ValType; 5544 else if (Form == Copy || Form == Xchg) { 5545 if (IsPassedByAddress) { 5546 // The value pointer is always dereferenced, a nullptr is undefined. 5547 CheckNonNullArgument(*this, APIOrderedArgs[i], 5548 ExprRange.getBegin()); 5549 } 5550 Ty = ByValType; 5551 } else { 5552 Expr *ValArg = APIOrderedArgs[i]; 5553 // The value pointer is always dereferenced, a nullptr is undefined. 5554 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5555 LangAS AS = LangAS::Default; 5556 // Keep address space of non-atomic pointer type. 5557 if (const PointerType *PtrTy = 5558 ValArg->getType()->getAs<PointerType>()) { 5559 AS = PtrTy->getPointeeType().getAddressSpace(); 5560 } 5561 Ty = Context.getPointerType( 5562 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5563 } 5564 break; 5565 case 2: 5566 // The third argument to compare_exchange / GNU exchange is the desired 5567 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5568 if (IsPassedByAddress) 5569 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5570 Ty = ByValType; 5571 break; 5572 case 3: 5573 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5574 Ty = Context.BoolTy; 5575 break; 5576 } 5577 } else { 5578 // The order(s) and scope are always converted to int. 5579 Ty = Context.IntTy; 5580 } 5581 5582 InitializedEntity Entity = 5583 InitializedEntity::InitializeParameter(Context, Ty, false); 5584 ExprResult Arg = APIOrderedArgs[i]; 5585 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5586 if (Arg.isInvalid()) 5587 return true; 5588 APIOrderedArgs[i] = Arg.get(); 5589 } 5590 5591 // Permute the arguments into a 'consistent' order. 5592 SmallVector<Expr*, 5> SubExprs; 5593 SubExprs.push_back(Ptr); 5594 switch (Form) { 5595 case Init: 5596 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5597 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5598 break; 5599 case Load: 5600 SubExprs.push_back(APIOrderedArgs[1]); // Order 5601 break; 5602 case LoadCopy: 5603 case Copy: 5604 case Arithmetic: 5605 case Xchg: 5606 SubExprs.push_back(APIOrderedArgs[2]); // Order 5607 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5608 break; 5609 case GNUXchg: 5610 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5611 SubExprs.push_back(APIOrderedArgs[3]); // Order 5612 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5613 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5614 break; 5615 case C11CmpXchg: 5616 SubExprs.push_back(APIOrderedArgs[3]); // Order 5617 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5618 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5619 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5620 break; 5621 case GNUCmpXchg: 5622 SubExprs.push_back(APIOrderedArgs[4]); // Order 5623 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5624 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5625 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5626 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5627 break; 5628 } 5629 5630 if (SubExprs.size() >= 2 && Form != Init) { 5631 if (Optional<llvm::APSInt> Result = 5632 SubExprs[1]->getIntegerConstantExpr(Context)) 5633 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5634 Diag(SubExprs[1]->getBeginLoc(), 5635 diag::warn_atomic_op_has_invalid_memory_order) 5636 << SubExprs[1]->getSourceRange(); 5637 } 5638 5639 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5640 auto *Scope = Args[Args.size() - 1]; 5641 if (Optional<llvm::APSInt> Result = 5642 Scope->getIntegerConstantExpr(Context)) { 5643 if (!ScopeModel->isValid(Result->getZExtValue())) 5644 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5645 << Scope->getSourceRange(); 5646 } 5647 SubExprs.push_back(Scope); 5648 } 5649 5650 AtomicExpr *AE = new (Context) 5651 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5652 5653 if ((Op == AtomicExpr::AO__c11_atomic_load || 5654 Op == AtomicExpr::AO__c11_atomic_store || 5655 Op == AtomicExpr::AO__opencl_atomic_load || 5656 Op == AtomicExpr::AO__opencl_atomic_store ) && 5657 Context.AtomicUsesUnsupportedLibcall(AE)) 5658 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5659 << ((Op == AtomicExpr::AO__c11_atomic_load || 5660 Op == AtomicExpr::AO__opencl_atomic_load) 5661 ? 0 5662 : 1); 5663 5664 if (ValType->isExtIntType()) { 5665 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5666 return ExprError(); 5667 } 5668 5669 return AE; 5670 } 5671 5672 /// checkBuiltinArgument - Given a call to a builtin function, perform 5673 /// normal type-checking on the given argument, updating the call in 5674 /// place. This is useful when a builtin function requires custom 5675 /// type-checking for some of its arguments but not necessarily all of 5676 /// them. 5677 /// 5678 /// Returns true on error. 5679 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5680 FunctionDecl *Fn = E->getDirectCallee(); 5681 assert(Fn && "builtin call without direct callee!"); 5682 5683 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5684 InitializedEntity Entity = 5685 InitializedEntity::InitializeParameter(S.Context, Param); 5686 5687 ExprResult Arg = E->getArg(0); 5688 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5689 if (Arg.isInvalid()) 5690 return true; 5691 5692 E->setArg(ArgIndex, Arg.get()); 5693 return false; 5694 } 5695 5696 /// We have a call to a function like __sync_fetch_and_add, which is an 5697 /// overloaded function based on the pointer type of its first argument. 5698 /// The main BuildCallExpr routines have already promoted the types of 5699 /// arguments because all of these calls are prototyped as void(...). 5700 /// 5701 /// This function goes through and does final semantic checking for these 5702 /// builtins, as well as generating any warnings. 5703 ExprResult 5704 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5705 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5706 Expr *Callee = TheCall->getCallee(); 5707 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5708 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5709 5710 // Ensure that we have at least one argument to do type inference from. 5711 if (TheCall->getNumArgs() < 1) { 5712 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5713 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5714 return ExprError(); 5715 } 5716 5717 // Inspect the first argument of the atomic builtin. This should always be 5718 // a pointer type, whose element is an integral scalar or pointer type. 5719 // Because it is a pointer type, we don't have to worry about any implicit 5720 // casts here. 5721 // FIXME: We don't allow floating point scalars as input. 5722 Expr *FirstArg = TheCall->getArg(0); 5723 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5724 if (FirstArgResult.isInvalid()) 5725 return ExprError(); 5726 FirstArg = FirstArgResult.get(); 5727 TheCall->setArg(0, FirstArg); 5728 5729 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5730 if (!pointerType) { 5731 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5732 << FirstArg->getType() << FirstArg->getSourceRange(); 5733 return ExprError(); 5734 } 5735 5736 QualType ValType = pointerType->getPointeeType(); 5737 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5738 !ValType->isBlockPointerType()) { 5739 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5740 << FirstArg->getType() << FirstArg->getSourceRange(); 5741 return ExprError(); 5742 } 5743 5744 if (ValType.isConstQualified()) { 5745 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5746 << FirstArg->getType() << FirstArg->getSourceRange(); 5747 return ExprError(); 5748 } 5749 5750 switch (ValType.getObjCLifetime()) { 5751 case Qualifiers::OCL_None: 5752 case Qualifiers::OCL_ExplicitNone: 5753 // okay 5754 break; 5755 5756 case Qualifiers::OCL_Weak: 5757 case Qualifiers::OCL_Strong: 5758 case Qualifiers::OCL_Autoreleasing: 5759 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5760 << ValType << FirstArg->getSourceRange(); 5761 return ExprError(); 5762 } 5763 5764 // Strip any qualifiers off ValType. 5765 ValType = ValType.getUnqualifiedType(); 5766 5767 // The majority of builtins return a value, but a few have special return 5768 // types, so allow them to override appropriately below. 5769 QualType ResultType = ValType; 5770 5771 // We need to figure out which concrete builtin this maps onto. For example, 5772 // __sync_fetch_and_add with a 2 byte object turns into 5773 // __sync_fetch_and_add_2. 5774 #define BUILTIN_ROW(x) \ 5775 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5776 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5777 5778 static const unsigned BuiltinIndices[][5] = { 5779 BUILTIN_ROW(__sync_fetch_and_add), 5780 BUILTIN_ROW(__sync_fetch_and_sub), 5781 BUILTIN_ROW(__sync_fetch_and_or), 5782 BUILTIN_ROW(__sync_fetch_and_and), 5783 BUILTIN_ROW(__sync_fetch_and_xor), 5784 BUILTIN_ROW(__sync_fetch_and_nand), 5785 5786 BUILTIN_ROW(__sync_add_and_fetch), 5787 BUILTIN_ROW(__sync_sub_and_fetch), 5788 BUILTIN_ROW(__sync_and_and_fetch), 5789 BUILTIN_ROW(__sync_or_and_fetch), 5790 BUILTIN_ROW(__sync_xor_and_fetch), 5791 BUILTIN_ROW(__sync_nand_and_fetch), 5792 5793 BUILTIN_ROW(__sync_val_compare_and_swap), 5794 BUILTIN_ROW(__sync_bool_compare_and_swap), 5795 BUILTIN_ROW(__sync_lock_test_and_set), 5796 BUILTIN_ROW(__sync_lock_release), 5797 BUILTIN_ROW(__sync_swap) 5798 }; 5799 #undef BUILTIN_ROW 5800 5801 // Determine the index of the size. 5802 unsigned SizeIndex; 5803 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5804 case 1: SizeIndex = 0; break; 5805 case 2: SizeIndex = 1; break; 5806 case 4: SizeIndex = 2; break; 5807 case 8: SizeIndex = 3; break; 5808 case 16: SizeIndex = 4; break; 5809 default: 5810 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5811 << FirstArg->getType() << FirstArg->getSourceRange(); 5812 return ExprError(); 5813 } 5814 5815 // Each of these builtins has one pointer argument, followed by some number of 5816 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5817 // that we ignore. Find out which row of BuiltinIndices to read from as well 5818 // as the number of fixed args. 5819 unsigned BuiltinID = FDecl->getBuiltinID(); 5820 unsigned BuiltinIndex, NumFixed = 1; 5821 bool WarnAboutSemanticsChange = false; 5822 switch (BuiltinID) { 5823 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5824 case Builtin::BI__sync_fetch_and_add: 5825 case Builtin::BI__sync_fetch_and_add_1: 5826 case Builtin::BI__sync_fetch_and_add_2: 5827 case Builtin::BI__sync_fetch_and_add_4: 5828 case Builtin::BI__sync_fetch_and_add_8: 5829 case Builtin::BI__sync_fetch_and_add_16: 5830 BuiltinIndex = 0; 5831 break; 5832 5833 case Builtin::BI__sync_fetch_and_sub: 5834 case Builtin::BI__sync_fetch_and_sub_1: 5835 case Builtin::BI__sync_fetch_and_sub_2: 5836 case Builtin::BI__sync_fetch_and_sub_4: 5837 case Builtin::BI__sync_fetch_and_sub_8: 5838 case Builtin::BI__sync_fetch_and_sub_16: 5839 BuiltinIndex = 1; 5840 break; 5841 5842 case Builtin::BI__sync_fetch_and_or: 5843 case Builtin::BI__sync_fetch_and_or_1: 5844 case Builtin::BI__sync_fetch_and_or_2: 5845 case Builtin::BI__sync_fetch_and_or_4: 5846 case Builtin::BI__sync_fetch_and_or_8: 5847 case Builtin::BI__sync_fetch_and_or_16: 5848 BuiltinIndex = 2; 5849 break; 5850 5851 case Builtin::BI__sync_fetch_and_and: 5852 case Builtin::BI__sync_fetch_and_and_1: 5853 case Builtin::BI__sync_fetch_and_and_2: 5854 case Builtin::BI__sync_fetch_and_and_4: 5855 case Builtin::BI__sync_fetch_and_and_8: 5856 case Builtin::BI__sync_fetch_and_and_16: 5857 BuiltinIndex = 3; 5858 break; 5859 5860 case Builtin::BI__sync_fetch_and_xor: 5861 case Builtin::BI__sync_fetch_and_xor_1: 5862 case Builtin::BI__sync_fetch_and_xor_2: 5863 case Builtin::BI__sync_fetch_and_xor_4: 5864 case Builtin::BI__sync_fetch_and_xor_8: 5865 case Builtin::BI__sync_fetch_and_xor_16: 5866 BuiltinIndex = 4; 5867 break; 5868 5869 case Builtin::BI__sync_fetch_and_nand: 5870 case Builtin::BI__sync_fetch_and_nand_1: 5871 case Builtin::BI__sync_fetch_and_nand_2: 5872 case Builtin::BI__sync_fetch_and_nand_4: 5873 case Builtin::BI__sync_fetch_and_nand_8: 5874 case Builtin::BI__sync_fetch_and_nand_16: 5875 BuiltinIndex = 5; 5876 WarnAboutSemanticsChange = true; 5877 break; 5878 5879 case Builtin::BI__sync_add_and_fetch: 5880 case Builtin::BI__sync_add_and_fetch_1: 5881 case Builtin::BI__sync_add_and_fetch_2: 5882 case Builtin::BI__sync_add_and_fetch_4: 5883 case Builtin::BI__sync_add_and_fetch_8: 5884 case Builtin::BI__sync_add_and_fetch_16: 5885 BuiltinIndex = 6; 5886 break; 5887 5888 case Builtin::BI__sync_sub_and_fetch: 5889 case Builtin::BI__sync_sub_and_fetch_1: 5890 case Builtin::BI__sync_sub_and_fetch_2: 5891 case Builtin::BI__sync_sub_and_fetch_4: 5892 case Builtin::BI__sync_sub_and_fetch_8: 5893 case Builtin::BI__sync_sub_and_fetch_16: 5894 BuiltinIndex = 7; 5895 break; 5896 5897 case Builtin::BI__sync_and_and_fetch: 5898 case Builtin::BI__sync_and_and_fetch_1: 5899 case Builtin::BI__sync_and_and_fetch_2: 5900 case Builtin::BI__sync_and_and_fetch_4: 5901 case Builtin::BI__sync_and_and_fetch_8: 5902 case Builtin::BI__sync_and_and_fetch_16: 5903 BuiltinIndex = 8; 5904 break; 5905 5906 case Builtin::BI__sync_or_and_fetch: 5907 case Builtin::BI__sync_or_and_fetch_1: 5908 case Builtin::BI__sync_or_and_fetch_2: 5909 case Builtin::BI__sync_or_and_fetch_4: 5910 case Builtin::BI__sync_or_and_fetch_8: 5911 case Builtin::BI__sync_or_and_fetch_16: 5912 BuiltinIndex = 9; 5913 break; 5914 5915 case Builtin::BI__sync_xor_and_fetch: 5916 case Builtin::BI__sync_xor_and_fetch_1: 5917 case Builtin::BI__sync_xor_and_fetch_2: 5918 case Builtin::BI__sync_xor_and_fetch_4: 5919 case Builtin::BI__sync_xor_and_fetch_8: 5920 case Builtin::BI__sync_xor_and_fetch_16: 5921 BuiltinIndex = 10; 5922 break; 5923 5924 case Builtin::BI__sync_nand_and_fetch: 5925 case Builtin::BI__sync_nand_and_fetch_1: 5926 case Builtin::BI__sync_nand_and_fetch_2: 5927 case Builtin::BI__sync_nand_and_fetch_4: 5928 case Builtin::BI__sync_nand_and_fetch_8: 5929 case Builtin::BI__sync_nand_and_fetch_16: 5930 BuiltinIndex = 11; 5931 WarnAboutSemanticsChange = true; 5932 break; 5933 5934 case Builtin::BI__sync_val_compare_and_swap: 5935 case Builtin::BI__sync_val_compare_and_swap_1: 5936 case Builtin::BI__sync_val_compare_and_swap_2: 5937 case Builtin::BI__sync_val_compare_and_swap_4: 5938 case Builtin::BI__sync_val_compare_and_swap_8: 5939 case Builtin::BI__sync_val_compare_and_swap_16: 5940 BuiltinIndex = 12; 5941 NumFixed = 2; 5942 break; 5943 5944 case Builtin::BI__sync_bool_compare_and_swap: 5945 case Builtin::BI__sync_bool_compare_and_swap_1: 5946 case Builtin::BI__sync_bool_compare_and_swap_2: 5947 case Builtin::BI__sync_bool_compare_and_swap_4: 5948 case Builtin::BI__sync_bool_compare_and_swap_8: 5949 case Builtin::BI__sync_bool_compare_and_swap_16: 5950 BuiltinIndex = 13; 5951 NumFixed = 2; 5952 ResultType = Context.BoolTy; 5953 break; 5954 5955 case Builtin::BI__sync_lock_test_and_set: 5956 case Builtin::BI__sync_lock_test_and_set_1: 5957 case Builtin::BI__sync_lock_test_and_set_2: 5958 case Builtin::BI__sync_lock_test_and_set_4: 5959 case Builtin::BI__sync_lock_test_and_set_8: 5960 case Builtin::BI__sync_lock_test_and_set_16: 5961 BuiltinIndex = 14; 5962 break; 5963 5964 case Builtin::BI__sync_lock_release: 5965 case Builtin::BI__sync_lock_release_1: 5966 case Builtin::BI__sync_lock_release_2: 5967 case Builtin::BI__sync_lock_release_4: 5968 case Builtin::BI__sync_lock_release_8: 5969 case Builtin::BI__sync_lock_release_16: 5970 BuiltinIndex = 15; 5971 NumFixed = 0; 5972 ResultType = Context.VoidTy; 5973 break; 5974 5975 case Builtin::BI__sync_swap: 5976 case Builtin::BI__sync_swap_1: 5977 case Builtin::BI__sync_swap_2: 5978 case Builtin::BI__sync_swap_4: 5979 case Builtin::BI__sync_swap_8: 5980 case Builtin::BI__sync_swap_16: 5981 BuiltinIndex = 16; 5982 break; 5983 } 5984 5985 // Now that we know how many fixed arguments we expect, first check that we 5986 // have at least that many. 5987 if (TheCall->getNumArgs() < 1+NumFixed) { 5988 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5989 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5990 << Callee->getSourceRange(); 5991 return ExprError(); 5992 } 5993 5994 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5995 << Callee->getSourceRange(); 5996 5997 if (WarnAboutSemanticsChange) { 5998 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5999 << Callee->getSourceRange(); 6000 } 6001 6002 // Get the decl for the concrete builtin from this, we can tell what the 6003 // concrete integer type we should convert to is. 6004 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6005 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6006 FunctionDecl *NewBuiltinDecl; 6007 if (NewBuiltinID == BuiltinID) 6008 NewBuiltinDecl = FDecl; 6009 else { 6010 // Perform builtin lookup to avoid redeclaring it. 6011 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6012 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6013 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6014 assert(Res.getFoundDecl()); 6015 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6016 if (!NewBuiltinDecl) 6017 return ExprError(); 6018 } 6019 6020 // The first argument --- the pointer --- has a fixed type; we 6021 // deduce the types of the rest of the arguments accordingly. Walk 6022 // the remaining arguments, converting them to the deduced value type. 6023 for (unsigned i = 0; i != NumFixed; ++i) { 6024 ExprResult Arg = TheCall->getArg(i+1); 6025 6026 // GCC does an implicit conversion to the pointer or integer ValType. This 6027 // can fail in some cases (1i -> int**), check for this error case now. 6028 // Initialize the argument. 6029 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6030 ValType, /*consume*/ false); 6031 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6032 if (Arg.isInvalid()) 6033 return ExprError(); 6034 6035 // Okay, we have something that *can* be converted to the right type. Check 6036 // to see if there is a potentially weird extension going on here. This can 6037 // happen when you do an atomic operation on something like an char* and 6038 // pass in 42. The 42 gets converted to char. This is even more strange 6039 // for things like 45.123 -> char, etc. 6040 // FIXME: Do this check. 6041 TheCall->setArg(i+1, Arg.get()); 6042 } 6043 6044 // Create a new DeclRefExpr to refer to the new decl. 6045 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6046 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6047 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6048 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6049 6050 // Set the callee in the CallExpr. 6051 // FIXME: This loses syntactic information. 6052 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6053 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6054 CK_BuiltinFnToFnPtr); 6055 TheCall->setCallee(PromotedCall.get()); 6056 6057 // Change the result type of the call to match the original value type. This 6058 // is arbitrary, but the codegen for these builtins ins design to handle it 6059 // gracefully. 6060 TheCall->setType(ResultType); 6061 6062 // Prohibit use of _ExtInt with atomic builtins. 6063 // The arguments would have already been converted to the first argument's 6064 // type, so only need to check the first argument. 6065 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6066 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6067 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6068 return ExprError(); 6069 } 6070 6071 return TheCallResult; 6072 } 6073 6074 /// SemaBuiltinNontemporalOverloaded - We have a call to 6075 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6076 /// overloaded function based on the pointer type of its last argument. 6077 /// 6078 /// This function goes through and does final semantic checking for these 6079 /// builtins. 6080 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6081 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6082 DeclRefExpr *DRE = 6083 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6084 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6085 unsigned BuiltinID = FDecl->getBuiltinID(); 6086 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6087 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6088 "Unexpected nontemporal load/store builtin!"); 6089 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6090 unsigned numArgs = isStore ? 2 : 1; 6091 6092 // Ensure that we have the proper number of arguments. 6093 if (checkArgCount(*this, TheCall, numArgs)) 6094 return ExprError(); 6095 6096 // Inspect the last argument of the nontemporal builtin. This should always 6097 // be a pointer type, from which we imply the type of the memory access. 6098 // Because it is a pointer type, we don't have to worry about any implicit 6099 // casts here. 6100 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6101 ExprResult PointerArgResult = 6102 DefaultFunctionArrayLvalueConversion(PointerArg); 6103 6104 if (PointerArgResult.isInvalid()) 6105 return ExprError(); 6106 PointerArg = PointerArgResult.get(); 6107 TheCall->setArg(numArgs - 1, PointerArg); 6108 6109 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6110 if (!pointerType) { 6111 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6112 << PointerArg->getType() << PointerArg->getSourceRange(); 6113 return ExprError(); 6114 } 6115 6116 QualType ValType = pointerType->getPointeeType(); 6117 6118 // Strip any qualifiers off ValType. 6119 ValType = ValType.getUnqualifiedType(); 6120 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6121 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6122 !ValType->isVectorType()) { 6123 Diag(DRE->getBeginLoc(), 6124 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6125 << PointerArg->getType() << PointerArg->getSourceRange(); 6126 return ExprError(); 6127 } 6128 6129 if (!isStore) { 6130 TheCall->setType(ValType); 6131 return TheCallResult; 6132 } 6133 6134 ExprResult ValArg = TheCall->getArg(0); 6135 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6136 Context, ValType, /*consume*/ false); 6137 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6138 if (ValArg.isInvalid()) 6139 return ExprError(); 6140 6141 TheCall->setArg(0, ValArg.get()); 6142 TheCall->setType(Context.VoidTy); 6143 return TheCallResult; 6144 } 6145 6146 /// CheckObjCString - Checks that the argument to the builtin 6147 /// CFString constructor is correct 6148 /// Note: It might also make sense to do the UTF-16 conversion here (would 6149 /// simplify the backend). 6150 bool Sema::CheckObjCString(Expr *Arg) { 6151 Arg = Arg->IgnoreParenCasts(); 6152 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6153 6154 if (!Literal || !Literal->isAscii()) { 6155 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6156 << Arg->getSourceRange(); 6157 return true; 6158 } 6159 6160 if (Literal->containsNonAsciiOrNull()) { 6161 StringRef String = Literal->getString(); 6162 unsigned NumBytes = String.size(); 6163 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6164 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6165 llvm::UTF16 *ToPtr = &ToBuf[0]; 6166 6167 llvm::ConversionResult Result = 6168 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6169 ToPtr + NumBytes, llvm::strictConversion); 6170 // Check for conversion failure. 6171 if (Result != llvm::conversionOK) 6172 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6173 << Arg->getSourceRange(); 6174 } 6175 return false; 6176 } 6177 6178 /// CheckObjCString - Checks that the format string argument to the os_log() 6179 /// and os_trace() functions is correct, and converts it to const char *. 6180 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6181 Arg = Arg->IgnoreParenCasts(); 6182 auto *Literal = dyn_cast<StringLiteral>(Arg); 6183 if (!Literal) { 6184 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6185 Literal = ObjcLiteral->getString(); 6186 } 6187 } 6188 6189 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6190 return ExprError( 6191 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6192 << Arg->getSourceRange()); 6193 } 6194 6195 ExprResult Result(Literal); 6196 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6197 InitializedEntity Entity = 6198 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6199 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6200 return Result; 6201 } 6202 6203 /// Check that the user is calling the appropriate va_start builtin for the 6204 /// target and calling convention. 6205 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6206 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6207 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6208 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6209 TT.getArch() == llvm::Triple::aarch64_32); 6210 bool IsWindows = TT.isOSWindows(); 6211 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6212 if (IsX64 || IsAArch64) { 6213 CallingConv CC = CC_C; 6214 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6215 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6216 if (IsMSVAStart) { 6217 // Don't allow this in System V ABI functions. 6218 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6219 return S.Diag(Fn->getBeginLoc(), 6220 diag::err_ms_va_start_used_in_sysv_function); 6221 } else { 6222 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6223 // On x64 Windows, don't allow this in System V ABI functions. 6224 // (Yes, that means there's no corresponding way to support variadic 6225 // System V ABI functions on Windows.) 6226 if ((IsWindows && CC == CC_X86_64SysV) || 6227 (!IsWindows && CC == CC_Win64)) 6228 return S.Diag(Fn->getBeginLoc(), 6229 diag::err_va_start_used_in_wrong_abi_function) 6230 << !IsWindows; 6231 } 6232 return false; 6233 } 6234 6235 if (IsMSVAStart) 6236 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6237 return false; 6238 } 6239 6240 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6241 ParmVarDecl **LastParam = nullptr) { 6242 // Determine whether the current function, block, or obj-c method is variadic 6243 // and get its parameter list. 6244 bool IsVariadic = false; 6245 ArrayRef<ParmVarDecl *> Params; 6246 DeclContext *Caller = S.CurContext; 6247 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6248 IsVariadic = Block->isVariadic(); 6249 Params = Block->parameters(); 6250 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6251 IsVariadic = FD->isVariadic(); 6252 Params = FD->parameters(); 6253 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6254 IsVariadic = MD->isVariadic(); 6255 // FIXME: This isn't correct for methods (results in bogus warning). 6256 Params = MD->parameters(); 6257 } else if (isa<CapturedDecl>(Caller)) { 6258 // We don't support va_start in a CapturedDecl. 6259 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6260 return true; 6261 } else { 6262 // This must be some other declcontext that parses exprs. 6263 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6264 return true; 6265 } 6266 6267 if (!IsVariadic) { 6268 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6269 return true; 6270 } 6271 6272 if (LastParam) 6273 *LastParam = Params.empty() ? nullptr : Params.back(); 6274 6275 return false; 6276 } 6277 6278 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6279 /// for validity. Emit an error and return true on failure; return false 6280 /// on success. 6281 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6282 Expr *Fn = TheCall->getCallee(); 6283 6284 if (checkVAStartABI(*this, BuiltinID, Fn)) 6285 return true; 6286 6287 if (checkArgCount(*this, TheCall, 2)) 6288 return true; 6289 6290 // Type-check the first argument normally. 6291 if (checkBuiltinArgument(*this, TheCall, 0)) 6292 return true; 6293 6294 // Check that the current function is variadic, and get its last parameter. 6295 ParmVarDecl *LastParam; 6296 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6297 return true; 6298 6299 // Verify that the second argument to the builtin is the last argument of the 6300 // current function or method. 6301 bool SecondArgIsLastNamedArgument = false; 6302 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6303 6304 // These are valid if SecondArgIsLastNamedArgument is false after the next 6305 // block. 6306 QualType Type; 6307 SourceLocation ParamLoc; 6308 bool IsCRegister = false; 6309 6310 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6311 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6312 SecondArgIsLastNamedArgument = PV == LastParam; 6313 6314 Type = PV->getType(); 6315 ParamLoc = PV->getLocation(); 6316 IsCRegister = 6317 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6318 } 6319 } 6320 6321 if (!SecondArgIsLastNamedArgument) 6322 Diag(TheCall->getArg(1)->getBeginLoc(), 6323 diag::warn_second_arg_of_va_start_not_last_named_param); 6324 else if (IsCRegister || Type->isReferenceType() || 6325 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6326 // Promotable integers are UB, but enumerations need a bit of 6327 // extra checking to see what their promotable type actually is. 6328 if (!Type->isPromotableIntegerType()) 6329 return false; 6330 if (!Type->isEnumeralType()) 6331 return true; 6332 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6333 return !(ED && 6334 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6335 }()) { 6336 unsigned Reason = 0; 6337 if (Type->isReferenceType()) Reason = 1; 6338 else if (IsCRegister) Reason = 2; 6339 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6340 Diag(ParamLoc, diag::note_parameter_type) << Type; 6341 } 6342 6343 TheCall->setType(Context.VoidTy); 6344 return false; 6345 } 6346 6347 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6348 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6349 const LangOptions &LO = getLangOpts(); 6350 6351 if (LO.CPlusPlus) 6352 return Arg->getType() 6353 .getCanonicalType() 6354 .getTypePtr() 6355 ->getPointeeType() 6356 .withoutLocalFastQualifiers() == Context.CharTy; 6357 6358 // In C, allow aliasing through `char *`, this is required for AArch64 at 6359 // least. 6360 return true; 6361 }; 6362 6363 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6364 // const char *named_addr); 6365 6366 Expr *Func = Call->getCallee(); 6367 6368 if (Call->getNumArgs() < 3) 6369 return Diag(Call->getEndLoc(), 6370 diag::err_typecheck_call_too_few_args_at_least) 6371 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6372 6373 // Type-check the first argument normally. 6374 if (checkBuiltinArgument(*this, Call, 0)) 6375 return true; 6376 6377 // Check that the current function is variadic. 6378 if (checkVAStartIsInVariadicFunction(*this, Func)) 6379 return true; 6380 6381 // __va_start on Windows does not validate the parameter qualifiers 6382 6383 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6384 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6385 6386 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6387 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6388 6389 const QualType &ConstCharPtrTy = 6390 Context.getPointerType(Context.CharTy.withConst()); 6391 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6392 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6393 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6394 << 0 /* qualifier difference */ 6395 << 3 /* parameter mismatch */ 6396 << 2 << Arg1->getType() << ConstCharPtrTy; 6397 6398 const QualType SizeTy = Context.getSizeType(); 6399 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6400 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6401 << Arg2->getType() << SizeTy << 1 /* different class */ 6402 << 0 /* qualifier difference */ 6403 << 3 /* parameter mismatch */ 6404 << 3 << Arg2->getType() << SizeTy; 6405 6406 return false; 6407 } 6408 6409 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6410 /// friends. This is declared to take (...), so we have to check everything. 6411 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6412 if (checkArgCount(*this, TheCall, 2)) 6413 return true; 6414 6415 ExprResult OrigArg0 = TheCall->getArg(0); 6416 ExprResult OrigArg1 = TheCall->getArg(1); 6417 6418 // Do standard promotions between the two arguments, returning their common 6419 // type. 6420 QualType Res = UsualArithmeticConversions( 6421 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6422 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6423 return true; 6424 6425 // Make sure any conversions are pushed back into the call; this is 6426 // type safe since unordered compare builtins are declared as "_Bool 6427 // foo(...)". 6428 TheCall->setArg(0, OrigArg0.get()); 6429 TheCall->setArg(1, OrigArg1.get()); 6430 6431 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6432 return false; 6433 6434 // If the common type isn't a real floating type, then the arguments were 6435 // invalid for this operation. 6436 if (Res.isNull() || !Res->isRealFloatingType()) 6437 return Diag(OrigArg0.get()->getBeginLoc(), 6438 diag::err_typecheck_call_invalid_ordered_compare) 6439 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6440 << SourceRange(OrigArg0.get()->getBeginLoc(), 6441 OrigArg1.get()->getEndLoc()); 6442 6443 return false; 6444 } 6445 6446 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6447 /// __builtin_isnan and friends. This is declared to take (...), so we have 6448 /// to check everything. We expect the last argument to be a floating point 6449 /// value. 6450 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6451 if (checkArgCount(*this, TheCall, NumArgs)) 6452 return true; 6453 6454 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6455 // on all preceding parameters just being int. Try all of those. 6456 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6457 Expr *Arg = TheCall->getArg(i); 6458 6459 if (Arg->isTypeDependent()) 6460 return false; 6461 6462 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6463 6464 if (Res.isInvalid()) 6465 return true; 6466 TheCall->setArg(i, Res.get()); 6467 } 6468 6469 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6470 6471 if (OrigArg->isTypeDependent()) 6472 return false; 6473 6474 // Usual Unary Conversions will convert half to float, which we want for 6475 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6476 // type how it is, but do normal L->Rvalue conversions. 6477 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6478 OrigArg = UsualUnaryConversions(OrigArg).get(); 6479 else 6480 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6481 TheCall->setArg(NumArgs - 1, OrigArg); 6482 6483 // This operation requires a non-_Complex floating-point number. 6484 if (!OrigArg->getType()->isRealFloatingType()) 6485 return Diag(OrigArg->getBeginLoc(), 6486 diag::err_typecheck_call_invalid_unary_fp) 6487 << OrigArg->getType() << OrigArg->getSourceRange(); 6488 6489 return false; 6490 } 6491 6492 /// Perform semantic analysis for a call to __builtin_complex. 6493 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6494 if (checkArgCount(*this, TheCall, 2)) 6495 return true; 6496 6497 bool Dependent = false; 6498 for (unsigned I = 0; I != 2; ++I) { 6499 Expr *Arg = TheCall->getArg(I); 6500 QualType T = Arg->getType(); 6501 if (T->isDependentType()) { 6502 Dependent = true; 6503 continue; 6504 } 6505 6506 // Despite supporting _Complex int, GCC requires a real floating point type 6507 // for the operands of __builtin_complex. 6508 if (!T->isRealFloatingType()) { 6509 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6510 << Arg->getType() << Arg->getSourceRange(); 6511 } 6512 6513 ExprResult Converted = DefaultLvalueConversion(Arg); 6514 if (Converted.isInvalid()) 6515 return true; 6516 TheCall->setArg(I, Converted.get()); 6517 } 6518 6519 if (Dependent) { 6520 TheCall->setType(Context.DependentTy); 6521 return false; 6522 } 6523 6524 Expr *Real = TheCall->getArg(0); 6525 Expr *Imag = TheCall->getArg(1); 6526 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6527 return Diag(Real->getBeginLoc(), 6528 diag::err_typecheck_call_different_arg_types) 6529 << Real->getType() << Imag->getType() 6530 << Real->getSourceRange() << Imag->getSourceRange(); 6531 } 6532 6533 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6534 // don't allow this builtin to form those types either. 6535 // FIXME: Should we allow these types? 6536 if (Real->getType()->isFloat16Type()) 6537 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6538 << "_Float16"; 6539 if (Real->getType()->isHalfType()) 6540 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6541 << "half"; 6542 6543 TheCall->setType(Context.getComplexType(Real->getType())); 6544 return false; 6545 } 6546 6547 // Customized Sema Checking for VSX builtins that have the following signature: 6548 // vector [...] builtinName(vector [...], vector [...], const int); 6549 // Which takes the same type of vectors (any legal vector type) for the first 6550 // two arguments and takes compile time constant for the third argument. 6551 // Example builtins are : 6552 // vector double vec_xxpermdi(vector double, vector double, int); 6553 // vector short vec_xxsldwi(vector short, vector short, int); 6554 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6555 unsigned ExpectedNumArgs = 3; 6556 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6557 return true; 6558 6559 // Check the third argument is a compile time constant 6560 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6561 return Diag(TheCall->getBeginLoc(), 6562 diag::err_vsx_builtin_nonconstant_argument) 6563 << 3 /* argument index */ << TheCall->getDirectCallee() 6564 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6565 TheCall->getArg(2)->getEndLoc()); 6566 6567 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6568 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6569 6570 // Check the type of argument 1 and argument 2 are vectors. 6571 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6572 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6573 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6574 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6575 << TheCall->getDirectCallee() 6576 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6577 TheCall->getArg(1)->getEndLoc()); 6578 } 6579 6580 // Check the first two arguments are the same type. 6581 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6582 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6583 << TheCall->getDirectCallee() 6584 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6585 TheCall->getArg(1)->getEndLoc()); 6586 } 6587 6588 // When default clang type checking is turned off and the customized type 6589 // checking is used, the returning type of the function must be explicitly 6590 // set. Otherwise it is _Bool by default. 6591 TheCall->setType(Arg1Ty); 6592 6593 return false; 6594 } 6595 6596 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6597 // This is declared to take (...), so we have to check everything. 6598 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6599 if (TheCall->getNumArgs() < 2) 6600 return ExprError(Diag(TheCall->getEndLoc(), 6601 diag::err_typecheck_call_too_few_args_at_least) 6602 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6603 << TheCall->getSourceRange()); 6604 6605 // Determine which of the following types of shufflevector we're checking: 6606 // 1) unary, vector mask: (lhs, mask) 6607 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6608 QualType resType = TheCall->getArg(0)->getType(); 6609 unsigned numElements = 0; 6610 6611 if (!TheCall->getArg(0)->isTypeDependent() && 6612 !TheCall->getArg(1)->isTypeDependent()) { 6613 QualType LHSType = TheCall->getArg(0)->getType(); 6614 QualType RHSType = TheCall->getArg(1)->getType(); 6615 6616 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6617 return ExprError( 6618 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6619 << TheCall->getDirectCallee() 6620 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6621 TheCall->getArg(1)->getEndLoc())); 6622 6623 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6624 unsigned numResElements = TheCall->getNumArgs() - 2; 6625 6626 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6627 // with mask. If so, verify that RHS is an integer vector type with the 6628 // same number of elts as lhs. 6629 if (TheCall->getNumArgs() == 2) { 6630 if (!RHSType->hasIntegerRepresentation() || 6631 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6632 return ExprError(Diag(TheCall->getBeginLoc(), 6633 diag::err_vec_builtin_incompatible_vector) 6634 << TheCall->getDirectCallee() 6635 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6636 TheCall->getArg(1)->getEndLoc())); 6637 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6638 return ExprError(Diag(TheCall->getBeginLoc(), 6639 diag::err_vec_builtin_incompatible_vector) 6640 << TheCall->getDirectCallee() 6641 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6642 TheCall->getArg(1)->getEndLoc())); 6643 } else if (numElements != numResElements) { 6644 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6645 resType = Context.getVectorType(eltType, numResElements, 6646 VectorType::GenericVector); 6647 } 6648 } 6649 6650 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6651 if (TheCall->getArg(i)->isTypeDependent() || 6652 TheCall->getArg(i)->isValueDependent()) 6653 continue; 6654 6655 Optional<llvm::APSInt> Result; 6656 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6657 return ExprError(Diag(TheCall->getBeginLoc(), 6658 diag::err_shufflevector_nonconstant_argument) 6659 << TheCall->getArg(i)->getSourceRange()); 6660 6661 // Allow -1 which will be translated to undef in the IR. 6662 if (Result->isSigned() && Result->isAllOnes()) 6663 continue; 6664 6665 if (Result->getActiveBits() > 64 || 6666 Result->getZExtValue() >= numElements * 2) 6667 return ExprError(Diag(TheCall->getBeginLoc(), 6668 diag::err_shufflevector_argument_too_large) 6669 << TheCall->getArg(i)->getSourceRange()); 6670 } 6671 6672 SmallVector<Expr*, 32> exprs; 6673 6674 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6675 exprs.push_back(TheCall->getArg(i)); 6676 TheCall->setArg(i, nullptr); 6677 } 6678 6679 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6680 TheCall->getCallee()->getBeginLoc(), 6681 TheCall->getRParenLoc()); 6682 } 6683 6684 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6685 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6686 SourceLocation BuiltinLoc, 6687 SourceLocation RParenLoc) { 6688 ExprValueKind VK = VK_PRValue; 6689 ExprObjectKind OK = OK_Ordinary; 6690 QualType DstTy = TInfo->getType(); 6691 QualType SrcTy = E->getType(); 6692 6693 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6694 return ExprError(Diag(BuiltinLoc, 6695 diag::err_convertvector_non_vector) 6696 << E->getSourceRange()); 6697 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6698 return ExprError(Diag(BuiltinLoc, 6699 diag::err_convertvector_non_vector_type)); 6700 6701 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6702 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6703 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6704 if (SrcElts != DstElts) 6705 return ExprError(Diag(BuiltinLoc, 6706 diag::err_convertvector_incompatible_vector) 6707 << E->getSourceRange()); 6708 } 6709 6710 return new (Context) 6711 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6712 } 6713 6714 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6715 // This is declared to take (const void*, ...) and can take two 6716 // optional constant int args. 6717 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6718 unsigned NumArgs = TheCall->getNumArgs(); 6719 6720 if (NumArgs > 3) 6721 return Diag(TheCall->getEndLoc(), 6722 diag::err_typecheck_call_too_many_args_at_most) 6723 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6724 6725 // Argument 0 is checked for us and the remaining arguments must be 6726 // constant integers. 6727 for (unsigned i = 1; i != NumArgs; ++i) 6728 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6729 return true; 6730 6731 return false; 6732 } 6733 6734 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6735 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6736 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6737 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6738 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6739 if (checkArgCount(*this, TheCall, 1)) 6740 return true; 6741 Expr *Arg = TheCall->getArg(0); 6742 if (Arg->isInstantiationDependent()) 6743 return false; 6744 6745 QualType ArgTy = Arg->getType(); 6746 if (!ArgTy->hasFloatingRepresentation()) 6747 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6748 << ArgTy; 6749 if (Arg->isLValue()) { 6750 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6751 TheCall->setArg(0, FirstArg.get()); 6752 } 6753 TheCall->setType(TheCall->getArg(0)->getType()); 6754 return false; 6755 } 6756 6757 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6758 // __assume does not evaluate its arguments, and should warn if its argument 6759 // has side effects. 6760 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6761 Expr *Arg = TheCall->getArg(0); 6762 if (Arg->isInstantiationDependent()) return false; 6763 6764 if (Arg->HasSideEffects(Context)) 6765 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6766 << Arg->getSourceRange() 6767 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6768 6769 return false; 6770 } 6771 6772 /// Handle __builtin_alloca_with_align. This is declared 6773 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6774 /// than 8. 6775 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6776 // The alignment must be a constant integer. 6777 Expr *Arg = TheCall->getArg(1); 6778 6779 // We can't check the value of a dependent argument. 6780 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6781 if (const auto *UE = 6782 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6783 if (UE->getKind() == UETT_AlignOf || 6784 UE->getKind() == UETT_PreferredAlignOf) 6785 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6786 << Arg->getSourceRange(); 6787 6788 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6789 6790 if (!Result.isPowerOf2()) 6791 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6792 << Arg->getSourceRange(); 6793 6794 if (Result < Context.getCharWidth()) 6795 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6796 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6797 6798 if (Result > std::numeric_limits<int32_t>::max()) 6799 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6800 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6801 } 6802 6803 return false; 6804 } 6805 6806 /// Handle __builtin_assume_aligned. This is declared 6807 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6808 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6809 unsigned NumArgs = TheCall->getNumArgs(); 6810 6811 if (NumArgs > 3) 6812 return Diag(TheCall->getEndLoc(), 6813 diag::err_typecheck_call_too_many_args_at_most) 6814 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6815 6816 // The alignment must be a constant integer. 6817 Expr *Arg = TheCall->getArg(1); 6818 6819 // We can't check the value of a dependent argument. 6820 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6821 llvm::APSInt Result; 6822 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6823 return true; 6824 6825 if (!Result.isPowerOf2()) 6826 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6827 << Arg->getSourceRange(); 6828 6829 if (Result > Sema::MaximumAlignment) 6830 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6831 << Arg->getSourceRange() << Sema::MaximumAlignment; 6832 } 6833 6834 if (NumArgs > 2) { 6835 ExprResult Arg(TheCall->getArg(2)); 6836 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6837 Context.getSizeType(), false); 6838 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6839 if (Arg.isInvalid()) return true; 6840 TheCall->setArg(2, Arg.get()); 6841 } 6842 6843 return false; 6844 } 6845 6846 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6847 unsigned BuiltinID = 6848 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6849 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6850 6851 unsigned NumArgs = TheCall->getNumArgs(); 6852 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6853 if (NumArgs < NumRequiredArgs) { 6854 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6855 << 0 /* function call */ << NumRequiredArgs << NumArgs 6856 << TheCall->getSourceRange(); 6857 } 6858 if (NumArgs >= NumRequiredArgs + 0x100) { 6859 return Diag(TheCall->getEndLoc(), 6860 diag::err_typecheck_call_too_many_args_at_most) 6861 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6862 << TheCall->getSourceRange(); 6863 } 6864 unsigned i = 0; 6865 6866 // For formatting call, check buffer arg. 6867 if (!IsSizeCall) { 6868 ExprResult Arg(TheCall->getArg(i)); 6869 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6870 Context, Context.VoidPtrTy, false); 6871 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6872 if (Arg.isInvalid()) 6873 return true; 6874 TheCall->setArg(i, Arg.get()); 6875 i++; 6876 } 6877 6878 // Check string literal arg. 6879 unsigned FormatIdx = i; 6880 { 6881 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6882 if (Arg.isInvalid()) 6883 return true; 6884 TheCall->setArg(i, Arg.get()); 6885 i++; 6886 } 6887 6888 // Make sure variadic args are scalar. 6889 unsigned FirstDataArg = i; 6890 while (i < NumArgs) { 6891 ExprResult Arg = DefaultVariadicArgumentPromotion( 6892 TheCall->getArg(i), VariadicFunction, nullptr); 6893 if (Arg.isInvalid()) 6894 return true; 6895 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6896 if (ArgSize.getQuantity() >= 0x100) { 6897 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6898 << i << (int)ArgSize.getQuantity() << 0xff 6899 << TheCall->getSourceRange(); 6900 } 6901 TheCall->setArg(i, Arg.get()); 6902 i++; 6903 } 6904 6905 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6906 // call to avoid duplicate diagnostics. 6907 if (!IsSizeCall) { 6908 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6909 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6910 bool Success = CheckFormatArguments( 6911 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6912 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6913 CheckedVarArgs); 6914 if (!Success) 6915 return true; 6916 } 6917 6918 if (IsSizeCall) { 6919 TheCall->setType(Context.getSizeType()); 6920 } else { 6921 TheCall->setType(Context.VoidPtrTy); 6922 } 6923 return false; 6924 } 6925 6926 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6927 /// TheCall is a constant expression. 6928 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6929 llvm::APSInt &Result) { 6930 Expr *Arg = TheCall->getArg(ArgNum); 6931 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6932 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6933 6934 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6935 6936 Optional<llvm::APSInt> R; 6937 if (!(R = Arg->getIntegerConstantExpr(Context))) 6938 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6939 << FDecl->getDeclName() << Arg->getSourceRange(); 6940 Result = *R; 6941 return false; 6942 } 6943 6944 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6945 /// TheCall is a constant expression in the range [Low, High]. 6946 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6947 int Low, int High, bool RangeIsError) { 6948 if (isConstantEvaluated()) 6949 return false; 6950 llvm::APSInt Result; 6951 6952 // We can't check the value of a dependent argument. 6953 Expr *Arg = TheCall->getArg(ArgNum); 6954 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6955 return false; 6956 6957 // Check constant-ness first. 6958 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6959 return true; 6960 6961 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6962 if (RangeIsError) 6963 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6964 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 6965 else 6966 // Defer the warning until we know if the code will be emitted so that 6967 // dead code can ignore this. 6968 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6969 PDiag(diag::warn_argument_invalid_range) 6970 << toString(Result, 10) << Low << High 6971 << Arg->getSourceRange()); 6972 } 6973 6974 return false; 6975 } 6976 6977 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6978 /// TheCall is a constant expression is a multiple of Num.. 6979 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6980 unsigned Num) { 6981 llvm::APSInt Result; 6982 6983 // We can't check the value of a dependent argument. 6984 Expr *Arg = TheCall->getArg(ArgNum); 6985 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6986 return false; 6987 6988 // Check constant-ness first. 6989 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6990 return true; 6991 6992 if (Result.getSExtValue() % Num != 0) 6993 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6994 << Num << Arg->getSourceRange(); 6995 6996 return false; 6997 } 6998 6999 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7000 /// constant expression representing a power of 2. 7001 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7002 llvm::APSInt Result; 7003 7004 // We can't check the value of a dependent argument. 7005 Expr *Arg = TheCall->getArg(ArgNum); 7006 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7007 return false; 7008 7009 // Check constant-ness first. 7010 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7011 return true; 7012 7013 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7014 // and only if x is a power of 2. 7015 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7016 return false; 7017 7018 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7019 << Arg->getSourceRange(); 7020 } 7021 7022 static bool IsShiftedByte(llvm::APSInt Value) { 7023 if (Value.isNegative()) 7024 return false; 7025 7026 // Check if it's a shifted byte, by shifting it down 7027 while (true) { 7028 // If the value fits in the bottom byte, the check passes. 7029 if (Value < 0x100) 7030 return true; 7031 7032 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7033 // fails. 7034 if ((Value & 0xFF) != 0) 7035 return false; 7036 7037 // If the bottom 8 bits are all 0, but something above that is nonzero, 7038 // then shifting the value right by 8 bits won't affect whether it's a 7039 // shifted byte or not. So do that, and go round again. 7040 Value >>= 8; 7041 } 7042 } 7043 7044 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7045 /// a constant expression representing an arbitrary byte value shifted left by 7046 /// a multiple of 8 bits. 7047 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7048 unsigned ArgBits) { 7049 llvm::APSInt Result; 7050 7051 // We can't check the value of a dependent argument. 7052 Expr *Arg = TheCall->getArg(ArgNum); 7053 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7054 return false; 7055 7056 // Check constant-ness first. 7057 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7058 return true; 7059 7060 // Truncate to the given size. 7061 Result = Result.getLoBits(ArgBits); 7062 Result.setIsUnsigned(true); 7063 7064 if (IsShiftedByte(Result)) 7065 return false; 7066 7067 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7068 << Arg->getSourceRange(); 7069 } 7070 7071 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7072 /// TheCall is a constant expression representing either a shifted byte value, 7073 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7074 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7075 /// Arm MVE intrinsics. 7076 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7077 int ArgNum, 7078 unsigned ArgBits) { 7079 llvm::APSInt Result; 7080 7081 // We can't check the value of a dependent argument. 7082 Expr *Arg = TheCall->getArg(ArgNum); 7083 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7084 return false; 7085 7086 // Check constant-ness first. 7087 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7088 return true; 7089 7090 // Truncate to the given size. 7091 Result = Result.getLoBits(ArgBits); 7092 Result.setIsUnsigned(true); 7093 7094 // Check to see if it's in either of the required forms. 7095 if (IsShiftedByte(Result) || 7096 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7097 return false; 7098 7099 return Diag(TheCall->getBeginLoc(), 7100 diag::err_argument_not_shifted_byte_or_xxff) 7101 << Arg->getSourceRange(); 7102 } 7103 7104 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7105 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7106 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7107 if (checkArgCount(*this, TheCall, 2)) 7108 return true; 7109 Expr *Arg0 = TheCall->getArg(0); 7110 Expr *Arg1 = TheCall->getArg(1); 7111 7112 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7113 if (FirstArg.isInvalid()) 7114 return true; 7115 QualType FirstArgType = FirstArg.get()->getType(); 7116 if (!FirstArgType->isAnyPointerType()) 7117 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7118 << "first" << FirstArgType << Arg0->getSourceRange(); 7119 TheCall->setArg(0, FirstArg.get()); 7120 7121 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7122 if (SecArg.isInvalid()) 7123 return true; 7124 QualType SecArgType = SecArg.get()->getType(); 7125 if (!SecArgType->isIntegerType()) 7126 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7127 << "second" << SecArgType << Arg1->getSourceRange(); 7128 7129 // Derive the return type from the pointer argument. 7130 TheCall->setType(FirstArgType); 7131 return false; 7132 } 7133 7134 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7135 if (checkArgCount(*this, TheCall, 2)) 7136 return true; 7137 7138 Expr *Arg0 = TheCall->getArg(0); 7139 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7140 if (FirstArg.isInvalid()) 7141 return true; 7142 QualType FirstArgType = FirstArg.get()->getType(); 7143 if (!FirstArgType->isAnyPointerType()) 7144 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7145 << "first" << FirstArgType << Arg0->getSourceRange(); 7146 TheCall->setArg(0, FirstArg.get()); 7147 7148 // Derive the return type from the pointer argument. 7149 TheCall->setType(FirstArgType); 7150 7151 // Second arg must be an constant in range [0,15] 7152 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7153 } 7154 7155 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7156 if (checkArgCount(*this, TheCall, 2)) 7157 return true; 7158 Expr *Arg0 = TheCall->getArg(0); 7159 Expr *Arg1 = TheCall->getArg(1); 7160 7161 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7162 if (FirstArg.isInvalid()) 7163 return true; 7164 QualType FirstArgType = FirstArg.get()->getType(); 7165 if (!FirstArgType->isAnyPointerType()) 7166 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7167 << "first" << FirstArgType << Arg0->getSourceRange(); 7168 7169 QualType SecArgType = Arg1->getType(); 7170 if (!SecArgType->isIntegerType()) 7171 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7172 << "second" << SecArgType << Arg1->getSourceRange(); 7173 TheCall->setType(Context.IntTy); 7174 return false; 7175 } 7176 7177 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7178 BuiltinID == AArch64::BI__builtin_arm_stg) { 7179 if (checkArgCount(*this, TheCall, 1)) 7180 return true; 7181 Expr *Arg0 = TheCall->getArg(0); 7182 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7183 if (FirstArg.isInvalid()) 7184 return true; 7185 7186 QualType FirstArgType = FirstArg.get()->getType(); 7187 if (!FirstArgType->isAnyPointerType()) 7188 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7189 << "first" << FirstArgType << Arg0->getSourceRange(); 7190 TheCall->setArg(0, FirstArg.get()); 7191 7192 // Derive the return type from the pointer argument. 7193 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7194 TheCall->setType(FirstArgType); 7195 return false; 7196 } 7197 7198 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7199 Expr *ArgA = TheCall->getArg(0); 7200 Expr *ArgB = TheCall->getArg(1); 7201 7202 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7203 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7204 7205 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7206 return true; 7207 7208 QualType ArgTypeA = ArgExprA.get()->getType(); 7209 QualType ArgTypeB = ArgExprB.get()->getType(); 7210 7211 auto isNull = [&] (Expr *E) -> bool { 7212 return E->isNullPointerConstant( 7213 Context, Expr::NPC_ValueDependentIsNotNull); }; 7214 7215 // argument should be either a pointer or null 7216 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7217 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7218 << "first" << ArgTypeA << ArgA->getSourceRange(); 7219 7220 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7221 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7222 << "second" << ArgTypeB << ArgB->getSourceRange(); 7223 7224 // Ensure Pointee types are compatible 7225 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7226 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7227 QualType pointeeA = ArgTypeA->getPointeeType(); 7228 QualType pointeeB = ArgTypeB->getPointeeType(); 7229 if (!Context.typesAreCompatible( 7230 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7231 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7232 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7233 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7234 << ArgB->getSourceRange(); 7235 } 7236 } 7237 7238 // at least one argument should be pointer type 7239 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7240 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7241 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7242 7243 if (isNull(ArgA)) // adopt type of the other pointer 7244 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7245 7246 if (isNull(ArgB)) 7247 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7248 7249 TheCall->setArg(0, ArgExprA.get()); 7250 TheCall->setArg(1, ArgExprB.get()); 7251 TheCall->setType(Context.LongLongTy); 7252 return false; 7253 } 7254 assert(false && "Unhandled ARM MTE intrinsic"); 7255 return true; 7256 } 7257 7258 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7259 /// TheCall is an ARM/AArch64 special register string literal. 7260 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7261 int ArgNum, unsigned ExpectedFieldNum, 7262 bool AllowName) { 7263 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7264 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7265 BuiltinID == ARM::BI__builtin_arm_rsr || 7266 BuiltinID == ARM::BI__builtin_arm_rsrp || 7267 BuiltinID == ARM::BI__builtin_arm_wsr || 7268 BuiltinID == ARM::BI__builtin_arm_wsrp; 7269 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7270 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7271 BuiltinID == AArch64::BI__builtin_arm_rsr || 7272 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7273 BuiltinID == AArch64::BI__builtin_arm_wsr || 7274 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7275 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7276 7277 // We can't check the value of a dependent argument. 7278 Expr *Arg = TheCall->getArg(ArgNum); 7279 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7280 return false; 7281 7282 // Check if the argument is a string literal. 7283 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7284 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7285 << Arg->getSourceRange(); 7286 7287 // Check the type of special register given. 7288 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7289 SmallVector<StringRef, 6> Fields; 7290 Reg.split(Fields, ":"); 7291 7292 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7293 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7294 << Arg->getSourceRange(); 7295 7296 // If the string is the name of a register then we cannot check that it is 7297 // valid here but if the string is of one the forms described in ACLE then we 7298 // can check that the supplied fields are integers and within the valid 7299 // ranges. 7300 if (Fields.size() > 1) { 7301 bool FiveFields = Fields.size() == 5; 7302 7303 bool ValidString = true; 7304 if (IsARMBuiltin) { 7305 ValidString &= Fields[0].startswith_insensitive("cp") || 7306 Fields[0].startswith_insensitive("p"); 7307 if (ValidString) 7308 Fields[0] = Fields[0].drop_front( 7309 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7310 7311 ValidString &= Fields[2].startswith_insensitive("c"); 7312 if (ValidString) 7313 Fields[2] = Fields[2].drop_front(1); 7314 7315 if (FiveFields) { 7316 ValidString &= Fields[3].startswith_insensitive("c"); 7317 if (ValidString) 7318 Fields[3] = Fields[3].drop_front(1); 7319 } 7320 } 7321 7322 SmallVector<int, 5> Ranges; 7323 if (FiveFields) 7324 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7325 else 7326 Ranges.append({15, 7, 15}); 7327 7328 for (unsigned i=0; i<Fields.size(); ++i) { 7329 int IntField; 7330 ValidString &= !Fields[i].getAsInteger(10, IntField); 7331 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7332 } 7333 7334 if (!ValidString) 7335 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7336 << Arg->getSourceRange(); 7337 } else if (IsAArch64Builtin && Fields.size() == 1) { 7338 // If the register name is one of those that appear in the condition below 7339 // and the special register builtin being used is one of the write builtins, 7340 // then we require that the argument provided for writing to the register 7341 // is an integer constant expression. This is because it will be lowered to 7342 // an MSR (immediate) instruction, so we need to know the immediate at 7343 // compile time. 7344 if (TheCall->getNumArgs() != 2) 7345 return false; 7346 7347 std::string RegLower = Reg.lower(); 7348 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7349 RegLower != "pan" && RegLower != "uao") 7350 return false; 7351 7352 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7353 } 7354 7355 return false; 7356 } 7357 7358 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7359 /// Emit an error and return true on failure; return false on success. 7360 /// TypeStr is a string containing the type descriptor of the value returned by 7361 /// the builtin and the descriptors of the expected type of the arguments. 7362 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7363 const char *TypeStr) { 7364 7365 assert((TypeStr[0] != '\0') && 7366 "Invalid types in PPC MMA builtin declaration"); 7367 7368 switch (BuiltinID) { 7369 default: 7370 // This function is called in CheckPPCBuiltinFunctionCall where the 7371 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7372 // we are isolating the pair vector memop builtins that can be used with mma 7373 // off so the default case is every builtin that requires mma and paired 7374 // vector memops. 7375 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7376 diag::err_ppc_builtin_only_on_arch, "10") || 7377 SemaFeatureCheck(*this, TheCall, "mma", 7378 diag::err_ppc_builtin_only_on_arch, "10")) 7379 return true; 7380 break; 7381 case PPC::BI__builtin_vsx_lxvp: 7382 case PPC::BI__builtin_vsx_stxvp: 7383 case PPC::BI__builtin_vsx_assemble_pair: 7384 case PPC::BI__builtin_vsx_disassemble_pair: 7385 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7386 diag::err_ppc_builtin_only_on_arch, "10")) 7387 return true; 7388 break; 7389 } 7390 7391 unsigned Mask = 0; 7392 unsigned ArgNum = 0; 7393 7394 // The first type in TypeStr is the type of the value returned by the 7395 // builtin. So we first read that type and change the type of TheCall. 7396 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7397 TheCall->setType(type); 7398 7399 while (*TypeStr != '\0') { 7400 Mask = 0; 7401 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7402 if (ArgNum >= TheCall->getNumArgs()) { 7403 ArgNum++; 7404 break; 7405 } 7406 7407 Expr *Arg = TheCall->getArg(ArgNum); 7408 QualType PassedType = Arg->getType(); 7409 QualType StrippedRVType = PassedType.getCanonicalType(); 7410 7411 // Strip Restrict/Volatile qualifiers. 7412 if (StrippedRVType.isRestrictQualified() || 7413 StrippedRVType.isVolatileQualified()) 7414 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7415 7416 // The only case where the argument type and expected type are allowed to 7417 // mismatch is if the argument type is a non-void pointer and expected type 7418 // is a void pointer. 7419 if (StrippedRVType != ExpectedType) 7420 if (!(ExpectedType->isVoidPointerType() && 7421 StrippedRVType->isPointerType())) 7422 return Diag(Arg->getBeginLoc(), 7423 diag::err_typecheck_convert_incompatible) 7424 << PassedType << ExpectedType << 1 << 0 << 0; 7425 7426 // If the value of the Mask is not 0, we have a constraint in the size of 7427 // the integer argument so here we ensure the argument is a constant that 7428 // is in the valid range. 7429 if (Mask != 0 && 7430 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7431 return true; 7432 7433 ArgNum++; 7434 } 7435 7436 // In case we exited early from the previous loop, there are other types to 7437 // read from TypeStr. So we need to read them all to ensure we have the right 7438 // number of arguments in TheCall and if it is not the case, to display a 7439 // better error message. 7440 while (*TypeStr != '\0') { 7441 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7442 ArgNum++; 7443 } 7444 if (checkArgCount(*this, TheCall, ArgNum)) 7445 return true; 7446 7447 return false; 7448 } 7449 7450 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7451 /// This checks that the target supports __builtin_longjmp and 7452 /// that val is a constant 1. 7453 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7454 if (!Context.getTargetInfo().hasSjLjLowering()) 7455 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7456 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7457 7458 Expr *Arg = TheCall->getArg(1); 7459 llvm::APSInt Result; 7460 7461 // TODO: This is less than ideal. Overload this to take a value. 7462 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7463 return true; 7464 7465 if (Result != 1) 7466 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7467 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7468 7469 return false; 7470 } 7471 7472 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7473 /// This checks that the target supports __builtin_setjmp. 7474 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7475 if (!Context.getTargetInfo().hasSjLjLowering()) 7476 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7477 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7478 return false; 7479 } 7480 7481 namespace { 7482 7483 class UncoveredArgHandler { 7484 enum { Unknown = -1, AllCovered = -2 }; 7485 7486 signed FirstUncoveredArg = Unknown; 7487 SmallVector<const Expr *, 4> DiagnosticExprs; 7488 7489 public: 7490 UncoveredArgHandler() = default; 7491 7492 bool hasUncoveredArg() const { 7493 return (FirstUncoveredArg >= 0); 7494 } 7495 7496 unsigned getUncoveredArg() const { 7497 assert(hasUncoveredArg() && "no uncovered argument"); 7498 return FirstUncoveredArg; 7499 } 7500 7501 void setAllCovered() { 7502 // A string has been found with all arguments covered, so clear out 7503 // the diagnostics. 7504 DiagnosticExprs.clear(); 7505 FirstUncoveredArg = AllCovered; 7506 } 7507 7508 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7509 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7510 7511 // Don't update if a previous string covers all arguments. 7512 if (FirstUncoveredArg == AllCovered) 7513 return; 7514 7515 // UncoveredArgHandler tracks the highest uncovered argument index 7516 // and with it all the strings that match this index. 7517 if (NewFirstUncoveredArg == FirstUncoveredArg) 7518 DiagnosticExprs.push_back(StrExpr); 7519 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7520 DiagnosticExprs.clear(); 7521 DiagnosticExprs.push_back(StrExpr); 7522 FirstUncoveredArg = NewFirstUncoveredArg; 7523 } 7524 } 7525 7526 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7527 }; 7528 7529 enum StringLiteralCheckType { 7530 SLCT_NotALiteral, 7531 SLCT_UncheckedLiteral, 7532 SLCT_CheckedLiteral 7533 }; 7534 7535 } // namespace 7536 7537 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7538 BinaryOperatorKind BinOpKind, 7539 bool AddendIsRight) { 7540 unsigned BitWidth = Offset.getBitWidth(); 7541 unsigned AddendBitWidth = Addend.getBitWidth(); 7542 // There might be negative interim results. 7543 if (Addend.isUnsigned()) { 7544 Addend = Addend.zext(++AddendBitWidth); 7545 Addend.setIsSigned(true); 7546 } 7547 // Adjust the bit width of the APSInts. 7548 if (AddendBitWidth > BitWidth) { 7549 Offset = Offset.sext(AddendBitWidth); 7550 BitWidth = AddendBitWidth; 7551 } else if (BitWidth > AddendBitWidth) { 7552 Addend = Addend.sext(BitWidth); 7553 } 7554 7555 bool Ov = false; 7556 llvm::APSInt ResOffset = Offset; 7557 if (BinOpKind == BO_Add) 7558 ResOffset = Offset.sadd_ov(Addend, Ov); 7559 else { 7560 assert(AddendIsRight && BinOpKind == BO_Sub && 7561 "operator must be add or sub with addend on the right"); 7562 ResOffset = Offset.ssub_ov(Addend, Ov); 7563 } 7564 7565 // We add an offset to a pointer here so we should support an offset as big as 7566 // possible. 7567 if (Ov) { 7568 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7569 "index (intermediate) result too big"); 7570 Offset = Offset.sext(2 * BitWidth); 7571 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7572 return; 7573 } 7574 7575 Offset = ResOffset; 7576 } 7577 7578 namespace { 7579 7580 // This is a wrapper class around StringLiteral to support offsetted string 7581 // literals as format strings. It takes the offset into account when returning 7582 // the string and its length or the source locations to display notes correctly. 7583 class FormatStringLiteral { 7584 const StringLiteral *FExpr; 7585 int64_t Offset; 7586 7587 public: 7588 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7589 : FExpr(fexpr), Offset(Offset) {} 7590 7591 StringRef getString() const { 7592 return FExpr->getString().drop_front(Offset); 7593 } 7594 7595 unsigned getByteLength() const { 7596 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7597 } 7598 7599 unsigned getLength() const { return FExpr->getLength() - Offset; } 7600 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7601 7602 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7603 7604 QualType getType() const { return FExpr->getType(); } 7605 7606 bool isAscii() const { return FExpr->isAscii(); } 7607 bool isWide() const { return FExpr->isWide(); } 7608 bool isUTF8() const { return FExpr->isUTF8(); } 7609 bool isUTF16() const { return FExpr->isUTF16(); } 7610 bool isUTF32() const { return FExpr->isUTF32(); } 7611 bool isPascal() const { return FExpr->isPascal(); } 7612 7613 SourceLocation getLocationOfByte( 7614 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7615 const TargetInfo &Target, unsigned *StartToken = nullptr, 7616 unsigned *StartTokenByteOffset = nullptr) const { 7617 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7618 StartToken, StartTokenByteOffset); 7619 } 7620 7621 SourceLocation getBeginLoc() const LLVM_READONLY { 7622 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7623 } 7624 7625 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7626 }; 7627 7628 } // namespace 7629 7630 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7631 const Expr *OrigFormatExpr, 7632 ArrayRef<const Expr *> Args, 7633 bool HasVAListArg, unsigned format_idx, 7634 unsigned firstDataArg, 7635 Sema::FormatStringType Type, 7636 bool inFunctionCall, 7637 Sema::VariadicCallType CallType, 7638 llvm::SmallBitVector &CheckedVarArgs, 7639 UncoveredArgHandler &UncoveredArg, 7640 bool IgnoreStringsWithoutSpecifiers); 7641 7642 // Determine if an expression is a string literal or constant string. 7643 // If this function returns false on the arguments to a function expecting a 7644 // format string, we will usually need to emit a warning. 7645 // True string literals are then checked by CheckFormatString. 7646 static StringLiteralCheckType 7647 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7648 bool HasVAListArg, unsigned format_idx, 7649 unsigned firstDataArg, Sema::FormatStringType Type, 7650 Sema::VariadicCallType CallType, bool InFunctionCall, 7651 llvm::SmallBitVector &CheckedVarArgs, 7652 UncoveredArgHandler &UncoveredArg, 7653 llvm::APSInt Offset, 7654 bool IgnoreStringsWithoutSpecifiers = false) { 7655 if (S.isConstantEvaluated()) 7656 return SLCT_NotALiteral; 7657 tryAgain: 7658 assert(Offset.isSigned() && "invalid offset"); 7659 7660 if (E->isTypeDependent() || E->isValueDependent()) 7661 return SLCT_NotALiteral; 7662 7663 E = E->IgnoreParenCasts(); 7664 7665 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7666 // Technically -Wformat-nonliteral does not warn about this case. 7667 // The behavior of printf and friends in this case is implementation 7668 // dependent. Ideally if the format string cannot be null then 7669 // it should have a 'nonnull' attribute in the function prototype. 7670 return SLCT_UncheckedLiteral; 7671 7672 switch (E->getStmtClass()) { 7673 case Stmt::BinaryConditionalOperatorClass: 7674 case Stmt::ConditionalOperatorClass: { 7675 // The expression is a literal if both sub-expressions were, and it was 7676 // completely checked only if both sub-expressions were checked. 7677 const AbstractConditionalOperator *C = 7678 cast<AbstractConditionalOperator>(E); 7679 7680 // Determine whether it is necessary to check both sub-expressions, for 7681 // example, because the condition expression is a constant that can be 7682 // evaluated at compile time. 7683 bool CheckLeft = true, CheckRight = true; 7684 7685 bool Cond; 7686 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7687 S.isConstantEvaluated())) { 7688 if (Cond) 7689 CheckRight = false; 7690 else 7691 CheckLeft = false; 7692 } 7693 7694 // We need to maintain the offsets for the right and the left hand side 7695 // separately to check if every possible indexed expression is a valid 7696 // string literal. They might have different offsets for different string 7697 // literals in the end. 7698 StringLiteralCheckType Left; 7699 if (!CheckLeft) 7700 Left = SLCT_UncheckedLiteral; 7701 else { 7702 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7703 HasVAListArg, format_idx, firstDataArg, 7704 Type, CallType, InFunctionCall, 7705 CheckedVarArgs, UncoveredArg, Offset, 7706 IgnoreStringsWithoutSpecifiers); 7707 if (Left == SLCT_NotALiteral || !CheckRight) { 7708 return Left; 7709 } 7710 } 7711 7712 StringLiteralCheckType Right = checkFormatStringExpr( 7713 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7714 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7715 IgnoreStringsWithoutSpecifiers); 7716 7717 return (CheckLeft && Left < Right) ? Left : Right; 7718 } 7719 7720 case Stmt::ImplicitCastExprClass: 7721 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7722 goto tryAgain; 7723 7724 case Stmt::OpaqueValueExprClass: 7725 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7726 E = src; 7727 goto tryAgain; 7728 } 7729 return SLCT_NotALiteral; 7730 7731 case Stmt::PredefinedExprClass: 7732 // While __func__, etc., are technically not string literals, they 7733 // cannot contain format specifiers and thus are not a security 7734 // liability. 7735 return SLCT_UncheckedLiteral; 7736 7737 case Stmt::DeclRefExprClass: { 7738 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7739 7740 // As an exception, do not flag errors for variables binding to 7741 // const string literals. 7742 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7743 bool isConstant = false; 7744 QualType T = DR->getType(); 7745 7746 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7747 isConstant = AT->getElementType().isConstant(S.Context); 7748 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7749 isConstant = T.isConstant(S.Context) && 7750 PT->getPointeeType().isConstant(S.Context); 7751 } else if (T->isObjCObjectPointerType()) { 7752 // In ObjC, there is usually no "const ObjectPointer" type, 7753 // so don't check if the pointee type is constant. 7754 isConstant = T.isConstant(S.Context); 7755 } 7756 7757 if (isConstant) { 7758 if (const Expr *Init = VD->getAnyInitializer()) { 7759 // Look through initializers like const char c[] = { "foo" } 7760 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7761 if (InitList->isStringLiteralInit()) 7762 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7763 } 7764 return checkFormatStringExpr(S, Init, Args, 7765 HasVAListArg, format_idx, 7766 firstDataArg, Type, CallType, 7767 /*InFunctionCall*/ false, CheckedVarArgs, 7768 UncoveredArg, Offset); 7769 } 7770 } 7771 7772 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7773 // special check to see if the format string is a function parameter 7774 // of the function calling the printf function. If the function 7775 // has an attribute indicating it is a printf-like function, then we 7776 // should suppress warnings concerning non-literals being used in a call 7777 // to a vprintf function. For example: 7778 // 7779 // void 7780 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7781 // va_list ap; 7782 // va_start(ap, fmt); 7783 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7784 // ... 7785 // } 7786 if (HasVAListArg) { 7787 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7788 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 7789 int PVIndex = PV->getFunctionScopeIndex() + 1; 7790 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 7791 // adjust for implicit parameter 7792 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 7793 if (MD->isInstance()) 7794 ++PVIndex; 7795 // We also check if the formats are compatible. 7796 // We can't pass a 'scanf' string to a 'printf' function. 7797 if (PVIndex == PVFormat->getFormatIdx() && 7798 Type == S.GetFormatStringType(PVFormat)) 7799 return SLCT_UncheckedLiteral; 7800 } 7801 } 7802 } 7803 } 7804 } 7805 7806 return SLCT_NotALiteral; 7807 } 7808 7809 case Stmt::CallExprClass: 7810 case Stmt::CXXMemberCallExprClass: { 7811 const CallExpr *CE = cast<CallExpr>(E); 7812 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7813 bool IsFirst = true; 7814 StringLiteralCheckType CommonResult; 7815 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7816 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7817 StringLiteralCheckType Result = checkFormatStringExpr( 7818 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7819 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7820 IgnoreStringsWithoutSpecifiers); 7821 if (IsFirst) { 7822 CommonResult = Result; 7823 IsFirst = false; 7824 } 7825 } 7826 if (!IsFirst) 7827 return CommonResult; 7828 7829 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7830 unsigned BuiltinID = FD->getBuiltinID(); 7831 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7832 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7833 const Expr *Arg = CE->getArg(0); 7834 return checkFormatStringExpr(S, Arg, Args, 7835 HasVAListArg, format_idx, 7836 firstDataArg, Type, CallType, 7837 InFunctionCall, CheckedVarArgs, 7838 UncoveredArg, Offset, 7839 IgnoreStringsWithoutSpecifiers); 7840 } 7841 } 7842 } 7843 7844 return SLCT_NotALiteral; 7845 } 7846 case Stmt::ObjCMessageExprClass: { 7847 const auto *ME = cast<ObjCMessageExpr>(E); 7848 if (const auto *MD = ME->getMethodDecl()) { 7849 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7850 // As a special case heuristic, if we're using the method -[NSBundle 7851 // localizedStringForKey:value:table:], ignore any key strings that lack 7852 // format specifiers. The idea is that if the key doesn't have any 7853 // format specifiers then its probably just a key to map to the 7854 // localized strings. If it does have format specifiers though, then its 7855 // likely that the text of the key is the format string in the 7856 // programmer's language, and should be checked. 7857 const ObjCInterfaceDecl *IFace; 7858 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7859 IFace->getIdentifier()->isStr("NSBundle") && 7860 MD->getSelector().isKeywordSelector( 7861 {"localizedStringForKey", "value", "table"})) { 7862 IgnoreStringsWithoutSpecifiers = true; 7863 } 7864 7865 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7866 return checkFormatStringExpr( 7867 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7868 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7869 IgnoreStringsWithoutSpecifiers); 7870 } 7871 } 7872 7873 return SLCT_NotALiteral; 7874 } 7875 case Stmt::ObjCStringLiteralClass: 7876 case Stmt::StringLiteralClass: { 7877 const StringLiteral *StrE = nullptr; 7878 7879 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7880 StrE = ObjCFExpr->getString(); 7881 else 7882 StrE = cast<StringLiteral>(E); 7883 7884 if (StrE) { 7885 if (Offset.isNegative() || Offset > StrE->getLength()) { 7886 // TODO: It would be better to have an explicit warning for out of 7887 // bounds literals. 7888 return SLCT_NotALiteral; 7889 } 7890 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7891 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7892 firstDataArg, Type, InFunctionCall, CallType, 7893 CheckedVarArgs, UncoveredArg, 7894 IgnoreStringsWithoutSpecifiers); 7895 return SLCT_CheckedLiteral; 7896 } 7897 7898 return SLCT_NotALiteral; 7899 } 7900 case Stmt::BinaryOperatorClass: { 7901 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7902 7903 // A string literal + an int offset is still a string literal. 7904 if (BinOp->isAdditiveOp()) { 7905 Expr::EvalResult LResult, RResult; 7906 7907 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7908 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7909 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7910 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7911 7912 if (LIsInt != RIsInt) { 7913 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7914 7915 if (LIsInt) { 7916 if (BinOpKind == BO_Add) { 7917 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7918 E = BinOp->getRHS(); 7919 goto tryAgain; 7920 } 7921 } else { 7922 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7923 E = BinOp->getLHS(); 7924 goto tryAgain; 7925 } 7926 } 7927 } 7928 7929 return SLCT_NotALiteral; 7930 } 7931 case Stmt::UnaryOperatorClass: { 7932 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7933 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7934 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7935 Expr::EvalResult IndexResult; 7936 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7937 Expr::SE_NoSideEffects, 7938 S.isConstantEvaluated())) { 7939 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7940 /*RHS is int*/ true); 7941 E = ASE->getBase(); 7942 goto tryAgain; 7943 } 7944 } 7945 7946 return SLCT_NotALiteral; 7947 } 7948 7949 default: 7950 return SLCT_NotALiteral; 7951 } 7952 } 7953 7954 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7955 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7956 .Case("scanf", FST_Scanf) 7957 .Cases("printf", "printf0", FST_Printf) 7958 .Cases("NSString", "CFString", FST_NSString) 7959 .Case("strftime", FST_Strftime) 7960 .Case("strfmon", FST_Strfmon) 7961 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7962 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7963 .Case("os_trace", FST_OSLog) 7964 .Case("os_log", FST_OSLog) 7965 .Default(FST_Unknown); 7966 } 7967 7968 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7969 /// functions) for correct use of format strings. 7970 /// Returns true if a format string has been fully checked. 7971 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7972 ArrayRef<const Expr *> Args, 7973 bool IsCXXMember, 7974 VariadicCallType CallType, 7975 SourceLocation Loc, SourceRange Range, 7976 llvm::SmallBitVector &CheckedVarArgs) { 7977 FormatStringInfo FSI; 7978 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7979 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7980 FSI.FirstDataArg, GetFormatStringType(Format), 7981 CallType, Loc, Range, CheckedVarArgs); 7982 return false; 7983 } 7984 7985 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7986 bool HasVAListArg, unsigned format_idx, 7987 unsigned firstDataArg, FormatStringType Type, 7988 VariadicCallType CallType, 7989 SourceLocation Loc, SourceRange Range, 7990 llvm::SmallBitVector &CheckedVarArgs) { 7991 // CHECK: printf/scanf-like function is called with no format string. 7992 if (format_idx >= Args.size()) { 7993 Diag(Loc, diag::warn_missing_format_string) << Range; 7994 return false; 7995 } 7996 7997 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7998 7999 // CHECK: format string is not a string literal. 8000 // 8001 // Dynamically generated format strings are difficult to 8002 // automatically vet at compile time. Requiring that format strings 8003 // are string literals: (1) permits the checking of format strings by 8004 // the compiler and thereby (2) can practically remove the source of 8005 // many format string exploits. 8006 8007 // Format string can be either ObjC string (e.g. @"%d") or 8008 // C string (e.g. "%d") 8009 // ObjC string uses the same format specifiers as C string, so we can use 8010 // the same format string checking logic for both ObjC and C strings. 8011 UncoveredArgHandler UncoveredArg; 8012 StringLiteralCheckType CT = 8013 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8014 format_idx, firstDataArg, Type, CallType, 8015 /*IsFunctionCall*/ true, CheckedVarArgs, 8016 UncoveredArg, 8017 /*no string offset*/ llvm::APSInt(64, false) = 0); 8018 8019 // Generate a diagnostic where an uncovered argument is detected. 8020 if (UncoveredArg.hasUncoveredArg()) { 8021 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8022 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8023 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8024 } 8025 8026 if (CT != SLCT_NotALiteral) 8027 // Literal format string found, check done! 8028 return CT == SLCT_CheckedLiteral; 8029 8030 // Strftime is particular as it always uses a single 'time' argument, 8031 // so it is safe to pass a non-literal string. 8032 if (Type == FST_Strftime) 8033 return false; 8034 8035 // Do not emit diag when the string param is a macro expansion and the 8036 // format is either NSString or CFString. This is a hack to prevent 8037 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8038 // which are usually used in place of NS and CF string literals. 8039 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8040 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8041 return false; 8042 8043 // If there are no arguments specified, warn with -Wformat-security, otherwise 8044 // warn only with -Wformat-nonliteral. 8045 if (Args.size() == firstDataArg) { 8046 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8047 << OrigFormatExpr->getSourceRange(); 8048 switch (Type) { 8049 default: 8050 break; 8051 case FST_Kprintf: 8052 case FST_FreeBSDKPrintf: 8053 case FST_Printf: 8054 Diag(FormatLoc, diag::note_format_security_fixit) 8055 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8056 break; 8057 case FST_NSString: 8058 Diag(FormatLoc, diag::note_format_security_fixit) 8059 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8060 break; 8061 } 8062 } else { 8063 Diag(FormatLoc, diag::warn_format_nonliteral) 8064 << OrigFormatExpr->getSourceRange(); 8065 } 8066 return false; 8067 } 8068 8069 namespace { 8070 8071 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8072 protected: 8073 Sema &S; 8074 const FormatStringLiteral *FExpr; 8075 const Expr *OrigFormatExpr; 8076 const Sema::FormatStringType FSType; 8077 const unsigned FirstDataArg; 8078 const unsigned NumDataArgs; 8079 const char *Beg; // Start of format string. 8080 const bool HasVAListArg; 8081 ArrayRef<const Expr *> Args; 8082 unsigned FormatIdx; 8083 llvm::SmallBitVector CoveredArgs; 8084 bool usesPositionalArgs = false; 8085 bool atFirstArg = true; 8086 bool inFunctionCall; 8087 Sema::VariadicCallType CallType; 8088 llvm::SmallBitVector &CheckedVarArgs; 8089 UncoveredArgHandler &UncoveredArg; 8090 8091 public: 8092 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8093 const Expr *origFormatExpr, 8094 const Sema::FormatStringType type, unsigned firstDataArg, 8095 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8096 ArrayRef<const Expr *> Args, unsigned formatIdx, 8097 bool inFunctionCall, Sema::VariadicCallType callType, 8098 llvm::SmallBitVector &CheckedVarArgs, 8099 UncoveredArgHandler &UncoveredArg) 8100 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8101 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8102 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8103 inFunctionCall(inFunctionCall), CallType(callType), 8104 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8105 CoveredArgs.resize(numDataArgs); 8106 CoveredArgs.reset(); 8107 } 8108 8109 void DoneProcessing(); 8110 8111 void HandleIncompleteSpecifier(const char *startSpecifier, 8112 unsigned specifierLen) override; 8113 8114 void HandleInvalidLengthModifier( 8115 const analyze_format_string::FormatSpecifier &FS, 8116 const analyze_format_string::ConversionSpecifier &CS, 8117 const char *startSpecifier, unsigned specifierLen, 8118 unsigned DiagID); 8119 8120 void HandleNonStandardLengthModifier( 8121 const analyze_format_string::FormatSpecifier &FS, 8122 const char *startSpecifier, unsigned specifierLen); 8123 8124 void HandleNonStandardConversionSpecifier( 8125 const analyze_format_string::ConversionSpecifier &CS, 8126 const char *startSpecifier, unsigned specifierLen); 8127 8128 void HandlePosition(const char *startPos, unsigned posLen) override; 8129 8130 void HandleInvalidPosition(const char *startSpecifier, 8131 unsigned specifierLen, 8132 analyze_format_string::PositionContext p) override; 8133 8134 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8135 8136 void HandleNullChar(const char *nullCharacter) override; 8137 8138 template <typename Range> 8139 static void 8140 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8141 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8142 bool IsStringLocation, Range StringRange, 8143 ArrayRef<FixItHint> Fixit = None); 8144 8145 protected: 8146 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8147 const char *startSpec, 8148 unsigned specifierLen, 8149 const char *csStart, unsigned csLen); 8150 8151 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8152 const char *startSpec, 8153 unsigned specifierLen); 8154 8155 SourceRange getFormatStringRange(); 8156 CharSourceRange getSpecifierRange(const char *startSpecifier, 8157 unsigned specifierLen); 8158 SourceLocation getLocationOfByte(const char *x); 8159 8160 const Expr *getDataArg(unsigned i) const; 8161 8162 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8163 const analyze_format_string::ConversionSpecifier &CS, 8164 const char *startSpecifier, unsigned specifierLen, 8165 unsigned argIndex); 8166 8167 template <typename Range> 8168 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8169 bool IsStringLocation, Range StringRange, 8170 ArrayRef<FixItHint> Fixit = None); 8171 }; 8172 8173 } // namespace 8174 8175 SourceRange CheckFormatHandler::getFormatStringRange() { 8176 return OrigFormatExpr->getSourceRange(); 8177 } 8178 8179 CharSourceRange CheckFormatHandler:: 8180 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8181 SourceLocation Start = getLocationOfByte(startSpecifier); 8182 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8183 8184 // Advance the end SourceLocation by one due to half-open ranges. 8185 End = End.getLocWithOffset(1); 8186 8187 return CharSourceRange::getCharRange(Start, End); 8188 } 8189 8190 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8191 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8192 S.getLangOpts(), S.Context.getTargetInfo()); 8193 } 8194 8195 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8196 unsigned specifierLen){ 8197 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8198 getLocationOfByte(startSpecifier), 8199 /*IsStringLocation*/true, 8200 getSpecifierRange(startSpecifier, specifierLen)); 8201 } 8202 8203 void CheckFormatHandler::HandleInvalidLengthModifier( 8204 const analyze_format_string::FormatSpecifier &FS, 8205 const analyze_format_string::ConversionSpecifier &CS, 8206 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8207 using namespace analyze_format_string; 8208 8209 const LengthModifier &LM = FS.getLengthModifier(); 8210 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8211 8212 // See if we know how to fix this length modifier. 8213 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8214 if (FixedLM) { 8215 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8216 getLocationOfByte(LM.getStart()), 8217 /*IsStringLocation*/true, 8218 getSpecifierRange(startSpecifier, specifierLen)); 8219 8220 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8221 << FixedLM->toString() 8222 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8223 8224 } else { 8225 FixItHint Hint; 8226 if (DiagID == diag::warn_format_nonsensical_length) 8227 Hint = FixItHint::CreateRemoval(LMRange); 8228 8229 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8230 getLocationOfByte(LM.getStart()), 8231 /*IsStringLocation*/true, 8232 getSpecifierRange(startSpecifier, specifierLen), 8233 Hint); 8234 } 8235 } 8236 8237 void CheckFormatHandler::HandleNonStandardLengthModifier( 8238 const analyze_format_string::FormatSpecifier &FS, 8239 const char *startSpecifier, unsigned specifierLen) { 8240 using namespace analyze_format_string; 8241 8242 const LengthModifier &LM = FS.getLengthModifier(); 8243 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8244 8245 // See if we know how to fix this length modifier. 8246 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8247 if (FixedLM) { 8248 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8249 << LM.toString() << 0, 8250 getLocationOfByte(LM.getStart()), 8251 /*IsStringLocation*/true, 8252 getSpecifierRange(startSpecifier, specifierLen)); 8253 8254 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8255 << FixedLM->toString() 8256 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8257 8258 } else { 8259 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8260 << LM.toString() << 0, 8261 getLocationOfByte(LM.getStart()), 8262 /*IsStringLocation*/true, 8263 getSpecifierRange(startSpecifier, specifierLen)); 8264 } 8265 } 8266 8267 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8268 const analyze_format_string::ConversionSpecifier &CS, 8269 const char *startSpecifier, unsigned specifierLen) { 8270 using namespace analyze_format_string; 8271 8272 // See if we know how to fix this conversion specifier. 8273 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8274 if (FixedCS) { 8275 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8276 << CS.toString() << /*conversion specifier*/1, 8277 getLocationOfByte(CS.getStart()), 8278 /*IsStringLocation*/true, 8279 getSpecifierRange(startSpecifier, specifierLen)); 8280 8281 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8282 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8283 << FixedCS->toString() 8284 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8285 } else { 8286 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8287 << CS.toString() << /*conversion specifier*/1, 8288 getLocationOfByte(CS.getStart()), 8289 /*IsStringLocation*/true, 8290 getSpecifierRange(startSpecifier, specifierLen)); 8291 } 8292 } 8293 8294 void CheckFormatHandler::HandlePosition(const char *startPos, 8295 unsigned posLen) { 8296 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8297 getLocationOfByte(startPos), 8298 /*IsStringLocation*/true, 8299 getSpecifierRange(startPos, posLen)); 8300 } 8301 8302 void 8303 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8304 analyze_format_string::PositionContext p) { 8305 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8306 << (unsigned) p, 8307 getLocationOfByte(startPos), /*IsStringLocation*/true, 8308 getSpecifierRange(startPos, posLen)); 8309 } 8310 8311 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8312 unsigned posLen) { 8313 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8314 getLocationOfByte(startPos), 8315 /*IsStringLocation*/true, 8316 getSpecifierRange(startPos, posLen)); 8317 } 8318 8319 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8320 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8321 // The presence of a null character is likely an error. 8322 EmitFormatDiagnostic( 8323 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8324 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8325 getFormatStringRange()); 8326 } 8327 } 8328 8329 // Note that this may return NULL if there was an error parsing or building 8330 // one of the argument expressions. 8331 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8332 return Args[FirstDataArg + i]; 8333 } 8334 8335 void CheckFormatHandler::DoneProcessing() { 8336 // Does the number of data arguments exceed the number of 8337 // format conversions in the format string? 8338 if (!HasVAListArg) { 8339 // Find any arguments that weren't covered. 8340 CoveredArgs.flip(); 8341 signed notCoveredArg = CoveredArgs.find_first(); 8342 if (notCoveredArg >= 0) { 8343 assert((unsigned)notCoveredArg < NumDataArgs); 8344 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8345 } else { 8346 UncoveredArg.setAllCovered(); 8347 } 8348 } 8349 } 8350 8351 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8352 const Expr *ArgExpr) { 8353 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8354 "Invalid state"); 8355 8356 if (!ArgExpr) 8357 return; 8358 8359 SourceLocation Loc = ArgExpr->getBeginLoc(); 8360 8361 if (S.getSourceManager().isInSystemMacro(Loc)) 8362 return; 8363 8364 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8365 for (auto E : DiagnosticExprs) 8366 PDiag << E->getSourceRange(); 8367 8368 CheckFormatHandler::EmitFormatDiagnostic( 8369 S, IsFunctionCall, DiagnosticExprs[0], 8370 PDiag, Loc, /*IsStringLocation*/false, 8371 DiagnosticExprs[0]->getSourceRange()); 8372 } 8373 8374 bool 8375 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8376 SourceLocation Loc, 8377 const char *startSpec, 8378 unsigned specifierLen, 8379 const char *csStart, 8380 unsigned csLen) { 8381 bool keepGoing = true; 8382 if (argIndex < NumDataArgs) { 8383 // Consider the argument coverered, even though the specifier doesn't 8384 // make sense. 8385 CoveredArgs.set(argIndex); 8386 } 8387 else { 8388 // If argIndex exceeds the number of data arguments we 8389 // don't issue a warning because that is just a cascade of warnings (and 8390 // they may have intended '%%' anyway). We don't want to continue processing 8391 // the format string after this point, however, as we will like just get 8392 // gibberish when trying to match arguments. 8393 keepGoing = false; 8394 } 8395 8396 StringRef Specifier(csStart, csLen); 8397 8398 // If the specifier in non-printable, it could be the first byte of a UTF-8 8399 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8400 // hex value. 8401 std::string CodePointStr; 8402 if (!llvm::sys::locale::isPrint(*csStart)) { 8403 llvm::UTF32 CodePoint; 8404 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8405 const llvm::UTF8 *E = 8406 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8407 llvm::ConversionResult Result = 8408 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8409 8410 if (Result != llvm::conversionOK) { 8411 unsigned char FirstChar = *csStart; 8412 CodePoint = (llvm::UTF32)FirstChar; 8413 } 8414 8415 llvm::raw_string_ostream OS(CodePointStr); 8416 if (CodePoint < 256) 8417 OS << "\\x" << llvm::format("%02x", CodePoint); 8418 else if (CodePoint <= 0xFFFF) 8419 OS << "\\u" << llvm::format("%04x", CodePoint); 8420 else 8421 OS << "\\U" << llvm::format("%08x", CodePoint); 8422 OS.flush(); 8423 Specifier = CodePointStr; 8424 } 8425 8426 EmitFormatDiagnostic( 8427 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8428 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8429 8430 return keepGoing; 8431 } 8432 8433 void 8434 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8435 const char *startSpec, 8436 unsigned specifierLen) { 8437 EmitFormatDiagnostic( 8438 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8439 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8440 } 8441 8442 bool 8443 CheckFormatHandler::CheckNumArgs( 8444 const analyze_format_string::FormatSpecifier &FS, 8445 const analyze_format_string::ConversionSpecifier &CS, 8446 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8447 8448 if (argIndex >= NumDataArgs) { 8449 PartialDiagnostic PDiag = FS.usesPositionalArg() 8450 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8451 << (argIndex+1) << NumDataArgs) 8452 : S.PDiag(diag::warn_printf_insufficient_data_args); 8453 EmitFormatDiagnostic( 8454 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8455 getSpecifierRange(startSpecifier, specifierLen)); 8456 8457 // Since more arguments than conversion tokens are given, by extension 8458 // all arguments are covered, so mark this as so. 8459 UncoveredArg.setAllCovered(); 8460 return false; 8461 } 8462 return true; 8463 } 8464 8465 template<typename Range> 8466 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8467 SourceLocation Loc, 8468 bool IsStringLocation, 8469 Range StringRange, 8470 ArrayRef<FixItHint> FixIt) { 8471 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8472 Loc, IsStringLocation, StringRange, FixIt); 8473 } 8474 8475 /// If the format string is not within the function call, emit a note 8476 /// so that the function call and string are in diagnostic messages. 8477 /// 8478 /// \param InFunctionCall if true, the format string is within the function 8479 /// call and only one diagnostic message will be produced. Otherwise, an 8480 /// extra note will be emitted pointing to location of the format string. 8481 /// 8482 /// \param ArgumentExpr the expression that is passed as the format string 8483 /// argument in the function call. Used for getting locations when two 8484 /// diagnostics are emitted. 8485 /// 8486 /// \param PDiag the callee should already have provided any strings for the 8487 /// diagnostic message. This function only adds locations and fixits 8488 /// to diagnostics. 8489 /// 8490 /// \param Loc primary location for diagnostic. If two diagnostics are 8491 /// required, one will be at Loc and a new SourceLocation will be created for 8492 /// the other one. 8493 /// 8494 /// \param IsStringLocation if true, Loc points to the format string should be 8495 /// used for the note. Otherwise, Loc points to the argument list and will 8496 /// be used with PDiag. 8497 /// 8498 /// \param StringRange some or all of the string to highlight. This is 8499 /// templated so it can accept either a CharSourceRange or a SourceRange. 8500 /// 8501 /// \param FixIt optional fix it hint for the format string. 8502 template <typename Range> 8503 void CheckFormatHandler::EmitFormatDiagnostic( 8504 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8505 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8506 Range StringRange, ArrayRef<FixItHint> FixIt) { 8507 if (InFunctionCall) { 8508 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8509 D << StringRange; 8510 D << FixIt; 8511 } else { 8512 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8513 << ArgumentExpr->getSourceRange(); 8514 8515 const Sema::SemaDiagnosticBuilder &Note = 8516 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8517 diag::note_format_string_defined); 8518 8519 Note << StringRange; 8520 Note << FixIt; 8521 } 8522 } 8523 8524 //===--- CHECK: Printf format string checking ------------------------------===// 8525 8526 namespace { 8527 8528 class CheckPrintfHandler : public CheckFormatHandler { 8529 public: 8530 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8531 const Expr *origFormatExpr, 8532 const Sema::FormatStringType type, unsigned firstDataArg, 8533 unsigned numDataArgs, bool isObjC, const char *beg, 8534 bool hasVAListArg, ArrayRef<const Expr *> Args, 8535 unsigned formatIdx, bool inFunctionCall, 8536 Sema::VariadicCallType CallType, 8537 llvm::SmallBitVector &CheckedVarArgs, 8538 UncoveredArgHandler &UncoveredArg) 8539 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8540 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8541 inFunctionCall, CallType, CheckedVarArgs, 8542 UncoveredArg) {} 8543 8544 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8545 8546 /// Returns true if '%@' specifiers are allowed in the format string. 8547 bool allowsObjCArg() const { 8548 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8549 FSType == Sema::FST_OSTrace; 8550 } 8551 8552 bool HandleInvalidPrintfConversionSpecifier( 8553 const analyze_printf::PrintfSpecifier &FS, 8554 const char *startSpecifier, 8555 unsigned specifierLen) override; 8556 8557 void handleInvalidMaskType(StringRef MaskType) override; 8558 8559 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8560 const char *startSpecifier, 8561 unsigned specifierLen) override; 8562 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8563 const char *StartSpecifier, 8564 unsigned SpecifierLen, 8565 const Expr *E); 8566 8567 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8568 const char *startSpecifier, unsigned specifierLen); 8569 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8570 const analyze_printf::OptionalAmount &Amt, 8571 unsigned type, 8572 const char *startSpecifier, unsigned specifierLen); 8573 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8574 const analyze_printf::OptionalFlag &flag, 8575 const char *startSpecifier, unsigned specifierLen); 8576 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8577 const analyze_printf::OptionalFlag &ignoredFlag, 8578 const analyze_printf::OptionalFlag &flag, 8579 const char *startSpecifier, unsigned specifierLen); 8580 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8581 const Expr *E); 8582 8583 void HandleEmptyObjCModifierFlag(const char *startFlag, 8584 unsigned flagLen) override; 8585 8586 void HandleInvalidObjCModifierFlag(const char *startFlag, 8587 unsigned flagLen) override; 8588 8589 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8590 const char *flagsEnd, 8591 const char *conversionPosition) 8592 override; 8593 }; 8594 8595 } // namespace 8596 8597 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8598 const analyze_printf::PrintfSpecifier &FS, 8599 const char *startSpecifier, 8600 unsigned specifierLen) { 8601 const analyze_printf::PrintfConversionSpecifier &CS = 8602 FS.getConversionSpecifier(); 8603 8604 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8605 getLocationOfByte(CS.getStart()), 8606 startSpecifier, specifierLen, 8607 CS.getStart(), CS.getLength()); 8608 } 8609 8610 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8611 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8612 } 8613 8614 bool CheckPrintfHandler::HandleAmount( 8615 const analyze_format_string::OptionalAmount &Amt, 8616 unsigned k, const char *startSpecifier, 8617 unsigned specifierLen) { 8618 if (Amt.hasDataArgument()) { 8619 if (!HasVAListArg) { 8620 unsigned argIndex = Amt.getArgIndex(); 8621 if (argIndex >= NumDataArgs) { 8622 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8623 << k, 8624 getLocationOfByte(Amt.getStart()), 8625 /*IsStringLocation*/true, 8626 getSpecifierRange(startSpecifier, specifierLen)); 8627 // Don't do any more checking. We will just emit 8628 // spurious errors. 8629 return false; 8630 } 8631 8632 // Type check the data argument. It should be an 'int'. 8633 // Although not in conformance with C99, we also allow the argument to be 8634 // an 'unsigned int' as that is a reasonably safe case. GCC also 8635 // doesn't emit a warning for that case. 8636 CoveredArgs.set(argIndex); 8637 const Expr *Arg = getDataArg(argIndex); 8638 if (!Arg) 8639 return false; 8640 8641 QualType T = Arg->getType(); 8642 8643 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8644 assert(AT.isValid()); 8645 8646 if (!AT.matchesType(S.Context, T)) { 8647 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8648 << k << AT.getRepresentativeTypeName(S.Context) 8649 << T << Arg->getSourceRange(), 8650 getLocationOfByte(Amt.getStart()), 8651 /*IsStringLocation*/true, 8652 getSpecifierRange(startSpecifier, specifierLen)); 8653 // Don't do any more checking. We will just emit 8654 // spurious errors. 8655 return false; 8656 } 8657 } 8658 } 8659 return true; 8660 } 8661 8662 void CheckPrintfHandler::HandleInvalidAmount( 8663 const analyze_printf::PrintfSpecifier &FS, 8664 const analyze_printf::OptionalAmount &Amt, 8665 unsigned type, 8666 const char *startSpecifier, 8667 unsigned specifierLen) { 8668 const analyze_printf::PrintfConversionSpecifier &CS = 8669 FS.getConversionSpecifier(); 8670 8671 FixItHint fixit = 8672 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8673 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8674 Amt.getConstantLength())) 8675 : FixItHint(); 8676 8677 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8678 << type << CS.toString(), 8679 getLocationOfByte(Amt.getStart()), 8680 /*IsStringLocation*/true, 8681 getSpecifierRange(startSpecifier, specifierLen), 8682 fixit); 8683 } 8684 8685 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8686 const analyze_printf::OptionalFlag &flag, 8687 const char *startSpecifier, 8688 unsigned specifierLen) { 8689 // Warn about pointless flag with a fixit removal. 8690 const analyze_printf::PrintfConversionSpecifier &CS = 8691 FS.getConversionSpecifier(); 8692 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8693 << flag.toString() << CS.toString(), 8694 getLocationOfByte(flag.getPosition()), 8695 /*IsStringLocation*/true, 8696 getSpecifierRange(startSpecifier, specifierLen), 8697 FixItHint::CreateRemoval( 8698 getSpecifierRange(flag.getPosition(), 1))); 8699 } 8700 8701 void CheckPrintfHandler::HandleIgnoredFlag( 8702 const analyze_printf::PrintfSpecifier &FS, 8703 const analyze_printf::OptionalFlag &ignoredFlag, 8704 const analyze_printf::OptionalFlag &flag, 8705 const char *startSpecifier, 8706 unsigned specifierLen) { 8707 // Warn about ignored flag with a fixit removal. 8708 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8709 << ignoredFlag.toString() << flag.toString(), 8710 getLocationOfByte(ignoredFlag.getPosition()), 8711 /*IsStringLocation*/true, 8712 getSpecifierRange(startSpecifier, specifierLen), 8713 FixItHint::CreateRemoval( 8714 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8715 } 8716 8717 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8718 unsigned flagLen) { 8719 // Warn about an empty flag. 8720 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8721 getLocationOfByte(startFlag), 8722 /*IsStringLocation*/true, 8723 getSpecifierRange(startFlag, flagLen)); 8724 } 8725 8726 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8727 unsigned flagLen) { 8728 // Warn about an invalid flag. 8729 auto Range = getSpecifierRange(startFlag, flagLen); 8730 StringRef flag(startFlag, flagLen); 8731 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8732 getLocationOfByte(startFlag), 8733 /*IsStringLocation*/true, 8734 Range, FixItHint::CreateRemoval(Range)); 8735 } 8736 8737 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8738 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8739 // Warn about using '[...]' without a '@' conversion. 8740 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8741 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8742 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8743 getLocationOfByte(conversionPosition), 8744 /*IsStringLocation*/true, 8745 Range, FixItHint::CreateRemoval(Range)); 8746 } 8747 8748 // Determines if the specified is a C++ class or struct containing 8749 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8750 // "c_str()"). 8751 template<typename MemberKind> 8752 static llvm::SmallPtrSet<MemberKind*, 1> 8753 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8754 const RecordType *RT = Ty->getAs<RecordType>(); 8755 llvm::SmallPtrSet<MemberKind*, 1> Results; 8756 8757 if (!RT) 8758 return Results; 8759 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8760 if (!RD || !RD->getDefinition()) 8761 return Results; 8762 8763 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8764 Sema::LookupMemberName); 8765 R.suppressDiagnostics(); 8766 8767 // We just need to include all members of the right kind turned up by the 8768 // filter, at this point. 8769 if (S.LookupQualifiedName(R, RT->getDecl())) 8770 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8771 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8772 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8773 Results.insert(FK); 8774 } 8775 return Results; 8776 } 8777 8778 /// Check if we could call '.c_str()' on an object. 8779 /// 8780 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8781 /// allow the call, or if it would be ambiguous). 8782 bool Sema::hasCStrMethod(const Expr *E) { 8783 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8784 8785 MethodSet Results = 8786 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8787 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8788 MI != ME; ++MI) 8789 if ((*MI)->getMinRequiredArguments() == 0) 8790 return true; 8791 return false; 8792 } 8793 8794 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8795 // better diagnostic if so. AT is assumed to be valid. 8796 // Returns true when a c_str() conversion method is found. 8797 bool CheckPrintfHandler::checkForCStrMembers( 8798 const analyze_printf::ArgType &AT, const Expr *E) { 8799 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8800 8801 MethodSet Results = 8802 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8803 8804 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8805 MI != ME; ++MI) { 8806 const CXXMethodDecl *Method = *MI; 8807 if (Method->getMinRequiredArguments() == 0 && 8808 AT.matchesType(S.Context, Method->getReturnType())) { 8809 // FIXME: Suggest parens if the expression needs them. 8810 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8811 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8812 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8813 return true; 8814 } 8815 } 8816 8817 return false; 8818 } 8819 8820 bool 8821 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8822 &FS, 8823 const char *startSpecifier, 8824 unsigned specifierLen) { 8825 using namespace analyze_format_string; 8826 using namespace analyze_printf; 8827 8828 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8829 8830 if (FS.consumesDataArgument()) { 8831 if (atFirstArg) { 8832 atFirstArg = false; 8833 usesPositionalArgs = FS.usesPositionalArg(); 8834 } 8835 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8836 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8837 startSpecifier, specifierLen); 8838 return false; 8839 } 8840 } 8841 8842 // First check if the field width, precision, and conversion specifier 8843 // have matching data arguments. 8844 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8845 startSpecifier, specifierLen)) { 8846 return false; 8847 } 8848 8849 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8850 startSpecifier, specifierLen)) { 8851 return false; 8852 } 8853 8854 if (!CS.consumesDataArgument()) { 8855 // FIXME: Technically specifying a precision or field width here 8856 // makes no sense. Worth issuing a warning at some point. 8857 return true; 8858 } 8859 8860 // Consume the argument. 8861 unsigned argIndex = FS.getArgIndex(); 8862 if (argIndex < NumDataArgs) { 8863 // The check to see if the argIndex is valid will come later. 8864 // We set the bit here because we may exit early from this 8865 // function if we encounter some other error. 8866 CoveredArgs.set(argIndex); 8867 } 8868 8869 // FreeBSD kernel extensions. 8870 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8871 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8872 // We need at least two arguments. 8873 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8874 return false; 8875 8876 // Claim the second argument. 8877 CoveredArgs.set(argIndex + 1); 8878 8879 // Type check the first argument (int for %b, pointer for %D) 8880 const Expr *Ex = getDataArg(argIndex); 8881 const analyze_printf::ArgType &AT = 8882 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8883 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8884 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8885 EmitFormatDiagnostic( 8886 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8887 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8888 << false << Ex->getSourceRange(), 8889 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8890 getSpecifierRange(startSpecifier, specifierLen)); 8891 8892 // Type check the second argument (char * for both %b and %D) 8893 Ex = getDataArg(argIndex + 1); 8894 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8895 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8896 EmitFormatDiagnostic( 8897 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8898 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8899 << false << Ex->getSourceRange(), 8900 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8901 getSpecifierRange(startSpecifier, specifierLen)); 8902 8903 return true; 8904 } 8905 8906 // Check for using an Objective-C specific conversion specifier 8907 // in a non-ObjC literal. 8908 if (!allowsObjCArg() && CS.isObjCArg()) { 8909 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8910 specifierLen); 8911 } 8912 8913 // %P can only be used with os_log. 8914 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8915 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8916 specifierLen); 8917 } 8918 8919 // %n is not allowed with os_log. 8920 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8921 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8922 getLocationOfByte(CS.getStart()), 8923 /*IsStringLocation*/ false, 8924 getSpecifierRange(startSpecifier, specifierLen)); 8925 8926 return true; 8927 } 8928 8929 // Only scalars are allowed for os_trace. 8930 if (FSType == Sema::FST_OSTrace && 8931 (CS.getKind() == ConversionSpecifier::PArg || 8932 CS.getKind() == ConversionSpecifier::sArg || 8933 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8934 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8935 specifierLen); 8936 } 8937 8938 // Check for use of public/private annotation outside of os_log(). 8939 if (FSType != Sema::FST_OSLog) { 8940 if (FS.isPublic().isSet()) { 8941 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8942 << "public", 8943 getLocationOfByte(FS.isPublic().getPosition()), 8944 /*IsStringLocation*/ false, 8945 getSpecifierRange(startSpecifier, specifierLen)); 8946 } 8947 if (FS.isPrivate().isSet()) { 8948 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8949 << "private", 8950 getLocationOfByte(FS.isPrivate().getPosition()), 8951 /*IsStringLocation*/ false, 8952 getSpecifierRange(startSpecifier, specifierLen)); 8953 } 8954 } 8955 8956 // Check for invalid use of field width 8957 if (!FS.hasValidFieldWidth()) { 8958 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8959 startSpecifier, specifierLen); 8960 } 8961 8962 // Check for invalid use of precision 8963 if (!FS.hasValidPrecision()) { 8964 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8965 startSpecifier, specifierLen); 8966 } 8967 8968 // Precision is mandatory for %P specifier. 8969 if (CS.getKind() == ConversionSpecifier::PArg && 8970 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8971 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8972 getLocationOfByte(startSpecifier), 8973 /*IsStringLocation*/ false, 8974 getSpecifierRange(startSpecifier, specifierLen)); 8975 } 8976 8977 // Check each flag does not conflict with any other component. 8978 if (!FS.hasValidThousandsGroupingPrefix()) 8979 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8980 if (!FS.hasValidLeadingZeros()) 8981 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8982 if (!FS.hasValidPlusPrefix()) 8983 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8984 if (!FS.hasValidSpacePrefix()) 8985 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8986 if (!FS.hasValidAlternativeForm()) 8987 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8988 if (!FS.hasValidLeftJustified()) 8989 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8990 8991 // Check that flags are not ignored by another flag 8992 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8993 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8994 startSpecifier, specifierLen); 8995 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8996 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8997 startSpecifier, specifierLen); 8998 8999 // Check the length modifier is valid with the given conversion specifier. 9000 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9001 S.getLangOpts())) 9002 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9003 diag::warn_format_nonsensical_length); 9004 else if (!FS.hasStandardLengthModifier()) 9005 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9006 else if (!FS.hasStandardLengthConversionCombination()) 9007 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9008 diag::warn_format_non_standard_conversion_spec); 9009 9010 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9011 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9012 9013 // The remaining checks depend on the data arguments. 9014 if (HasVAListArg) 9015 return true; 9016 9017 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9018 return false; 9019 9020 const Expr *Arg = getDataArg(argIndex); 9021 if (!Arg) 9022 return true; 9023 9024 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9025 } 9026 9027 static bool requiresParensToAddCast(const Expr *E) { 9028 // FIXME: We should have a general way to reason about operator 9029 // precedence and whether parens are actually needed here. 9030 // Take care of a few common cases where they aren't. 9031 const Expr *Inside = E->IgnoreImpCasts(); 9032 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9033 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9034 9035 switch (Inside->getStmtClass()) { 9036 case Stmt::ArraySubscriptExprClass: 9037 case Stmt::CallExprClass: 9038 case Stmt::CharacterLiteralClass: 9039 case Stmt::CXXBoolLiteralExprClass: 9040 case Stmt::DeclRefExprClass: 9041 case Stmt::FloatingLiteralClass: 9042 case Stmt::IntegerLiteralClass: 9043 case Stmt::MemberExprClass: 9044 case Stmt::ObjCArrayLiteralClass: 9045 case Stmt::ObjCBoolLiteralExprClass: 9046 case Stmt::ObjCBoxedExprClass: 9047 case Stmt::ObjCDictionaryLiteralClass: 9048 case Stmt::ObjCEncodeExprClass: 9049 case Stmt::ObjCIvarRefExprClass: 9050 case Stmt::ObjCMessageExprClass: 9051 case Stmt::ObjCPropertyRefExprClass: 9052 case Stmt::ObjCStringLiteralClass: 9053 case Stmt::ObjCSubscriptRefExprClass: 9054 case Stmt::ParenExprClass: 9055 case Stmt::StringLiteralClass: 9056 case Stmt::UnaryOperatorClass: 9057 return false; 9058 default: 9059 return true; 9060 } 9061 } 9062 9063 static std::pair<QualType, StringRef> 9064 shouldNotPrintDirectly(const ASTContext &Context, 9065 QualType IntendedTy, 9066 const Expr *E) { 9067 // Use a 'while' to peel off layers of typedefs. 9068 QualType TyTy = IntendedTy; 9069 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9070 StringRef Name = UserTy->getDecl()->getName(); 9071 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9072 .Case("CFIndex", Context.getNSIntegerType()) 9073 .Case("NSInteger", Context.getNSIntegerType()) 9074 .Case("NSUInteger", Context.getNSUIntegerType()) 9075 .Case("SInt32", Context.IntTy) 9076 .Case("UInt32", Context.UnsignedIntTy) 9077 .Default(QualType()); 9078 9079 if (!CastTy.isNull()) 9080 return std::make_pair(CastTy, Name); 9081 9082 TyTy = UserTy->desugar(); 9083 } 9084 9085 // Strip parens if necessary. 9086 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9087 return shouldNotPrintDirectly(Context, 9088 PE->getSubExpr()->getType(), 9089 PE->getSubExpr()); 9090 9091 // If this is a conditional expression, then its result type is constructed 9092 // via usual arithmetic conversions and thus there might be no necessary 9093 // typedef sugar there. Recurse to operands to check for NSInteger & 9094 // Co. usage condition. 9095 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9096 QualType TrueTy, FalseTy; 9097 StringRef TrueName, FalseName; 9098 9099 std::tie(TrueTy, TrueName) = 9100 shouldNotPrintDirectly(Context, 9101 CO->getTrueExpr()->getType(), 9102 CO->getTrueExpr()); 9103 std::tie(FalseTy, FalseName) = 9104 shouldNotPrintDirectly(Context, 9105 CO->getFalseExpr()->getType(), 9106 CO->getFalseExpr()); 9107 9108 if (TrueTy == FalseTy) 9109 return std::make_pair(TrueTy, TrueName); 9110 else if (TrueTy.isNull()) 9111 return std::make_pair(FalseTy, FalseName); 9112 else if (FalseTy.isNull()) 9113 return std::make_pair(TrueTy, TrueName); 9114 } 9115 9116 return std::make_pair(QualType(), StringRef()); 9117 } 9118 9119 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9120 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9121 /// type do not count. 9122 static bool 9123 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9124 QualType From = ICE->getSubExpr()->getType(); 9125 QualType To = ICE->getType(); 9126 // It's an integer promotion if the destination type is the promoted 9127 // source type. 9128 if (ICE->getCastKind() == CK_IntegralCast && 9129 From->isPromotableIntegerType() && 9130 S.Context.getPromotedIntegerType(From) == To) 9131 return true; 9132 // Look through vector types, since we do default argument promotion for 9133 // those in OpenCL. 9134 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9135 From = VecTy->getElementType(); 9136 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9137 To = VecTy->getElementType(); 9138 // It's a floating promotion if the source type is a lower rank. 9139 return ICE->getCastKind() == CK_FloatingCast && 9140 S.Context.getFloatingTypeOrder(From, To) < 0; 9141 } 9142 9143 bool 9144 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9145 const char *StartSpecifier, 9146 unsigned SpecifierLen, 9147 const Expr *E) { 9148 using namespace analyze_format_string; 9149 using namespace analyze_printf; 9150 9151 // Now type check the data expression that matches the 9152 // format specifier. 9153 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9154 if (!AT.isValid()) 9155 return true; 9156 9157 QualType ExprTy = E->getType(); 9158 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9159 ExprTy = TET->getUnderlyingExpr()->getType(); 9160 } 9161 9162 // Diagnose attempts to print a boolean value as a character. Unlike other 9163 // -Wformat diagnostics, this is fine from a type perspective, but it still 9164 // doesn't make sense. 9165 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9166 E->isKnownToHaveBooleanValue()) { 9167 const CharSourceRange &CSR = 9168 getSpecifierRange(StartSpecifier, SpecifierLen); 9169 SmallString<4> FSString; 9170 llvm::raw_svector_ostream os(FSString); 9171 FS.toString(os); 9172 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9173 << FSString, 9174 E->getExprLoc(), false, CSR); 9175 return true; 9176 } 9177 9178 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9179 if (Match == analyze_printf::ArgType::Match) 9180 return true; 9181 9182 // Look through argument promotions for our error message's reported type. 9183 // This includes the integral and floating promotions, but excludes array 9184 // and function pointer decay (seeing that an argument intended to be a 9185 // string has type 'char [6]' is probably more confusing than 'char *') and 9186 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9187 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9188 if (isArithmeticArgumentPromotion(S, ICE)) { 9189 E = ICE->getSubExpr(); 9190 ExprTy = E->getType(); 9191 9192 // Check if we didn't match because of an implicit cast from a 'char' 9193 // or 'short' to an 'int'. This is done because printf is a varargs 9194 // function. 9195 if (ICE->getType() == S.Context.IntTy || 9196 ICE->getType() == S.Context.UnsignedIntTy) { 9197 // All further checking is done on the subexpression 9198 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9199 AT.matchesType(S.Context, ExprTy); 9200 if (ImplicitMatch == analyze_printf::ArgType::Match) 9201 return true; 9202 if (ImplicitMatch == ArgType::NoMatchPedantic || 9203 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9204 Match = ImplicitMatch; 9205 } 9206 } 9207 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9208 // Special case for 'a', which has type 'int' in C. 9209 // Note, however, that we do /not/ want to treat multibyte constants like 9210 // 'MooV' as characters! This form is deprecated but still exists. In 9211 // addition, don't treat expressions as of type 'char' if one byte length 9212 // modifier is provided. 9213 if (ExprTy == S.Context.IntTy && 9214 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9215 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9216 ExprTy = S.Context.CharTy; 9217 } 9218 9219 // Look through enums to their underlying type. 9220 bool IsEnum = false; 9221 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9222 ExprTy = EnumTy->getDecl()->getIntegerType(); 9223 IsEnum = true; 9224 } 9225 9226 // %C in an Objective-C context prints a unichar, not a wchar_t. 9227 // If the argument is an integer of some kind, believe the %C and suggest 9228 // a cast instead of changing the conversion specifier. 9229 QualType IntendedTy = ExprTy; 9230 if (isObjCContext() && 9231 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9232 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9233 !ExprTy->isCharType()) { 9234 // 'unichar' is defined as a typedef of unsigned short, but we should 9235 // prefer using the typedef if it is visible. 9236 IntendedTy = S.Context.UnsignedShortTy; 9237 9238 // While we are here, check if the value is an IntegerLiteral that happens 9239 // to be within the valid range. 9240 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9241 const llvm::APInt &V = IL->getValue(); 9242 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9243 return true; 9244 } 9245 9246 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9247 Sema::LookupOrdinaryName); 9248 if (S.LookupName(Result, S.getCurScope())) { 9249 NamedDecl *ND = Result.getFoundDecl(); 9250 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9251 if (TD->getUnderlyingType() == IntendedTy) 9252 IntendedTy = S.Context.getTypedefType(TD); 9253 } 9254 } 9255 } 9256 9257 // Special-case some of Darwin's platform-independence types by suggesting 9258 // casts to primitive types that are known to be large enough. 9259 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9260 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9261 QualType CastTy; 9262 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9263 if (!CastTy.isNull()) { 9264 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9265 // (long in ASTContext). Only complain to pedants. 9266 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9267 (AT.isSizeT() || AT.isPtrdiffT()) && 9268 AT.matchesType(S.Context, CastTy)) 9269 Match = ArgType::NoMatchPedantic; 9270 IntendedTy = CastTy; 9271 ShouldNotPrintDirectly = true; 9272 } 9273 } 9274 9275 // We may be able to offer a FixItHint if it is a supported type. 9276 PrintfSpecifier fixedFS = FS; 9277 bool Success = 9278 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9279 9280 if (Success) { 9281 // Get the fix string from the fixed format specifier 9282 SmallString<16> buf; 9283 llvm::raw_svector_ostream os(buf); 9284 fixedFS.toString(os); 9285 9286 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9287 9288 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9289 unsigned Diag; 9290 switch (Match) { 9291 case ArgType::Match: llvm_unreachable("expected non-matching"); 9292 case ArgType::NoMatchPedantic: 9293 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9294 break; 9295 case ArgType::NoMatchTypeConfusion: 9296 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9297 break; 9298 case ArgType::NoMatch: 9299 Diag = diag::warn_format_conversion_argument_type_mismatch; 9300 break; 9301 } 9302 9303 // In this case, the specifier is wrong and should be changed to match 9304 // the argument. 9305 EmitFormatDiagnostic(S.PDiag(Diag) 9306 << AT.getRepresentativeTypeName(S.Context) 9307 << IntendedTy << IsEnum << E->getSourceRange(), 9308 E->getBeginLoc(), 9309 /*IsStringLocation*/ false, SpecRange, 9310 FixItHint::CreateReplacement(SpecRange, os.str())); 9311 } else { 9312 // The canonical type for formatting this value is different from the 9313 // actual type of the expression. (This occurs, for example, with Darwin's 9314 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9315 // should be printed as 'long' for 64-bit compatibility.) 9316 // Rather than emitting a normal format/argument mismatch, we want to 9317 // add a cast to the recommended type (and correct the format string 9318 // if necessary). 9319 SmallString<16> CastBuf; 9320 llvm::raw_svector_ostream CastFix(CastBuf); 9321 CastFix << "("; 9322 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9323 CastFix << ")"; 9324 9325 SmallVector<FixItHint,4> Hints; 9326 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9327 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9328 9329 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9330 // If there's already a cast present, just replace it. 9331 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9332 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9333 9334 } else if (!requiresParensToAddCast(E)) { 9335 // If the expression has high enough precedence, 9336 // just write the C-style cast. 9337 Hints.push_back( 9338 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9339 } else { 9340 // Otherwise, add parens around the expression as well as the cast. 9341 CastFix << "("; 9342 Hints.push_back( 9343 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9344 9345 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9346 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9347 } 9348 9349 if (ShouldNotPrintDirectly) { 9350 // The expression has a type that should not be printed directly. 9351 // We extract the name from the typedef because we don't want to show 9352 // the underlying type in the diagnostic. 9353 StringRef Name; 9354 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9355 Name = TypedefTy->getDecl()->getName(); 9356 else 9357 Name = CastTyName; 9358 unsigned Diag = Match == ArgType::NoMatchPedantic 9359 ? diag::warn_format_argument_needs_cast_pedantic 9360 : diag::warn_format_argument_needs_cast; 9361 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9362 << E->getSourceRange(), 9363 E->getBeginLoc(), /*IsStringLocation=*/false, 9364 SpecRange, Hints); 9365 } else { 9366 // In this case, the expression could be printed using a different 9367 // specifier, but we've decided that the specifier is probably correct 9368 // and we should cast instead. Just use the normal warning message. 9369 EmitFormatDiagnostic( 9370 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9371 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9372 << E->getSourceRange(), 9373 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9374 } 9375 } 9376 } else { 9377 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9378 SpecifierLen); 9379 // Since the warning for passing non-POD types to variadic functions 9380 // was deferred until now, we emit a warning for non-POD 9381 // arguments here. 9382 switch (S.isValidVarArgType(ExprTy)) { 9383 case Sema::VAK_Valid: 9384 case Sema::VAK_ValidInCXX11: { 9385 unsigned Diag; 9386 switch (Match) { 9387 case ArgType::Match: llvm_unreachable("expected non-matching"); 9388 case ArgType::NoMatchPedantic: 9389 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9390 break; 9391 case ArgType::NoMatchTypeConfusion: 9392 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9393 break; 9394 case ArgType::NoMatch: 9395 Diag = diag::warn_format_conversion_argument_type_mismatch; 9396 break; 9397 } 9398 9399 EmitFormatDiagnostic( 9400 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9401 << IsEnum << CSR << E->getSourceRange(), 9402 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9403 break; 9404 } 9405 case Sema::VAK_Undefined: 9406 case Sema::VAK_MSVCUndefined: 9407 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9408 << S.getLangOpts().CPlusPlus11 << ExprTy 9409 << CallType 9410 << AT.getRepresentativeTypeName(S.Context) << CSR 9411 << E->getSourceRange(), 9412 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9413 checkForCStrMembers(AT, E); 9414 break; 9415 9416 case Sema::VAK_Invalid: 9417 if (ExprTy->isObjCObjectType()) 9418 EmitFormatDiagnostic( 9419 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9420 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9421 << AT.getRepresentativeTypeName(S.Context) << CSR 9422 << E->getSourceRange(), 9423 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9424 else 9425 // FIXME: If this is an initializer list, suggest removing the braces 9426 // or inserting a cast to the target type. 9427 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9428 << isa<InitListExpr>(E) << ExprTy << CallType 9429 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9430 break; 9431 } 9432 9433 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9434 "format string specifier index out of range"); 9435 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9436 } 9437 9438 return true; 9439 } 9440 9441 //===--- CHECK: Scanf format string checking ------------------------------===// 9442 9443 namespace { 9444 9445 class CheckScanfHandler : public CheckFormatHandler { 9446 public: 9447 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9448 const Expr *origFormatExpr, Sema::FormatStringType type, 9449 unsigned firstDataArg, unsigned numDataArgs, 9450 const char *beg, bool hasVAListArg, 9451 ArrayRef<const Expr *> Args, unsigned formatIdx, 9452 bool inFunctionCall, Sema::VariadicCallType CallType, 9453 llvm::SmallBitVector &CheckedVarArgs, 9454 UncoveredArgHandler &UncoveredArg) 9455 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9456 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9457 inFunctionCall, CallType, CheckedVarArgs, 9458 UncoveredArg) {} 9459 9460 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9461 const char *startSpecifier, 9462 unsigned specifierLen) override; 9463 9464 bool HandleInvalidScanfConversionSpecifier( 9465 const analyze_scanf::ScanfSpecifier &FS, 9466 const char *startSpecifier, 9467 unsigned specifierLen) override; 9468 9469 void HandleIncompleteScanList(const char *start, const char *end) override; 9470 }; 9471 9472 } // namespace 9473 9474 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9475 const char *end) { 9476 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9477 getLocationOfByte(end), /*IsStringLocation*/true, 9478 getSpecifierRange(start, end - start)); 9479 } 9480 9481 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9482 const analyze_scanf::ScanfSpecifier &FS, 9483 const char *startSpecifier, 9484 unsigned specifierLen) { 9485 const analyze_scanf::ScanfConversionSpecifier &CS = 9486 FS.getConversionSpecifier(); 9487 9488 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9489 getLocationOfByte(CS.getStart()), 9490 startSpecifier, specifierLen, 9491 CS.getStart(), CS.getLength()); 9492 } 9493 9494 bool CheckScanfHandler::HandleScanfSpecifier( 9495 const analyze_scanf::ScanfSpecifier &FS, 9496 const char *startSpecifier, 9497 unsigned specifierLen) { 9498 using namespace analyze_scanf; 9499 using namespace analyze_format_string; 9500 9501 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9502 9503 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9504 // be used to decide if we are using positional arguments consistently. 9505 if (FS.consumesDataArgument()) { 9506 if (atFirstArg) { 9507 atFirstArg = false; 9508 usesPositionalArgs = FS.usesPositionalArg(); 9509 } 9510 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9511 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9512 startSpecifier, specifierLen); 9513 return false; 9514 } 9515 } 9516 9517 // Check if the field with is non-zero. 9518 const OptionalAmount &Amt = FS.getFieldWidth(); 9519 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9520 if (Amt.getConstantAmount() == 0) { 9521 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9522 Amt.getConstantLength()); 9523 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9524 getLocationOfByte(Amt.getStart()), 9525 /*IsStringLocation*/true, R, 9526 FixItHint::CreateRemoval(R)); 9527 } 9528 } 9529 9530 if (!FS.consumesDataArgument()) { 9531 // FIXME: Technically specifying a precision or field width here 9532 // makes no sense. Worth issuing a warning at some point. 9533 return true; 9534 } 9535 9536 // Consume the argument. 9537 unsigned argIndex = FS.getArgIndex(); 9538 if (argIndex < NumDataArgs) { 9539 // The check to see if the argIndex is valid will come later. 9540 // We set the bit here because we may exit early from this 9541 // function if we encounter some other error. 9542 CoveredArgs.set(argIndex); 9543 } 9544 9545 // Check the length modifier is valid with the given conversion specifier. 9546 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9547 S.getLangOpts())) 9548 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9549 diag::warn_format_nonsensical_length); 9550 else if (!FS.hasStandardLengthModifier()) 9551 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9552 else if (!FS.hasStandardLengthConversionCombination()) 9553 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9554 diag::warn_format_non_standard_conversion_spec); 9555 9556 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9557 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9558 9559 // The remaining checks depend on the data arguments. 9560 if (HasVAListArg) 9561 return true; 9562 9563 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9564 return false; 9565 9566 // Check that the argument type matches the format specifier. 9567 const Expr *Ex = getDataArg(argIndex); 9568 if (!Ex) 9569 return true; 9570 9571 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9572 9573 if (!AT.isValid()) { 9574 return true; 9575 } 9576 9577 analyze_format_string::ArgType::MatchKind Match = 9578 AT.matchesType(S.Context, Ex->getType()); 9579 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9580 if (Match == analyze_format_string::ArgType::Match) 9581 return true; 9582 9583 ScanfSpecifier fixedFS = FS; 9584 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9585 S.getLangOpts(), S.Context); 9586 9587 unsigned Diag = 9588 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9589 : diag::warn_format_conversion_argument_type_mismatch; 9590 9591 if (Success) { 9592 // Get the fix string from the fixed format specifier. 9593 SmallString<128> buf; 9594 llvm::raw_svector_ostream os(buf); 9595 fixedFS.toString(os); 9596 9597 EmitFormatDiagnostic( 9598 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9599 << Ex->getType() << false << Ex->getSourceRange(), 9600 Ex->getBeginLoc(), 9601 /*IsStringLocation*/ false, 9602 getSpecifierRange(startSpecifier, specifierLen), 9603 FixItHint::CreateReplacement( 9604 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9605 } else { 9606 EmitFormatDiagnostic(S.PDiag(Diag) 9607 << AT.getRepresentativeTypeName(S.Context) 9608 << Ex->getType() << false << Ex->getSourceRange(), 9609 Ex->getBeginLoc(), 9610 /*IsStringLocation*/ false, 9611 getSpecifierRange(startSpecifier, specifierLen)); 9612 } 9613 9614 return true; 9615 } 9616 9617 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9618 const Expr *OrigFormatExpr, 9619 ArrayRef<const Expr *> Args, 9620 bool HasVAListArg, unsigned format_idx, 9621 unsigned firstDataArg, 9622 Sema::FormatStringType Type, 9623 bool inFunctionCall, 9624 Sema::VariadicCallType CallType, 9625 llvm::SmallBitVector &CheckedVarArgs, 9626 UncoveredArgHandler &UncoveredArg, 9627 bool IgnoreStringsWithoutSpecifiers) { 9628 // CHECK: is the format string a wide literal? 9629 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9630 CheckFormatHandler::EmitFormatDiagnostic( 9631 S, inFunctionCall, Args[format_idx], 9632 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9633 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9634 return; 9635 } 9636 9637 // Str - The format string. NOTE: this is NOT null-terminated! 9638 StringRef StrRef = FExpr->getString(); 9639 const char *Str = StrRef.data(); 9640 // Account for cases where the string literal is truncated in a declaration. 9641 const ConstantArrayType *T = 9642 S.Context.getAsConstantArrayType(FExpr->getType()); 9643 assert(T && "String literal not of constant array type!"); 9644 size_t TypeSize = T->getSize().getZExtValue(); 9645 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9646 const unsigned numDataArgs = Args.size() - firstDataArg; 9647 9648 if (IgnoreStringsWithoutSpecifiers && 9649 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9650 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9651 return; 9652 9653 // Emit a warning if the string literal is truncated and does not contain an 9654 // embedded null character. 9655 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 9656 CheckFormatHandler::EmitFormatDiagnostic( 9657 S, inFunctionCall, Args[format_idx], 9658 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9659 FExpr->getBeginLoc(), 9660 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9661 return; 9662 } 9663 9664 // CHECK: empty format string? 9665 if (StrLen == 0 && numDataArgs > 0) { 9666 CheckFormatHandler::EmitFormatDiagnostic( 9667 S, inFunctionCall, Args[format_idx], 9668 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9669 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9670 return; 9671 } 9672 9673 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9674 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9675 Type == Sema::FST_OSTrace) { 9676 CheckPrintfHandler H( 9677 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9678 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9679 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9680 CheckedVarArgs, UncoveredArg); 9681 9682 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9683 S.getLangOpts(), 9684 S.Context.getTargetInfo(), 9685 Type == Sema::FST_FreeBSDKPrintf)) 9686 H.DoneProcessing(); 9687 } else if (Type == Sema::FST_Scanf) { 9688 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9689 numDataArgs, Str, HasVAListArg, Args, format_idx, 9690 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9691 9692 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9693 S.getLangOpts(), 9694 S.Context.getTargetInfo())) 9695 H.DoneProcessing(); 9696 } // TODO: handle other formats 9697 } 9698 9699 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9700 // Str - The format string. NOTE: this is NOT null-terminated! 9701 StringRef StrRef = FExpr->getString(); 9702 const char *Str = StrRef.data(); 9703 // Account for cases where the string literal is truncated in a declaration. 9704 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9705 assert(T && "String literal not of constant array type!"); 9706 size_t TypeSize = T->getSize().getZExtValue(); 9707 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9708 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9709 getLangOpts(), 9710 Context.getTargetInfo()); 9711 } 9712 9713 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9714 9715 // Returns the related absolute value function that is larger, of 0 if one 9716 // does not exist. 9717 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9718 switch (AbsFunction) { 9719 default: 9720 return 0; 9721 9722 case Builtin::BI__builtin_abs: 9723 return Builtin::BI__builtin_labs; 9724 case Builtin::BI__builtin_labs: 9725 return Builtin::BI__builtin_llabs; 9726 case Builtin::BI__builtin_llabs: 9727 return 0; 9728 9729 case Builtin::BI__builtin_fabsf: 9730 return Builtin::BI__builtin_fabs; 9731 case Builtin::BI__builtin_fabs: 9732 return Builtin::BI__builtin_fabsl; 9733 case Builtin::BI__builtin_fabsl: 9734 return 0; 9735 9736 case Builtin::BI__builtin_cabsf: 9737 return Builtin::BI__builtin_cabs; 9738 case Builtin::BI__builtin_cabs: 9739 return Builtin::BI__builtin_cabsl; 9740 case Builtin::BI__builtin_cabsl: 9741 return 0; 9742 9743 case Builtin::BIabs: 9744 return Builtin::BIlabs; 9745 case Builtin::BIlabs: 9746 return Builtin::BIllabs; 9747 case Builtin::BIllabs: 9748 return 0; 9749 9750 case Builtin::BIfabsf: 9751 return Builtin::BIfabs; 9752 case Builtin::BIfabs: 9753 return Builtin::BIfabsl; 9754 case Builtin::BIfabsl: 9755 return 0; 9756 9757 case Builtin::BIcabsf: 9758 return Builtin::BIcabs; 9759 case Builtin::BIcabs: 9760 return Builtin::BIcabsl; 9761 case Builtin::BIcabsl: 9762 return 0; 9763 } 9764 } 9765 9766 // Returns the argument type of the absolute value function. 9767 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9768 unsigned AbsType) { 9769 if (AbsType == 0) 9770 return QualType(); 9771 9772 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9773 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9774 if (Error != ASTContext::GE_None) 9775 return QualType(); 9776 9777 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9778 if (!FT) 9779 return QualType(); 9780 9781 if (FT->getNumParams() != 1) 9782 return QualType(); 9783 9784 return FT->getParamType(0); 9785 } 9786 9787 // Returns the best absolute value function, or zero, based on type and 9788 // current absolute value function. 9789 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9790 unsigned AbsFunctionKind) { 9791 unsigned BestKind = 0; 9792 uint64_t ArgSize = Context.getTypeSize(ArgType); 9793 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9794 Kind = getLargerAbsoluteValueFunction(Kind)) { 9795 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9796 if (Context.getTypeSize(ParamType) >= ArgSize) { 9797 if (BestKind == 0) 9798 BestKind = Kind; 9799 else if (Context.hasSameType(ParamType, ArgType)) { 9800 BestKind = Kind; 9801 break; 9802 } 9803 } 9804 } 9805 return BestKind; 9806 } 9807 9808 enum AbsoluteValueKind { 9809 AVK_Integer, 9810 AVK_Floating, 9811 AVK_Complex 9812 }; 9813 9814 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9815 if (T->isIntegralOrEnumerationType()) 9816 return AVK_Integer; 9817 if (T->isRealFloatingType()) 9818 return AVK_Floating; 9819 if (T->isAnyComplexType()) 9820 return AVK_Complex; 9821 9822 llvm_unreachable("Type not integer, floating, or complex"); 9823 } 9824 9825 // Changes the absolute value function to a different type. Preserves whether 9826 // the function is a builtin. 9827 static unsigned changeAbsFunction(unsigned AbsKind, 9828 AbsoluteValueKind ValueKind) { 9829 switch (ValueKind) { 9830 case AVK_Integer: 9831 switch (AbsKind) { 9832 default: 9833 return 0; 9834 case Builtin::BI__builtin_fabsf: 9835 case Builtin::BI__builtin_fabs: 9836 case Builtin::BI__builtin_fabsl: 9837 case Builtin::BI__builtin_cabsf: 9838 case Builtin::BI__builtin_cabs: 9839 case Builtin::BI__builtin_cabsl: 9840 return Builtin::BI__builtin_abs; 9841 case Builtin::BIfabsf: 9842 case Builtin::BIfabs: 9843 case Builtin::BIfabsl: 9844 case Builtin::BIcabsf: 9845 case Builtin::BIcabs: 9846 case Builtin::BIcabsl: 9847 return Builtin::BIabs; 9848 } 9849 case AVK_Floating: 9850 switch (AbsKind) { 9851 default: 9852 return 0; 9853 case Builtin::BI__builtin_abs: 9854 case Builtin::BI__builtin_labs: 9855 case Builtin::BI__builtin_llabs: 9856 case Builtin::BI__builtin_cabsf: 9857 case Builtin::BI__builtin_cabs: 9858 case Builtin::BI__builtin_cabsl: 9859 return Builtin::BI__builtin_fabsf; 9860 case Builtin::BIabs: 9861 case Builtin::BIlabs: 9862 case Builtin::BIllabs: 9863 case Builtin::BIcabsf: 9864 case Builtin::BIcabs: 9865 case Builtin::BIcabsl: 9866 return Builtin::BIfabsf; 9867 } 9868 case AVK_Complex: 9869 switch (AbsKind) { 9870 default: 9871 return 0; 9872 case Builtin::BI__builtin_abs: 9873 case Builtin::BI__builtin_labs: 9874 case Builtin::BI__builtin_llabs: 9875 case Builtin::BI__builtin_fabsf: 9876 case Builtin::BI__builtin_fabs: 9877 case Builtin::BI__builtin_fabsl: 9878 return Builtin::BI__builtin_cabsf; 9879 case Builtin::BIabs: 9880 case Builtin::BIlabs: 9881 case Builtin::BIllabs: 9882 case Builtin::BIfabsf: 9883 case Builtin::BIfabs: 9884 case Builtin::BIfabsl: 9885 return Builtin::BIcabsf; 9886 } 9887 } 9888 llvm_unreachable("Unable to convert function"); 9889 } 9890 9891 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9892 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9893 if (!FnInfo) 9894 return 0; 9895 9896 switch (FDecl->getBuiltinID()) { 9897 default: 9898 return 0; 9899 case Builtin::BI__builtin_abs: 9900 case Builtin::BI__builtin_fabs: 9901 case Builtin::BI__builtin_fabsf: 9902 case Builtin::BI__builtin_fabsl: 9903 case Builtin::BI__builtin_labs: 9904 case Builtin::BI__builtin_llabs: 9905 case Builtin::BI__builtin_cabs: 9906 case Builtin::BI__builtin_cabsf: 9907 case Builtin::BI__builtin_cabsl: 9908 case Builtin::BIabs: 9909 case Builtin::BIlabs: 9910 case Builtin::BIllabs: 9911 case Builtin::BIfabs: 9912 case Builtin::BIfabsf: 9913 case Builtin::BIfabsl: 9914 case Builtin::BIcabs: 9915 case Builtin::BIcabsf: 9916 case Builtin::BIcabsl: 9917 return FDecl->getBuiltinID(); 9918 } 9919 llvm_unreachable("Unknown Builtin type"); 9920 } 9921 9922 // If the replacement is valid, emit a note with replacement function. 9923 // Additionally, suggest including the proper header if not already included. 9924 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9925 unsigned AbsKind, QualType ArgType) { 9926 bool EmitHeaderHint = true; 9927 const char *HeaderName = nullptr; 9928 const char *FunctionName = nullptr; 9929 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9930 FunctionName = "std::abs"; 9931 if (ArgType->isIntegralOrEnumerationType()) { 9932 HeaderName = "cstdlib"; 9933 } else if (ArgType->isRealFloatingType()) { 9934 HeaderName = "cmath"; 9935 } else { 9936 llvm_unreachable("Invalid Type"); 9937 } 9938 9939 // Lookup all std::abs 9940 if (NamespaceDecl *Std = S.getStdNamespace()) { 9941 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9942 R.suppressDiagnostics(); 9943 S.LookupQualifiedName(R, Std); 9944 9945 for (const auto *I : R) { 9946 const FunctionDecl *FDecl = nullptr; 9947 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9948 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9949 } else { 9950 FDecl = dyn_cast<FunctionDecl>(I); 9951 } 9952 if (!FDecl) 9953 continue; 9954 9955 // Found std::abs(), check that they are the right ones. 9956 if (FDecl->getNumParams() != 1) 9957 continue; 9958 9959 // Check that the parameter type can handle the argument. 9960 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9961 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9962 S.Context.getTypeSize(ArgType) <= 9963 S.Context.getTypeSize(ParamType)) { 9964 // Found a function, don't need the header hint. 9965 EmitHeaderHint = false; 9966 break; 9967 } 9968 } 9969 } 9970 } else { 9971 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9972 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9973 9974 if (HeaderName) { 9975 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9976 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9977 R.suppressDiagnostics(); 9978 S.LookupName(R, S.getCurScope()); 9979 9980 if (R.isSingleResult()) { 9981 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9982 if (FD && FD->getBuiltinID() == AbsKind) { 9983 EmitHeaderHint = false; 9984 } else { 9985 return; 9986 } 9987 } else if (!R.empty()) { 9988 return; 9989 } 9990 } 9991 } 9992 9993 S.Diag(Loc, diag::note_replace_abs_function) 9994 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9995 9996 if (!HeaderName) 9997 return; 9998 9999 if (!EmitHeaderHint) 10000 return; 10001 10002 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10003 << FunctionName; 10004 } 10005 10006 template <std::size_t StrLen> 10007 static bool IsStdFunction(const FunctionDecl *FDecl, 10008 const char (&Str)[StrLen]) { 10009 if (!FDecl) 10010 return false; 10011 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10012 return false; 10013 if (!FDecl->isInStdNamespace()) 10014 return false; 10015 10016 return true; 10017 } 10018 10019 // Warn when using the wrong abs() function. 10020 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10021 const FunctionDecl *FDecl) { 10022 if (Call->getNumArgs() != 1) 10023 return; 10024 10025 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10026 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10027 if (AbsKind == 0 && !IsStdAbs) 10028 return; 10029 10030 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10031 QualType ParamType = Call->getArg(0)->getType(); 10032 10033 // Unsigned types cannot be negative. Suggest removing the absolute value 10034 // function call. 10035 if (ArgType->isUnsignedIntegerType()) { 10036 const char *FunctionName = 10037 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10038 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10039 Diag(Call->getExprLoc(), diag::note_remove_abs) 10040 << FunctionName 10041 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10042 return; 10043 } 10044 10045 // Taking the absolute value of a pointer is very suspicious, they probably 10046 // wanted to index into an array, dereference a pointer, call a function, etc. 10047 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10048 unsigned DiagType = 0; 10049 if (ArgType->isFunctionType()) 10050 DiagType = 1; 10051 else if (ArgType->isArrayType()) 10052 DiagType = 2; 10053 10054 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10055 return; 10056 } 10057 10058 // std::abs has overloads which prevent most of the absolute value problems 10059 // from occurring. 10060 if (IsStdAbs) 10061 return; 10062 10063 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10064 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10065 10066 // The argument and parameter are the same kind. Check if they are the right 10067 // size. 10068 if (ArgValueKind == ParamValueKind) { 10069 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10070 return; 10071 10072 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10073 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10074 << FDecl << ArgType << ParamType; 10075 10076 if (NewAbsKind == 0) 10077 return; 10078 10079 emitReplacement(*this, Call->getExprLoc(), 10080 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10081 return; 10082 } 10083 10084 // ArgValueKind != ParamValueKind 10085 // The wrong type of absolute value function was used. Attempt to find the 10086 // proper one. 10087 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10088 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10089 if (NewAbsKind == 0) 10090 return; 10091 10092 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10093 << FDecl << ParamValueKind << ArgValueKind; 10094 10095 emitReplacement(*this, Call->getExprLoc(), 10096 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10097 } 10098 10099 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10100 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10101 const FunctionDecl *FDecl) { 10102 if (!Call || !FDecl) return; 10103 10104 // Ignore template specializations and macros. 10105 if (inTemplateInstantiation()) return; 10106 if (Call->getExprLoc().isMacroID()) return; 10107 10108 // Only care about the one template argument, two function parameter std::max 10109 if (Call->getNumArgs() != 2) return; 10110 if (!IsStdFunction(FDecl, "max")) return; 10111 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10112 if (!ArgList) return; 10113 if (ArgList->size() != 1) return; 10114 10115 // Check that template type argument is unsigned integer. 10116 const auto& TA = ArgList->get(0); 10117 if (TA.getKind() != TemplateArgument::Type) return; 10118 QualType ArgType = TA.getAsType(); 10119 if (!ArgType->isUnsignedIntegerType()) return; 10120 10121 // See if either argument is a literal zero. 10122 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10123 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10124 if (!MTE) return false; 10125 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10126 if (!Num) return false; 10127 if (Num->getValue() != 0) return false; 10128 return true; 10129 }; 10130 10131 const Expr *FirstArg = Call->getArg(0); 10132 const Expr *SecondArg = Call->getArg(1); 10133 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10134 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10135 10136 // Only warn when exactly one argument is zero. 10137 if (IsFirstArgZero == IsSecondArgZero) return; 10138 10139 SourceRange FirstRange = FirstArg->getSourceRange(); 10140 SourceRange SecondRange = SecondArg->getSourceRange(); 10141 10142 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10143 10144 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10145 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10146 10147 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10148 SourceRange RemovalRange; 10149 if (IsFirstArgZero) { 10150 RemovalRange = SourceRange(FirstRange.getBegin(), 10151 SecondRange.getBegin().getLocWithOffset(-1)); 10152 } else { 10153 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10154 SecondRange.getEnd()); 10155 } 10156 10157 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10158 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10159 << FixItHint::CreateRemoval(RemovalRange); 10160 } 10161 10162 //===--- CHECK: Standard memory functions ---------------------------------===// 10163 10164 /// Takes the expression passed to the size_t parameter of functions 10165 /// such as memcmp, strncat, etc and warns if it's a comparison. 10166 /// 10167 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10168 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10169 IdentifierInfo *FnName, 10170 SourceLocation FnLoc, 10171 SourceLocation RParenLoc) { 10172 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10173 if (!Size) 10174 return false; 10175 10176 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10177 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10178 return false; 10179 10180 SourceRange SizeRange = Size->getSourceRange(); 10181 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10182 << SizeRange << FnName; 10183 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10184 << FnName 10185 << FixItHint::CreateInsertion( 10186 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10187 << FixItHint::CreateRemoval(RParenLoc); 10188 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10189 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10190 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10191 ")"); 10192 10193 return true; 10194 } 10195 10196 /// Determine whether the given type is or contains a dynamic class type 10197 /// (e.g., whether it has a vtable). 10198 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10199 bool &IsContained) { 10200 // Look through array types while ignoring qualifiers. 10201 const Type *Ty = T->getBaseElementTypeUnsafe(); 10202 IsContained = false; 10203 10204 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10205 RD = RD ? RD->getDefinition() : nullptr; 10206 if (!RD || RD->isInvalidDecl()) 10207 return nullptr; 10208 10209 if (RD->isDynamicClass()) 10210 return RD; 10211 10212 // Check all the fields. If any bases were dynamic, the class is dynamic. 10213 // It's impossible for a class to transitively contain itself by value, so 10214 // infinite recursion is impossible. 10215 for (auto *FD : RD->fields()) { 10216 bool SubContained; 10217 if (const CXXRecordDecl *ContainedRD = 10218 getContainedDynamicClass(FD->getType(), SubContained)) { 10219 IsContained = true; 10220 return ContainedRD; 10221 } 10222 } 10223 10224 return nullptr; 10225 } 10226 10227 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10228 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10229 if (Unary->getKind() == UETT_SizeOf) 10230 return Unary; 10231 return nullptr; 10232 } 10233 10234 /// If E is a sizeof expression, returns its argument expression, 10235 /// otherwise returns NULL. 10236 static const Expr *getSizeOfExprArg(const Expr *E) { 10237 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10238 if (!SizeOf->isArgumentType()) 10239 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10240 return nullptr; 10241 } 10242 10243 /// If E is a sizeof expression, returns its argument type. 10244 static QualType getSizeOfArgType(const Expr *E) { 10245 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10246 return SizeOf->getTypeOfArgument(); 10247 return QualType(); 10248 } 10249 10250 namespace { 10251 10252 struct SearchNonTrivialToInitializeField 10253 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10254 using Super = 10255 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10256 10257 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10258 10259 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10260 SourceLocation SL) { 10261 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10262 asDerived().visitArray(PDIK, AT, SL); 10263 return; 10264 } 10265 10266 Super::visitWithKind(PDIK, FT, SL); 10267 } 10268 10269 void visitARCStrong(QualType FT, SourceLocation SL) { 10270 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10271 } 10272 void visitARCWeak(QualType FT, SourceLocation SL) { 10273 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10274 } 10275 void visitStruct(QualType FT, SourceLocation SL) { 10276 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10277 visit(FD->getType(), FD->getLocation()); 10278 } 10279 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10280 const ArrayType *AT, SourceLocation SL) { 10281 visit(getContext().getBaseElementType(AT), SL); 10282 } 10283 void visitTrivial(QualType FT, SourceLocation SL) {} 10284 10285 static void diag(QualType RT, const Expr *E, Sema &S) { 10286 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10287 } 10288 10289 ASTContext &getContext() { return S.getASTContext(); } 10290 10291 const Expr *E; 10292 Sema &S; 10293 }; 10294 10295 struct SearchNonTrivialToCopyField 10296 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10297 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10298 10299 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10300 10301 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10302 SourceLocation SL) { 10303 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10304 asDerived().visitArray(PCK, AT, SL); 10305 return; 10306 } 10307 10308 Super::visitWithKind(PCK, FT, SL); 10309 } 10310 10311 void visitARCStrong(QualType FT, SourceLocation SL) { 10312 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10313 } 10314 void visitARCWeak(QualType FT, SourceLocation SL) { 10315 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10316 } 10317 void visitStruct(QualType FT, SourceLocation SL) { 10318 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10319 visit(FD->getType(), FD->getLocation()); 10320 } 10321 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10322 SourceLocation SL) { 10323 visit(getContext().getBaseElementType(AT), SL); 10324 } 10325 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10326 SourceLocation SL) {} 10327 void visitTrivial(QualType FT, SourceLocation SL) {} 10328 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10329 10330 static void diag(QualType RT, const Expr *E, Sema &S) { 10331 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10332 } 10333 10334 ASTContext &getContext() { return S.getASTContext(); } 10335 10336 const Expr *E; 10337 Sema &S; 10338 }; 10339 10340 } 10341 10342 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10343 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10344 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10345 10346 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10347 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10348 return false; 10349 10350 return doesExprLikelyComputeSize(BO->getLHS()) || 10351 doesExprLikelyComputeSize(BO->getRHS()); 10352 } 10353 10354 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10355 } 10356 10357 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10358 /// 10359 /// \code 10360 /// #define MACRO 0 10361 /// foo(MACRO); 10362 /// foo(0); 10363 /// \endcode 10364 /// 10365 /// This should return true for the first call to foo, but not for the second 10366 /// (regardless of whether foo is a macro or function). 10367 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10368 SourceLocation CallLoc, 10369 SourceLocation ArgLoc) { 10370 if (!CallLoc.isMacroID()) 10371 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10372 10373 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10374 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10375 } 10376 10377 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10378 /// last two arguments transposed. 10379 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10380 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10381 return; 10382 10383 const Expr *SizeArg = 10384 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10385 10386 auto isLiteralZero = [](const Expr *E) { 10387 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10388 }; 10389 10390 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10391 SourceLocation CallLoc = Call->getRParenLoc(); 10392 SourceManager &SM = S.getSourceManager(); 10393 if (isLiteralZero(SizeArg) && 10394 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10395 10396 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10397 10398 // Some platforms #define bzero to __builtin_memset. See if this is the 10399 // case, and if so, emit a better diagnostic. 10400 if (BId == Builtin::BIbzero || 10401 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10402 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10403 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10404 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10405 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10406 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10407 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10408 } 10409 return; 10410 } 10411 10412 // If the second argument to a memset is a sizeof expression and the third 10413 // isn't, this is also likely an error. This should catch 10414 // 'memset(buf, sizeof(buf), 0xff)'. 10415 if (BId == Builtin::BImemset && 10416 doesExprLikelyComputeSize(Call->getArg(1)) && 10417 !doesExprLikelyComputeSize(Call->getArg(2))) { 10418 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10419 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10420 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10421 return; 10422 } 10423 } 10424 10425 /// Check for dangerous or invalid arguments to memset(). 10426 /// 10427 /// This issues warnings on known problematic, dangerous or unspecified 10428 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10429 /// function calls. 10430 /// 10431 /// \param Call The call expression to diagnose. 10432 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10433 unsigned BId, 10434 IdentifierInfo *FnName) { 10435 assert(BId != 0); 10436 10437 // It is possible to have a non-standard definition of memset. Validate 10438 // we have enough arguments, and if not, abort further checking. 10439 unsigned ExpectedNumArgs = 10440 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10441 if (Call->getNumArgs() < ExpectedNumArgs) 10442 return; 10443 10444 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10445 BId == Builtin::BIstrndup ? 1 : 2); 10446 unsigned LenArg = 10447 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10448 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10449 10450 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10451 Call->getBeginLoc(), Call->getRParenLoc())) 10452 return; 10453 10454 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10455 CheckMemaccessSize(*this, BId, Call); 10456 10457 // We have special checking when the length is a sizeof expression. 10458 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10459 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10460 llvm::FoldingSetNodeID SizeOfArgID; 10461 10462 // Although widely used, 'bzero' is not a standard function. Be more strict 10463 // with the argument types before allowing diagnostics and only allow the 10464 // form bzero(ptr, sizeof(...)). 10465 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10466 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10467 return; 10468 10469 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10470 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10471 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10472 10473 QualType DestTy = Dest->getType(); 10474 QualType PointeeTy; 10475 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10476 PointeeTy = DestPtrTy->getPointeeType(); 10477 10478 // Never warn about void type pointers. This can be used to suppress 10479 // false positives. 10480 if (PointeeTy->isVoidType()) 10481 continue; 10482 10483 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10484 // actually comparing the expressions for equality. Because computing the 10485 // expression IDs can be expensive, we only do this if the diagnostic is 10486 // enabled. 10487 if (SizeOfArg && 10488 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10489 SizeOfArg->getExprLoc())) { 10490 // We only compute IDs for expressions if the warning is enabled, and 10491 // cache the sizeof arg's ID. 10492 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10493 SizeOfArg->Profile(SizeOfArgID, Context, true); 10494 llvm::FoldingSetNodeID DestID; 10495 Dest->Profile(DestID, Context, true); 10496 if (DestID == SizeOfArgID) { 10497 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10498 // over sizeof(src) as well. 10499 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10500 StringRef ReadableName = FnName->getName(); 10501 10502 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10503 if (UnaryOp->getOpcode() == UO_AddrOf) 10504 ActionIdx = 1; // If its an address-of operator, just remove it. 10505 if (!PointeeTy->isIncompleteType() && 10506 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10507 ActionIdx = 2; // If the pointee's size is sizeof(char), 10508 // suggest an explicit length. 10509 10510 // If the function is defined as a builtin macro, do not show macro 10511 // expansion. 10512 SourceLocation SL = SizeOfArg->getExprLoc(); 10513 SourceRange DSR = Dest->getSourceRange(); 10514 SourceRange SSR = SizeOfArg->getSourceRange(); 10515 SourceManager &SM = getSourceManager(); 10516 10517 if (SM.isMacroArgExpansion(SL)) { 10518 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10519 SL = SM.getSpellingLoc(SL); 10520 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10521 SM.getSpellingLoc(DSR.getEnd())); 10522 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10523 SM.getSpellingLoc(SSR.getEnd())); 10524 } 10525 10526 DiagRuntimeBehavior(SL, SizeOfArg, 10527 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10528 << ReadableName 10529 << PointeeTy 10530 << DestTy 10531 << DSR 10532 << SSR); 10533 DiagRuntimeBehavior(SL, SizeOfArg, 10534 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10535 << ActionIdx 10536 << SSR); 10537 10538 break; 10539 } 10540 } 10541 10542 // Also check for cases where the sizeof argument is the exact same 10543 // type as the memory argument, and where it points to a user-defined 10544 // record type. 10545 if (SizeOfArgTy != QualType()) { 10546 if (PointeeTy->isRecordType() && 10547 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10548 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10549 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10550 << FnName << SizeOfArgTy << ArgIdx 10551 << PointeeTy << Dest->getSourceRange() 10552 << LenExpr->getSourceRange()); 10553 break; 10554 } 10555 } 10556 } else if (DestTy->isArrayType()) { 10557 PointeeTy = DestTy; 10558 } 10559 10560 if (PointeeTy == QualType()) 10561 continue; 10562 10563 // Always complain about dynamic classes. 10564 bool IsContained; 10565 if (const CXXRecordDecl *ContainedRD = 10566 getContainedDynamicClass(PointeeTy, IsContained)) { 10567 10568 unsigned OperationType = 0; 10569 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10570 // "overwritten" if we're warning about the destination for any call 10571 // but memcmp; otherwise a verb appropriate to the call. 10572 if (ArgIdx != 0 || IsCmp) { 10573 if (BId == Builtin::BImemcpy) 10574 OperationType = 1; 10575 else if(BId == Builtin::BImemmove) 10576 OperationType = 2; 10577 else if (IsCmp) 10578 OperationType = 3; 10579 } 10580 10581 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10582 PDiag(diag::warn_dyn_class_memaccess) 10583 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10584 << IsContained << ContainedRD << OperationType 10585 << Call->getCallee()->getSourceRange()); 10586 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10587 BId != Builtin::BImemset) 10588 DiagRuntimeBehavior( 10589 Dest->getExprLoc(), Dest, 10590 PDiag(diag::warn_arc_object_memaccess) 10591 << ArgIdx << FnName << PointeeTy 10592 << Call->getCallee()->getSourceRange()); 10593 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10594 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10595 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10596 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10597 PDiag(diag::warn_cstruct_memaccess) 10598 << ArgIdx << FnName << PointeeTy << 0); 10599 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10600 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10601 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10602 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10603 PDiag(diag::warn_cstruct_memaccess) 10604 << ArgIdx << FnName << PointeeTy << 1); 10605 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10606 } else { 10607 continue; 10608 } 10609 } else 10610 continue; 10611 10612 DiagRuntimeBehavior( 10613 Dest->getExprLoc(), Dest, 10614 PDiag(diag::note_bad_memaccess_silence) 10615 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10616 break; 10617 } 10618 } 10619 10620 // A little helper routine: ignore addition and subtraction of integer literals. 10621 // This intentionally does not ignore all integer constant expressions because 10622 // we don't want to remove sizeof(). 10623 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10624 Ex = Ex->IgnoreParenCasts(); 10625 10626 while (true) { 10627 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10628 if (!BO || !BO->isAdditiveOp()) 10629 break; 10630 10631 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10632 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10633 10634 if (isa<IntegerLiteral>(RHS)) 10635 Ex = LHS; 10636 else if (isa<IntegerLiteral>(LHS)) 10637 Ex = RHS; 10638 else 10639 break; 10640 } 10641 10642 return Ex; 10643 } 10644 10645 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10646 ASTContext &Context) { 10647 // Only handle constant-sized or VLAs, but not flexible members. 10648 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10649 // Only issue the FIXIT for arrays of size > 1. 10650 if (CAT->getSize().getSExtValue() <= 1) 10651 return false; 10652 } else if (!Ty->isVariableArrayType()) { 10653 return false; 10654 } 10655 return true; 10656 } 10657 10658 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10659 // be the size of the source, instead of the destination. 10660 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10661 IdentifierInfo *FnName) { 10662 10663 // Don't crash if the user has the wrong number of arguments 10664 unsigned NumArgs = Call->getNumArgs(); 10665 if ((NumArgs != 3) && (NumArgs != 4)) 10666 return; 10667 10668 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10669 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10670 const Expr *CompareWithSrc = nullptr; 10671 10672 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10673 Call->getBeginLoc(), Call->getRParenLoc())) 10674 return; 10675 10676 // Look for 'strlcpy(dst, x, sizeof(x))' 10677 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10678 CompareWithSrc = Ex; 10679 else { 10680 // Look for 'strlcpy(dst, x, strlen(x))' 10681 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10682 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10683 SizeCall->getNumArgs() == 1) 10684 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10685 } 10686 } 10687 10688 if (!CompareWithSrc) 10689 return; 10690 10691 // Determine if the argument to sizeof/strlen is equal to the source 10692 // argument. In principle there's all kinds of things you could do 10693 // here, for instance creating an == expression and evaluating it with 10694 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10695 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10696 if (!SrcArgDRE) 10697 return; 10698 10699 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10700 if (!CompareWithSrcDRE || 10701 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10702 return; 10703 10704 const Expr *OriginalSizeArg = Call->getArg(2); 10705 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10706 << OriginalSizeArg->getSourceRange() << FnName; 10707 10708 // Output a FIXIT hint if the destination is an array (rather than a 10709 // pointer to an array). This could be enhanced to handle some 10710 // pointers if we know the actual size, like if DstArg is 'array+2' 10711 // we could say 'sizeof(array)-2'. 10712 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10713 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10714 return; 10715 10716 SmallString<128> sizeString; 10717 llvm::raw_svector_ostream OS(sizeString); 10718 OS << "sizeof("; 10719 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10720 OS << ")"; 10721 10722 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10723 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10724 OS.str()); 10725 } 10726 10727 /// Check if two expressions refer to the same declaration. 10728 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10729 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10730 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10731 return D1->getDecl() == D2->getDecl(); 10732 return false; 10733 } 10734 10735 static const Expr *getStrlenExprArg(const Expr *E) { 10736 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10737 const FunctionDecl *FD = CE->getDirectCallee(); 10738 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10739 return nullptr; 10740 return CE->getArg(0)->IgnoreParenCasts(); 10741 } 10742 return nullptr; 10743 } 10744 10745 // Warn on anti-patterns as the 'size' argument to strncat. 10746 // The correct size argument should look like following: 10747 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10748 void Sema::CheckStrncatArguments(const CallExpr *CE, 10749 IdentifierInfo *FnName) { 10750 // Don't crash if the user has the wrong number of arguments. 10751 if (CE->getNumArgs() < 3) 10752 return; 10753 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10754 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10755 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10756 10757 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10758 CE->getRParenLoc())) 10759 return; 10760 10761 // Identify common expressions, which are wrongly used as the size argument 10762 // to strncat and may lead to buffer overflows. 10763 unsigned PatternType = 0; 10764 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10765 // - sizeof(dst) 10766 if (referToTheSameDecl(SizeOfArg, DstArg)) 10767 PatternType = 1; 10768 // - sizeof(src) 10769 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10770 PatternType = 2; 10771 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10772 if (BE->getOpcode() == BO_Sub) { 10773 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10774 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10775 // - sizeof(dst) - strlen(dst) 10776 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10777 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10778 PatternType = 1; 10779 // - sizeof(src) - (anything) 10780 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10781 PatternType = 2; 10782 } 10783 } 10784 10785 if (PatternType == 0) 10786 return; 10787 10788 // Generate the diagnostic. 10789 SourceLocation SL = LenArg->getBeginLoc(); 10790 SourceRange SR = LenArg->getSourceRange(); 10791 SourceManager &SM = getSourceManager(); 10792 10793 // If the function is defined as a builtin macro, do not show macro expansion. 10794 if (SM.isMacroArgExpansion(SL)) { 10795 SL = SM.getSpellingLoc(SL); 10796 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10797 SM.getSpellingLoc(SR.getEnd())); 10798 } 10799 10800 // Check if the destination is an array (rather than a pointer to an array). 10801 QualType DstTy = DstArg->getType(); 10802 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10803 Context); 10804 if (!isKnownSizeArray) { 10805 if (PatternType == 1) 10806 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10807 else 10808 Diag(SL, diag::warn_strncat_src_size) << SR; 10809 return; 10810 } 10811 10812 if (PatternType == 1) 10813 Diag(SL, diag::warn_strncat_large_size) << SR; 10814 else 10815 Diag(SL, diag::warn_strncat_src_size) << SR; 10816 10817 SmallString<128> sizeString; 10818 llvm::raw_svector_ostream OS(sizeString); 10819 OS << "sizeof("; 10820 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10821 OS << ") - "; 10822 OS << "strlen("; 10823 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10824 OS << ") - 1"; 10825 10826 Diag(SL, diag::note_strncat_wrong_size) 10827 << FixItHint::CreateReplacement(SR, OS.str()); 10828 } 10829 10830 namespace { 10831 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10832 const UnaryOperator *UnaryExpr, const Decl *D) { 10833 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10834 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10835 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10836 return; 10837 } 10838 } 10839 10840 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10841 const UnaryOperator *UnaryExpr) { 10842 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10843 const Decl *D = Lvalue->getDecl(); 10844 if (isa<DeclaratorDecl>(D)) 10845 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10846 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10847 } 10848 10849 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10850 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10851 Lvalue->getMemberDecl()); 10852 } 10853 10854 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10855 const UnaryOperator *UnaryExpr) { 10856 const auto *Lambda = dyn_cast<LambdaExpr>( 10857 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10858 if (!Lambda) 10859 return; 10860 10861 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10862 << CalleeName << 2 /*object: lambda expression*/; 10863 } 10864 10865 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10866 const DeclRefExpr *Lvalue) { 10867 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10868 if (Var == nullptr) 10869 return; 10870 10871 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10872 << CalleeName << 0 /*object: */ << Var; 10873 } 10874 10875 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10876 const CastExpr *Cast) { 10877 SmallString<128> SizeString; 10878 llvm::raw_svector_ostream OS(SizeString); 10879 10880 clang::CastKind Kind = Cast->getCastKind(); 10881 if (Kind == clang::CK_BitCast && 10882 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10883 return; 10884 if (Kind == clang::CK_IntegralToPointer && 10885 !isa<IntegerLiteral>( 10886 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10887 return; 10888 10889 switch (Cast->getCastKind()) { 10890 case clang::CK_BitCast: 10891 case clang::CK_IntegralToPointer: 10892 case clang::CK_FunctionToPointerDecay: 10893 OS << '\''; 10894 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10895 OS << '\''; 10896 break; 10897 default: 10898 return; 10899 } 10900 10901 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10902 << CalleeName << 0 /*object: */ << OS.str(); 10903 } 10904 } // namespace 10905 10906 /// Alerts the user that they are attempting to free a non-malloc'd object. 10907 void Sema::CheckFreeArguments(const CallExpr *E) { 10908 const std::string CalleeName = 10909 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10910 10911 { // Prefer something that doesn't involve a cast to make things simpler. 10912 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10913 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10914 switch (UnaryExpr->getOpcode()) { 10915 case UnaryOperator::Opcode::UO_AddrOf: 10916 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10917 case UnaryOperator::Opcode::UO_Plus: 10918 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10919 default: 10920 break; 10921 } 10922 10923 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10924 if (Lvalue->getType()->isArrayType()) 10925 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10926 10927 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10928 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10929 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10930 return; 10931 } 10932 10933 if (isa<BlockExpr>(Arg)) { 10934 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10935 << CalleeName << 1 /*object: block*/; 10936 return; 10937 } 10938 } 10939 // Maybe the cast was important, check after the other cases. 10940 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10941 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10942 } 10943 10944 void 10945 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10946 SourceLocation ReturnLoc, 10947 bool isObjCMethod, 10948 const AttrVec *Attrs, 10949 const FunctionDecl *FD) { 10950 // Check if the return value is null but should not be. 10951 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10952 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10953 CheckNonNullExpr(*this, RetValExp)) 10954 Diag(ReturnLoc, diag::warn_null_ret) 10955 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10956 10957 // C++11 [basic.stc.dynamic.allocation]p4: 10958 // If an allocation function declared with a non-throwing 10959 // exception-specification fails to allocate storage, it shall return 10960 // a null pointer. Any other allocation function that fails to allocate 10961 // storage shall indicate failure only by throwing an exception [...] 10962 if (FD) { 10963 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10964 if (Op == OO_New || Op == OO_Array_New) { 10965 const FunctionProtoType *Proto 10966 = FD->getType()->castAs<FunctionProtoType>(); 10967 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10968 CheckNonNullExpr(*this, RetValExp)) 10969 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10970 << FD << getLangOpts().CPlusPlus11; 10971 } 10972 } 10973 10974 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10975 // here prevent the user from using a PPC MMA type as trailing return type. 10976 if (Context.getTargetInfo().getTriple().isPPC64()) 10977 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10978 } 10979 10980 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10981 10982 /// Check for comparisons of floating point operands using != and ==. 10983 /// Issue a warning if these are no self-comparisons, as they are not likely 10984 /// to do what the programmer intended. 10985 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10986 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10987 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10988 10989 // Special case: check for x == x (which is OK). 10990 // Do not emit warnings for such cases. 10991 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10992 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10993 if (DRL->getDecl() == DRR->getDecl()) 10994 return; 10995 10996 // Special case: check for comparisons against literals that can be exactly 10997 // represented by APFloat. In such cases, do not emit a warning. This 10998 // is a heuristic: often comparison against such literals are used to 10999 // detect if a value in a variable has not changed. This clearly can 11000 // lead to false negatives. 11001 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11002 if (FLL->isExact()) 11003 return; 11004 } else 11005 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11006 if (FLR->isExact()) 11007 return; 11008 11009 // Check for comparisons with builtin types. 11010 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11011 if (CL->getBuiltinCallee()) 11012 return; 11013 11014 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11015 if (CR->getBuiltinCallee()) 11016 return; 11017 11018 // Emit the diagnostic. 11019 Diag(Loc, diag::warn_floatingpoint_eq) 11020 << LHS->getSourceRange() << RHS->getSourceRange(); 11021 } 11022 11023 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11024 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11025 11026 namespace { 11027 11028 /// Structure recording the 'active' range of an integer-valued 11029 /// expression. 11030 struct IntRange { 11031 /// The number of bits active in the int. Note that this includes exactly one 11032 /// sign bit if !NonNegative. 11033 unsigned Width; 11034 11035 /// True if the int is known not to have negative values. If so, all leading 11036 /// bits before Width are known zero, otherwise they are known to be the 11037 /// same as the MSB within Width. 11038 bool NonNegative; 11039 11040 IntRange(unsigned Width, bool NonNegative) 11041 : Width(Width), NonNegative(NonNegative) {} 11042 11043 /// Number of bits excluding the sign bit. 11044 unsigned valueBits() const { 11045 return NonNegative ? Width : Width - 1; 11046 } 11047 11048 /// Returns the range of the bool type. 11049 static IntRange forBoolType() { 11050 return IntRange(1, true); 11051 } 11052 11053 /// Returns the range of an opaque value of the given integral type. 11054 static IntRange forValueOfType(ASTContext &C, QualType T) { 11055 return forValueOfCanonicalType(C, 11056 T->getCanonicalTypeInternal().getTypePtr()); 11057 } 11058 11059 /// Returns the range of an opaque value of a canonical integral type. 11060 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11061 assert(T->isCanonicalUnqualified()); 11062 11063 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11064 T = VT->getElementType().getTypePtr(); 11065 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11066 T = CT->getElementType().getTypePtr(); 11067 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11068 T = AT->getValueType().getTypePtr(); 11069 11070 if (!C.getLangOpts().CPlusPlus) { 11071 // For enum types in C code, use the underlying datatype. 11072 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11073 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11074 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11075 // For enum types in C++, use the known bit width of the enumerators. 11076 EnumDecl *Enum = ET->getDecl(); 11077 // In C++11, enums can have a fixed underlying type. Use this type to 11078 // compute the range. 11079 if (Enum->isFixed()) { 11080 return IntRange(C.getIntWidth(QualType(T, 0)), 11081 !ET->isSignedIntegerOrEnumerationType()); 11082 } 11083 11084 unsigned NumPositive = Enum->getNumPositiveBits(); 11085 unsigned NumNegative = Enum->getNumNegativeBits(); 11086 11087 if (NumNegative == 0) 11088 return IntRange(NumPositive, true/*NonNegative*/); 11089 else 11090 return IntRange(std::max(NumPositive + 1, NumNegative), 11091 false/*NonNegative*/); 11092 } 11093 11094 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11095 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11096 11097 const BuiltinType *BT = cast<BuiltinType>(T); 11098 assert(BT->isInteger()); 11099 11100 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11101 } 11102 11103 /// Returns the "target" range of a canonical integral type, i.e. 11104 /// the range of values expressible in the type. 11105 /// 11106 /// This matches forValueOfCanonicalType except that enums have the 11107 /// full range of their type, not the range of their enumerators. 11108 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11109 assert(T->isCanonicalUnqualified()); 11110 11111 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11112 T = VT->getElementType().getTypePtr(); 11113 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11114 T = CT->getElementType().getTypePtr(); 11115 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11116 T = AT->getValueType().getTypePtr(); 11117 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11118 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11119 11120 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11121 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11122 11123 const BuiltinType *BT = cast<BuiltinType>(T); 11124 assert(BT->isInteger()); 11125 11126 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11127 } 11128 11129 /// Returns the supremum of two ranges: i.e. their conservative merge. 11130 static IntRange join(IntRange L, IntRange R) { 11131 bool Unsigned = L.NonNegative && R.NonNegative; 11132 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11133 L.NonNegative && R.NonNegative); 11134 } 11135 11136 /// Return the range of a bitwise-AND of the two ranges. 11137 static IntRange bit_and(IntRange L, IntRange R) { 11138 unsigned Bits = std::max(L.Width, R.Width); 11139 bool NonNegative = false; 11140 if (L.NonNegative) { 11141 Bits = std::min(Bits, L.Width); 11142 NonNegative = true; 11143 } 11144 if (R.NonNegative) { 11145 Bits = std::min(Bits, R.Width); 11146 NonNegative = true; 11147 } 11148 return IntRange(Bits, NonNegative); 11149 } 11150 11151 /// Return the range of a sum of the two ranges. 11152 static IntRange sum(IntRange L, IntRange R) { 11153 bool Unsigned = L.NonNegative && R.NonNegative; 11154 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11155 Unsigned); 11156 } 11157 11158 /// Return the range of a difference of the two ranges. 11159 static IntRange difference(IntRange L, IntRange R) { 11160 // We need a 1-bit-wider range if: 11161 // 1) LHS can be negative: least value can be reduced. 11162 // 2) RHS can be negative: greatest value can be increased. 11163 bool CanWiden = !L.NonNegative || !R.NonNegative; 11164 bool Unsigned = L.NonNegative && R.Width == 0; 11165 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11166 !Unsigned, 11167 Unsigned); 11168 } 11169 11170 /// Return the range of a product of the two ranges. 11171 static IntRange product(IntRange L, IntRange R) { 11172 // If both LHS and RHS can be negative, we can form 11173 // -2^L * -2^R = 2^(L + R) 11174 // which requires L + R + 1 value bits to represent. 11175 bool CanWiden = !L.NonNegative && !R.NonNegative; 11176 bool Unsigned = L.NonNegative && R.NonNegative; 11177 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11178 Unsigned); 11179 } 11180 11181 /// Return the range of a remainder operation between the two ranges. 11182 static IntRange rem(IntRange L, IntRange R) { 11183 // The result of a remainder can't be larger than the result of 11184 // either side. The sign of the result is the sign of the LHS. 11185 bool Unsigned = L.NonNegative; 11186 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11187 Unsigned); 11188 } 11189 }; 11190 11191 } // namespace 11192 11193 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11194 unsigned MaxWidth) { 11195 if (value.isSigned() && value.isNegative()) 11196 return IntRange(value.getMinSignedBits(), false); 11197 11198 if (value.getBitWidth() > MaxWidth) 11199 value = value.trunc(MaxWidth); 11200 11201 // isNonNegative() just checks the sign bit without considering 11202 // signedness. 11203 return IntRange(value.getActiveBits(), true); 11204 } 11205 11206 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11207 unsigned MaxWidth) { 11208 if (result.isInt()) 11209 return GetValueRange(C, result.getInt(), MaxWidth); 11210 11211 if (result.isVector()) { 11212 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11213 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11214 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11215 R = IntRange::join(R, El); 11216 } 11217 return R; 11218 } 11219 11220 if (result.isComplexInt()) { 11221 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11222 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11223 return IntRange::join(R, I); 11224 } 11225 11226 // This can happen with lossless casts to intptr_t of "based" lvalues. 11227 // Assume it might use arbitrary bits. 11228 // FIXME: The only reason we need to pass the type in here is to get 11229 // the sign right on this one case. It would be nice if APValue 11230 // preserved this. 11231 assert(result.isLValue() || result.isAddrLabelDiff()); 11232 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11233 } 11234 11235 static QualType GetExprType(const Expr *E) { 11236 QualType Ty = E->getType(); 11237 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11238 Ty = AtomicRHS->getValueType(); 11239 return Ty; 11240 } 11241 11242 /// Pseudo-evaluate the given integer expression, estimating the 11243 /// range of values it might take. 11244 /// 11245 /// \param MaxWidth The width to which the value will be truncated. 11246 /// \param Approximate If \c true, return a likely range for the result: in 11247 /// particular, assume that arithmetic on narrower types doesn't leave 11248 /// those types. If \c false, return a range including all possible 11249 /// result values. 11250 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11251 bool InConstantContext, bool Approximate) { 11252 E = E->IgnoreParens(); 11253 11254 // Try a full evaluation first. 11255 Expr::EvalResult result; 11256 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11257 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11258 11259 // I think we only want to look through implicit casts here; if the 11260 // user has an explicit widening cast, we should treat the value as 11261 // being of the new, wider type. 11262 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11263 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11264 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11265 Approximate); 11266 11267 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11268 11269 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11270 CE->getCastKind() == CK_BooleanToSignedIntegral; 11271 11272 // Assume that non-integer casts can span the full range of the type. 11273 if (!isIntegerCast) 11274 return OutputTypeRange; 11275 11276 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11277 std::min(MaxWidth, OutputTypeRange.Width), 11278 InConstantContext, Approximate); 11279 11280 // Bail out if the subexpr's range is as wide as the cast type. 11281 if (SubRange.Width >= OutputTypeRange.Width) 11282 return OutputTypeRange; 11283 11284 // Otherwise, we take the smaller width, and we're non-negative if 11285 // either the output type or the subexpr is. 11286 return IntRange(SubRange.Width, 11287 SubRange.NonNegative || OutputTypeRange.NonNegative); 11288 } 11289 11290 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11291 // If we can fold the condition, just take that operand. 11292 bool CondResult; 11293 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11294 return GetExprRange(C, 11295 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11296 MaxWidth, InConstantContext, Approximate); 11297 11298 // Otherwise, conservatively merge. 11299 // GetExprRange requires an integer expression, but a throw expression 11300 // results in a void type. 11301 Expr *E = CO->getTrueExpr(); 11302 IntRange L = E->getType()->isVoidType() 11303 ? IntRange{0, true} 11304 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11305 E = CO->getFalseExpr(); 11306 IntRange R = E->getType()->isVoidType() 11307 ? IntRange{0, true} 11308 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11309 return IntRange::join(L, R); 11310 } 11311 11312 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11313 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11314 11315 switch (BO->getOpcode()) { 11316 case BO_Cmp: 11317 llvm_unreachable("builtin <=> should have class type"); 11318 11319 // Boolean-valued operations are single-bit and positive. 11320 case BO_LAnd: 11321 case BO_LOr: 11322 case BO_LT: 11323 case BO_GT: 11324 case BO_LE: 11325 case BO_GE: 11326 case BO_EQ: 11327 case BO_NE: 11328 return IntRange::forBoolType(); 11329 11330 // The type of the assignments is the type of the LHS, so the RHS 11331 // is not necessarily the same type. 11332 case BO_MulAssign: 11333 case BO_DivAssign: 11334 case BO_RemAssign: 11335 case BO_AddAssign: 11336 case BO_SubAssign: 11337 case BO_XorAssign: 11338 case BO_OrAssign: 11339 // TODO: bitfields? 11340 return IntRange::forValueOfType(C, GetExprType(E)); 11341 11342 // Simple assignments just pass through the RHS, which will have 11343 // been coerced to the LHS type. 11344 case BO_Assign: 11345 // TODO: bitfields? 11346 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11347 Approximate); 11348 11349 // Operations with opaque sources are black-listed. 11350 case BO_PtrMemD: 11351 case BO_PtrMemI: 11352 return IntRange::forValueOfType(C, GetExprType(E)); 11353 11354 // Bitwise-and uses the *infinum* of the two source ranges. 11355 case BO_And: 11356 case BO_AndAssign: 11357 Combine = IntRange::bit_and; 11358 break; 11359 11360 // Left shift gets black-listed based on a judgement call. 11361 case BO_Shl: 11362 // ...except that we want to treat '1 << (blah)' as logically 11363 // positive. It's an important idiom. 11364 if (IntegerLiteral *I 11365 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11366 if (I->getValue() == 1) { 11367 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11368 return IntRange(R.Width, /*NonNegative*/ true); 11369 } 11370 } 11371 LLVM_FALLTHROUGH; 11372 11373 case BO_ShlAssign: 11374 return IntRange::forValueOfType(C, GetExprType(E)); 11375 11376 // Right shift by a constant can narrow its left argument. 11377 case BO_Shr: 11378 case BO_ShrAssign: { 11379 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11380 Approximate); 11381 11382 // If the shift amount is a positive constant, drop the width by 11383 // that much. 11384 if (Optional<llvm::APSInt> shift = 11385 BO->getRHS()->getIntegerConstantExpr(C)) { 11386 if (shift->isNonNegative()) { 11387 unsigned zext = shift->getZExtValue(); 11388 if (zext >= L.Width) 11389 L.Width = (L.NonNegative ? 0 : 1); 11390 else 11391 L.Width -= zext; 11392 } 11393 } 11394 11395 return L; 11396 } 11397 11398 // Comma acts as its right operand. 11399 case BO_Comma: 11400 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11401 Approximate); 11402 11403 case BO_Add: 11404 if (!Approximate) 11405 Combine = IntRange::sum; 11406 break; 11407 11408 case BO_Sub: 11409 if (BO->getLHS()->getType()->isPointerType()) 11410 return IntRange::forValueOfType(C, GetExprType(E)); 11411 if (!Approximate) 11412 Combine = IntRange::difference; 11413 break; 11414 11415 case BO_Mul: 11416 if (!Approximate) 11417 Combine = IntRange::product; 11418 break; 11419 11420 // The width of a division result is mostly determined by the size 11421 // of the LHS. 11422 case BO_Div: { 11423 // Don't 'pre-truncate' the operands. 11424 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11425 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11426 Approximate); 11427 11428 // If the divisor is constant, use that. 11429 if (Optional<llvm::APSInt> divisor = 11430 BO->getRHS()->getIntegerConstantExpr(C)) { 11431 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11432 if (log2 >= L.Width) 11433 L.Width = (L.NonNegative ? 0 : 1); 11434 else 11435 L.Width = std::min(L.Width - log2, MaxWidth); 11436 return L; 11437 } 11438 11439 // Otherwise, just use the LHS's width. 11440 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11441 // could be -1. 11442 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11443 Approximate); 11444 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11445 } 11446 11447 case BO_Rem: 11448 Combine = IntRange::rem; 11449 break; 11450 11451 // The default behavior is okay for these. 11452 case BO_Xor: 11453 case BO_Or: 11454 break; 11455 } 11456 11457 // Combine the two ranges, but limit the result to the type in which we 11458 // performed the computation. 11459 QualType T = GetExprType(E); 11460 unsigned opWidth = C.getIntWidth(T); 11461 IntRange L = 11462 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11463 IntRange R = 11464 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11465 IntRange C = Combine(L, R); 11466 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11467 C.Width = std::min(C.Width, MaxWidth); 11468 return C; 11469 } 11470 11471 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11472 switch (UO->getOpcode()) { 11473 // Boolean-valued operations are white-listed. 11474 case UO_LNot: 11475 return IntRange::forBoolType(); 11476 11477 // Operations with opaque sources are black-listed. 11478 case UO_Deref: 11479 case UO_AddrOf: // should be impossible 11480 return IntRange::forValueOfType(C, GetExprType(E)); 11481 11482 default: 11483 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11484 Approximate); 11485 } 11486 } 11487 11488 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11489 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11490 Approximate); 11491 11492 if (const auto *BitField = E->getSourceBitField()) 11493 return IntRange(BitField->getBitWidthValue(C), 11494 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11495 11496 return IntRange::forValueOfType(C, GetExprType(E)); 11497 } 11498 11499 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11500 bool InConstantContext, bool Approximate) { 11501 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11502 Approximate); 11503 } 11504 11505 /// Checks whether the given value, which currently has the given 11506 /// source semantics, has the same value when coerced through the 11507 /// target semantics. 11508 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11509 const llvm::fltSemantics &Src, 11510 const llvm::fltSemantics &Tgt) { 11511 llvm::APFloat truncated = value; 11512 11513 bool ignored; 11514 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11515 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11516 11517 return truncated.bitwiseIsEqual(value); 11518 } 11519 11520 /// Checks whether the given value, which currently has the given 11521 /// source semantics, has the same value when coerced through the 11522 /// target semantics. 11523 /// 11524 /// The value might be a vector of floats (or a complex number). 11525 static bool IsSameFloatAfterCast(const APValue &value, 11526 const llvm::fltSemantics &Src, 11527 const llvm::fltSemantics &Tgt) { 11528 if (value.isFloat()) 11529 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11530 11531 if (value.isVector()) { 11532 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11533 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11534 return false; 11535 return true; 11536 } 11537 11538 assert(value.isComplexFloat()); 11539 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11540 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11541 } 11542 11543 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11544 bool IsListInit = false); 11545 11546 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11547 // Suppress cases where we are comparing against an enum constant. 11548 if (const DeclRefExpr *DR = 11549 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11550 if (isa<EnumConstantDecl>(DR->getDecl())) 11551 return true; 11552 11553 // Suppress cases where the value is expanded from a macro, unless that macro 11554 // is how a language represents a boolean literal. This is the case in both C 11555 // and Objective-C. 11556 SourceLocation BeginLoc = E->getBeginLoc(); 11557 if (BeginLoc.isMacroID()) { 11558 StringRef MacroName = Lexer::getImmediateMacroName( 11559 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11560 return MacroName != "YES" && MacroName != "NO" && 11561 MacroName != "true" && MacroName != "false"; 11562 } 11563 11564 return false; 11565 } 11566 11567 static bool isKnownToHaveUnsignedValue(Expr *E) { 11568 return E->getType()->isIntegerType() && 11569 (!E->getType()->isSignedIntegerType() || 11570 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11571 } 11572 11573 namespace { 11574 /// The promoted range of values of a type. In general this has the 11575 /// following structure: 11576 /// 11577 /// |-----------| . . . |-----------| 11578 /// ^ ^ ^ ^ 11579 /// Min HoleMin HoleMax Max 11580 /// 11581 /// ... where there is only a hole if a signed type is promoted to unsigned 11582 /// (in which case Min and Max are the smallest and largest representable 11583 /// values). 11584 struct PromotedRange { 11585 // Min, or HoleMax if there is a hole. 11586 llvm::APSInt PromotedMin; 11587 // Max, or HoleMin if there is a hole. 11588 llvm::APSInt PromotedMax; 11589 11590 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11591 if (R.Width == 0) 11592 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11593 else if (R.Width >= BitWidth && !Unsigned) { 11594 // Promotion made the type *narrower*. This happens when promoting 11595 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11596 // Treat all values of 'signed int' as being in range for now. 11597 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11598 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11599 } else { 11600 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11601 .extOrTrunc(BitWidth); 11602 PromotedMin.setIsUnsigned(Unsigned); 11603 11604 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11605 .extOrTrunc(BitWidth); 11606 PromotedMax.setIsUnsigned(Unsigned); 11607 } 11608 } 11609 11610 // Determine whether this range is contiguous (has no hole). 11611 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11612 11613 // Where a constant value is within the range. 11614 enum ComparisonResult { 11615 LT = 0x1, 11616 LE = 0x2, 11617 GT = 0x4, 11618 GE = 0x8, 11619 EQ = 0x10, 11620 NE = 0x20, 11621 InRangeFlag = 0x40, 11622 11623 Less = LE | LT | NE, 11624 Min = LE | InRangeFlag, 11625 InRange = InRangeFlag, 11626 Max = GE | InRangeFlag, 11627 Greater = GE | GT | NE, 11628 11629 OnlyValue = LE | GE | EQ | InRangeFlag, 11630 InHole = NE 11631 }; 11632 11633 ComparisonResult compare(const llvm::APSInt &Value) const { 11634 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11635 Value.isUnsigned() == PromotedMin.isUnsigned()); 11636 if (!isContiguous()) { 11637 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11638 if (Value.isMinValue()) return Min; 11639 if (Value.isMaxValue()) return Max; 11640 if (Value >= PromotedMin) return InRange; 11641 if (Value <= PromotedMax) return InRange; 11642 return InHole; 11643 } 11644 11645 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11646 case -1: return Less; 11647 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11648 case 1: 11649 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11650 case -1: return InRange; 11651 case 0: return Max; 11652 case 1: return Greater; 11653 } 11654 } 11655 11656 llvm_unreachable("impossible compare result"); 11657 } 11658 11659 static llvm::Optional<StringRef> 11660 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11661 if (Op == BO_Cmp) { 11662 ComparisonResult LTFlag = LT, GTFlag = GT; 11663 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11664 11665 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11666 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11667 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11668 return llvm::None; 11669 } 11670 11671 ComparisonResult TrueFlag, FalseFlag; 11672 if (Op == BO_EQ) { 11673 TrueFlag = EQ; 11674 FalseFlag = NE; 11675 } else if (Op == BO_NE) { 11676 TrueFlag = NE; 11677 FalseFlag = EQ; 11678 } else { 11679 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11680 TrueFlag = LT; 11681 FalseFlag = GE; 11682 } else { 11683 TrueFlag = GT; 11684 FalseFlag = LE; 11685 } 11686 if (Op == BO_GE || Op == BO_LE) 11687 std::swap(TrueFlag, FalseFlag); 11688 } 11689 if (R & TrueFlag) 11690 return StringRef("true"); 11691 if (R & FalseFlag) 11692 return StringRef("false"); 11693 return llvm::None; 11694 } 11695 }; 11696 } 11697 11698 static bool HasEnumType(Expr *E) { 11699 // Strip off implicit integral promotions. 11700 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11701 if (ICE->getCastKind() != CK_IntegralCast && 11702 ICE->getCastKind() != CK_NoOp) 11703 break; 11704 E = ICE->getSubExpr(); 11705 } 11706 11707 return E->getType()->isEnumeralType(); 11708 } 11709 11710 static int classifyConstantValue(Expr *Constant) { 11711 // The values of this enumeration are used in the diagnostics 11712 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11713 enum ConstantValueKind { 11714 Miscellaneous = 0, 11715 LiteralTrue, 11716 LiteralFalse 11717 }; 11718 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11719 return BL->getValue() ? ConstantValueKind::LiteralTrue 11720 : ConstantValueKind::LiteralFalse; 11721 return ConstantValueKind::Miscellaneous; 11722 } 11723 11724 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11725 Expr *Constant, Expr *Other, 11726 const llvm::APSInt &Value, 11727 bool RhsConstant) { 11728 if (S.inTemplateInstantiation()) 11729 return false; 11730 11731 Expr *OriginalOther = Other; 11732 11733 Constant = Constant->IgnoreParenImpCasts(); 11734 Other = Other->IgnoreParenImpCasts(); 11735 11736 // Suppress warnings on tautological comparisons between values of the same 11737 // enumeration type. There are only two ways we could warn on this: 11738 // - If the constant is outside the range of representable values of 11739 // the enumeration. In such a case, we should warn about the cast 11740 // to enumeration type, not about the comparison. 11741 // - If the constant is the maximum / minimum in-range value. For an 11742 // enumeratin type, such comparisons can be meaningful and useful. 11743 if (Constant->getType()->isEnumeralType() && 11744 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11745 return false; 11746 11747 IntRange OtherValueRange = GetExprRange( 11748 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11749 11750 QualType OtherT = Other->getType(); 11751 if (const auto *AT = OtherT->getAs<AtomicType>()) 11752 OtherT = AT->getValueType(); 11753 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11754 11755 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11756 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11757 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11758 S.NSAPIObj->isObjCBOOLType(OtherT) && 11759 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11760 11761 // Whether we're treating Other as being a bool because of the form of 11762 // expression despite it having another type (typically 'int' in C). 11763 bool OtherIsBooleanDespiteType = 11764 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11765 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11766 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11767 11768 // Check if all values in the range of possible values of this expression 11769 // lead to the same comparison outcome. 11770 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11771 Value.isUnsigned()); 11772 auto Cmp = OtherPromotedValueRange.compare(Value); 11773 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11774 if (!Result) 11775 return false; 11776 11777 // Also consider the range determined by the type alone. This allows us to 11778 // classify the warning under the proper diagnostic group. 11779 bool TautologicalTypeCompare = false; 11780 { 11781 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11782 Value.isUnsigned()); 11783 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11784 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11785 RhsConstant)) { 11786 TautologicalTypeCompare = true; 11787 Cmp = TypeCmp; 11788 Result = TypeResult; 11789 } 11790 } 11791 11792 // Don't warn if the non-constant operand actually always evaluates to the 11793 // same value. 11794 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11795 return false; 11796 11797 // Suppress the diagnostic for an in-range comparison if the constant comes 11798 // from a macro or enumerator. We don't want to diagnose 11799 // 11800 // some_long_value <= INT_MAX 11801 // 11802 // when sizeof(int) == sizeof(long). 11803 bool InRange = Cmp & PromotedRange::InRangeFlag; 11804 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11805 return false; 11806 11807 // A comparison of an unsigned bit-field against 0 is really a type problem, 11808 // even though at the type level the bit-field might promote to 'signed int'. 11809 if (Other->refersToBitField() && InRange && Value == 0 && 11810 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11811 TautologicalTypeCompare = true; 11812 11813 // If this is a comparison to an enum constant, include that 11814 // constant in the diagnostic. 11815 const EnumConstantDecl *ED = nullptr; 11816 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11817 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11818 11819 // Should be enough for uint128 (39 decimal digits) 11820 SmallString<64> PrettySourceValue; 11821 llvm::raw_svector_ostream OS(PrettySourceValue); 11822 if (ED) { 11823 OS << '\'' << *ED << "' (" << Value << ")"; 11824 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11825 Constant->IgnoreParenImpCasts())) { 11826 OS << (BL->getValue() ? "YES" : "NO"); 11827 } else { 11828 OS << Value; 11829 } 11830 11831 if (!TautologicalTypeCompare) { 11832 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11833 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11834 << E->getOpcodeStr() << OS.str() << *Result 11835 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11836 return true; 11837 } 11838 11839 if (IsObjCSignedCharBool) { 11840 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11841 S.PDiag(diag::warn_tautological_compare_objc_bool) 11842 << OS.str() << *Result); 11843 return true; 11844 } 11845 11846 // FIXME: We use a somewhat different formatting for the in-range cases and 11847 // cases involving boolean values for historical reasons. We should pick a 11848 // consistent way of presenting these diagnostics. 11849 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11850 11851 S.DiagRuntimeBehavior( 11852 E->getOperatorLoc(), E, 11853 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11854 : diag::warn_tautological_bool_compare) 11855 << OS.str() << classifyConstantValue(Constant) << OtherT 11856 << OtherIsBooleanDespiteType << *Result 11857 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11858 } else { 11859 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11860 unsigned Diag = 11861 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11862 ? (HasEnumType(OriginalOther) 11863 ? diag::warn_unsigned_enum_always_true_comparison 11864 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11865 : diag::warn_unsigned_always_true_comparison) 11866 : diag::warn_tautological_constant_compare; 11867 11868 S.Diag(E->getOperatorLoc(), Diag) 11869 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11870 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11871 } 11872 11873 return true; 11874 } 11875 11876 /// Analyze the operands of the given comparison. Implements the 11877 /// fallback case from AnalyzeComparison. 11878 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11879 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11880 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11881 } 11882 11883 /// Implements -Wsign-compare. 11884 /// 11885 /// \param E the binary operator to check for warnings 11886 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11887 // The type the comparison is being performed in. 11888 QualType T = E->getLHS()->getType(); 11889 11890 // Only analyze comparison operators where both sides have been converted to 11891 // the same type. 11892 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11893 return AnalyzeImpConvsInComparison(S, E); 11894 11895 // Don't analyze value-dependent comparisons directly. 11896 if (E->isValueDependent()) 11897 return AnalyzeImpConvsInComparison(S, E); 11898 11899 Expr *LHS = E->getLHS(); 11900 Expr *RHS = E->getRHS(); 11901 11902 if (T->isIntegralType(S.Context)) { 11903 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11904 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11905 11906 // We don't care about expressions whose result is a constant. 11907 if (RHSValue && LHSValue) 11908 return AnalyzeImpConvsInComparison(S, E); 11909 11910 // We only care about expressions where just one side is literal 11911 if ((bool)RHSValue ^ (bool)LHSValue) { 11912 // Is the constant on the RHS or LHS? 11913 const bool RhsConstant = (bool)RHSValue; 11914 Expr *Const = RhsConstant ? RHS : LHS; 11915 Expr *Other = RhsConstant ? LHS : RHS; 11916 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11917 11918 // Check whether an integer constant comparison results in a value 11919 // of 'true' or 'false'. 11920 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11921 return AnalyzeImpConvsInComparison(S, E); 11922 } 11923 } 11924 11925 if (!T->hasUnsignedIntegerRepresentation()) { 11926 // We don't do anything special if this isn't an unsigned integral 11927 // comparison: we're only interested in integral comparisons, and 11928 // signed comparisons only happen in cases we don't care to warn about. 11929 return AnalyzeImpConvsInComparison(S, E); 11930 } 11931 11932 LHS = LHS->IgnoreParenImpCasts(); 11933 RHS = RHS->IgnoreParenImpCasts(); 11934 11935 if (!S.getLangOpts().CPlusPlus) { 11936 // Avoid warning about comparison of integers with different signs when 11937 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11938 // the type of `E`. 11939 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11940 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11941 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11942 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11943 } 11944 11945 // Check to see if one of the (unmodified) operands is of different 11946 // signedness. 11947 Expr *signedOperand, *unsignedOperand; 11948 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11949 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11950 "unsigned comparison between two signed integer expressions?"); 11951 signedOperand = LHS; 11952 unsignedOperand = RHS; 11953 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11954 signedOperand = RHS; 11955 unsignedOperand = LHS; 11956 } else { 11957 return AnalyzeImpConvsInComparison(S, E); 11958 } 11959 11960 // Otherwise, calculate the effective range of the signed operand. 11961 IntRange signedRange = GetExprRange( 11962 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11963 11964 // Go ahead and analyze implicit conversions in the operands. Note 11965 // that we skip the implicit conversions on both sides. 11966 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11967 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11968 11969 // If the signed range is non-negative, -Wsign-compare won't fire. 11970 if (signedRange.NonNegative) 11971 return; 11972 11973 // For (in)equality comparisons, if the unsigned operand is a 11974 // constant which cannot collide with a overflowed signed operand, 11975 // then reinterpreting the signed operand as unsigned will not 11976 // change the result of the comparison. 11977 if (E->isEqualityOp()) { 11978 unsigned comparisonWidth = S.Context.getIntWidth(T); 11979 IntRange unsignedRange = 11980 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11981 /*Approximate*/ true); 11982 11983 // We should never be unable to prove that the unsigned operand is 11984 // non-negative. 11985 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11986 11987 if (unsignedRange.Width < comparisonWidth) 11988 return; 11989 } 11990 11991 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11992 S.PDiag(diag::warn_mixed_sign_comparison) 11993 << LHS->getType() << RHS->getType() 11994 << LHS->getSourceRange() << RHS->getSourceRange()); 11995 } 11996 11997 /// Analyzes an attempt to assign the given value to a bitfield. 11998 /// 11999 /// Returns true if there was something fishy about the attempt. 12000 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12001 SourceLocation InitLoc) { 12002 assert(Bitfield->isBitField()); 12003 if (Bitfield->isInvalidDecl()) 12004 return false; 12005 12006 // White-list bool bitfields. 12007 QualType BitfieldType = Bitfield->getType(); 12008 if (BitfieldType->isBooleanType()) 12009 return false; 12010 12011 if (BitfieldType->isEnumeralType()) { 12012 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12013 // If the underlying enum type was not explicitly specified as an unsigned 12014 // type and the enum contain only positive values, MSVC++ will cause an 12015 // inconsistency by storing this as a signed type. 12016 if (S.getLangOpts().CPlusPlus11 && 12017 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12018 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12019 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12020 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12021 << BitfieldEnumDecl; 12022 } 12023 } 12024 12025 if (Bitfield->getType()->isBooleanType()) 12026 return false; 12027 12028 // Ignore value- or type-dependent expressions. 12029 if (Bitfield->getBitWidth()->isValueDependent() || 12030 Bitfield->getBitWidth()->isTypeDependent() || 12031 Init->isValueDependent() || 12032 Init->isTypeDependent()) 12033 return false; 12034 12035 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12036 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12037 12038 Expr::EvalResult Result; 12039 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12040 Expr::SE_AllowSideEffects)) { 12041 // The RHS is not constant. If the RHS has an enum type, make sure the 12042 // bitfield is wide enough to hold all the values of the enum without 12043 // truncation. 12044 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12045 EnumDecl *ED = EnumTy->getDecl(); 12046 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12047 12048 // Enum types are implicitly signed on Windows, so check if there are any 12049 // negative enumerators to see if the enum was intended to be signed or 12050 // not. 12051 bool SignedEnum = ED->getNumNegativeBits() > 0; 12052 12053 // Check for surprising sign changes when assigning enum values to a 12054 // bitfield of different signedness. If the bitfield is signed and we 12055 // have exactly the right number of bits to store this unsigned enum, 12056 // suggest changing the enum to an unsigned type. This typically happens 12057 // on Windows where unfixed enums always use an underlying type of 'int'. 12058 unsigned DiagID = 0; 12059 if (SignedEnum && !SignedBitfield) { 12060 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12061 } else if (SignedBitfield && !SignedEnum && 12062 ED->getNumPositiveBits() == FieldWidth) { 12063 DiagID = diag::warn_signed_bitfield_enum_conversion; 12064 } 12065 12066 if (DiagID) { 12067 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12068 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12069 SourceRange TypeRange = 12070 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12071 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12072 << SignedEnum << TypeRange; 12073 } 12074 12075 // Compute the required bitwidth. If the enum has negative values, we need 12076 // one more bit than the normal number of positive bits to represent the 12077 // sign bit. 12078 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12079 ED->getNumNegativeBits()) 12080 : ED->getNumPositiveBits(); 12081 12082 // Check the bitwidth. 12083 if (BitsNeeded > FieldWidth) { 12084 Expr *WidthExpr = Bitfield->getBitWidth(); 12085 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12086 << Bitfield << ED; 12087 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12088 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12089 } 12090 } 12091 12092 return false; 12093 } 12094 12095 llvm::APSInt Value = Result.Val.getInt(); 12096 12097 unsigned OriginalWidth = Value.getBitWidth(); 12098 12099 if (!Value.isSigned() || Value.isNegative()) 12100 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12101 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12102 OriginalWidth = Value.getMinSignedBits(); 12103 12104 if (OriginalWidth <= FieldWidth) 12105 return false; 12106 12107 // Compute the value which the bitfield will contain. 12108 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12109 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12110 12111 // Check whether the stored value is equal to the original value. 12112 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12113 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12114 return false; 12115 12116 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12117 // therefore don't strictly fit into a signed bitfield of width 1. 12118 if (FieldWidth == 1 && Value == 1) 12119 return false; 12120 12121 std::string PrettyValue = toString(Value, 10); 12122 std::string PrettyTrunc = toString(TruncatedValue, 10); 12123 12124 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12125 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12126 << Init->getSourceRange(); 12127 12128 return true; 12129 } 12130 12131 /// Analyze the given simple or compound assignment for warning-worthy 12132 /// operations. 12133 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12134 // Just recurse on the LHS. 12135 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12136 12137 // We want to recurse on the RHS as normal unless we're assigning to 12138 // a bitfield. 12139 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12140 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12141 E->getOperatorLoc())) { 12142 // Recurse, ignoring any implicit conversions on the RHS. 12143 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12144 E->getOperatorLoc()); 12145 } 12146 } 12147 12148 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12149 12150 // Diagnose implicitly sequentially-consistent atomic assignment. 12151 if (E->getLHS()->getType()->isAtomicType()) 12152 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12153 } 12154 12155 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12156 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12157 SourceLocation CContext, unsigned diag, 12158 bool pruneControlFlow = false) { 12159 if (pruneControlFlow) { 12160 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12161 S.PDiag(diag) 12162 << SourceType << T << E->getSourceRange() 12163 << SourceRange(CContext)); 12164 return; 12165 } 12166 S.Diag(E->getExprLoc(), diag) 12167 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12168 } 12169 12170 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12171 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12172 SourceLocation CContext, 12173 unsigned diag, bool pruneControlFlow = false) { 12174 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12175 } 12176 12177 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12178 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12179 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12180 } 12181 12182 static void adornObjCBoolConversionDiagWithTernaryFixit( 12183 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12184 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12185 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12186 Ignored = OVE->getSourceExpr(); 12187 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12188 isa<BinaryOperator>(Ignored) || 12189 isa<CXXOperatorCallExpr>(Ignored); 12190 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12191 if (NeedsParens) 12192 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12193 << FixItHint::CreateInsertion(EndLoc, ")"); 12194 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12195 } 12196 12197 /// Diagnose an implicit cast from a floating point value to an integer value. 12198 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12199 SourceLocation CContext) { 12200 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12201 const bool PruneWarnings = S.inTemplateInstantiation(); 12202 12203 Expr *InnerE = E->IgnoreParenImpCasts(); 12204 // We also want to warn on, e.g., "int i = -1.234" 12205 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12206 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12207 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12208 12209 const bool IsLiteral = 12210 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12211 12212 llvm::APFloat Value(0.0); 12213 bool IsConstant = 12214 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12215 if (!IsConstant) { 12216 if (isObjCSignedCharBool(S, T)) { 12217 return adornObjCBoolConversionDiagWithTernaryFixit( 12218 S, E, 12219 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12220 << E->getType()); 12221 } 12222 12223 return DiagnoseImpCast(S, E, T, CContext, 12224 diag::warn_impcast_float_integer, PruneWarnings); 12225 } 12226 12227 bool isExact = false; 12228 12229 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12230 T->hasUnsignedIntegerRepresentation()); 12231 llvm::APFloat::opStatus Result = Value.convertToInteger( 12232 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12233 12234 // FIXME: Force the precision of the source value down so we don't print 12235 // digits which are usually useless (we don't really care here if we 12236 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12237 // would automatically print the shortest representation, but it's a bit 12238 // tricky to implement. 12239 SmallString<16> PrettySourceValue; 12240 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12241 precision = (precision * 59 + 195) / 196; 12242 Value.toString(PrettySourceValue, precision); 12243 12244 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12245 return adornObjCBoolConversionDiagWithTernaryFixit( 12246 S, E, 12247 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12248 << PrettySourceValue); 12249 } 12250 12251 if (Result == llvm::APFloat::opOK && isExact) { 12252 if (IsLiteral) return; 12253 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12254 PruneWarnings); 12255 } 12256 12257 // Conversion of a floating-point value to a non-bool integer where the 12258 // integral part cannot be represented by the integer type is undefined. 12259 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12260 return DiagnoseImpCast( 12261 S, E, T, CContext, 12262 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12263 : diag::warn_impcast_float_to_integer_out_of_range, 12264 PruneWarnings); 12265 12266 unsigned DiagID = 0; 12267 if (IsLiteral) { 12268 // Warn on floating point literal to integer. 12269 DiagID = diag::warn_impcast_literal_float_to_integer; 12270 } else if (IntegerValue == 0) { 12271 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12272 return DiagnoseImpCast(S, E, T, CContext, 12273 diag::warn_impcast_float_integer, PruneWarnings); 12274 } 12275 // Warn on non-zero to zero conversion. 12276 DiagID = diag::warn_impcast_float_to_integer_zero; 12277 } else { 12278 if (IntegerValue.isUnsigned()) { 12279 if (!IntegerValue.isMaxValue()) { 12280 return DiagnoseImpCast(S, E, T, CContext, 12281 diag::warn_impcast_float_integer, PruneWarnings); 12282 } 12283 } else { // IntegerValue.isSigned() 12284 if (!IntegerValue.isMaxSignedValue() && 12285 !IntegerValue.isMinSignedValue()) { 12286 return DiagnoseImpCast(S, E, T, CContext, 12287 diag::warn_impcast_float_integer, PruneWarnings); 12288 } 12289 } 12290 // Warn on evaluatable floating point expression to integer conversion. 12291 DiagID = diag::warn_impcast_float_to_integer; 12292 } 12293 12294 SmallString<16> PrettyTargetValue; 12295 if (IsBool) 12296 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12297 else 12298 IntegerValue.toString(PrettyTargetValue); 12299 12300 if (PruneWarnings) { 12301 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12302 S.PDiag(DiagID) 12303 << E->getType() << T.getUnqualifiedType() 12304 << PrettySourceValue << PrettyTargetValue 12305 << E->getSourceRange() << SourceRange(CContext)); 12306 } else { 12307 S.Diag(E->getExprLoc(), DiagID) 12308 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12309 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12310 } 12311 } 12312 12313 /// Analyze the given compound assignment for the possible losing of 12314 /// floating-point precision. 12315 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12316 assert(isa<CompoundAssignOperator>(E) && 12317 "Must be compound assignment operation"); 12318 // Recurse on the LHS and RHS in here 12319 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12320 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12321 12322 if (E->getLHS()->getType()->isAtomicType()) 12323 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12324 12325 // Now check the outermost expression 12326 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12327 const auto *RBT = cast<CompoundAssignOperator>(E) 12328 ->getComputationResultType() 12329 ->getAs<BuiltinType>(); 12330 12331 // The below checks assume source is floating point. 12332 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12333 12334 // If source is floating point but target is an integer. 12335 if (ResultBT->isInteger()) 12336 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12337 E->getExprLoc(), diag::warn_impcast_float_integer); 12338 12339 if (!ResultBT->isFloatingPoint()) 12340 return; 12341 12342 // If both source and target are floating points, warn about losing precision. 12343 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12344 QualType(ResultBT, 0), QualType(RBT, 0)); 12345 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12346 // warn about dropping FP rank. 12347 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12348 diag::warn_impcast_float_result_precision); 12349 } 12350 12351 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12352 IntRange Range) { 12353 if (!Range.Width) return "0"; 12354 12355 llvm::APSInt ValueInRange = Value; 12356 ValueInRange.setIsSigned(!Range.NonNegative); 12357 ValueInRange = ValueInRange.trunc(Range.Width); 12358 return toString(ValueInRange, 10); 12359 } 12360 12361 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12362 if (!isa<ImplicitCastExpr>(Ex)) 12363 return false; 12364 12365 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12366 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12367 const Type *Source = 12368 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12369 if (Target->isDependentType()) 12370 return false; 12371 12372 const BuiltinType *FloatCandidateBT = 12373 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12374 const Type *BoolCandidateType = ToBool ? Target : Source; 12375 12376 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12377 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12378 } 12379 12380 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12381 SourceLocation CC) { 12382 unsigned NumArgs = TheCall->getNumArgs(); 12383 for (unsigned i = 0; i < NumArgs; ++i) { 12384 Expr *CurrA = TheCall->getArg(i); 12385 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12386 continue; 12387 12388 bool IsSwapped = ((i > 0) && 12389 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12390 IsSwapped |= ((i < (NumArgs - 1)) && 12391 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12392 if (IsSwapped) { 12393 // Warn on this floating-point to bool conversion. 12394 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12395 CurrA->getType(), CC, 12396 diag::warn_impcast_floating_point_to_bool); 12397 } 12398 } 12399 } 12400 12401 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12402 SourceLocation CC) { 12403 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12404 E->getExprLoc())) 12405 return; 12406 12407 // Don't warn on functions which have return type nullptr_t. 12408 if (isa<CallExpr>(E)) 12409 return; 12410 12411 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12412 const Expr::NullPointerConstantKind NullKind = 12413 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12414 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12415 return; 12416 12417 // Return if target type is a safe conversion. 12418 if (T->isAnyPointerType() || T->isBlockPointerType() || 12419 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12420 return; 12421 12422 SourceLocation Loc = E->getSourceRange().getBegin(); 12423 12424 // Venture through the macro stacks to get to the source of macro arguments. 12425 // The new location is a better location than the complete location that was 12426 // passed in. 12427 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12428 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12429 12430 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12431 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12432 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12433 Loc, S.SourceMgr, S.getLangOpts()); 12434 if (MacroName == "NULL") 12435 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12436 } 12437 12438 // Only warn if the null and context location are in the same macro expansion. 12439 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12440 return; 12441 12442 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12443 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12444 << FixItHint::CreateReplacement(Loc, 12445 S.getFixItZeroLiteralForType(T, Loc)); 12446 } 12447 12448 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12449 ObjCArrayLiteral *ArrayLiteral); 12450 12451 static void 12452 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12453 ObjCDictionaryLiteral *DictionaryLiteral); 12454 12455 /// Check a single element within a collection literal against the 12456 /// target element type. 12457 static void checkObjCCollectionLiteralElement(Sema &S, 12458 QualType TargetElementType, 12459 Expr *Element, 12460 unsigned ElementKind) { 12461 // Skip a bitcast to 'id' or qualified 'id'. 12462 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12463 if (ICE->getCastKind() == CK_BitCast && 12464 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12465 Element = ICE->getSubExpr(); 12466 } 12467 12468 QualType ElementType = Element->getType(); 12469 ExprResult ElementResult(Element); 12470 if (ElementType->getAs<ObjCObjectPointerType>() && 12471 S.CheckSingleAssignmentConstraints(TargetElementType, 12472 ElementResult, 12473 false, false) 12474 != Sema::Compatible) { 12475 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12476 << ElementType << ElementKind << TargetElementType 12477 << Element->getSourceRange(); 12478 } 12479 12480 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12481 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12482 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12483 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12484 } 12485 12486 /// Check an Objective-C array literal being converted to the given 12487 /// target type. 12488 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12489 ObjCArrayLiteral *ArrayLiteral) { 12490 if (!S.NSArrayDecl) 12491 return; 12492 12493 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12494 if (!TargetObjCPtr) 12495 return; 12496 12497 if (TargetObjCPtr->isUnspecialized() || 12498 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12499 != S.NSArrayDecl->getCanonicalDecl()) 12500 return; 12501 12502 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12503 if (TypeArgs.size() != 1) 12504 return; 12505 12506 QualType TargetElementType = TypeArgs[0]; 12507 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12508 checkObjCCollectionLiteralElement(S, TargetElementType, 12509 ArrayLiteral->getElement(I), 12510 0); 12511 } 12512 } 12513 12514 /// Check an Objective-C dictionary literal being converted to the given 12515 /// target type. 12516 static void 12517 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12518 ObjCDictionaryLiteral *DictionaryLiteral) { 12519 if (!S.NSDictionaryDecl) 12520 return; 12521 12522 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12523 if (!TargetObjCPtr) 12524 return; 12525 12526 if (TargetObjCPtr->isUnspecialized() || 12527 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12528 != S.NSDictionaryDecl->getCanonicalDecl()) 12529 return; 12530 12531 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12532 if (TypeArgs.size() != 2) 12533 return; 12534 12535 QualType TargetKeyType = TypeArgs[0]; 12536 QualType TargetObjectType = TypeArgs[1]; 12537 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12538 auto Element = DictionaryLiteral->getKeyValueElement(I); 12539 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12540 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12541 } 12542 } 12543 12544 // Helper function to filter out cases for constant width constant conversion. 12545 // Don't warn on char array initialization or for non-decimal values. 12546 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12547 SourceLocation CC) { 12548 // If initializing from a constant, and the constant starts with '0', 12549 // then it is a binary, octal, or hexadecimal. Allow these constants 12550 // to fill all the bits, even if there is a sign change. 12551 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12552 const char FirstLiteralCharacter = 12553 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12554 if (FirstLiteralCharacter == '0') 12555 return false; 12556 } 12557 12558 // If the CC location points to a '{', and the type is char, then assume 12559 // assume it is an array initialization. 12560 if (CC.isValid() && T->isCharType()) { 12561 const char FirstContextCharacter = 12562 S.getSourceManager().getCharacterData(CC)[0]; 12563 if (FirstContextCharacter == '{') 12564 return false; 12565 } 12566 12567 return true; 12568 } 12569 12570 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12571 const auto *IL = dyn_cast<IntegerLiteral>(E); 12572 if (!IL) { 12573 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12574 if (UO->getOpcode() == UO_Minus) 12575 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12576 } 12577 } 12578 12579 return IL; 12580 } 12581 12582 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12583 E = E->IgnoreParenImpCasts(); 12584 SourceLocation ExprLoc = E->getExprLoc(); 12585 12586 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12587 BinaryOperator::Opcode Opc = BO->getOpcode(); 12588 Expr::EvalResult Result; 12589 // Do not diagnose unsigned shifts. 12590 if (Opc == BO_Shl) { 12591 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12592 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12593 if (LHS && LHS->getValue() == 0) 12594 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12595 else if (!E->isValueDependent() && LHS && RHS && 12596 RHS->getValue().isNonNegative() && 12597 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12598 S.Diag(ExprLoc, diag::warn_left_shift_always) 12599 << (Result.Val.getInt() != 0); 12600 else if (E->getType()->isSignedIntegerType()) 12601 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12602 } 12603 } 12604 12605 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12606 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12607 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12608 if (!LHS || !RHS) 12609 return; 12610 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12611 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12612 // Do not diagnose common idioms. 12613 return; 12614 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12615 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12616 } 12617 } 12618 12619 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12620 SourceLocation CC, 12621 bool *ICContext = nullptr, 12622 bool IsListInit = false) { 12623 if (E->isTypeDependent() || E->isValueDependent()) return; 12624 12625 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12626 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12627 if (Source == Target) return; 12628 if (Target->isDependentType()) return; 12629 12630 // If the conversion context location is invalid don't complain. We also 12631 // don't want to emit a warning if the issue occurs from the expansion of 12632 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12633 // delay this check as long as possible. Once we detect we are in that 12634 // scenario, we just return. 12635 if (CC.isInvalid()) 12636 return; 12637 12638 if (Source->isAtomicType()) 12639 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12640 12641 // Diagnose implicit casts to bool. 12642 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12643 if (isa<StringLiteral>(E)) 12644 // Warn on string literal to bool. Checks for string literals in logical 12645 // and expressions, for instance, assert(0 && "error here"), are 12646 // prevented by a check in AnalyzeImplicitConversions(). 12647 return DiagnoseImpCast(S, E, T, CC, 12648 diag::warn_impcast_string_literal_to_bool); 12649 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12650 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12651 // This covers the literal expressions that evaluate to Objective-C 12652 // objects. 12653 return DiagnoseImpCast(S, E, T, CC, 12654 diag::warn_impcast_objective_c_literal_to_bool); 12655 } 12656 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12657 // Warn on pointer to bool conversion that is always true. 12658 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12659 SourceRange(CC)); 12660 } 12661 } 12662 12663 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12664 // is a typedef for signed char (macOS), then that constant value has to be 1 12665 // or 0. 12666 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12667 Expr::EvalResult Result; 12668 if (E->EvaluateAsInt(Result, S.getASTContext(), 12669 Expr::SE_AllowSideEffects)) { 12670 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12671 adornObjCBoolConversionDiagWithTernaryFixit( 12672 S, E, 12673 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12674 << toString(Result.Val.getInt(), 10)); 12675 } 12676 return; 12677 } 12678 } 12679 12680 // Check implicit casts from Objective-C collection literals to specialized 12681 // collection types, e.g., NSArray<NSString *> *. 12682 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12683 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12684 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12685 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12686 12687 // Strip vector types. 12688 if (isa<VectorType>(Source)) { 12689 if (Target->isVLSTBuiltinType() && 12690 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12691 QualType(Source, 0)) || 12692 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12693 QualType(Source, 0)))) 12694 return; 12695 12696 if (!isa<VectorType>(Target)) { 12697 if (S.SourceMgr.isInSystemMacro(CC)) 12698 return; 12699 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12700 } 12701 12702 // If the vector cast is cast between two vectors of the same size, it is 12703 // a bitcast, not a conversion. 12704 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12705 return; 12706 12707 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12708 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12709 } 12710 if (auto VecTy = dyn_cast<VectorType>(Target)) 12711 Target = VecTy->getElementType().getTypePtr(); 12712 12713 // Strip complex types. 12714 if (isa<ComplexType>(Source)) { 12715 if (!isa<ComplexType>(Target)) { 12716 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12717 return; 12718 12719 return DiagnoseImpCast(S, E, T, CC, 12720 S.getLangOpts().CPlusPlus 12721 ? diag::err_impcast_complex_scalar 12722 : diag::warn_impcast_complex_scalar); 12723 } 12724 12725 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12726 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12727 } 12728 12729 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12730 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12731 12732 // If the source is floating point... 12733 if (SourceBT && SourceBT->isFloatingPoint()) { 12734 // ...and the target is floating point... 12735 if (TargetBT && TargetBT->isFloatingPoint()) { 12736 // ...then warn if we're dropping FP rank. 12737 12738 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12739 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12740 if (Order > 0) { 12741 // Don't warn about float constants that are precisely 12742 // representable in the target type. 12743 Expr::EvalResult result; 12744 if (E->EvaluateAsRValue(result, S.Context)) { 12745 // Value might be a float, a float vector, or a float complex. 12746 if (IsSameFloatAfterCast(result.Val, 12747 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12748 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12749 return; 12750 } 12751 12752 if (S.SourceMgr.isInSystemMacro(CC)) 12753 return; 12754 12755 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12756 } 12757 // ... or possibly if we're increasing rank, too 12758 else if (Order < 0) { 12759 if (S.SourceMgr.isInSystemMacro(CC)) 12760 return; 12761 12762 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12763 } 12764 return; 12765 } 12766 12767 // If the target is integral, always warn. 12768 if (TargetBT && TargetBT->isInteger()) { 12769 if (S.SourceMgr.isInSystemMacro(CC)) 12770 return; 12771 12772 DiagnoseFloatingImpCast(S, E, T, CC); 12773 } 12774 12775 // Detect the case where a call result is converted from floating-point to 12776 // to bool, and the final argument to the call is converted from bool, to 12777 // discover this typo: 12778 // 12779 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12780 // 12781 // FIXME: This is an incredibly special case; is there some more general 12782 // way to detect this class of misplaced-parentheses bug? 12783 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12784 // Check last argument of function call to see if it is an 12785 // implicit cast from a type matching the type the result 12786 // is being cast to. 12787 CallExpr *CEx = cast<CallExpr>(E); 12788 if (unsigned NumArgs = CEx->getNumArgs()) { 12789 Expr *LastA = CEx->getArg(NumArgs - 1); 12790 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12791 if (isa<ImplicitCastExpr>(LastA) && 12792 InnerE->getType()->isBooleanType()) { 12793 // Warn on this floating-point to bool conversion 12794 DiagnoseImpCast(S, E, T, CC, 12795 diag::warn_impcast_floating_point_to_bool); 12796 } 12797 } 12798 } 12799 return; 12800 } 12801 12802 // Valid casts involving fixed point types should be accounted for here. 12803 if (Source->isFixedPointType()) { 12804 if (Target->isUnsaturatedFixedPointType()) { 12805 Expr::EvalResult Result; 12806 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12807 S.isConstantEvaluated())) { 12808 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12809 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12810 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12811 if (Value > MaxVal || Value < MinVal) { 12812 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12813 S.PDiag(diag::warn_impcast_fixed_point_range) 12814 << Value.toString() << T 12815 << E->getSourceRange() 12816 << clang::SourceRange(CC)); 12817 return; 12818 } 12819 } 12820 } else if (Target->isIntegerType()) { 12821 Expr::EvalResult Result; 12822 if (!S.isConstantEvaluated() && 12823 E->EvaluateAsFixedPoint(Result, S.Context, 12824 Expr::SE_AllowSideEffects)) { 12825 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12826 12827 bool Overflowed; 12828 llvm::APSInt IntResult = FXResult.convertToInt( 12829 S.Context.getIntWidth(T), 12830 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12831 12832 if (Overflowed) { 12833 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12834 S.PDiag(diag::warn_impcast_fixed_point_range) 12835 << FXResult.toString() << T 12836 << E->getSourceRange() 12837 << clang::SourceRange(CC)); 12838 return; 12839 } 12840 } 12841 } 12842 } else if (Target->isUnsaturatedFixedPointType()) { 12843 if (Source->isIntegerType()) { 12844 Expr::EvalResult Result; 12845 if (!S.isConstantEvaluated() && 12846 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12847 llvm::APSInt Value = Result.Val.getInt(); 12848 12849 bool Overflowed; 12850 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12851 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12852 12853 if (Overflowed) { 12854 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12855 S.PDiag(diag::warn_impcast_fixed_point_range) 12856 << toString(Value, /*Radix=*/10) << T 12857 << E->getSourceRange() 12858 << clang::SourceRange(CC)); 12859 return; 12860 } 12861 } 12862 } 12863 } 12864 12865 // If we are casting an integer type to a floating point type without 12866 // initialization-list syntax, we might lose accuracy if the floating 12867 // point type has a narrower significand than the integer type. 12868 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12869 TargetBT->isFloatingType() && !IsListInit) { 12870 // Determine the number of precision bits in the source integer type. 12871 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12872 /*Approximate*/ true); 12873 unsigned int SourcePrecision = SourceRange.Width; 12874 12875 // Determine the number of precision bits in the 12876 // target floating point type. 12877 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12878 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12879 12880 if (SourcePrecision > 0 && TargetPrecision > 0 && 12881 SourcePrecision > TargetPrecision) { 12882 12883 if (Optional<llvm::APSInt> SourceInt = 12884 E->getIntegerConstantExpr(S.Context)) { 12885 // If the source integer is a constant, convert it to the target 12886 // floating point type. Issue a warning if the value changes 12887 // during the whole conversion. 12888 llvm::APFloat TargetFloatValue( 12889 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12890 llvm::APFloat::opStatus ConversionStatus = 12891 TargetFloatValue.convertFromAPInt( 12892 *SourceInt, SourceBT->isSignedInteger(), 12893 llvm::APFloat::rmNearestTiesToEven); 12894 12895 if (ConversionStatus != llvm::APFloat::opOK) { 12896 SmallString<32> PrettySourceValue; 12897 SourceInt->toString(PrettySourceValue, 10); 12898 SmallString<32> PrettyTargetValue; 12899 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12900 12901 S.DiagRuntimeBehavior( 12902 E->getExprLoc(), E, 12903 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12904 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12905 << E->getSourceRange() << clang::SourceRange(CC)); 12906 } 12907 } else { 12908 // Otherwise, the implicit conversion may lose precision. 12909 DiagnoseImpCast(S, E, T, CC, 12910 diag::warn_impcast_integer_float_precision); 12911 } 12912 } 12913 } 12914 12915 DiagnoseNullConversion(S, E, T, CC); 12916 12917 S.DiscardMisalignedMemberAddress(Target, E); 12918 12919 if (Target->isBooleanType()) 12920 DiagnoseIntInBoolContext(S, E); 12921 12922 if (!Source->isIntegerType() || !Target->isIntegerType()) 12923 return; 12924 12925 // TODO: remove this early return once the false positives for constant->bool 12926 // in templates, macros, etc, are reduced or removed. 12927 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12928 return; 12929 12930 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12931 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12932 return adornObjCBoolConversionDiagWithTernaryFixit( 12933 S, E, 12934 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12935 << E->getType()); 12936 } 12937 12938 IntRange SourceTypeRange = 12939 IntRange::forTargetOfCanonicalType(S.Context, Source); 12940 IntRange LikelySourceRange = 12941 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12942 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12943 12944 if (LikelySourceRange.Width > TargetRange.Width) { 12945 // If the source is a constant, use a default-on diagnostic. 12946 // TODO: this should happen for bitfield stores, too. 12947 Expr::EvalResult Result; 12948 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12949 S.isConstantEvaluated())) { 12950 llvm::APSInt Value(32); 12951 Value = Result.Val.getInt(); 12952 12953 if (S.SourceMgr.isInSystemMacro(CC)) 12954 return; 12955 12956 std::string PrettySourceValue = toString(Value, 10); 12957 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12958 12959 S.DiagRuntimeBehavior( 12960 E->getExprLoc(), E, 12961 S.PDiag(diag::warn_impcast_integer_precision_constant) 12962 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12963 << E->getSourceRange() << SourceRange(CC)); 12964 return; 12965 } 12966 12967 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12968 if (S.SourceMgr.isInSystemMacro(CC)) 12969 return; 12970 12971 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12972 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12973 /* pruneControlFlow */ true); 12974 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12975 } 12976 12977 if (TargetRange.Width > SourceTypeRange.Width) { 12978 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12979 if (UO->getOpcode() == UO_Minus) 12980 if (Source->isUnsignedIntegerType()) { 12981 if (Target->isUnsignedIntegerType()) 12982 return DiagnoseImpCast(S, E, T, CC, 12983 diag::warn_impcast_high_order_zero_bits); 12984 if (Target->isSignedIntegerType()) 12985 return DiagnoseImpCast(S, E, T, CC, 12986 diag::warn_impcast_nonnegative_result); 12987 } 12988 } 12989 12990 if (TargetRange.Width == LikelySourceRange.Width && 12991 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12992 Source->isSignedIntegerType()) { 12993 // Warn when doing a signed to signed conversion, warn if the positive 12994 // source value is exactly the width of the target type, which will 12995 // cause a negative value to be stored. 12996 12997 Expr::EvalResult Result; 12998 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12999 !S.SourceMgr.isInSystemMacro(CC)) { 13000 llvm::APSInt Value = Result.Val.getInt(); 13001 if (isSameWidthConstantConversion(S, E, T, CC)) { 13002 std::string PrettySourceValue = toString(Value, 10); 13003 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13004 13005 S.DiagRuntimeBehavior( 13006 E->getExprLoc(), E, 13007 S.PDiag(diag::warn_impcast_integer_precision_constant) 13008 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13009 << E->getSourceRange() << SourceRange(CC)); 13010 return; 13011 } 13012 } 13013 13014 // Fall through for non-constants to give a sign conversion warning. 13015 } 13016 13017 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13018 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13019 LikelySourceRange.Width == TargetRange.Width)) { 13020 if (S.SourceMgr.isInSystemMacro(CC)) 13021 return; 13022 13023 unsigned DiagID = diag::warn_impcast_integer_sign; 13024 13025 // Traditionally, gcc has warned about this under -Wsign-compare. 13026 // We also want to warn about it in -Wconversion. 13027 // So if -Wconversion is off, use a completely identical diagnostic 13028 // in the sign-compare group. 13029 // The conditional-checking code will 13030 if (ICContext) { 13031 DiagID = diag::warn_impcast_integer_sign_conditional; 13032 *ICContext = true; 13033 } 13034 13035 return DiagnoseImpCast(S, E, T, CC, DiagID); 13036 } 13037 13038 // Diagnose conversions between different enumeration types. 13039 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13040 // type, to give us better diagnostics. 13041 QualType SourceType = E->getType(); 13042 if (!S.getLangOpts().CPlusPlus) { 13043 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13044 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13045 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13046 SourceType = S.Context.getTypeDeclType(Enum); 13047 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13048 } 13049 } 13050 13051 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13052 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13053 if (SourceEnum->getDecl()->hasNameForLinkage() && 13054 TargetEnum->getDecl()->hasNameForLinkage() && 13055 SourceEnum != TargetEnum) { 13056 if (S.SourceMgr.isInSystemMacro(CC)) 13057 return; 13058 13059 return DiagnoseImpCast(S, E, SourceType, T, CC, 13060 diag::warn_impcast_different_enum_types); 13061 } 13062 } 13063 13064 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13065 SourceLocation CC, QualType T); 13066 13067 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13068 SourceLocation CC, bool &ICContext) { 13069 E = E->IgnoreParenImpCasts(); 13070 13071 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13072 return CheckConditionalOperator(S, CO, CC, T); 13073 13074 AnalyzeImplicitConversions(S, E, CC); 13075 if (E->getType() != T) 13076 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13077 } 13078 13079 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13080 SourceLocation CC, QualType T) { 13081 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13082 13083 Expr *TrueExpr = E->getTrueExpr(); 13084 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13085 TrueExpr = BCO->getCommon(); 13086 13087 bool Suspicious = false; 13088 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13089 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13090 13091 if (T->isBooleanType()) 13092 DiagnoseIntInBoolContext(S, E); 13093 13094 // If -Wconversion would have warned about either of the candidates 13095 // for a signedness conversion to the context type... 13096 if (!Suspicious) return; 13097 13098 // ...but it's currently ignored... 13099 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13100 return; 13101 13102 // ...then check whether it would have warned about either of the 13103 // candidates for a signedness conversion to the condition type. 13104 if (E->getType() == T) return; 13105 13106 Suspicious = false; 13107 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13108 E->getType(), CC, &Suspicious); 13109 if (!Suspicious) 13110 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13111 E->getType(), CC, &Suspicious); 13112 } 13113 13114 /// Check conversion of given expression to boolean. 13115 /// Input argument E is a logical expression. 13116 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13117 if (S.getLangOpts().Bool) 13118 return; 13119 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13120 return; 13121 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13122 } 13123 13124 namespace { 13125 struct AnalyzeImplicitConversionsWorkItem { 13126 Expr *E; 13127 SourceLocation CC; 13128 bool IsListInit; 13129 }; 13130 } 13131 13132 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13133 /// that should be visited are added to WorkList. 13134 static void AnalyzeImplicitConversions( 13135 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13136 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13137 Expr *OrigE = Item.E; 13138 SourceLocation CC = Item.CC; 13139 13140 QualType T = OrigE->getType(); 13141 Expr *E = OrigE->IgnoreParenImpCasts(); 13142 13143 // Propagate whether we are in a C++ list initialization expression. 13144 // If so, we do not issue warnings for implicit int-float conversion 13145 // precision loss, because C++11 narrowing already handles it. 13146 bool IsListInit = Item.IsListInit || 13147 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13148 13149 if (E->isTypeDependent() || E->isValueDependent()) 13150 return; 13151 13152 Expr *SourceExpr = E; 13153 // Examine, but don't traverse into the source expression of an 13154 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13155 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13156 // evaluate it in the context of checking the specific conversion to T though. 13157 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13158 if (auto *Src = OVE->getSourceExpr()) 13159 SourceExpr = Src; 13160 13161 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13162 if (UO->getOpcode() == UO_Not && 13163 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13164 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13165 << OrigE->getSourceRange() << T->isBooleanType() 13166 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13167 13168 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13169 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13170 BO->getLHS()->isKnownToHaveBooleanValue() && 13171 BO->getRHS()->isKnownToHaveBooleanValue() && 13172 BO->getLHS()->HasSideEffects(S.Context) && 13173 BO->getRHS()->HasSideEffects(S.Context)) { 13174 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13175 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13176 << FixItHint::CreateReplacement( 13177 BO->getOperatorLoc(), 13178 (BO->getOpcode() == BO_And ? "&&" : "||")); 13179 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13180 } 13181 13182 // For conditional operators, we analyze the arguments as if they 13183 // were being fed directly into the output. 13184 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13185 CheckConditionalOperator(S, CO, CC, T); 13186 return; 13187 } 13188 13189 // Check implicit argument conversions for function calls. 13190 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13191 CheckImplicitArgumentConversions(S, Call, CC); 13192 13193 // Go ahead and check any implicit conversions we might have skipped. 13194 // The non-canonical typecheck is just an optimization; 13195 // CheckImplicitConversion will filter out dead implicit conversions. 13196 if (SourceExpr->getType() != T) 13197 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13198 13199 // Now continue drilling into this expression. 13200 13201 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13202 // The bound subexpressions in a PseudoObjectExpr are not reachable 13203 // as transitive children. 13204 // FIXME: Use a more uniform representation for this. 13205 for (auto *SE : POE->semantics()) 13206 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13207 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13208 } 13209 13210 // Skip past explicit casts. 13211 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13212 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13213 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13214 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13215 WorkList.push_back({E, CC, IsListInit}); 13216 return; 13217 } 13218 13219 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13220 // Do a somewhat different check with comparison operators. 13221 if (BO->isComparisonOp()) 13222 return AnalyzeComparison(S, BO); 13223 13224 // And with simple assignments. 13225 if (BO->getOpcode() == BO_Assign) 13226 return AnalyzeAssignment(S, BO); 13227 // And with compound assignments. 13228 if (BO->isAssignmentOp()) 13229 return AnalyzeCompoundAssignment(S, BO); 13230 } 13231 13232 // These break the otherwise-useful invariant below. Fortunately, 13233 // we don't really need to recurse into them, because any internal 13234 // expressions should have been analyzed already when they were 13235 // built into statements. 13236 if (isa<StmtExpr>(E)) return; 13237 13238 // Don't descend into unevaluated contexts. 13239 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13240 13241 // Now just recurse over the expression's children. 13242 CC = E->getExprLoc(); 13243 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13244 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13245 for (Stmt *SubStmt : E->children()) { 13246 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13247 if (!ChildExpr) 13248 continue; 13249 13250 if (IsLogicalAndOperator && 13251 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13252 // Ignore checking string literals that are in logical and operators. 13253 // This is a common pattern for asserts. 13254 continue; 13255 WorkList.push_back({ChildExpr, CC, IsListInit}); 13256 } 13257 13258 if (BO && BO->isLogicalOp()) { 13259 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13260 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13261 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13262 13263 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13264 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13265 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13266 } 13267 13268 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13269 if (U->getOpcode() == UO_LNot) { 13270 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13271 } else if (U->getOpcode() != UO_AddrOf) { 13272 if (U->getSubExpr()->getType()->isAtomicType()) 13273 S.Diag(U->getSubExpr()->getBeginLoc(), 13274 diag::warn_atomic_implicit_seq_cst); 13275 } 13276 } 13277 } 13278 13279 /// AnalyzeImplicitConversions - Find and report any interesting 13280 /// implicit conversions in the given expression. There are a couple 13281 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13282 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13283 bool IsListInit/*= false*/) { 13284 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13285 WorkList.push_back({OrigE, CC, IsListInit}); 13286 while (!WorkList.empty()) 13287 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13288 } 13289 13290 /// Diagnose integer type and any valid implicit conversion to it. 13291 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13292 // Taking into account implicit conversions, 13293 // allow any integer. 13294 if (!E->getType()->isIntegerType()) { 13295 S.Diag(E->getBeginLoc(), 13296 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13297 return true; 13298 } 13299 // Potentially emit standard warnings for implicit conversions if enabled 13300 // using -Wconversion. 13301 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13302 return false; 13303 } 13304 13305 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13306 // Returns true when emitting a warning about taking the address of a reference. 13307 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13308 const PartialDiagnostic &PD) { 13309 E = E->IgnoreParenImpCasts(); 13310 13311 const FunctionDecl *FD = nullptr; 13312 13313 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13314 if (!DRE->getDecl()->getType()->isReferenceType()) 13315 return false; 13316 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13317 if (!M->getMemberDecl()->getType()->isReferenceType()) 13318 return false; 13319 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13320 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13321 return false; 13322 FD = Call->getDirectCallee(); 13323 } else { 13324 return false; 13325 } 13326 13327 SemaRef.Diag(E->getExprLoc(), PD); 13328 13329 // If possible, point to location of function. 13330 if (FD) { 13331 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13332 } 13333 13334 return true; 13335 } 13336 13337 // Returns true if the SourceLocation is expanded from any macro body. 13338 // Returns false if the SourceLocation is invalid, is from not in a macro 13339 // expansion, or is from expanded from a top-level macro argument. 13340 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13341 if (Loc.isInvalid()) 13342 return false; 13343 13344 while (Loc.isMacroID()) { 13345 if (SM.isMacroBodyExpansion(Loc)) 13346 return true; 13347 Loc = SM.getImmediateMacroCallerLoc(Loc); 13348 } 13349 13350 return false; 13351 } 13352 13353 /// Diagnose pointers that are always non-null. 13354 /// \param E the expression containing the pointer 13355 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13356 /// compared to a null pointer 13357 /// \param IsEqual True when the comparison is equal to a null pointer 13358 /// \param Range Extra SourceRange to highlight in the diagnostic 13359 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13360 Expr::NullPointerConstantKind NullKind, 13361 bool IsEqual, SourceRange Range) { 13362 if (!E) 13363 return; 13364 13365 // Don't warn inside macros. 13366 if (E->getExprLoc().isMacroID()) { 13367 const SourceManager &SM = getSourceManager(); 13368 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13369 IsInAnyMacroBody(SM, Range.getBegin())) 13370 return; 13371 } 13372 E = E->IgnoreImpCasts(); 13373 13374 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13375 13376 if (isa<CXXThisExpr>(E)) { 13377 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13378 : diag::warn_this_bool_conversion; 13379 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13380 return; 13381 } 13382 13383 bool IsAddressOf = false; 13384 13385 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13386 if (UO->getOpcode() != UO_AddrOf) 13387 return; 13388 IsAddressOf = true; 13389 E = UO->getSubExpr(); 13390 } 13391 13392 if (IsAddressOf) { 13393 unsigned DiagID = IsCompare 13394 ? diag::warn_address_of_reference_null_compare 13395 : diag::warn_address_of_reference_bool_conversion; 13396 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13397 << IsEqual; 13398 if (CheckForReference(*this, E, PD)) { 13399 return; 13400 } 13401 } 13402 13403 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13404 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13405 std::string Str; 13406 llvm::raw_string_ostream S(Str); 13407 E->printPretty(S, nullptr, getPrintingPolicy()); 13408 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13409 : diag::warn_cast_nonnull_to_bool; 13410 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13411 << E->getSourceRange() << Range << IsEqual; 13412 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13413 }; 13414 13415 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13416 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13417 if (auto *Callee = Call->getDirectCallee()) { 13418 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13419 ComplainAboutNonnullParamOrCall(A); 13420 return; 13421 } 13422 } 13423 } 13424 13425 // Expect to find a single Decl. Skip anything more complicated. 13426 ValueDecl *D = nullptr; 13427 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13428 D = R->getDecl(); 13429 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13430 D = M->getMemberDecl(); 13431 } 13432 13433 // Weak Decls can be null. 13434 if (!D || D->isWeak()) 13435 return; 13436 13437 // Check for parameter decl with nonnull attribute 13438 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13439 if (getCurFunction() && 13440 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13441 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13442 ComplainAboutNonnullParamOrCall(A); 13443 return; 13444 } 13445 13446 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13447 // Skip function template not specialized yet. 13448 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13449 return; 13450 auto ParamIter = llvm::find(FD->parameters(), PV); 13451 assert(ParamIter != FD->param_end()); 13452 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13453 13454 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13455 if (!NonNull->args_size()) { 13456 ComplainAboutNonnullParamOrCall(NonNull); 13457 return; 13458 } 13459 13460 for (const ParamIdx &ArgNo : NonNull->args()) { 13461 if (ArgNo.getASTIndex() == ParamNo) { 13462 ComplainAboutNonnullParamOrCall(NonNull); 13463 return; 13464 } 13465 } 13466 } 13467 } 13468 } 13469 } 13470 13471 QualType T = D->getType(); 13472 const bool IsArray = T->isArrayType(); 13473 const bool IsFunction = T->isFunctionType(); 13474 13475 // Address of function is used to silence the function warning. 13476 if (IsAddressOf && IsFunction) { 13477 return; 13478 } 13479 13480 // Found nothing. 13481 if (!IsAddressOf && !IsFunction && !IsArray) 13482 return; 13483 13484 // Pretty print the expression for the diagnostic. 13485 std::string Str; 13486 llvm::raw_string_ostream S(Str); 13487 E->printPretty(S, nullptr, getPrintingPolicy()); 13488 13489 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13490 : diag::warn_impcast_pointer_to_bool; 13491 enum { 13492 AddressOf, 13493 FunctionPointer, 13494 ArrayPointer 13495 } DiagType; 13496 if (IsAddressOf) 13497 DiagType = AddressOf; 13498 else if (IsFunction) 13499 DiagType = FunctionPointer; 13500 else if (IsArray) 13501 DiagType = ArrayPointer; 13502 else 13503 llvm_unreachable("Could not determine diagnostic."); 13504 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13505 << Range << IsEqual; 13506 13507 if (!IsFunction) 13508 return; 13509 13510 // Suggest '&' to silence the function warning. 13511 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13512 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13513 13514 // Check to see if '()' fixit should be emitted. 13515 QualType ReturnType; 13516 UnresolvedSet<4> NonTemplateOverloads; 13517 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13518 if (ReturnType.isNull()) 13519 return; 13520 13521 if (IsCompare) { 13522 // There are two cases here. If there is null constant, the only suggest 13523 // for a pointer return type. If the null is 0, then suggest if the return 13524 // type is a pointer or an integer type. 13525 if (!ReturnType->isPointerType()) { 13526 if (NullKind == Expr::NPCK_ZeroExpression || 13527 NullKind == Expr::NPCK_ZeroLiteral) { 13528 if (!ReturnType->isIntegerType()) 13529 return; 13530 } else { 13531 return; 13532 } 13533 } 13534 } else { // !IsCompare 13535 // For function to bool, only suggest if the function pointer has bool 13536 // return type. 13537 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13538 return; 13539 } 13540 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13541 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13542 } 13543 13544 /// Diagnoses "dangerous" implicit conversions within the given 13545 /// expression (which is a full expression). Implements -Wconversion 13546 /// and -Wsign-compare. 13547 /// 13548 /// \param CC the "context" location of the implicit conversion, i.e. 13549 /// the most location of the syntactic entity requiring the implicit 13550 /// conversion 13551 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13552 // Don't diagnose in unevaluated contexts. 13553 if (isUnevaluatedContext()) 13554 return; 13555 13556 // Don't diagnose for value- or type-dependent expressions. 13557 if (E->isTypeDependent() || E->isValueDependent()) 13558 return; 13559 13560 // Check for array bounds violations in cases where the check isn't triggered 13561 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13562 // ArraySubscriptExpr is on the RHS of a variable initialization. 13563 CheckArrayAccess(E); 13564 13565 // This is not the right CC for (e.g.) a variable initialization. 13566 AnalyzeImplicitConversions(*this, E, CC); 13567 } 13568 13569 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13570 /// Input argument E is a logical expression. 13571 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13572 ::CheckBoolLikeConversion(*this, E, CC); 13573 } 13574 13575 /// Diagnose when expression is an integer constant expression and its evaluation 13576 /// results in integer overflow 13577 void Sema::CheckForIntOverflow (Expr *E) { 13578 // Use a work list to deal with nested struct initializers. 13579 SmallVector<Expr *, 2> Exprs(1, E); 13580 13581 do { 13582 Expr *OriginalE = Exprs.pop_back_val(); 13583 Expr *E = OriginalE->IgnoreParenCasts(); 13584 13585 if (isa<BinaryOperator>(E)) { 13586 E->EvaluateForOverflow(Context); 13587 continue; 13588 } 13589 13590 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13591 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13592 else if (isa<ObjCBoxedExpr>(OriginalE)) 13593 E->EvaluateForOverflow(Context); 13594 else if (auto Call = dyn_cast<CallExpr>(E)) 13595 Exprs.append(Call->arg_begin(), Call->arg_end()); 13596 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13597 Exprs.append(Message->arg_begin(), Message->arg_end()); 13598 } while (!Exprs.empty()); 13599 } 13600 13601 namespace { 13602 13603 /// Visitor for expressions which looks for unsequenced operations on the 13604 /// same object. 13605 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13606 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13607 13608 /// A tree of sequenced regions within an expression. Two regions are 13609 /// unsequenced if one is an ancestor or a descendent of the other. When we 13610 /// finish processing an expression with sequencing, such as a comma 13611 /// expression, we fold its tree nodes into its parent, since they are 13612 /// unsequenced with respect to nodes we will visit later. 13613 class SequenceTree { 13614 struct Value { 13615 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13616 unsigned Parent : 31; 13617 unsigned Merged : 1; 13618 }; 13619 SmallVector<Value, 8> Values; 13620 13621 public: 13622 /// A region within an expression which may be sequenced with respect 13623 /// to some other region. 13624 class Seq { 13625 friend class SequenceTree; 13626 13627 unsigned Index; 13628 13629 explicit Seq(unsigned N) : Index(N) {} 13630 13631 public: 13632 Seq() : Index(0) {} 13633 }; 13634 13635 SequenceTree() { Values.push_back(Value(0)); } 13636 Seq root() const { return Seq(0); } 13637 13638 /// Create a new sequence of operations, which is an unsequenced 13639 /// subset of \p Parent. This sequence of operations is sequenced with 13640 /// respect to other children of \p Parent. 13641 Seq allocate(Seq Parent) { 13642 Values.push_back(Value(Parent.Index)); 13643 return Seq(Values.size() - 1); 13644 } 13645 13646 /// Merge a sequence of operations into its parent. 13647 void merge(Seq S) { 13648 Values[S.Index].Merged = true; 13649 } 13650 13651 /// Determine whether two operations are unsequenced. This operation 13652 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13653 /// should have been merged into its parent as appropriate. 13654 bool isUnsequenced(Seq Cur, Seq Old) { 13655 unsigned C = representative(Cur.Index); 13656 unsigned Target = representative(Old.Index); 13657 while (C >= Target) { 13658 if (C == Target) 13659 return true; 13660 C = Values[C].Parent; 13661 } 13662 return false; 13663 } 13664 13665 private: 13666 /// Pick a representative for a sequence. 13667 unsigned representative(unsigned K) { 13668 if (Values[K].Merged) 13669 // Perform path compression as we go. 13670 return Values[K].Parent = representative(Values[K].Parent); 13671 return K; 13672 } 13673 }; 13674 13675 /// An object for which we can track unsequenced uses. 13676 using Object = const NamedDecl *; 13677 13678 /// Different flavors of object usage which we track. We only track the 13679 /// least-sequenced usage of each kind. 13680 enum UsageKind { 13681 /// A read of an object. Multiple unsequenced reads are OK. 13682 UK_Use, 13683 13684 /// A modification of an object which is sequenced before the value 13685 /// computation of the expression, such as ++n in C++. 13686 UK_ModAsValue, 13687 13688 /// A modification of an object which is not sequenced before the value 13689 /// computation of the expression, such as n++. 13690 UK_ModAsSideEffect, 13691 13692 UK_Count = UK_ModAsSideEffect + 1 13693 }; 13694 13695 /// Bundle together a sequencing region and the expression corresponding 13696 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13697 struct Usage { 13698 const Expr *UsageExpr; 13699 SequenceTree::Seq Seq; 13700 13701 Usage() : UsageExpr(nullptr), Seq() {} 13702 }; 13703 13704 struct UsageInfo { 13705 Usage Uses[UK_Count]; 13706 13707 /// Have we issued a diagnostic for this object already? 13708 bool Diagnosed; 13709 13710 UsageInfo() : Uses(), Diagnosed(false) {} 13711 }; 13712 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13713 13714 Sema &SemaRef; 13715 13716 /// Sequenced regions within the expression. 13717 SequenceTree Tree; 13718 13719 /// Declaration modifications and references which we have seen. 13720 UsageInfoMap UsageMap; 13721 13722 /// The region we are currently within. 13723 SequenceTree::Seq Region; 13724 13725 /// Filled in with declarations which were modified as a side-effect 13726 /// (that is, post-increment operations). 13727 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13728 13729 /// Expressions to check later. We defer checking these to reduce 13730 /// stack usage. 13731 SmallVectorImpl<const Expr *> &WorkList; 13732 13733 /// RAII object wrapping the visitation of a sequenced subexpression of an 13734 /// expression. At the end of this process, the side-effects of the evaluation 13735 /// become sequenced with respect to the value computation of the result, so 13736 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13737 /// UK_ModAsValue. 13738 struct SequencedSubexpression { 13739 SequencedSubexpression(SequenceChecker &Self) 13740 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13741 Self.ModAsSideEffect = &ModAsSideEffect; 13742 } 13743 13744 ~SequencedSubexpression() { 13745 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13746 // Add a new usage with usage kind UK_ModAsValue, and then restore 13747 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13748 // the previous one was empty). 13749 UsageInfo &UI = Self.UsageMap[M.first]; 13750 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13751 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13752 SideEffectUsage = M.second; 13753 } 13754 Self.ModAsSideEffect = OldModAsSideEffect; 13755 } 13756 13757 SequenceChecker &Self; 13758 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13759 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13760 }; 13761 13762 /// RAII object wrapping the visitation of a subexpression which we might 13763 /// choose to evaluate as a constant. If any subexpression is evaluated and 13764 /// found to be non-constant, this allows us to suppress the evaluation of 13765 /// the outer expression. 13766 class EvaluationTracker { 13767 public: 13768 EvaluationTracker(SequenceChecker &Self) 13769 : Self(Self), Prev(Self.EvalTracker) { 13770 Self.EvalTracker = this; 13771 } 13772 13773 ~EvaluationTracker() { 13774 Self.EvalTracker = Prev; 13775 if (Prev) 13776 Prev->EvalOK &= EvalOK; 13777 } 13778 13779 bool evaluate(const Expr *E, bool &Result) { 13780 if (!EvalOK || E->isValueDependent()) 13781 return false; 13782 EvalOK = E->EvaluateAsBooleanCondition( 13783 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13784 return EvalOK; 13785 } 13786 13787 private: 13788 SequenceChecker &Self; 13789 EvaluationTracker *Prev; 13790 bool EvalOK = true; 13791 } *EvalTracker = nullptr; 13792 13793 /// Find the object which is produced by the specified expression, 13794 /// if any. 13795 Object getObject(const Expr *E, bool Mod) const { 13796 E = E->IgnoreParenCasts(); 13797 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13798 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13799 return getObject(UO->getSubExpr(), Mod); 13800 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13801 if (BO->getOpcode() == BO_Comma) 13802 return getObject(BO->getRHS(), Mod); 13803 if (Mod && BO->isAssignmentOp()) 13804 return getObject(BO->getLHS(), Mod); 13805 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13806 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13807 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13808 return ME->getMemberDecl(); 13809 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13810 // FIXME: If this is a reference, map through to its value. 13811 return DRE->getDecl(); 13812 return nullptr; 13813 } 13814 13815 /// Note that an object \p O was modified or used by an expression 13816 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13817 /// the object \p O as obtained via the \p UsageMap. 13818 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13819 // Get the old usage for the given object and usage kind. 13820 Usage &U = UI.Uses[UK]; 13821 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13822 // If we have a modification as side effect and are in a sequenced 13823 // subexpression, save the old Usage so that we can restore it later 13824 // in SequencedSubexpression::~SequencedSubexpression. 13825 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13826 ModAsSideEffect->push_back(std::make_pair(O, U)); 13827 // Then record the new usage with the current sequencing region. 13828 U.UsageExpr = UsageExpr; 13829 U.Seq = Region; 13830 } 13831 } 13832 13833 /// Check whether a modification or use of an object \p O in an expression 13834 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13835 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13836 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13837 /// usage and false we are checking for a mod-use unsequenced usage. 13838 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13839 UsageKind OtherKind, bool IsModMod) { 13840 if (UI.Diagnosed) 13841 return; 13842 13843 const Usage &U = UI.Uses[OtherKind]; 13844 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13845 return; 13846 13847 const Expr *Mod = U.UsageExpr; 13848 const Expr *ModOrUse = UsageExpr; 13849 if (OtherKind == UK_Use) 13850 std::swap(Mod, ModOrUse); 13851 13852 SemaRef.DiagRuntimeBehavior( 13853 Mod->getExprLoc(), {Mod, ModOrUse}, 13854 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13855 : diag::warn_unsequenced_mod_use) 13856 << O << SourceRange(ModOrUse->getExprLoc())); 13857 UI.Diagnosed = true; 13858 } 13859 13860 // A note on note{Pre, Post}{Use, Mod}: 13861 // 13862 // (It helps to follow the algorithm with an expression such as 13863 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13864 // operations before C++17 and both are well-defined in C++17). 13865 // 13866 // When visiting a node which uses/modify an object we first call notePreUse 13867 // or notePreMod before visiting its sub-expression(s). At this point the 13868 // children of the current node have not yet been visited and so the eventual 13869 // uses/modifications resulting from the children of the current node have not 13870 // been recorded yet. 13871 // 13872 // We then visit the children of the current node. After that notePostUse or 13873 // notePostMod is called. These will 1) detect an unsequenced modification 13874 // as side effect (as in "k++ + k") and 2) add a new usage with the 13875 // appropriate usage kind. 13876 // 13877 // We also have to be careful that some operation sequences modification as 13878 // side effect as well (for example: || or ,). To account for this we wrap 13879 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13880 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13881 // which record usages which are modifications as side effect, and then 13882 // downgrade them (or more accurately restore the previous usage which was a 13883 // modification as side effect) when exiting the scope of the sequenced 13884 // subexpression. 13885 13886 void notePreUse(Object O, const Expr *UseExpr) { 13887 UsageInfo &UI = UsageMap[O]; 13888 // Uses conflict with other modifications. 13889 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13890 } 13891 13892 void notePostUse(Object O, const Expr *UseExpr) { 13893 UsageInfo &UI = UsageMap[O]; 13894 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13895 /*IsModMod=*/false); 13896 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13897 } 13898 13899 void notePreMod(Object O, const Expr *ModExpr) { 13900 UsageInfo &UI = UsageMap[O]; 13901 // Modifications conflict with other modifications and with uses. 13902 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13903 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13904 } 13905 13906 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13907 UsageInfo &UI = UsageMap[O]; 13908 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13909 /*IsModMod=*/true); 13910 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13911 } 13912 13913 public: 13914 SequenceChecker(Sema &S, const Expr *E, 13915 SmallVectorImpl<const Expr *> &WorkList) 13916 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13917 Visit(E); 13918 // Silence a -Wunused-private-field since WorkList is now unused. 13919 // TODO: Evaluate if it can be used, and if not remove it. 13920 (void)this->WorkList; 13921 } 13922 13923 void VisitStmt(const Stmt *S) { 13924 // Skip all statements which aren't expressions for now. 13925 } 13926 13927 void VisitExpr(const Expr *E) { 13928 // By default, just recurse to evaluated subexpressions. 13929 Base::VisitStmt(E); 13930 } 13931 13932 void VisitCastExpr(const CastExpr *E) { 13933 Object O = Object(); 13934 if (E->getCastKind() == CK_LValueToRValue) 13935 O = getObject(E->getSubExpr(), false); 13936 13937 if (O) 13938 notePreUse(O, E); 13939 VisitExpr(E); 13940 if (O) 13941 notePostUse(O, E); 13942 } 13943 13944 void VisitSequencedExpressions(const Expr *SequencedBefore, 13945 const Expr *SequencedAfter) { 13946 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13947 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13948 SequenceTree::Seq OldRegion = Region; 13949 13950 { 13951 SequencedSubexpression SeqBefore(*this); 13952 Region = BeforeRegion; 13953 Visit(SequencedBefore); 13954 } 13955 13956 Region = AfterRegion; 13957 Visit(SequencedAfter); 13958 13959 Region = OldRegion; 13960 13961 Tree.merge(BeforeRegion); 13962 Tree.merge(AfterRegion); 13963 } 13964 13965 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13966 // C++17 [expr.sub]p1: 13967 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13968 // expression E1 is sequenced before the expression E2. 13969 if (SemaRef.getLangOpts().CPlusPlus17) 13970 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13971 else { 13972 Visit(ASE->getLHS()); 13973 Visit(ASE->getRHS()); 13974 } 13975 } 13976 13977 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13978 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13979 void VisitBinPtrMem(const BinaryOperator *BO) { 13980 // C++17 [expr.mptr.oper]p4: 13981 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13982 // the expression E1 is sequenced before the expression E2. 13983 if (SemaRef.getLangOpts().CPlusPlus17) 13984 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13985 else { 13986 Visit(BO->getLHS()); 13987 Visit(BO->getRHS()); 13988 } 13989 } 13990 13991 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13992 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13993 void VisitBinShlShr(const BinaryOperator *BO) { 13994 // C++17 [expr.shift]p4: 13995 // The expression E1 is sequenced before the expression E2. 13996 if (SemaRef.getLangOpts().CPlusPlus17) 13997 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13998 else { 13999 Visit(BO->getLHS()); 14000 Visit(BO->getRHS()); 14001 } 14002 } 14003 14004 void VisitBinComma(const BinaryOperator *BO) { 14005 // C++11 [expr.comma]p1: 14006 // Every value computation and side effect associated with the left 14007 // expression is sequenced before every value computation and side 14008 // effect associated with the right expression. 14009 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14010 } 14011 14012 void VisitBinAssign(const BinaryOperator *BO) { 14013 SequenceTree::Seq RHSRegion; 14014 SequenceTree::Seq LHSRegion; 14015 if (SemaRef.getLangOpts().CPlusPlus17) { 14016 RHSRegion = Tree.allocate(Region); 14017 LHSRegion = Tree.allocate(Region); 14018 } else { 14019 RHSRegion = Region; 14020 LHSRegion = Region; 14021 } 14022 SequenceTree::Seq OldRegion = Region; 14023 14024 // C++11 [expr.ass]p1: 14025 // [...] the assignment is sequenced after the value computation 14026 // of the right and left operands, [...] 14027 // 14028 // so check it before inspecting the operands and update the 14029 // map afterwards. 14030 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14031 if (O) 14032 notePreMod(O, BO); 14033 14034 if (SemaRef.getLangOpts().CPlusPlus17) { 14035 // C++17 [expr.ass]p1: 14036 // [...] The right operand is sequenced before the left operand. [...] 14037 { 14038 SequencedSubexpression SeqBefore(*this); 14039 Region = RHSRegion; 14040 Visit(BO->getRHS()); 14041 } 14042 14043 Region = LHSRegion; 14044 Visit(BO->getLHS()); 14045 14046 if (O && isa<CompoundAssignOperator>(BO)) 14047 notePostUse(O, BO); 14048 14049 } else { 14050 // C++11 does not specify any sequencing between the LHS and RHS. 14051 Region = LHSRegion; 14052 Visit(BO->getLHS()); 14053 14054 if (O && isa<CompoundAssignOperator>(BO)) 14055 notePostUse(O, BO); 14056 14057 Region = RHSRegion; 14058 Visit(BO->getRHS()); 14059 } 14060 14061 // C++11 [expr.ass]p1: 14062 // the assignment is sequenced [...] before the value computation of the 14063 // assignment expression. 14064 // C11 6.5.16/3 has no such rule. 14065 Region = OldRegion; 14066 if (O) 14067 notePostMod(O, BO, 14068 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14069 : UK_ModAsSideEffect); 14070 if (SemaRef.getLangOpts().CPlusPlus17) { 14071 Tree.merge(RHSRegion); 14072 Tree.merge(LHSRegion); 14073 } 14074 } 14075 14076 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14077 VisitBinAssign(CAO); 14078 } 14079 14080 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14081 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14082 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14083 Object O = getObject(UO->getSubExpr(), true); 14084 if (!O) 14085 return VisitExpr(UO); 14086 14087 notePreMod(O, UO); 14088 Visit(UO->getSubExpr()); 14089 // C++11 [expr.pre.incr]p1: 14090 // the expression ++x is equivalent to x+=1 14091 notePostMod(O, UO, 14092 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14093 : UK_ModAsSideEffect); 14094 } 14095 14096 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14097 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14098 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14099 Object O = getObject(UO->getSubExpr(), true); 14100 if (!O) 14101 return VisitExpr(UO); 14102 14103 notePreMod(O, UO); 14104 Visit(UO->getSubExpr()); 14105 notePostMod(O, UO, UK_ModAsSideEffect); 14106 } 14107 14108 void VisitBinLOr(const BinaryOperator *BO) { 14109 // C++11 [expr.log.or]p2: 14110 // If the second expression is evaluated, every value computation and 14111 // side effect associated with the first expression is sequenced before 14112 // every value computation and side effect associated with the 14113 // second expression. 14114 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14115 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14116 SequenceTree::Seq OldRegion = Region; 14117 14118 EvaluationTracker Eval(*this); 14119 { 14120 SequencedSubexpression Sequenced(*this); 14121 Region = LHSRegion; 14122 Visit(BO->getLHS()); 14123 } 14124 14125 // C++11 [expr.log.or]p1: 14126 // [...] the second operand is not evaluated if the first operand 14127 // evaluates to true. 14128 bool EvalResult = false; 14129 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14130 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14131 if (ShouldVisitRHS) { 14132 Region = RHSRegion; 14133 Visit(BO->getRHS()); 14134 } 14135 14136 Region = OldRegion; 14137 Tree.merge(LHSRegion); 14138 Tree.merge(RHSRegion); 14139 } 14140 14141 void VisitBinLAnd(const BinaryOperator *BO) { 14142 // C++11 [expr.log.and]p2: 14143 // If the second expression is evaluated, every value computation and 14144 // side effect associated with the first expression is sequenced before 14145 // every value computation and side effect associated with the 14146 // second expression. 14147 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14148 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14149 SequenceTree::Seq OldRegion = Region; 14150 14151 EvaluationTracker Eval(*this); 14152 { 14153 SequencedSubexpression Sequenced(*this); 14154 Region = LHSRegion; 14155 Visit(BO->getLHS()); 14156 } 14157 14158 // C++11 [expr.log.and]p1: 14159 // [...] the second operand is not evaluated if the first operand is false. 14160 bool EvalResult = false; 14161 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14162 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14163 if (ShouldVisitRHS) { 14164 Region = RHSRegion; 14165 Visit(BO->getRHS()); 14166 } 14167 14168 Region = OldRegion; 14169 Tree.merge(LHSRegion); 14170 Tree.merge(RHSRegion); 14171 } 14172 14173 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14174 // C++11 [expr.cond]p1: 14175 // [...] Every value computation and side effect associated with the first 14176 // expression is sequenced before every value computation and side effect 14177 // associated with the second or third expression. 14178 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14179 14180 // No sequencing is specified between the true and false expression. 14181 // However since exactly one of both is going to be evaluated we can 14182 // consider them to be sequenced. This is needed to avoid warning on 14183 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14184 // both the true and false expressions because we can't evaluate x. 14185 // This will still allow us to detect an expression like (pre C++17) 14186 // "(x ? y += 1 : y += 2) = y". 14187 // 14188 // We don't wrap the visitation of the true and false expression with 14189 // SequencedSubexpression because we don't want to downgrade modifications 14190 // as side effect in the true and false expressions after the visition 14191 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14192 // not warn between the two "y++", but we should warn between the "y++" 14193 // and the "y". 14194 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14195 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14196 SequenceTree::Seq OldRegion = Region; 14197 14198 EvaluationTracker Eval(*this); 14199 { 14200 SequencedSubexpression Sequenced(*this); 14201 Region = ConditionRegion; 14202 Visit(CO->getCond()); 14203 } 14204 14205 // C++11 [expr.cond]p1: 14206 // [...] The first expression is contextually converted to bool (Clause 4). 14207 // It is evaluated and if it is true, the result of the conditional 14208 // expression is the value of the second expression, otherwise that of the 14209 // third expression. Only one of the second and third expressions is 14210 // evaluated. [...] 14211 bool EvalResult = false; 14212 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14213 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14214 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14215 if (ShouldVisitTrueExpr) { 14216 Region = TrueRegion; 14217 Visit(CO->getTrueExpr()); 14218 } 14219 if (ShouldVisitFalseExpr) { 14220 Region = FalseRegion; 14221 Visit(CO->getFalseExpr()); 14222 } 14223 14224 Region = OldRegion; 14225 Tree.merge(ConditionRegion); 14226 Tree.merge(TrueRegion); 14227 Tree.merge(FalseRegion); 14228 } 14229 14230 void VisitCallExpr(const CallExpr *CE) { 14231 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14232 14233 if (CE->isUnevaluatedBuiltinCall(Context)) 14234 return; 14235 14236 // C++11 [intro.execution]p15: 14237 // When calling a function [...], every value computation and side effect 14238 // associated with any argument expression, or with the postfix expression 14239 // designating the called function, is sequenced before execution of every 14240 // expression or statement in the body of the function [and thus before 14241 // the value computation of its result]. 14242 SequencedSubexpression Sequenced(*this); 14243 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14244 // C++17 [expr.call]p5 14245 // The postfix-expression is sequenced before each expression in the 14246 // expression-list and any default argument. [...] 14247 SequenceTree::Seq CalleeRegion; 14248 SequenceTree::Seq OtherRegion; 14249 if (SemaRef.getLangOpts().CPlusPlus17) { 14250 CalleeRegion = Tree.allocate(Region); 14251 OtherRegion = Tree.allocate(Region); 14252 } else { 14253 CalleeRegion = Region; 14254 OtherRegion = Region; 14255 } 14256 SequenceTree::Seq OldRegion = Region; 14257 14258 // Visit the callee expression first. 14259 Region = CalleeRegion; 14260 if (SemaRef.getLangOpts().CPlusPlus17) { 14261 SequencedSubexpression Sequenced(*this); 14262 Visit(CE->getCallee()); 14263 } else { 14264 Visit(CE->getCallee()); 14265 } 14266 14267 // Then visit the argument expressions. 14268 Region = OtherRegion; 14269 for (const Expr *Argument : CE->arguments()) 14270 Visit(Argument); 14271 14272 Region = OldRegion; 14273 if (SemaRef.getLangOpts().CPlusPlus17) { 14274 Tree.merge(CalleeRegion); 14275 Tree.merge(OtherRegion); 14276 } 14277 }); 14278 } 14279 14280 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14281 // C++17 [over.match.oper]p2: 14282 // [...] the operator notation is first transformed to the equivalent 14283 // function-call notation as summarized in Table 12 (where @ denotes one 14284 // of the operators covered in the specified subclause). However, the 14285 // operands are sequenced in the order prescribed for the built-in 14286 // operator (Clause 8). 14287 // 14288 // From the above only overloaded binary operators and overloaded call 14289 // operators have sequencing rules in C++17 that we need to handle 14290 // separately. 14291 if (!SemaRef.getLangOpts().CPlusPlus17 || 14292 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14293 return VisitCallExpr(CXXOCE); 14294 14295 enum { 14296 NoSequencing, 14297 LHSBeforeRHS, 14298 RHSBeforeLHS, 14299 LHSBeforeRest 14300 } SequencingKind; 14301 switch (CXXOCE->getOperator()) { 14302 case OO_Equal: 14303 case OO_PlusEqual: 14304 case OO_MinusEqual: 14305 case OO_StarEqual: 14306 case OO_SlashEqual: 14307 case OO_PercentEqual: 14308 case OO_CaretEqual: 14309 case OO_AmpEqual: 14310 case OO_PipeEqual: 14311 case OO_LessLessEqual: 14312 case OO_GreaterGreaterEqual: 14313 SequencingKind = RHSBeforeLHS; 14314 break; 14315 14316 case OO_LessLess: 14317 case OO_GreaterGreater: 14318 case OO_AmpAmp: 14319 case OO_PipePipe: 14320 case OO_Comma: 14321 case OO_ArrowStar: 14322 case OO_Subscript: 14323 SequencingKind = LHSBeforeRHS; 14324 break; 14325 14326 case OO_Call: 14327 SequencingKind = LHSBeforeRest; 14328 break; 14329 14330 default: 14331 SequencingKind = NoSequencing; 14332 break; 14333 } 14334 14335 if (SequencingKind == NoSequencing) 14336 return VisitCallExpr(CXXOCE); 14337 14338 // This is a call, so all subexpressions are sequenced before the result. 14339 SequencedSubexpression Sequenced(*this); 14340 14341 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14342 assert(SemaRef.getLangOpts().CPlusPlus17 && 14343 "Should only get there with C++17 and above!"); 14344 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14345 "Should only get there with an overloaded binary operator" 14346 " or an overloaded call operator!"); 14347 14348 if (SequencingKind == LHSBeforeRest) { 14349 assert(CXXOCE->getOperator() == OO_Call && 14350 "We should only have an overloaded call operator here!"); 14351 14352 // This is very similar to VisitCallExpr, except that we only have the 14353 // C++17 case. The postfix-expression is the first argument of the 14354 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14355 // are in the following arguments. 14356 // 14357 // Note that we intentionally do not visit the callee expression since 14358 // it is just a decayed reference to a function. 14359 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14360 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14361 SequenceTree::Seq OldRegion = Region; 14362 14363 assert(CXXOCE->getNumArgs() >= 1 && 14364 "An overloaded call operator must have at least one argument" 14365 " for the postfix-expression!"); 14366 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14367 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14368 CXXOCE->getNumArgs() - 1); 14369 14370 // Visit the postfix-expression first. 14371 { 14372 Region = PostfixExprRegion; 14373 SequencedSubexpression Sequenced(*this); 14374 Visit(PostfixExpr); 14375 } 14376 14377 // Then visit the argument expressions. 14378 Region = ArgsRegion; 14379 for (const Expr *Arg : Args) 14380 Visit(Arg); 14381 14382 Region = OldRegion; 14383 Tree.merge(PostfixExprRegion); 14384 Tree.merge(ArgsRegion); 14385 } else { 14386 assert(CXXOCE->getNumArgs() == 2 && 14387 "Should only have two arguments here!"); 14388 assert((SequencingKind == LHSBeforeRHS || 14389 SequencingKind == RHSBeforeLHS) && 14390 "Unexpected sequencing kind!"); 14391 14392 // We do not visit the callee expression since it is just a decayed 14393 // reference to a function. 14394 const Expr *E1 = CXXOCE->getArg(0); 14395 const Expr *E2 = CXXOCE->getArg(1); 14396 if (SequencingKind == RHSBeforeLHS) 14397 std::swap(E1, E2); 14398 14399 return VisitSequencedExpressions(E1, E2); 14400 } 14401 }); 14402 } 14403 14404 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14405 // This is a call, so all subexpressions are sequenced before the result. 14406 SequencedSubexpression Sequenced(*this); 14407 14408 if (!CCE->isListInitialization()) 14409 return VisitExpr(CCE); 14410 14411 // In C++11, list initializations are sequenced. 14412 SmallVector<SequenceTree::Seq, 32> Elts; 14413 SequenceTree::Seq Parent = Region; 14414 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14415 E = CCE->arg_end(); 14416 I != E; ++I) { 14417 Region = Tree.allocate(Parent); 14418 Elts.push_back(Region); 14419 Visit(*I); 14420 } 14421 14422 // Forget that the initializers are sequenced. 14423 Region = Parent; 14424 for (unsigned I = 0; I < Elts.size(); ++I) 14425 Tree.merge(Elts[I]); 14426 } 14427 14428 void VisitInitListExpr(const InitListExpr *ILE) { 14429 if (!SemaRef.getLangOpts().CPlusPlus11) 14430 return VisitExpr(ILE); 14431 14432 // In C++11, list initializations are sequenced. 14433 SmallVector<SequenceTree::Seq, 32> Elts; 14434 SequenceTree::Seq Parent = Region; 14435 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14436 const Expr *E = ILE->getInit(I); 14437 if (!E) 14438 continue; 14439 Region = Tree.allocate(Parent); 14440 Elts.push_back(Region); 14441 Visit(E); 14442 } 14443 14444 // Forget that the initializers are sequenced. 14445 Region = Parent; 14446 for (unsigned I = 0; I < Elts.size(); ++I) 14447 Tree.merge(Elts[I]); 14448 } 14449 }; 14450 14451 } // namespace 14452 14453 void Sema::CheckUnsequencedOperations(const Expr *E) { 14454 SmallVector<const Expr *, 8> WorkList; 14455 WorkList.push_back(E); 14456 while (!WorkList.empty()) { 14457 const Expr *Item = WorkList.pop_back_val(); 14458 SequenceChecker(*this, Item, WorkList); 14459 } 14460 } 14461 14462 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14463 bool IsConstexpr) { 14464 llvm::SaveAndRestore<bool> ConstantContext( 14465 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14466 CheckImplicitConversions(E, CheckLoc); 14467 if (!E->isInstantiationDependent()) 14468 CheckUnsequencedOperations(E); 14469 if (!IsConstexpr && !E->isValueDependent()) 14470 CheckForIntOverflow(E); 14471 DiagnoseMisalignedMembers(); 14472 } 14473 14474 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14475 FieldDecl *BitField, 14476 Expr *Init) { 14477 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14478 } 14479 14480 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14481 SourceLocation Loc) { 14482 if (!PType->isVariablyModifiedType()) 14483 return; 14484 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14485 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14486 return; 14487 } 14488 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14489 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14490 return; 14491 } 14492 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14493 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14494 return; 14495 } 14496 14497 const ArrayType *AT = S.Context.getAsArrayType(PType); 14498 if (!AT) 14499 return; 14500 14501 if (AT->getSizeModifier() != ArrayType::Star) { 14502 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14503 return; 14504 } 14505 14506 S.Diag(Loc, diag::err_array_star_in_function_definition); 14507 } 14508 14509 /// CheckParmsForFunctionDef - Check that the parameters of the given 14510 /// function are appropriate for the definition of a function. This 14511 /// takes care of any checks that cannot be performed on the 14512 /// declaration itself, e.g., that the types of each of the function 14513 /// parameters are complete. 14514 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14515 bool CheckParameterNames) { 14516 bool HasInvalidParm = false; 14517 for (ParmVarDecl *Param : Parameters) { 14518 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14519 // function declarator that is part of a function definition of 14520 // that function shall not have incomplete type. 14521 // 14522 // This is also C++ [dcl.fct]p6. 14523 if (!Param->isInvalidDecl() && 14524 RequireCompleteType(Param->getLocation(), Param->getType(), 14525 diag::err_typecheck_decl_incomplete_type)) { 14526 Param->setInvalidDecl(); 14527 HasInvalidParm = true; 14528 } 14529 14530 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14531 // declaration of each parameter shall include an identifier. 14532 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14533 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14534 // Diagnose this as an extension in C17 and earlier. 14535 if (!getLangOpts().C2x) 14536 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14537 } 14538 14539 // C99 6.7.5.3p12: 14540 // If the function declarator is not part of a definition of that 14541 // function, parameters may have incomplete type and may use the [*] 14542 // notation in their sequences of declarator specifiers to specify 14543 // variable length array types. 14544 QualType PType = Param->getOriginalType(); 14545 // FIXME: This diagnostic should point the '[*]' if source-location 14546 // information is added for it. 14547 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14548 14549 // If the parameter is a c++ class type and it has to be destructed in the 14550 // callee function, declare the destructor so that it can be called by the 14551 // callee function. Do not perform any direct access check on the dtor here. 14552 if (!Param->isInvalidDecl()) { 14553 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14554 if (!ClassDecl->isInvalidDecl() && 14555 !ClassDecl->hasIrrelevantDestructor() && 14556 !ClassDecl->isDependentContext() && 14557 ClassDecl->isParamDestroyedInCallee()) { 14558 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14559 MarkFunctionReferenced(Param->getLocation(), Destructor); 14560 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14561 } 14562 } 14563 } 14564 14565 // Parameters with the pass_object_size attribute only need to be marked 14566 // constant at function definitions. Because we lack information about 14567 // whether we're on a declaration or definition when we're instantiating the 14568 // attribute, we need to check for constness here. 14569 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14570 if (!Param->getType().isConstQualified()) 14571 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14572 << Attr->getSpelling() << 1; 14573 14574 // Check for parameter names shadowing fields from the class. 14575 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14576 // The owning context for the parameter should be the function, but we 14577 // want to see if this function's declaration context is a record. 14578 DeclContext *DC = Param->getDeclContext(); 14579 if (DC && DC->isFunctionOrMethod()) { 14580 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14581 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14582 RD, /*DeclIsField*/ false); 14583 } 14584 } 14585 } 14586 14587 return HasInvalidParm; 14588 } 14589 14590 Optional<std::pair<CharUnits, CharUnits>> 14591 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14592 14593 /// Compute the alignment and offset of the base class object given the 14594 /// derived-to-base cast expression and the alignment and offset of the derived 14595 /// class object. 14596 static std::pair<CharUnits, CharUnits> 14597 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14598 CharUnits BaseAlignment, CharUnits Offset, 14599 ASTContext &Ctx) { 14600 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14601 ++PathI) { 14602 const CXXBaseSpecifier *Base = *PathI; 14603 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14604 if (Base->isVirtual()) { 14605 // The complete object may have a lower alignment than the non-virtual 14606 // alignment of the base, in which case the base may be misaligned. Choose 14607 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14608 // conservative lower bound of the complete object alignment. 14609 CharUnits NonVirtualAlignment = 14610 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14611 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14612 Offset = CharUnits::Zero(); 14613 } else { 14614 const ASTRecordLayout &RL = 14615 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14616 Offset += RL.getBaseClassOffset(BaseDecl); 14617 } 14618 DerivedType = Base->getType(); 14619 } 14620 14621 return std::make_pair(BaseAlignment, Offset); 14622 } 14623 14624 /// Compute the alignment and offset of a binary additive operator. 14625 static Optional<std::pair<CharUnits, CharUnits>> 14626 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14627 bool IsSub, ASTContext &Ctx) { 14628 QualType PointeeType = PtrE->getType()->getPointeeType(); 14629 14630 if (!PointeeType->isConstantSizeType()) 14631 return llvm::None; 14632 14633 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14634 14635 if (!P) 14636 return llvm::None; 14637 14638 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14639 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14640 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14641 if (IsSub) 14642 Offset = -Offset; 14643 return std::make_pair(P->first, P->second + Offset); 14644 } 14645 14646 // If the integer expression isn't a constant expression, compute the lower 14647 // bound of the alignment using the alignment and offset of the pointer 14648 // expression and the element size. 14649 return std::make_pair( 14650 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14651 CharUnits::Zero()); 14652 } 14653 14654 /// This helper function takes an lvalue expression and returns the alignment of 14655 /// a VarDecl and a constant offset from the VarDecl. 14656 Optional<std::pair<CharUnits, CharUnits>> 14657 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14658 E = E->IgnoreParens(); 14659 switch (E->getStmtClass()) { 14660 default: 14661 break; 14662 case Stmt::CStyleCastExprClass: 14663 case Stmt::CXXStaticCastExprClass: 14664 case Stmt::ImplicitCastExprClass: { 14665 auto *CE = cast<CastExpr>(E); 14666 const Expr *From = CE->getSubExpr(); 14667 switch (CE->getCastKind()) { 14668 default: 14669 break; 14670 case CK_NoOp: 14671 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14672 case CK_UncheckedDerivedToBase: 14673 case CK_DerivedToBase: { 14674 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14675 if (!P) 14676 break; 14677 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14678 P->second, Ctx); 14679 } 14680 } 14681 break; 14682 } 14683 case Stmt::ArraySubscriptExprClass: { 14684 auto *ASE = cast<ArraySubscriptExpr>(E); 14685 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14686 false, Ctx); 14687 } 14688 case Stmt::DeclRefExprClass: { 14689 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14690 // FIXME: If VD is captured by copy or is an escaping __block variable, 14691 // use the alignment of VD's type. 14692 if (!VD->getType()->isReferenceType()) 14693 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14694 if (VD->hasInit()) 14695 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14696 } 14697 break; 14698 } 14699 case Stmt::MemberExprClass: { 14700 auto *ME = cast<MemberExpr>(E); 14701 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14702 if (!FD || FD->getType()->isReferenceType() || 14703 FD->getParent()->isInvalidDecl()) 14704 break; 14705 Optional<std::pair<CharUnits, CharUnits>> P; 14706 if (ME->isArrow()) 14707 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14708 else 14709 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14710 if (!P) 14711 break; 14712 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14713 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14714 return std::make_pair(P->first, 14715 P->second + CharUnits::fromQuantity(Offset)); 14716 } 14717 case Stmt::UnaryOperatorClass: { 14718 auto *UO = cast<UnaryOperator>(E); 14719 switch (UO->getOpcode()) { 14720 default: 14721 break; 14722 case UO_Deref: 14723 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14724 } 14725 break; 14726 } 14727 case Stmt::BinaryOperatorClass: { 14728 auto *BO = cast<BinaryOperator>(E); 14729 auto Opcode = BO->getOpcode(); 14730 switch (Opcode) { 14731 default: 14732 break; 14733 case BO_Comma: 14734 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14735 } 14736 break; 14737 } 14738 } 14739 return llvm::None; 14740 } 14741 14742 /// This helper function takes a pointer expression and returns the alignment of 14743 /// a VarDecl and a constant offset from the VarDecl. 14744 Optional<std::pair<CharUnits, CharUnits>> 14745 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14746 E = E->IgnoreParens(); 14747 switch (E->getStmtClass()) { 14748 default: 14749 break; 14750 case Stmt::CStyleCastExprClass: 14751 case Stmt::CXXStaticCastExprClass: 14752 case Stmt::ImplicitCastExprClass: { 14753 auto *CE = cast<CastExpr>(E); 14754 const Expr *From = CE->getSubExpr(); 14755 switch (CE->getCastKind()) { 14756 default: 14757 break; 14758 case CK_NoOp: 14759 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14760 case CK_ArrayToPointerDecay: 14761 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14762 case CK_UncheckedDerivedToBase: 14763 case CK_DerivedToBase: { 14764 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14765 if (!P) 14766 break; 14767 return getDerivedToBaseAlignmentAndOffset( 14768 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14769 } 14770 } 14771 break; 14772 } 14773 case Stmt::CXXThisExprClass: { 14774 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14775 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14776 return std::make_pair(Alignment, CharUnits::Zero()); 14777 } 14778 case Stmt::UnaryOperatorClass: { 14779 auto *UO = cast<UnaryOperator>(E); 14780 if (UO->getOpcode() == UO_AddrOf) 14781 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14782 break; 14783 } 14784 case Stmt::BinaryOperatorClass: { 14785 auto *BO = cast<BinaryOperator>(E); 14786 auto Opcode = BO->getOpcode(); 14787 switch (Opcode) { 14788 default: 14789 break; 14790 case BO_Add: 14791 case BO_Sub: { 14792 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14793 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14794 std::swap(LHS, RHS); 14795 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14796 Ctx); 14797 } 14798 case BO_Comma: 14799 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14800 } 14801 break; 14802 } 14803 } 14804 return llvm::None; 14805 } 14806 14807 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14808 // See if we can compute the alignment of a VarDecl and an offset from it. 14809 Optional<std::pair<CharUnits, CharUnits>> P = 14810 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14811 14812 if (P) 14813 return P->first.alignmentAtOffset(P->second); 14814 14815 // If that failed, return the type's alignment. 14816 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14817 } 14818 14819 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14820 /// pointer cast increases the alignment requirements. 14821 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14822 // This is actually a lot of work to potentially be doing on every 14823 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14824 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14825 return; 14826 14827 // Ignore dependent types. 14828 if (T->isDependentType() || Op->getType()->isDependentType()) 14829 return; 14830 14831 // Require that the destination be a pointer type. 14832 const PointerType *DestPtr = T->getAs<PointerType>(); 14833 if (!DestPtr) return; 14834 14835 // If the destination has alignment 1, we're done. 14836 QualType DestPointee = DestPtr->getPointeeType(); 14837 if (DestPointee->isIncompleteType()) return; 14838 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14839 if (DestAlign.isOne()) return; 14840 14841 // Require that the source be a pointer type. 14842 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14843 if (!SrcPtr) return; 14844 QualType SrcPointee = SrcPtr->getPointeeType(); 14845 14846 // Explicitly allow casts from cv void*. We already implicitly 14847 // allowed casts to cv void*, since they have alignment 1. 14848 // Also allow casts involving incomplete types, which implicitly 14849 // includes 'void'. 14850 if (SrcPointee->isIncompleteType()) return; 14851 14852 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14853 14854 if (SrcAlign >= DestAlign) return; 14855 14856 Diag(TRange.getBegin(), diag::warn_cast_align) 14857 << Op->getType() << T 14858 << static_cast<unsigned>(SrcAlign.getQuantity()) 14859 << static_cast<unsigned>(DestAlign.getQuantity()) 14860 << TRange << Op->getSourceRange(); 14861 } 14862 14863 /// Check whether this array fits the idiom of a size-one tail padded 14864 /// array member of a struct. 14865 /// 14866 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14867 /// commonly used to emulate flexible arrays in C89 code. 14868 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14869 const NamedDecl *ND) { 14870 if (Size != 1 || !ND) return false; 14871 14872 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14873 if (!FD) return false; 14874 14875 // Don't consider sizes resulting from macro expansions or template argument 14876 // substitution to form C89 tail-padded arrays. 14877 14878 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14879 while (TInfo) { 14880 TypeLoc TL = TInfo->getTypeLoc(); 14881 // Look through typedefs. 14882 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14883 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14884 TInfo = TDL->getTypeSourceInfo(); 14885 continue; 14886 } 14887 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14888 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14889 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14890 return false; 14891 } 14892 break; 14893 } 14894 14895 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14896 if (!RD) return false; 14897 if (RD->isUnion()) return false; 14898 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14899 if (!CRD->isStandardLayout()) return false; 14900 } 14901 14902 // See if this is the last field decl in the record. 14903 const Decl *D = FD; 14904 while ((D = D->getNextDeclInContext())) 14905 if (isa<FieldDecl>(D)) 14906 return false; 14907 return true; 14908 } 14909 14910 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14911 const ArraySubscriptExpr *ASE, 14912 bool AllowOnePastEnd, bool IndexNegated) { 14913 // Already diagnosed by the constant evaluator. 14914 if (isConstantEvaluated()) 14915 return; 14916 14917 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14918 if (IndexExpr->isValueDependent()) 14919 return; 14920 14921 const Type *EffectiveType = 14922 BaseExpr->getType()->getPointeeOrArrayElementType(); 14923 BaseExpr = BaseExpr->IgnoreParenCasts(); 14924 const ConstantArrayType *ArrayTy = 14925 Context.getAsConstantArrayType(BaseExpr->getType()); 14926 14927 const Type *BaseType = 14928 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 14929 bool IsUnboundedArray = (BaseType == nullptr); 14930 if (EffectiveType->isDependentType() || 14931 (!IsUnboundedArray && BaseType->isDependentType())) 14932 return; 14933 14934 Expr::EvalResult Result; 14935 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14936 return; 14937 14938 llvm::APSInt index = Result.Val.getInt(); 14939 if (IndexNegated) { 14940 index.setIsUnsigned(false); 14941 index = -index; 14942 } 14943 14944 const NamedDecl *ND = nullptr; 14945 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14946 ND = DRE->getDecl(); 14947 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14948 ND = ME->getMemberDecl(); 14949 14950 if (IsUnboundedArray) { 14951 if (index.isUnsigned() || !index.isNegative()) { 14952 const auto &ASTC = getASTContext(); 14953 unsigned AddrBits = 14954 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 14955 EffectiveType->getCanonicalTypeInternal())); 14956 if (index.getBitWidth() < AddrBits) 14957 index = index.zext(AddrBits); 14958 Optional<CharUnits> ElemCharUnits = 14959 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 14960 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 14961 // pointer) bounds-checking isn't meaningful. 14962 if (!ElemCharUnits) 14963 return; 14964 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 14965 // If index has more active bits than address space, we already know 14966 // we have a bounds violation to warn about. Otherwise, compute 14967 // address of (index + 1)th element, and warn about bounds violation 14968 // only if that address exceeds address space. 14969 if (index.getActiveBits() <= AddrBits) { 14970 bool Overflow; 14971 llvm::APInt Product(index); 14972 Product += 1; 14973 Product = Product.umul_ov(ElemBytes, Overflow); 14974 if (!Overflow && Product.getActiveBits() <= AddrBits) 14975 return; 14976 } 14977 14978 // Need to compute max possible elements in address space, since that 14979 // is included in diag message. 14980 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 14981 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 14982 MaxElems += 1; 14983 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 14984 MaxElems = MaxElems.udiv(ElemBytes); 14985 14986 unsigned DiagID = 14987 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 14988 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 14989 14990 // Diag message shows element size in bits and in "bytes" (platform- 14991 // dependent CharUnits) 14992 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14993 PDiag(DiagID) 14994 << toString(index, 10, true) << AddrBits 14995 << (unsigned)ASTC.toBits(*ElemCharUnits) 14996 << toString(ElemBytes, 10, false) 14997 << toString(MaxElems, 10, false) 14998 << (unsigned)MaxElems.getLimitedValue(~0U) 14999 << IndexExpr->getSourceRange()); 15000 15001 if (!ND) { 15002 // Try harder to find a NamedDecl to point at in the note. 15003 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15004 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15005 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15006 ND = DRE->getDecl(); 15007 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15008 ND = ME->getMemberDecl(); 15009 } 15010 15011 if (ND) 15012 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15013 PDiag(diag::note_array_declared_here) << ND); 15014 } 15015 return; 15016 } 15017 15018 if (index.isUnsigned() || !index.isNegative()) { 15019 // It is possible that the type of the base expression after 15020 // IgnoreParenCasts is incomplete, even though the type of the base 15021 // expression before IgnoreParenCasts is complete (see PR39746 for an 15022 // example). In this case we have no information about whether the array 15023 // access exceeds the array bounds. However we can still diagnose an array 15024 // access which precedes the array bounds. 15025 if (BaseType->isIncompleteType()) 15026 return; 15027 15028 llvm::APInt size = ArrayTy->getSize(); 15029 if (!size.isStrictlyPositive()) 15030 return; 15031 15032 if (BaseType != EffectiveType) { 15033 // Make sure we're comparing apples to apples when comparing index to size 15034 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15035 uint64_t array_typesize = Context.getTypeSize(BaseType); 15036 // Handle ptrarith_typesize being zero, such as when casting to void* 15037 if (!ptrarith_typesize) ptrarith_typesize = 1; 15038 if (ptrarith_typesize != array_typesize) { 15039 // There's a cast to a different size type involved 15040 uint64_t ratio = array_typesize / ptrarith_typesize; 15041 // TODO: Be smarter about handling cases where array_typesize is not a 15042 // multiple of ptrarith_typesize 15043 if (ptrarith_typesize * ratio == array_typesize) 15044 size *= llvm::APInt(size.getBitWidth(), ratio); 15045 } 15046 } 15047 15048 if (size.getBitWidth() > index.getBitWidth()) 15049 index = index.zext(size.getBitWidth()); 15050 else if (size.getBitWidth() < index.getBitWidth()) 15051 size = size.zext(index.getBitWidth()); 15052 15053 // For array subscripting the index must be less than size, but for pointer 15054 // arithmetic also allow the index (offset) to be equal to size since 15055 // computing the next address after the end of the array is legal and 15056 // commonly done e.g. in C++ iterators and range-based for loops. 15057 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15058 return; 15059 15060 // Also don't warn for arrays of size 1 which are members of some 15061 // structure. These are often used to approximate flexible arrays in C89 15062 // code. 15063 if (IsTailPaddedMemberArray(*this, size, ND)) 15064 return; 15065 15066 // Suppress the warning if the subscript expression (as identified by the 15067 // ']' location) and the index expression are both from macro expansions 15068 // within a system header. 15069 if (ASE) { 15070 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15071 ASE->getRBracketLoc()); 15072 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15073 SourceLocation IndexLoc = 15074 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15075 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15076 return; 15077 } 15078 } 15079 15080 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15081 : diag::warn_ptr_arith_exceeds_bounds; 15082 15083 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15084 PDiag(DiagID) << toString(index, 10, true) 15085 << toString(size, 10, true) 15086 << (unsigned)size.getLimitedValue(~0U) 15087 << IndexExpr->getSourceRange()); 15088 } else { 15089 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15090 if (!ASE) { 15091 DiagID = diag::warn_ptr_arith_precedes_bounds; 15092 if (index.isNegative()) index = -index; 15093 } 15094 15095 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15096 PDiag(DiagID) << toString(index, 10, true) 15097 << IndexExpr->getSourceRange()); 15098 } 15099 15100 if (!ND) { 15101 // Try harder to find a NamedDecl to point at in the note. 15102 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15103 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15104 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15105 ND = DRE->getDecl(); 15106 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15107 ND = ME->getMemberDecl(); 15108 } 15109 15110 if (ND) 15111 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15112 PDiag(diag::note_array_declared_here) << ND); 15113 } 15114 15115 void Sema::CheckArrayAccess(const Expr *expr) { 15116 int AllowOnePastEnd = 0; 15117 while (expr) { 15118 expr = expr->IgnoreParenImpCasts(); 15119 switch (expr->getStmtClass()) { 15120 case Stmt::ArraySubscriptExprClass: { 15121 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15122 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15123 AllowOnePastEnd > 0); 15124 expr = ASE->getBase(); 15125 break; 15126 } 15127 case Stmt::MemberExprClass: { 15128 expr = cast<MemberExpr>(expr)->getBase(); 15129 break; 15130 } 15131 case Stmt::OMPArraySectionExprClass: { 15132 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15133 if (ASE->getLowerBound()) 15134 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15135 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15136 return; 15137 } 15138 case Stmt::UnaryOperatorClass: { 15139 // Only unwrap the * and & unary operators 15140 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15141 expr = UO->getSubExpr(); 15142 switch (UO->getOpcode()) { 15143 case UO_AddrOf: 15144 AllowOnePastEnd++; 15145 break; 15146 case UO_Deref: 15147 AllowOnePastEnd--; 15148 break; 15149 default: 15150 return; 15151 } 15152 break; 15153 } 15154 case Stmt::ConditionalOperatorClass: { 15155 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15156 if (const Expr *lhs = cond->getLHS()) 15157 CheckArrayAccess(lhs); 15158 if (const Expr *rhs = cond->getRHS()) 15159 CheckArrayAccess(rhs); 15160 return; 15161 } 15162 case Stmt::CXXOperatorCallExprClass: { 15163 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15164 for (const auto *Arg : OCE->arguments()) 15165 CheckArrayAccess(Arg); 15166 return; 15167 } 15168 default: 15169 return; 15170 } 15171 } 15172 } 15173 15174 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15175 15176 namespace { 15177 15178 struct RetainCycleOwner { 15179 VarDecl *Variable = nullptr; 15180 SourceRange Range; 15181 SourceLocation Loc; 15182 bool Indirect = false; 15183 15184 RetainCycleOwner() = default; 15185 15186 void setLocsFrom(Expr *e) { 15187 Loc = e->getExprLoc(); 15188 Range = e->getSourceRange(); 15189 } 15190 }; 15191 15192 } // namespace 15193 15194 /// Consider whether capturing the given variable can possibly lead to 15195 /// a retain cycle. 15196 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15197 // In ARC, it's captured strongly iff the variable has __strong 15198 // lifetime. In MRR, it's captured strongly if the variable is 15199 // __block and has an appropriate type. 15200 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15201 return false; 15202 15203 owner.Variable = var; 15204 if (ref) 15205 owner.setLocsFrom(ref); 15206 return true; 15207 } 15208 15209 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15210 while (true) { 15211 e = e->IgnoreParens(); 15212 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15213 switch (cast->getCastKind()) { 15214 case CK_BitCast: 15215 case CK_LValueBitCast: 15216 case CK_LValueToRValue: 15217 case CK_ARCReclaimReturnedObject: 15218 e = cast->getSubExpr(); 15219 continue; 15220 15221 default: 15222 return false; 15223 } 15224 } 15225 15226 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15227 ObjCIvarDecl *ivar = ref->getDecl(); 15228 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15229 return false; 15230 15231 // Try to find a retain cycle in the base. 15232 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15233 return false; 15234 15235 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15236 owner.Indirect = true; 15237 return true; 15238 } 15239 15240 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15241 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15242 if (!var) return false; 15243 return considerVariable(var, ref, owner); 15244 } 15245 15246 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15247 if (member->isArrow()) return false; 15248 15249 // Don't count this as an indirect ownership. 15250 e = member->getBase(); 15251 continue; 15252 } 15253 15254 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15255 // Only pay attention to pseudo-objects on property references. 15256 ObjCPropertyRefExpr *pre 15257 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15258 ->IgnoreParens()); 15259 if (!pre) return false; 15260 if (pre->isImplicitProperty()) return false; 15261 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15262 if (!property->isRetaining() && 15263 !(property->getPropertyIvarDecl() && 15264 property->getPropertyIvarDecl()->getType() 15265 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15266 return false; 15267 15268 owner.Indirect = true; 15269 if (pre->isSuperReceiver()) { 15270 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15271 if (!owner.Variable) 15272 return false; 15273 owner.Loc = pre->getLocation(); 15274 owner.Range = pre->getSourceRange(); 15275 return true; 15276 } 15277 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15278 ->getSourceExpr()); 15279 continue; 15280 } 15281 15282 // Array ivars? 15283 15284 return false; 15285 } 15286 } 15287 15288 namespace { 15289 15290 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15291 ASTContext &Context; 15292 VarDecl *Variable; 15293 Expr *Capturer = nullptr; 15294 bool VarWillBeReased = false; 15295 15296 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15297 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15298 Context(Context), Variable(variable) {} 15299 15300 void VisitDeclRefExpr(DeclRefExpr *ref) { 15301 if (ref->getDecl() == Variable && !Capturer) 15302 Capturer = ref; 15303 } 15304 15305 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15306 if (Capturer) return; 15307 Visit(ref->getBase()); 15308 if (Capturer && ref->isFreeIvar()) 15309 Capturer = ref; 15310 } 15311 15312 void VisitBlockExpr(BlockExpr *block) { 15313 // Look inside nested blocks 15314 if (block->getBlockDecl()->capturesVariable(Variable)) 15315 Visit(block->getBlockDecl()->getBody()); 15316 } 15317 15318 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15319 if (Capturer) return; 15320 if (OVE->getSourceExpr()) 15321 Visit(OVE->getSourceExpr()); 15322 } 15323 15324 void VisitBinaryOperator(BinaryOperator *BinOp) { 15325 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15326 return; 15327 Expr *LHS = BinOp->getLHS(); 15328 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15329 if (DRE->getDecl() != Variable) 15330 return; 15331 if (Expr *RHS = BinOp->getRHS()) { 15332 RHS = RHS->IgnoreParenCasts(); 15333 Optional<llvm::APSInt> Value; 15334 VarWillBeReased = 15335 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15336 *Value == 0); 15337 } 15338 } 15339 } 15340 }; 15341 15342 } // namespace 15343 15344 /// Check whether the given argument is a block which captures a 15345 /// variable. 15346 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15347 assert(owner.Variable && owner.Loc.isValid()); 15348 15349 e = e->IgnoreParenCasts(); 15350 15351 // Look through [^{...} copy] and Block_copy(^{...}). 15352 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15353 Selector Cmd = ME->getSelector(); 15354 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15355 e = ME->getInstanceReceiver(); 15356 if (!e) 15357 return nullptr; 15358 e = e->IgnoreParenCasts(); 15359 } 15360 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15361 if (CE->getNumArgs() == 1) { 15362 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15363 if (Fn) { 15364 const IdentifierInfo *FnI = Fn->getIdentifier(); 15365 if (FnI && FnI->isStr("_Block_copy")) { 15366 e = CE->getArg(0)->IgnoreParenCasts(); 15367 } 15368 } 15369 } 15370 } 15371 15372 BlockExpr *block = dyn_cast<BlockExpr>(e); 15373 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15374 return nullptr; 15375 15376 FindCaptureVisitor visitor(S.Context, owner.Variable); 15377 visitor.Visit(block->getBlockDecl()->getBody()); 15378 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15379 } 15380 15381 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15382 RetainCycleOwner &owner) { 15383 assert(capturer); 15384 assert(owner.Variable && owner.Loc.isValid()); 15385 15386 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15387 << owner.Variable << capturer->getSourceRange(); 15388 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15389 << owner.Indirect << owner.Range; 15390 } 15391 15392 /// Check for a keyword selector that starts with the word 'add' or 15393 /// 'set'. 15394 static bool isSetterLikeSelector(Selector sel) { 15395 if (sel.isUnarySelector()) return false; 15396 15397 StringRef str = sel.getNameForSlot(0); 15398 while (!str.empty() && str.front() == '_') str = str.substr(1); 15399 if (str.startswith("set")) 15400 str = str.substr(3); 15401 else if (str.startswith("add")) { 15402 // Specially allow 'addOperationWithBlock:'. 15403 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15404 return false; 15405 str = str.substr(3); 15406 } 15407 else 15408 return false; 15409 15410 if (str.empty()) return true; 15411 return !isLowercase(str.front()); 15412 } 15413 15414 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15415 ObjCMessageExpr *Message) { 15416 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15417 Message->getReceiverInterface(), 15418 NSAPI::ClassId_NSMutableArray); 15419 if (!IsMutableArray) { 15420 return None; 15421 } 15422 15423 Selector Sel = Message->getSelector(); 15424 15425 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15426 S.NSAPIObj->getNSArrayMethodKind(Sel); 15427 if (!MKOpt) { 15428 return None; 15429 } 15430 15431 NSAPI::NSArrayMethodKind MK = *MKOpt; 15432 15433 switch (MK) { 15434 case NSAPI::NSMutableArr_addObject: 15435 case NSAPI::NSMutableArr_insertObjectAtIndex: 15436 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15437 return 0; 15438 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15439 return 1; 15440 15441 default: 15442 return None; 15443 } 15444 15445 return None; 15446 } 15447 15448 static 15449 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15450 ObjCMessageExpr *Message) { 15451 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15452 Message->getReceiverInterface(), 15453 NSAPI::ClassId_NSMutableDictionary); 15454 if (!IsMutableDictionary) { 15455 return None; 15456 } 15457 15458 Selector Sel = Message->getSelector(); 15459 15460 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15461 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15462 if (!MKOpt) { 15463 return None; 15464 } 15465 15466 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15467 15468 switch (MK) { 15469 case NSAPI::NSMutableDict_setObjectForKey: 15470 case NSAPI::NSMutableDict_setValueForKey: 15471 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15472 return 0; 15473 15474 default: 15475 return None; 15476 } 15477 15478 return None; 15479 } 15480 15481 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15482 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15483 Message->getReceiverInterface(), 15484 NSAPI::ClassId_NSMutableSet); 15485 15486 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15487 Message->getReceiverInterface(), 15488 NSAPI::ClassId_NSMutableOrderedSet); 15489 if (!IsMutableSet && !IsMutableOrderedSet) { 15490 return None; 15491 } 15492 15493 Selector Sel = Message->getSelector(); 15494 15495 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15496 if (!MKOpt) { 15497 return None; 15498 } 15499 15500 NSAPI::NSSetMethodKind MK = *MKOpt; 15501 15502 switch (MK) { 15503 case NSAPI::NSMutableSet_addObject: 15504 case NSAPI::NSOrderedSet_setObjectAtIndex: 15505 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15506 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15507 return 0; 15508 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15509 return 1; 15510 } 15511 15512 return None; 15513 } 15514 15515 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15516 if (!Message->isInstanceMessage()) { 15517 return; 15518 } 15519 15520 Optional<int> ArgOpt; 15521 15522 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15523 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15524 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15525 return; 15526 } 15527 15528 int ArgIndex = *ArgOpt; 15529 15530 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15531 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15532 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15533 } 15534 15535 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15536 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15537 if (ArgRE->isObjCSelfExpr()) { 15538 Diag(Message->getSourceRange().getBegin(), 15539 diag::warn_objc_circular_container) 15540 << ArgRE->getDecl() << StringRef("'super'"); 15541 } 15542 } 15543 } else { 15544 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15545 15546 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15547 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15548 } 15549 15550 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15551 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15552 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15553 ValueDecl *Decl = ReceiverRE->getDecl(); 15554 Diag(Message->getSourceRange().getBegin(), 15555 diag::warn_objc_circular_container) 15556 << Decl << Decl; 15557 if (!ArgRE->isObjCSelfExpr()) { 15558 Diag(Decl->getLocation(), 15559 diag::note_objc_circular_container_declared_here) 15560 << Decl; 15561 } 15562 } 15563 } 15564 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15565 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15566 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15567 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15568 Diag(Message->getSourceRange().getBegin(), 15569 diag::warn_objc_circular_container) 15570 << Decl << Decl; 15571 Diag(Decl->getLocation(), 15572 diag::note_objc_circular_container_declared_here) 15573 << Decl; 15574 } 15575 } 15576 } 15577 } 15578 } 15579 15580 /// Check a message send to see if it's likely to cause a retain cycle. 15581 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15582 // Only check instance methods whose selector looks like a setter. 15583 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15584 return; 15585 15586 // Try to find a variable that the receiver is strongly owned by. 15587 RetainCycleOwner owner; 15588 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15589 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15590 return; 15591 } else { 15592 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15593 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15594 owner.Loc = msg->getSuperLoc(); 15595 owner.Range = msg->getSuperLoc(); 15596 } 15597 15598 // Check whether the receiver is captured by any of the arguments. 15599 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15600 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15601 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15602 // noescape blocks should not be retained by the method. 15603 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15604 continue; 15605 return diagnoseRetainCycle(*this, capturer, owner); 15606 } 15607 } 15608 } 15609 15610 /// Check a property assign to see if it's likely to cause a retain cycle. 15611 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15612 RetainCycleOwner owner; 15613 if (!findRetainCycleOwner(*this, receiver, owner)) 15614 return; 15615 15616 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15617 diagnoseRetainCycle(*this, capturer, owner); 15618 } 15619 15620 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15621 RetainCycleOwner Owner; 15622 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15623 return; 15624 15625 // Because we don't have an expression for the variable, we have to set the 15626 // location explicitly here. 15627 Owner.Loc = Var->getLocation(); 15628 Owner.Range = Var->getSourceRange(); 15629 15630 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15631 diagnoseRetainCycle(*this, Capturer, Owner); 15632 } 15633 15634 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15635 Expr *RHS, bool isProperty) { 15636 // Check if RHS is an Objective-C object literal, which also can get 15637 // immediately zapped in a weak reference. Note that we explicitly 15638 // allow ObjCStringLiterals, since those are designed to never really die. 15639 RHS = RHS->IgnoreParenImpCasts(); 15640 15641 // This enum needs to match with the 'select' in 15642 // warn_objc_arc_literal_assign (off-by-1). 15643 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15644 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15645 return false; 15646 15647 S.Diag(Loc, diag::warn_arc_literal_assign) 15648 << (unsigned) Kind 15649 << (isProperty ? 0 : 1) 15650 << RHS->getSourceRange(); 15651 15652 return true; 15653 } 15654 15655 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15656 Qualifiers::ObjCLifetime LT, 15657 Expr *RHS, bool isProperty) { 15658 // Strip off any implicit cast added to get to the one ARC-specific. 15659 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15660 if (cast->getCastKind() == CK_ARCConsumeObject) { 15661 S.Diag(Loc, diag::warn_arc_retained_assign) 15662 << (LT == Qualifiers::OCL_ExplicitNone) 15663 << (isProperty ? 0 : 1) 15664 << RHS->getSourceRange(); 15665 return true; 15666 } 15667 RHS = cast->getSubExpr(); 15668 } 15669 15670 if (LT == Qualifiers::OCL_Weak && 15671 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15672 return true; 15673 15674 return false; 15675 } 15676 15677 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15678 QualType LHS, Expr *RHS) { 15679 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15680 15681 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15682 return false; 15683 15684 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15685 return true; 15686 15687 return false; 15688 } 15689 15690 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15691 Expr *LHS, Expr *RHS) { 15692 QualType LHSType; 15693 // PropertyRef on LHS type need be directly obtained from 15694 // its declaration as it has a PseudoType. 15695 ObjCPropertyRefExpr *PRE 15696 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15697 if (PRE && !PRE->isImplicitProperty()) { 15698 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15699 if (PD) 15700 LHSType = PD->getType(); 15701 } 15702 15703 if (LHSType.isNull()) 15704 LHSType = LHS->getType(); 15705 15706 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15707 15708 if (LT == Qualifiers::OCL_Weak) { 15709 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15710 getCurFunction()->markSafeWeakUse(LHS); 15711 } 15712 15713 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15714 return; 15715 15716 // FIXME. Check for other life times. 15717 if (LT != Qualifiers::OCL_None) 15718 return; 15719 15720 if (PRE) { 15721 if (PRE->isImplicitProperty()) 15722 return; 15723 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15724 if (!PD) 15725 return; 15726 15727 unsigned Attributes = PD->getPropertyAttributes(); 15728 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15729 // when 'assign' attribute was not explicitly specified 15730 // by user, ignore it and rely on property type itself 15731 // for lifetime info. 15732 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15733 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15734 LHSType->isObjCRetainableType()) 15735 return; 15736 15737 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15738 if (cast->getCastKind() == CK_ARCConsumeObject) { 15739 Diag(Loc, diag::warn_arc_retained_property_assign) 15740 << RHS->getSourceRange(); 15741 return; 15742 } 15743 RHS = cast->getSubExpr(); 15744 } 15745 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15746 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15747 return; 15748 } 15749 } 15750 } 15751 15752 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15753 15754 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15755 SourceLocation StmtLoc, 15756 const NullStmt *Body) { 15757 // Do not warn if the body is a macro that expands to nothing, e.g: 15758 // 15759 // #define CALL(x) 15760 // if (condition) 15761 // CALL(0); 15762 if (Body->hasLeadingEmptyMacro()) 15763 return false; 15764 15765 // Get line numbers of statement and body. 15766 bool StmtLineInvalid; 15767 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15768 &StmtLineInvalid); 15769 if (StmtLineInvalid) 15770 return false; 15771 15772 bool BodyLineInvalid; 15773 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15774 &BodyLineInvalid); 15775 if (BodyLineInvalid) 15776 return false; 15777 15778 // Warn if null statement and body are on the same line. 15779 if (StmtLine != BodyLine) 15780 return false; 15781 15782 return true; 15783 } 15784 15785 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15786 const Stmt *Body, 15787 unsigned DiagID) { 15788 // Since this is a syntactic check, don't emit diagnostic for template 15789 // instantiations, this just adds noise. 15790 if (CurrentInstantiationScope) 15791 return; 15792 15793 // The body should be a null statement. 15794 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15795 if (!NBody) 15796 return; 15797 15798 // Do the usual checks. 15799 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15800 return; 15801 15802 Diag(NBody->getSemiLoc(), DiagID); 15803 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15804 } 15805 15806 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15807 const Stmt *PossibleBody) { 15808 assert(!CurrentInstantiationScope); // Ensured by caller 15809 15810 SourceLocation StmtLoc; 15811 const Stmt *Body; 15812 unsigned DiagID; 15813 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15814 StmtLoc = FS->getRParenLoc(); 15815 Body = FS->getBody(); 15816 DiagID = diag::warn_empty_for_body; 15817 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15818 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15819 Body = WS->getBody(); 15820 DiagID = diag::warn_empty_while_body; 15821 } else 15822 return; // Neither `for' nor `while'. 15823 15824 // The body should be a null statement. 15825 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15826 if (!NBody) 15827 return; 15828 15829 // Skip expensive checks if diagnostic is disabled. 15830 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15831 return; 15832 15833 // Do the usual checks. 15834 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15835 return; 15836 15837 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15838 // noise level low, emit diagnostics only if for/while is followed by a 15839 // CompoundStmt, e.g.: 15840 // for (int i = 0; i < n; i++); 15841 // { 15842 // a(i); 15843 // } 15844 // or if for/while is followed by a statement with more indentation 15845 // than for/while itself: 15846 // for (int i = 0; i < n; i++); 15847 // a(i); 15848 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15849 if (!ProbableTypo) { 15850 bool BodyColInvalid; 15851 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15852 PossibleBody->getBeginLoc(), &BodyColInvalid); 15853 if (BodyColInvalid) 15854 return; 15855 15856 bool StmtColInvalid; 15857 unsigned StmtCol = 15858 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15859 if (StmtColInvalid) 15860 return; 15861 15862 if (BodyCol > StmtCol) 15863 ProbableTypo = true; 15864 } 15865 15866 if (ProbableTypo) { 15867 Diag(NBody->getSemiLoc(), DiagID); 15868 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15869 } 15870 } 15871 15872 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15873 15874 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15875 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15876 SourceLocation OpLoc) { 15877 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15878 return; 15879 15880 if (inTemplateInstantiation()) 15881 return; 15882 15883 // Strip parens and casts away. 15884 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15885 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15886 15887 // Check for a call expression 15888 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15889 if (!CE || CE->getNumArgs() != 1) 15890 return; 15891 15892 // Check for a call to std::move 15893 if (!CE->isCallToStdMove()) 15894 return; 15895 15896 // Get argument from std::move 15897 RHSExpr = CE->getArg(0); 15898 15899 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15900 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15901 15902 // Two DeclRefExpr's, check that the decls are the same. 15903 if (LHSDeclRef && RHSDeclRef) { 15904 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15905 return; 15906 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15907 RHSDeclRef->getDecl()->getCanonicalDecl()) 15908 return; 15909 15910 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15911 << LHSExpr->getSourceRange() 15912 << RHSExpr->getSourceRange(); 15913 return; 15914 } 15915 15916 // Member variables require a different approach to check for self moves. 15917 // MemberExpr's are the same if every nested MemberExpr refers to the same 15918 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15919 // the base Expr's are CXXThisExpr's. 15920 const Expr *LHSBase = LHSExpr; 15921 const Expr *RHSBase = RHSExpr; 15922 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15923 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15924 if (!LHSME || !RHSME) 15925 return; 15926 15927 while (LHSME && RHSME) { 15928 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15929 RHSME->getMemberDecl()->getCanonicalDecl()) 15930 return; 15931 15932 LHSBase = LHSME->getBase(); 15933 RHSBase = RHSME->getBase(); 15934 LHSME = dyn_cast<MemberExpr>(LHSBase); 15935 RHSME = dyn_cast<MemberExpr>(RHSBase); 15936 } 15937 15938 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15939 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15940 if (LHSDeclRef && RHSDeclRef) { 15941 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15942 return; 15943 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15944 RHSDeclRef->getDecl()->getCanonicalDecl()) 15945 return; 15946 15947 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15948 << LHSExpr->getSourceRange() 15949 << RHSExpr->getSourceRange(); 15950 return; 15951 } 15952 15953 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15954 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15955 << LHSExpr->getSourceRange() 15956 << RHSExpr->getSourceRange(); 15957 } 15958 15959 //===--- Layout compatibility ----------------------------------------------// 15960 15961 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15962 15963 /// Check if two enumeration types are layout-compatible. 15964 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15965 // C++11 [dcl.enum] p8: 15966 // Two enumeration types are layout-compatible if they have the same 15967 // underlying type. 15968 return ED1->isComplete() && ED2->isComplete() && 15969 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15970 } 15971 15972 /// Check if two fields are layout-compatible. 15973 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15974 FieldDecl *Field2) { 15975 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15976 return false; 15977 15978 if (Field1->isBitField() != Field2->isBitField()) 15979 return false; 15980 15981 if (Field1->isBitField()) { 15982 // Make sure that the bit-fields are the same length. 15983 unsigned Bits1 = Field1->getBitWidthValue(C); 15984 unsigned Bits2 = Field2->getBitWidthValue(C); 15985 15986 if (Bits1 != Bits2) 15987 return false; 15988 } 15989 15990 return true; 15991 } 15992 15993 /// Check if two standard-layout structs are layout-compatible. 15994 /// (C++11 [class.mem] p17) 15995 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15996 RecordDecl *RD2) { 15997 // If both records are C++ classes, check that base classes match. 15998 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15999 // If one of records is a CXXRecordDecl we are in C++ mode, 16000 // thus the other one is a CXXRecordDecl, too. 16001 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16002 // Check number of base classes. 16003 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16004 return false; 16005 16006 // Check the base classes. 16007 for (CXXRecordDecl::base_class_const_iterator 16008 Base1 = D1CXX->bases_begin(), 16009 BaseEnd1 = D1CXX->bases_end(), 16010 Base2 = D2CXX->bases_begin(); 16011 Base1 != BaseEnd1; 16012 ++Base1, ++Base2) { 16013 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16014 return false; 16015 } 16016 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16017 // If only RD2 is a C++ class, it should have zero base classes. 16018 if (D2CXX->getNumBases() > 0) 16019 return false; 16020 } 16021 16022 // Check the fields. 16023 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16024 Field2End = RD2->field_end(), 16025 Field1 = RD1->field_begin(), 16026 Field1End = RD1->field_end(); 16027 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16028 if (!isLayoutCompatible(C, *Field1, *Field2)) 16029 return false; 16030 } 16031 if (Field1 != Field1End || Field2 != Field2End) 16032 return false; 16033 16034 return true; 16035 } 16036 16037 /// Check if two standard-layout unions are layout-compatible. 16038 /// (C++11 [class.mem] p18) 16039 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16040 RecordDecl *RD2) { 16041 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16042 for (auto *Field2 : RD2->fields()) 16043 UnmatchedFields.insert(Field2); 16044 16045 for (auto *Field1 : RD1->fields()) { 16046 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16047 I = UnmatchedFields.begin(), 16048 E = UnmatchedFields.end(); 16049 16050 for ( ; I != E; ++I) { 16051 if (isLayoutCompatible(C, Field1, *I)) { 16052 bool Result = UnmatchedFields.erase(*I); 16053 (void) Result; 16054 assert(Result); 16055 break; 16056 } 16057 } 16058 if (I == E) 16059 return false; 16060 } 16061 16062 return UnmatchedFields.empty(); 16063 } 16064 16065 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16066 RecordDecl *RD2) { 16067 if (RD1->isUnion() != RD2->isUnion()) 16068 return false; 16069 16070 if (RD1->isUnion()) 16071 return isLayoutCompatibleUnion(C, RD1, RD2); 16072 else 16073 return isLayoutCompatibleStruct(C, RD1, RD2); 16074 } 16075 16076 /// Check if two types are layout-compatible in C++11 sense. 16077 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16078 if (T1.isNull() || T2.isNull()) 16079 return false; 16080 16081 // C++11 [basic.types] p11: 16082 // If two types T1 and T2 are the same type, then T1 and T2 are 16083 // layout-compatible types. 16084 if (C.hasSameType(T1, T2)) 16085 return true; 16086 16087 T1 = T1.getCanonicalType().getUnqualifiedType(); 16088 T2 = T2.getCanonicalType().getUnqualifiedType(); 16089 16090 const Type::TypeClass TC1 = T1->getTypeClass(); 16091 const Type::TypeClass TC2 = T2->getTypeClass(); 16092 16093 if (TC1 != TC2) 16094 return false; 16095 16096 if (TC1 == Type::Enum) { 16097 return isLayoutCompatible(C, 16098 cast<EnumType>(T1)->getDecl(), 16099 cast<EnumType>(T2)->getDecl()); 16100 } else if (TC1 == Type::Record) { 16101 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16102 return false; 16103 16104 return isLayoutCompatible(C, 16105 cast<RecordType>(T1)->getDecl(), 16106 cast<RecordType>(T2)->getDecl()); 16107 } 16108 16109 return false; 16110 } 16111 16112 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16113 16114 /// Given a type tag expression find the type tag itself. 16115 /// 16116 /// \param TypeExpr Type tag expression, as it appears in user's code. 16117 /// 16118 /// \param VD Declaration of an identifier that appears in a type tag. 16119 /// 16120 /// \param MagicValue Type tag magic value. 16121 /// 16122 /// \param isConstantEvaluated whether the evalaution should be performed in 16123 16124 /// constant context. 16125 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16126 const ValueDecl **VD, uint64_t *MagicValue, 16127 bool isConstantEvaluated) { 16128 while(true) { 16129 if (!TypeExpr) 16130 return false; 16131 16132 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16133 16134 switch (TypeExpr->getStmtClass()) { 16135 case Stmt::UnaryOperatorClass: { 16136 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16137 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16138 TypeExpr = UO->getSubExpr(); 16139 continue; 16140 } 16141 return false; 16142 } 16143 16144 case Stmt::DeclRefExprClass: { 16145 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16146 *VD = DRE->getDecl(); 16147 return true; 16148 } 16149 16150 case Stmt::IntegerLiteralClass: { 16151 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16152 llvm::APInt MagicValueAPInt = IL->getValue(); 16153 if (MagicValueAPInt.getActiveBits() <= 64) { 16154 *MagicValue = MagicValueAPInt.getZExtValue(); 16155 return true; 16156 } else 16157 return false; 16158 } 16159 16160 case Stmt::BinaryConditionalOperatorClass: 16161 case Stmt::ConditionalOperatorClass: { 16162 const AbstractConditionalOperator *ACO = 16163 cast<AbstractConditionalOperator>(TypeExpr); 16164 bool Result; 16165 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16166 isConstantEvaluated)) { 16167 if (Result) 16168 TypeExpr = ACO->getTrueExpr(); 16169 else 16170 TypeExpr = ACO->getFalseExpr(); 16171 continue; 16172 } 16173 return false; 16174 } 16175 16176 case Stmt::BinaryOperatorClass: { 16177 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16178 if (BO->getOpcode() == BO_Comma) { 16179 TypeExpr = BO->getRHS(); 16180 continue; 16181 } 16182 return false; 16183 } 16184 16185 default: 16186 return false; 16187 } 16188 } 16189 } 16190 16191 /// Retrieve the C type corresponding to type tag TypeExpr. 16192 /// 16193 /// \param TypeExpr Expression that specifies a type tag. 16194 /// 16195 /// \param MagicValues Registered magic values. 16196 /// 16197 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16198 /// kind. 16199 /// 16200 /// \param TypeInfo Information about the corresponding C type. 16201 /// 16202 /// \param isConstantEvaluated whether the evalaution should be performed in 16203 /// constant context. 16204 /// 16205 /// \returns true if the corresponding C type was found. 16206 static bool GetMatchingCType( 16207 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16208 const ASTContext &Ctx, 16209 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16210 *MagicValues, 16211 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16212 bool isConstantEvaluated) { 16213 FoundWrongKind = false; 16214 16215 // Variable declaration that has type_tag_for_datatype attribute. 16216 const ValueDecl *VD = nullptr; 16217 16218 uint64_t MagicValue; 16219 16220 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16221 return false; 16222 16223 if (VD) { 16224 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16225 if (I->getArgumentKind() != ArgumentKind) { 16226 FoundWrongKind = true; 16227 return false; 16228 } 16229 TypeInfo.Type = I->getMatchingCType(); 16230 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16231 TypeInfo.MustBeNull = I->getMustBeNull(); 16232 return true; 16233 } 16234 return false; 16235 } 16236 16237 if (!MagicValues) 16238 return false; 16239 16240 llvm::DenseMap<Sema::TypeTagMagicValue, 16241 Sema::TypeTagData>::const_iterator I = 16242 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16243 if (I == MagicValues->end()) 16244 return false; 16245 16246 TypeInfo = I->second; 16247 return true; 16248 } 16249 16250 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16251 uint64_t MagicValue, QualType Type, 16252 bool LayoutCompatible, 16253 bool MustBeNull) { 16254 if (!TypeTagForDatatypeMagicValues) 16255 TypeTagForDatatypeMagicValues.reset( 16256 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16257 16258 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16259 (*TypeTagForDatatypeMagicValues)[Magic] = 16260 TypeTagData(Type, LayoutCompatible, MustBeNull); 16261 } 16262 16263 static bool IsSameCharType(QualType T1, QualType T2) { 16264 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16265 if (!BT1) 16266 return false; 16267 16268 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16269 if (!BT2) 16270 return false; 16271 16272 BuiltinType::Kind T1Kind = BT1->getKind(); 16273 BuiltinType::Kind T2Kind = BT2->getKind(); 16274 16275 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16276 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16277 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16278 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16279 } 16280 16281 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16282 const ArrayRef<const Expr *> ExprArgs, 16283 SourceLocation CallSiteLoc) { 16284 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16285 bool IsPointerAttr = Attr->getIsPointer(); 16286 16287 // Retrieve the argument representing the 'type_tag'. 16288 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16289 if (TypeTagIdxAST >= ExprArgs.size()) { 16290 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16291 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16292 return; 16293 } 16294 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16295 bool FoundWrongKind; 16296 TypeTagData TypeInfo; 16297 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16298 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16299 TypeInfo, isConstantEvaluated())) { 16300 if (FoundWrongKind) 16301 Diag(TypeTagExpr->getExprLoc(), 16302 diag::warn_type_tag_for_datatype_wrong_kind) 16303 << TypeTagExpr->getSourceRange(); 16304 return; 16305 } 16306 16307 // Retrieve the argument representing the 'arg_idx'. 16308 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16309 if (ArgumentIdxAST >= ExprArgs.size()) { 16310 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16311 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16312 return; 16313 } 16314 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16315 if (IsPointerAttr) { 16316 // Skip implicit cast of pointer to `void *' (as a function argument). 16317 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16318 if (ICE->getType()->isVoidPointerType() && 16319 ICE->getCastKind() == CK_BitCast) 16320 ArgumentExpr = ICE->getSubExpr(); 16321 } 16322 QualType ArgumentType = ArgumentExpr->getType(); 16323 16324 // Passing a `void*' pointer shouldn't trigger a warning. 16325 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16326 return; 16327 16328 if (TypeInfo.MustBeNull) { 16329 // Type tag with matching void type requires a null pointer. 16330 if (!ArgumentExpr->isNullPointerConstant(Context, 16331 Expr::NPC_ValueDependentIsNotNull)) { 16332 Diag(ArgumentExpr->getExprLoc(), 16333 diag::warn_type_safety_null_pointer_required) 16334 << ArgumentKind->getName() 16335 << ArgumentExpr->getSourceRange() 16336 << TypeTagExpr->getSourceRange(); 16337 } 16338 return; 16339 } 16340 16341 QualType RequiredType = TypeInfo.Type; 16342 if (IsPointerAttr) 16343 RequiredType = Context.getPointerType(RequiredType); 16344 16345 bool mismatch = false; 16346 if (!TypeInfo.LayoutCompatible) { 16347 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16348 16349 // C++11 [basic.fundamental] p1: 16350 // Plain char, signed char, and unsigned char are three distinct types. 16351 // 16352 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16353 // char' depending on the current char signedness mode. 16354 if (mismatch) 16355 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16356 RequiredType->getPointeeType())) || 16357 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16358 mismatch = false; 16359 } else 16360 if (IsPointerAttr) 16361 mismatch = !isLayoutCompatible(Context, 16362 ArgumentType->getPointeeType(), 16363 RequiredType->getPointeeType()); 16364 else 16365 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16366 16367 if (mismatch) 16368 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16369 << ArgumentType << ArgumentKind 16370 << TypeInfo.LayoutCompatible << RequiredType 16371 << ArgumentExpr->getSourceRange() 16372 << TypeTagExpr->getSourceRange(); 16373 } 16374 16375 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16376 CharUnits Alignment) { 16377 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16378 } 16379 16380 void Sema::DiagnoseMisalignedMembers() { 16381 for (MisalignedMember &m : MisalignedMembers) { 16382 const NamedDecl *ND = m.RD; 16383 if (ND->getName().empty()) { 16384 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16385 ND = TD; 16386 } 16387 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16388 << m.MD << ND << m.E->getSourceRange(); 16389 } 16390 MisalignedMembers.clear(); 16391 } 16392 16393 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16394 E = E->IgnoreParens(); 16395 if (!T->isPointerType() && !T->isIntegerType()) 16396 return; 16397 if (isa<UnaryOperator>(E) && 16398 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16399 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16400 if (isa<MemberExpr>(Op)) { 16401 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16402 if (MA != MisalignedMembers.end() && 16403 (T->isIntegerType() || 16404 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16405 Context.getTypeAlignInChars( 16406 T->getPointeeType()) <= MA->Alignment)))) 16407 MisalignedMembers.erase(MA); 16408 } 16409 } 16410 } 16411 16412 void Sema::RefersToMemberWithReducedAlignment( 16413 Expr *E, 16414 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16415 Action) { 16416 const auto *ME = dyn_cast<MemberExpr>(E); 16417 if (!ME) 16418 return; 16419 16420 // No need to check expressions with an __unaligned-qualified type. 16421 if (E->getType().getQualifiers().hasUnaligned()) 16422 return; 16423 16424 // For a chain of MemberExpr like "a.b.c.d" this list 16425 // will keep FieldDecl's like [d, c, b]. 16426 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16427 const MemberExpr *TopME = nullptr; 16428 bool AnyIsPacked = false; 16429 do { 16430 QualType BaseType = ME->getBase()->getType(); 16431 if (BaseType->isDependentType()) 16432 return; 16433 if (ME->isArrow()) 16434 BaseType = BaseType->getPointeeType(); 16435 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16436 if (RD->isInvalidDecl()) 16437 return; 16438 16439 ValueDecl *MD = ME->getMemberDecl(); 16440 auto *FD = dyn_cast<FieldDecl>(MD); 16441 // We do not care about non-data members. 16442 if (!FD || FD->isInvalidDecl()) 16443 return; 16444 16445 AnyIsPacked = 16446 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16447 ReverseMemberChain.push_back(FD); 16448 16449 TopME = ME; 16450 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16451 } while (ME); 16452 assert(TopME && "We did not compute a topmost MemberExpr!"); 16453 16454 // Not the scope of this diagnostic. 16455 if (!AnyIsPacked) 16456 return; 16457 16458 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16459 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16460 // TODO: The innermost base of the member expression may be too complicated. 16461 // For now, just disregard these cases. This is left for future 16462 // improvement. 16463 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16464 return; 16465 16466 // Alignment expected by the whole expression. 16467 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16468 16469 // No need to do anything else with this case. 16470 if (ExpectedAlignment.isOne()) 16471 return; 16472 16473 // Synthesize offset of the whole access. 16474 CharUnits Offset; 16475 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16476 I++) { 16477 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16478 } 16479 16480 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16481 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16482 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16483 16484 // The base expression of the innermost MemberExpr may give 16485 // stronger guarantees than the class containing the member. 16486 if (DRE && !TopME->isArrow()) { 16487 const ValueDecl *VD = DRE->getDecl(); 16488 if (!VD->getType()->isReferenceType()) 16489 CompleteObjectAlignment = 16490 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16491 } 16492 16493 // Check if the synthesized offset fulfills the alignment. 16494 if (Offset % ExpectedAlignment != 0 || 16495 // It may fulfill the offset it but the effective alignment may still be 16496 // lower than the expected expression alignment. 16497 CompleteObjectAlignment < ExpectedAlignment) { 16498 // If this happens, we want to determine a sensible culprit of this. 16499 // Intuitively, watching the chain of member expressions from right to 16500 // left, we start with the required alignment (as required by the field 16501 // type) but some packed attribute in that chain has reduced the alignment. 16502 // It may happen that another packed structure increases it again. But if 16503 // we are here such increase has not been enough. So pointing the first 16504 // FieldDecl that either is packed or else its RecordDecl is, 16505 // seems reasonable. 16506 FieldDecl *FD = nullptr; 16507 CharUnits Alignment; 16508 for (FieldDecl *FDI : ReverseMemberChain) { 16509 if (FDI->hasAttr<PackedAttr>() || 16510 FDI->getParent()->hasAttr<PackedAttr>()) { 16511 FD = FDI; 16512 Alignment = std::min( 16513 Context.getTypeAlignInChars(FD->getType()), 16514 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16515 break; 16516 } 16517 } 16518 assert(FD && "We did not find a packed FieldDecl!"); 16519 Action(E, FD->getParent(), FD, Alignment); 16520 } 16521 } 16522 16523 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16524 using namespace std::placeholders; 16525 16526 RefersToMemberWithReducedAlignment( 16527 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16528 _2, _3, _4)); 16529 } 16530 16531 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 16532 // not a valid type, emit an error message and return true. Otherwise return 16533 // false. 16534 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 16535 QualType Ty) { 16536 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 16537 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 16538 << 1 << /* vector, integer or float ty*/ 0 << Ty; 16539 return true; 16540 } 16541 return false; 16542 } 16543 16544 bool Sema::SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall) { 16545 if (checkArgCount(*this, TheCall, 1)) 16546 return true; 16547 16548 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16549 SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc(); 16550 if (A.isInvalid()) 16551 return true; 16552 16553 TheCall->setArg(0, A.get()); 16554 QualType TyA = A.get()->getType(); 16555 if (checkMathBuiltinElementType(*this, ArgLoc, TyA)) 16556 return true; 16557 16558 QualType EltTy = TyA; 16559 if (auto *VecTy = EltTy->getAs<VectorType>()) 16560 EltTy = VecTy->getElementType(); 16561 if (EltTy->isUnsignedIntegerType()) 16562 return Diag(ArgLoc, diag::err_builtin_invalid_arg_type) 16563 << 1 << /*signed integer or float ty*/ 3 << TyA; 16564 16565 TheCall->setType(TyA); 16566 return false; 16567 } 16568 16569 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 16570 if (checkArgCount(*this, TheCall, 2)) 16571 return true; 16572 16573 ExprResult A = TheCall->getArg(0); 16574 ExprResult B = TheCall->getArg(1); 16575 // Do standard promotions between the two arguments, returning their common 16576 // type. 16577 QualType Res = 16578 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 16579 if (A.isInvalid() || B.isInvalid()) 16580 return true; 16581 16582 QualType TyA = A.get()->getType(); 16583 QualType TyB = B.get()->getType(); 16584 16585 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 16586 return Diag(A.get()->getBeginLoc(), 16587 diag::err_typecheck_call_different_arg_types) 16588 << TyA << TyB; 16589 16590 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16591 return true; 16592 16593 TheCall->setArg(0, A.get()); 16594 TheCall->setArg(1, B.get()); 16595 TheCall->setType(Res); 16596 return false; 16597 } 16598 16599 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16600 ExprResult CallResult) { 16601 if (checkArgCount(*this, TheCall, 1)) 16602 return ExprError(); 16603 16604 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16605 if (MatrixArg.isInvalid()) 16606 return MatrixArg; 16607 Expr *Matrix = MatrixArg.get(); 16608 16609 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16610 if (!MType) { 16611 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16612 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 16613 return ExprError(); 16614 } 16615 16616 // Create returned matrix type by swapping rows and columns of the argument 16617 // matrix type. 16618 QualType ResultType = Context.getConstantMatrixType( 16619 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16620 16621 // Change the return type to the type of the returned matrix. 16622 TheCall->setType(ResultType); 16623 16624 // Update call argument to use the possibly converted matrix argument. 16625 TheCall->setArg(0, Matrix); 16626 return CallResult; 16627 } 16628 16629 // Get and verify the matrix dimensions. 16630 static llvm::Optional<unsigned> 16631 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16632 SourceLocation ErrorPos; 16633 Optional<llvm::APSInt> Value = 16634 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16635 if (!Value) { 16636 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16637 << Name; 16638 return {}; 16639 } 16640 uint64_t Dim = Value->getZExtValue(); 16641 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16642 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16643 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16644 return {}; 16645 } 16646 return Dim; 16647 } 16648 16649 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16650 ExprResult CallResult) { 16651 if (!getLangOpts().MatrixTypes) { 16652 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16653 return ExprError(); 16654 } 16655 16656 if (checkArgCount(*this, TheCall, 4)) 16657 return ExprError(); 16658 16659 unsigned PtrArgIdx = 0; 16660 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16661 Expr *RowsExpr = TheCall->getArg(1); 16662 Expr *ColumnsExpr = TheCall->getArg(2); 16663 Expr *StrideExpr = TheCall->getArg(3); 16664 16665 bool ArgError = false; 16666 16667 // Check pointer argument. 16668 { 16669 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16670 if (PtrConv.isInvalid()) 16671 return PtrConv; 16672 PtrExpr = PtrConv.get(); 16673 TheCall->setArg(0, PtrExpr); 16674 if (PtrExpr->isTypeDependent()) { 16675 TheCall->setType(Context.DependentTy); 16676 return TheCall; 16677 } 16678 } 16679 16680 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16681 QualType ElementTy; 16682 if (!PtrTy) { 16683 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16684 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 16685 ArgError = true; 16686 } else { 16687 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16688 16689 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16690 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16691 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 16692 << PtrExpr->getType(); 16693 ArgError = true; 16694 } 16695 } 16696 16697 // Apply default Lvalue conversions and convert the expression to size_t. 16698 auto ApplyArgumentConversions = [this](Expr *E) { 16699 ExprResult Conv = DefaultLvalueConversion(E); 16700 if (Conv.isInvalid()) 16701 return Conv; 16702 16703 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16704 }; 16705 16706 // Apply conversion to row and column expressions. 16707 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16708 if (!RowsConv.isInvalid()) { 16709 RowsExpr = RowsConv.get(); 16710 TheCall->setArg(1, RowsExpr); 16711 } else 16712 RowsExpr = nullptr; 16713 16714 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16715 if (!ColumnsConv.isInvalid()) { 16716 ColumnsExpr = ColumnsConv.get(); 16717 TheCall->setArg(2, ColumnsExpr); 16718 } else 16719 ColumnsExpr = nullptr; 16720 16721 // If any any part of the result matrix type is still pending, just use 16722 // Context.DependentTy, until all parts are resolved. 16723 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16724 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16725 TheCall->setType(Context.DependentTy); 16726 return CallResult; 16727 } 16728 16729 // Check row and column dimensions. 16730 llvm::Optional<unsigned> MaybeRows; 16731 if (RowsExpr) 16732 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16733 16734 llvm::Optional<unsigned> MaybeColumns; 16735 if (ColumnsExpr) 16736 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16737 16738 // Check stride argument. 16739 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16740 if (StrideConv.isInvalid()) 16741 return ExprError(); 16742 StrideExpr = StrideConv.get(); 16743 TheCall->setArg(3, StrideExpr); 16744 16745 if (MaybeRows) { 16746 if (Optional<llvm::APSInt> Value = 16747 StrideExpr->getIntegerConstantExpr(Context)) { 16748 uint64_t Stride = Value->getZExtValue(); 16749 if (Stride < *MaybeRows) { 16750 Diag(StrideExpr->getBeginLoc(), 16751 diag::err_builtin_matrix_stride_too_small); 16752 ArgError = true; 16753 } 16754 } 16755 } 16756 16757 if (ArgError || !MaybeRows || !MaybeColumns) 16758 return ExprError(); 16759 16760 TheCall->setType( 16761 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16762 return CallResult; 16763 } 16764 16765 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16766 ExprResult CallResult) { 16767 if (checkArgCount(*this, TheCall, 3)) 16768 return ExprError(); 16769 16770 unsigned PtrArgIdx = 1; 16771 Expr *MatrixExpr = TheCall->getArg(0); 16772 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16773 Expr *StrideExpr = TheCall->getArg(2); 16774 16775 bool ArgError = false; 16776 16777 { 16778 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16779 if (MatrixConv.isInvalid()) 16780 return MatrixConv; 16781 MatrixExpr = MatrixConv.get(); 16782 TheCall->setArg(0, MatrixExpr); 16783 } 16784 if (MatrixExpr->isTypeDependent()) { 16785 TheCall->setType(Context.DependentTy); 16786 return TheCall; 16787 } 16788 16789 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16790 if (!MatrixTy) { 16791 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16792 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 16793 ArgError = true; 16794 } 16795 16796 { 16797 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16798 if (PtrConv.isInvalid()) 16799 return PtrConv; 16800 PtrExpr = PtrConv.get(); 16801 TheCall->setArg(1, PtrExpr); 16802 if (PtrExpr->isTypeDependent()) { 16803 TheCall->setType(Context.DependentTy); 16804 return TheCall; 16805 } 16806 } 16807 16808 // Check pointer argument. 16809 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16810 if (!PtrTy) { 16811 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16812 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 16813 ArgError = true; 16814 } else { 16815 QualType ElementTy = PtrTy->getPointeeType(); 16816 if (ElementTy.isConstQualified()) { 16817 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16818 ArgError = true; 16819 } 16820 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16821 if (MatrixTy && 16822 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16823 Diag(PtrExpr->getBeginLoc(), 16824 diag::err_builtin_matrix_pointer_arg_mismatch) 16825 << ElementTy << MatrixTy->getElementType(); 16826 ArgError = true; 16827 } 16828 } 16829 16830 // Apply default Lvalue conversions and convert the stride expression to 16831 // size_t. 16832 { 16833 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16834 if (StrideConv.isInvalid()) 16835 return StrideConv; 16836 16837 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16838 if (StrideConv.isInvalid()) 16839 return StrideConv; 16840 StrideExpr = StrideConv.get(); 16841 TheCall->setArg(2, StrideExpr); 16842 } 16843 16844 // Check stride argument. 16845 if (MatrixTy) { 16846 if (Optional<llvm::APSInt> Value = 16847 StrideExpr->getIntegerConstantExpr(Context)) { 16848 uint64_t Stride = Value->getZExtValue(); 16849 if (Stride < MatrixTy->getNumRows()) { 16850 Diag(StrideExpr->getBeginLoc(), 16851 diag::err_builtin_matrix_stride_too_small); 16852 ArgError = true; 16853 } 16854 } 16855 } 16856 16857 if (ArgError) 16858 return ExprError(); 16859 16860 return CallResult; 16861 } 16862 16863 /// \brief Enforce the bounds of a TCB 16864 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16865 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16866 /// and enforce_tcb_leaf attributes. 16867 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16868 const FunctionDecl *Callee) { 16869 const FunctionDecl *Caller = getCurFunctionDecl(); 16870 16871 // Calls to builtins are not enforced. 16872 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16873 Callee->getBuiltinID() != 0) 16874 return; 16875 16876 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16877 // all TCBs the callee is a part of. 16878 llvm::StringSet<> CalleeTCBs; 16879 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16880 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16881 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16882 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16883 16884 // Go through the TCBs the caller is a part of and emit warnings if Caller 16885 // is in a TCB that the Callee is not. 16886 for_each( 16887 Caller->specific_attrs<EnforceTCBAttr>(), 16888 [&](const auto *A) { 16889 StringRef CallerTCB = A->getTCBName(); 16890 if (CalleeTCBs.count(CallerTCB) == 0) { 16891 this->Diag(TheCall->getExprLoc(), 16892 diag::warn_tcb_enforcement_violation) << Callee 16893 << CallerTCB; 16894 } 16895 }); 16896 } 16897