1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 594 isConstantEvaluated()) 595 return; 596 597 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 598 if (!BuiltinID) 599 return; 600 601 const TargetInfo &TI = getASTContext().getTargetInfo(); 602 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 603 604 auto ComputeExplicitObjectSizeArgument = 605 [&](unsigned Index) -> Optional<llvm::APSInt> { 606 Expr::EvalResult Result; 607 Expr *SizeArg = TheCall->getArg(Index); 608 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 609 return llvm::None; 610 return Result.Val.getInt(); 611 }; 612 613 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 614 // If the parameter has a pass_object_size attribute, then we should use its 615 // (potentially) more strict checking mode. Otherwise, conservatively assume 616 // type 0. 617 int BOSType = 0; 618 if (const auto *POS = 619 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 620 BOSType = POS->getType(); 621 622 const Expr *ObjArg = TheCall->getArg(Index); 623 uint64_t Result; 624 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 625 return llvm::None; 626 627 // Get the object size in the target's size_t width. 628 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 629 }; 630 631 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 632 Expr *ObjArg = TheCall->getArg(Index); 633 uint64_t Result; 634 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 635 return llvm::None; 636 // Add 1 for null byte. 637 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 638 }; 639 640 Optional<llvm::APSInt> SourceSize; 641 Optional<llvm::APSInt> DestinationSize; 642 unsigned DiagID = 0; 643 bool IsChkVariant = false; 644 645 switch (BuiltinID) { 646 default: 647 return; 648 case Builtin::BI__builtin_strcpy: 649 case Builtin::BIstrcpy: { 650 DiagID = diag::warn_fortify_strlen_overflow; 651 SourceSize = ComputeStrLenArgument(1); 652 DestinationSize = ComputeSizeArgument(0); 653 break; 654 } 655 656 case Builtin::BI__builtin___strcpy_chk: { 657 DiagID = diag::warn_fortify_strlen_overflow; 658 SourceSize = ComputeStrLenArgument(1); 659 DestinationSize = ComputeExplicitObjectSizeArgument(2); 660 IsChkVariant = true; 661 break; 662 } 663 664 case Builtin::BIsprintf: 665 case Builtin::BI__builtin___sprintf_chk: { 666 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 667 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 668 669 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 670 671 if (!Format->isAscii() && !Format->isUTF8()) 672 return; 673 674 StringRef FormatStrRef = Format->getString(); 675 EstimateSizeFormatHandler H(FormatStrRef); 676 const char *FormatBytes = FormatStrRef.data(); 677 const ConstantArrayType *T = 678 Context.getAsConstantArrayType(Format->getType()); 679 assert(T && "String literal not of constant array type!"); 680 size_t TypeSize = T->getSize().getZExtValue(); 681 682 // In case there's a null byte somewhere. 683 size_t StrLen = 684 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 685 if (!analyze_format_string::ParsePrintfString( 686 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 687 Context.getTargetInfo(), false)) { 688 DiagID = diag::warn_fortify_source_format_overflow; 689 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 690 .extOrTrunc(SizeTypeWidth); 691 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 692 DestinationSize = ComputeExplicitObjectSizeArgument(2); 693 IsChkVariant = true; 694 } else { 695 DestinationSize = ComputeSizeArgument(0); 696 } 697 break; 698 } 699 } 700 return; 701 } 702 case Builtin::BI__builtin___memcpy_chk: 703 case Builtin::BI__builtin___memmove_chk: 704 case Builtin::BI__builtin___memset_chk: 705 case Builtin::BI__builtin___strlcat_chk: 706 case Builtin::BI__builtin___strlcpy_chk: 707 case Builtin::BI__builtin___strncat_chk: 708 case Builtin::BI__builtin___strncpy_chk: 709 case Builtin::BI__builtin___stpncpy_chk: 710 case Builtin::BI__builtin___memccpy_chk: 711 case Builtin::BI__builtin___mempcpy_chk: { 712 DiagID = diag::warn_builtin_chk_overflow; 713 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 714 DestinationSize = 715 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 716 IsChkVariant = true; 717 break; 718 } 719 720 case Builtin::BI__builtin___snprintf_chk: 721 case Builtin::BI__builtin___vsnprintf_chk: { 722 DiagID = diag::warn_builtin_chk_overflow; 723 SourceSize = ComputeExplicitObjectSizeArgument(1); 724 DestinationSize = ComputeExplicitObjectSizeArgument(3); 725 IsChkVariant = true; 726 break; 727 } 728 729 case Builtin::BIstrncat: 730 case Builtin::BI__builtin_strncat: 731 case Builtin::BIstrncpy: 732 case Builtin::BI__builtin_strncpy: 733 case Builtin::BIstpncpy: 734 case Builtin::BI__builtin_stpncpy: { 735 // Whether these functions overflow depends on the runtime strlen of the 736 // string, not just the buffer size, so emitting the "always overflow" 737 // diagnostic isn't quite right. We should still diagnose passing a buffer 738 // size larger than the destination buffer though; this is a runtime abort 739 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 740 DiagID = diag::warn_fortify_source_size_mismatch; 741 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 742 DestinationSize = ComputeSizeArgument(0); 743 break; 744 } 745 746 case Builtin::BImemcpy: 747 case Builtin::BI__builtin_memcpy: 748 case Builtin::BImemmove: 749 case Builtin::BI__builtin_memmove: 750 case Builtin::BImemset: 751 case Builtin::BI__builtin_memset: 752 case Builtin::BImempcpy: 753 case Builtin::BI__builtin_mempcpy: { 754 DiagID = diag::warn_fortify_source_overflow; 755 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 756 DestinationSize = ComputeSizeArgument(0); 757 break; 758 } 759 case Builtin::BIsnprintf: 760 case Builtin::BI__builtin_snprintf: 761 case Builtin::BIvsnprintf: 762 case Builtin::BI__builtin_vsnprintf: { 763 DiagID = diag::warn_fortify_source_size_mismatch; 764 SourceSize = ComputeExplicitObjectSizeArgument(1); 765 DestinationSize = ComputeSizeArgument(0); 766 break; 767 } 768 } 769 770 if (!SourceSize || !DestinationSize || 771 SourceSize.getValue().ule(DestinationSize.getValue())) 772 return; 773 774 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 775 // Skim off the details of whichever builtin was called to produce a better 776 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 777 if (IsChkVariant) { 778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 779 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 780 } else if (FunctionName.startswith("__builtin_")) { 781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 782 } 783 784 SmallString<16> DestinationStr; 785 SmallString<16> SourceStr; 786 DestinationSize->toString(DestinationStr, /*Radix=*/10); 787 SourceSize->toString(SourceStr, /*Radix=*/10); 788 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 789 PDiag(DiagID) 790 << FunctionName << DestinationStr << SourceStr); 791 } 792 793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 794 Scope::ScopeFlags NeededScopeFlags, 795 unsigned DiagID) { 796 // Scopes aren't available during instantiation. Fortunately, builtin 797 // functions cannot be template args so they cannot be formed through template 798 // instantiation. Therefore checking once during the parse is sufficient. 799 if (SemaRef.inTemplateInstantiation()) 800 return false; 801 802 Scope *S = SemaRef.getCurScope(); 803 while (S && !S->isSEHExceptScope()) 804 S = S->getParent(); 805 if (!S || !(S->getFlags() & NeededScopeFlags)) { 806 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 807 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 808 << DRE->getDecl()->getIdentifier(); 809 return true; 810 } 811 812 return false; 813 } 814 815 static inline bool isBlockPointer(Expr *Arg) { 816 return Arg->getType()->isBlockPointerType(); 817 } 818 819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 820 /// void*, which is a requirement of device side enqueue. 821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 822 const BlockPointerType *BPT = 823 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 824 ArrayRef<QualType> Params = 825 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 826 unsigned ArgCounter = 0; 827 bool IllegalParams = false; 828 // Iterate through the block parameters until either one is found that is not 829 // a local void*, or the block is valid. 830 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 831 I != E; ++I, ++ArgCounter) { 832 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 833 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 834 LangAS::opencl_local) { 835 // Get the location of the error. If a block literal has been passed 836 // (BlockExpr) then we can point straight to the offending argument, 837 // else we just point to the variable reference. 838 SourceLocation ErrorLoc; 839 if (isa<BlockExpr>(BlockArg)) { 840 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 841 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 842 } else if (isa<DeclRefExpr>(BlockArg)) { 843 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 844 } 845 S.Diag(ErrorLoc, 846 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 847 IllegalParams = true; 848 } 849 } 850 851 return IllegalParams; 852 } 853 854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 855 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 857 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 858 return true; 859 } 860 return false; 861 } 862 863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 864 if (checkArgCount(S, TheCall, 2)) 865 return true; 866 867 if (checkOpenCLSubgroupExt(S, TheCall)) 868 return true; 869 870 // First argument is an ndrange_t type. 871 Expr *NDRangeArg = TheCall->getArg(0); 872 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 873 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 874 << TheCall->getDirectCallee() << "'ndrange_t'"; 875 return true; 876 } 877 878 Expr *BlockArg = TheCall->getArg(1); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 888 /// get_kernel_work_group_size 889 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 891 if (checkArgCount(S, TheCall, 1)) 892 return true; 893 894 Expr *BlockArg = TheCall->getArg(0); 895 if (!isBlockPointer(BlockArg)) { 896 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 897 << TheCall->getDirectCallee() << "block"; 898 return true; 899 } 900 return checkOpenCLBlockArgs(S, BlockArg); 901 } 902 903 /// Diagnose integer type and any valid implicit conversion to it. 904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 905 const QualType &IntType); 906 907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 908 unsigned Start, unsigned End) { 909 bool IllegalParams = false; 910 for (unsigned I = Start; I <= End; ++I) 911 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 912 S.Context.getSizeType()); 913 return IllegalParams; 914 } 915 916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 917 /// 'local void*' parameter of passed block. 918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 919 Expr *BlockArg, 920 unsigned NumNonVarArgs) { 921 const BlockPointerType *BPT = 922 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 923 unsigned NumBlockParams = 924 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 925 unsigned TotalNumArgs = TheCall->getNumArgs(); 926 927 // For each argument passed to the block, a corresponding uint needs to 928 // be passed to describe the size of the local memory. 929 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 930 S.Diag(TheCall->getBeginLoc(), 931 diag::err_opencl_enqueue_kernel_local_size_args); 932 return true; 933 } 934 935 // Check that the sizes of the local memory are specified by integers. 936 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 937 TotalNumArgs - 1); 938 } 939 940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 941 /// overload formats specified in Table 6.13.17.1. 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// void (^block)(void)) 946 /// int enqueue_kernel(queue_t queue, 947 /// kernel_enqueue_flags_t flags, 948 /// const ndrange_t ndrange, 949 /// uint num_events_in_wait_list, 950 /// clk_event_t *event_wait_list, 951 /// clk_event_t *event_ret, 952 /// void (^block)(void)) 953 /// int enqueue_kernel(queue_t queue, 954 /// kernel_enqueue_flags_t flags, 955 /// const ndrange_t ndrange, 956 /// void (^block)(local void*, ...), 957 /// uint size0, ...) 958 /// int enqueue_kernel(queue_t queue, 959 /// kernel_enqueue_flags_t flags, 960 /// const ndrange_t ndrange, 961 /// uint num_events_in_wait_list, 962 /// clk_event_t *event_wait_list, 963 /// clk_event_t *event_ret, 964 /// void (^block)(local void*, ...), 965 /// uint size0, ...) 966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 967 unsigned NumArgs = TheCall->getNumArgs(); 968 969 if (NumArgs < 4) { 970 S.Diag(TheCall->getBeginLoc(), 971 diag::err_typecheck_call_too_few_args_at_least) 972 << 0 << 4 << NumArgs; 973 return true; 974 } 975 976 Expr *Arg0 = TheCall->getArg(0); 977 Expr *Arg1 = TheCall->getArg(1); 978 Expr *Arg2 = TheCall->getArg(2); 979 Expr *Arg3 = TheCall->getArg(3); 980 981 // First argument always needs to be a queue_t type. 982 if (!Arg0->getType()->isQueueT()) { 983 S.Diag(TheCall->getArg(0)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 986 return true; 987 } 988 989 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 990 if (!Arg1->getType()->isIntegerType()) { 991 S.Diag(TheCall->getArg(1)->getBeginLoc(), 992 diag::err_opencl_builtin_expected_type) 993 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 994 return true; 995 } 996 997 // Third argument is always an ndrange_t type. 998 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 999 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1000 diag::err_opencl_builtin_expected_type) 1001 << TheCall->getDirectCallee() << "'ndrange_t'"; 1002 return true; 1003 } 1004 1005 // With four arguments, there is only one form that the function could be 1006 // called in: no events and no variable arguments. 1007 if (NumArgs == 4) { 1008 // check that the last argument is the right block type. 1009 if (!isBlockPointer(Arg3)) { 1010 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1011 << TheCall->getDirectCallee() << "block"; 1012 return true; 1013 } 1014 // we have a block type, check the prototype 1015 const BlockPointerType *BPT = 1016 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1017 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1018 S.Diag(Arg3->getBeginLoc(), 1019 diag::err_opencl_enqueue_kernel_blocks_no_args); 1020 return true; 1021 } 1022 return false; 1023 } 1024 // we can have block + varargs. 1025 if (isBlockPointer(Arg3)) 1026 return (checkOpenCLBlockArgs(S, Arg3) || 1027 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1028 // last two cases with either exactly 7 args or 7 args and varargs. 1029 if (NumArgs >= 7) { 1030 // check common block argument. 1031 Expr *Arg6 = TheCall->getArg(6); 1032 if (!isBlockPointer(Arg6)) { 1033 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1034 << TheCall->getDirectCallee() << "block"; 1035 return true; 1036 } 1037 if (checkOpenCLBlockArgs(S, Arg6)) 1038 return true; 1039 1040 // Forth argument has to be any integer type. 1041 if (!Arg3->getType()->isIntegerType()) { 1042 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1043 diag::err_opencl_builtin_expected_type) 1044 << TheCall->getDirectCallee() << "integer"; 1045 return true; 1046 } 1047 // check remaining common arguments. 1048 Expr *Arg4 = TheCall->getArg(4); 1049 Expr *Arg5 = TheCall->getArg(5); 1050 1051 // Fifth argument is always passed as a pointer to clk_event_t. 1052 if (!Arg4->isNullPointerConstant(S.Context, 1053 Expr::NPC_ValueDependentIsNotNull) && 1054 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1055 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1056 diag::err_opencl_builtin_expected_type) 1057 << TheCall->getDirectCallee() 1058 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1059 return true; 1060 } 1061 1062 // Sixth argument is always passed as a pointer to clk_event_t. 1063 if (!Arg5->isNullPointerConstant(S.Context, 1064 Expr::NPC_ValueDependentIsNotNull) && 1065 !(Arg5->getType()->isPointerType() && 1066 Arg5->getType()->getPointeeType()->isClkEventT())) { 1067 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1068 diag::err_opencl_builtin_expected_type) 1069 << TheCall->getDirectCallee() 1070 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1071 return true; 1072 } 1073 1074 if (NumArgs == 7) 1075 return false; 1076 1077 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1078 } 1079 1080 // None of the specific case has been detected, give generic error 1081 S.Diag(TheCall->getBeginLoc(), 1082 diag::err_opencl_enqueue_kernel_incorrect_args); 1083 return true; 1084 } 1085 1086 /// Returns OpenCL access qual. 1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1088 return D->getAttr<OpenCLAccessAttr>(); 1089 } 1090 1091 /// Returns true if pipe element type is different from the pointer. 1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1093 const Expr *Arg0 = Call->getArg(0); 1094 // First argument type should always be pipe. 1095 if (!Arg0->getType()->isPipeType()) { 1096 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1097 << Call->getDirectCallee() << Arg0->getSourceRange(); 1098 return true; 1099 } 1100 OpenCLAccessAttr *AccessQual = 1101 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1102 // Validates the access qualifier is compatible with the call. 1103 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1104 // read_only and write_only, and assumed to be read_only if no qualifier is 1105 // specified. 1106 switch (Call->getDirectCallee()->getBuiltinID()) { 1107 case Builtin::BIread_pipe: 1108 case Builtin::BIreserve_read_pipe: 1109 case Builtin::BIcommit_read_pipe: 1110 case Builtin::BIwork_group_reserve_read_pipe: 1111 case Builtin::BIsub_group_reserve_read_pipe: 1112 case Builtin::BIwork_group_commit_read_pipe: 1113 case Builtin::BIsub_group_commit_read_pipe: 1114 if (!(!AccessQual || AccessQual->isReadOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "read_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 case Builtin::BIwrite_pipe: 1122 case Builtin::BIreserve_write_pipe: 1123 case Builtin::BIcommit_write_pipe: 1124 case Builtin::BIwork_group_reserve_write_pipe: 1125 case Builtin::BIsub_group_reserve_write_pipe: 1126 case Builtin::BIwork_group_commit_write_pipe: 1127 case Builtin::BIsub_group_commit_write_pipe: 1128 if (!(AccessQual && AccessQual->isWriteOnly())) { 1129 S.Diag(Arg0->getBeginLoc(), 1130 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1131 << "write_only" << Arg0->getSourceRange(); 1132 return true; 1133 } 1134 break; 1135 default: 1136 break; 1137 } 1138 return false; 1139 } 1140 1141 /// Returns true if pipe element type is different from the pointer. 1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1143 const Expr *Arg0 = Call->getArg(0); 1144 const Expr *ArgIdx = Call->getArg(Idx); 1145 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1146 const QualType EltTy = PipeTy->getElementType(); 1147 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1148 // The Idx argument should be a pointer and the type of the pointer and 1149 // the type of pipe element should also be the same. 1150 if (!ArgTy || 1151 !S.Context.hasSameType( 1152 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1153 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1154 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1155 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 // Performs semantic analysis for the read/write_pipe call. 1162 // \param S Reference to the semantic analyzer. 1163 // \param Call A pointer to the builtin call. 1164 // \return True if a semantic error has been found, false otherwise. 1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1166 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1167 // functions have two forms. 1168 switch (Call->getNumArgs()) { 1169 case 2: 1170 if (checkOpenCLPipeArg(S, Call)) 1171 return true; 1172 // The call with 2 arguments should be 1173 // read/write_pipe(pipe T, T*). 1174 // Check packet type T. 1175 if (checkOpenCLPipePacketType(S, Call, 1)) 1176 return true; 1177 break; 1178 1179 case 4: { 1180 if (checkOpenCLPipeArg(S, Call)) 1181 return true; 1182 // The call with 4 arguments should be 1183 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1184 // Check reserve_id_t. 1185 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1186 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1187 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1188 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1189 return true; 1190 } 1191 1192 // Check the index. 1193 const Expr *Arg2 = Call->getArg(2); 1194 if (!Arg2->getType()->isIntegerType() && 1195 !Arg2->getType()->isUnsignedIntegerType()) { 1196 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1197 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1198 << Arg2->getType() << Arg2->getSourceRange(); 1199 return true; 1200 } 1201 1202 // Check packet type T. 1203 if (checkOpenCLPipePacketType(S, Call, 3)) 1204 return true; 1205 } break; 1206 default: 1207 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1208 << Call->getDirectCallee() << Call->getSourceRange(); 1209 return true; 1210 } 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on the {work_group_/sub_group_ 1216 // /_}reserve_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check the reserve size. 1228 if (!Call->getArg(1)->getType()->isIntegerType() && 1229 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1230 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1231 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1232 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1233 return true; 1234 } 1235 1236 // Since return type of reserve_read/write_pipe built-in function is 1237 // reserve_id_t, which is not defined in the builtin def file , we used int 1238 // as return type and need to override the return type of these functions. 1239 Call->setType(S.Context.OCLReserveIDTy); 1240 1241 return false; 1242 } 1243 1244 // Performs a semantic analysis on {work_group_/sub_group_ 1245 // /_}commit_{read/write}_pipe 1246 // \param S Reference to the semantic analyzer. 1247 // \param Call The call to the builtin function to be analyzed. 1248 // \return True if a semantic error was found, false otherwise. 1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1250 if (checkArgCount(S, Call, 2)) 1251 return true; 1252 1253 if (checkOpenCLPipeArg(S, Call)) 1254 return true; 1255 1256 // Check reserve_id_t. 1257 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1258 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1259 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1260 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1261 return true; 1262 } 1263 1264 return false; 1265 } 1266 1267 // Performs a semantic analysis on the call to built-in Pipe 1268 // Query Functions. 1269 // \param S Reference to the semantic analyzer. 1270 // \param Call The call to the builtin function to be analyzed. 1271 // \return True if a semantic error was found, false otherwise. 1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1273 if (checkArgCount(S, Call, 1)) 1274 return true; 1275 1276 if (!Call->getArg(0)->getType()->isPipeType()) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1278 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1279 return true; 1280 } 1281 1282 return false; 1283 } 1284 1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1286 // Performs semantic analysis for the to_global/local/private call. 1287 // \param S Reference to the semantic analyzer. 1288 // \param BuiltinID ID of the builtin function. 1289 // \param Call A pointer to the builtin call. 1290 // \return True if a semantic error has been found, false otherwise. 1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1292 CallExpr *Call) { 1293 if (checkArgCount(S, Call, 1)) 1294 return true; 1295 1296 auto RT = Call->getArg(0)->getType(); 1297 if (!RT->isPointerType() || RT->getPointeeType() 1298 .getAddressSpace() == LangAS::opencl_constant) { 1299 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1300 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1301 return true; 1302 } 1303 1304 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1305 S.Diag(Call->getArg(0)->getBeginLoc(), 1306 diag::warn_opencl_generic_address_space_arg) 1307 << Call->getDirectCallee()->getNameInfo().getAsString() 1308 << Call->getArg(0)->getSourceRange(); 1309 } 1310 1311 RT = RT->getPointeeType(); 1312 auto Qual = RT.getQualifiers(); 1313 switch (BuiltinID) { 1314 case Builtin::BIto_global: 1315 Qual.setAddressSpace(LangAS::opencl_global); 1316 break; 1317 case Builtin::BIto_local: 1318 Qual.setAddressSpace(LangAS::opencl_local); 1319 break; 1320 case Builtin::BIto_private: 1321 Qual.setAddressSpace(LangAS::opencl_private); 1322 break; 1323 default: 1324 llvm_unreachable("Invalid builtin function"); 1325 } 1326 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1327 RT.getUnqualifiedType(), Qual))); 1328 1329 return false; 1330 } 1331 1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1333 if (checkArgCount(S, TheCall, 1)) 1334 return ExprError(); 1335 1336 // Compute __builtin_launder's parameter type from the argument. 1337 // The parameter type is: 1338 // * The type of the argument if it's not an array or function type, 1339 // Otherwise, 1340 // * The decayed argument type. 1341 QualType ParamTy = [&]() { 1342 QualType ArgTy = TheCall->getArg(0)->getType(); 1343 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1344 return S.Context.getPointerType(Ty->getElementType()); 1345 if (ArgTy->isFunctionType()) { 1346 return S.Context.getPointerType(ArgTy); 1347 } 1348 return ArgTy; 1349 }(); 1350 1351 TheCall->setType(ParamTy); 1352 1353 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1354 if (!ParamTy->isPointerType()) 1355 return 0; 1356 if (ParamTy->isFunctionPointerType()) 1357 return 1; 1358 if (ParamTy->isVoidPointerType()) 1359 return 2; 1360 return llvm::Optional<unsigned>{}; 1361 }(); 1362 if (DiagSelect.hasValue()) { 1363 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1364 << DiagSelect.getValue() << TheCall->getSourceRange(); 1365 return ExprError(); 1366 } 1367 1368 // We either have an incomplete class type, or we have a class template 1369 // whose instantiation has not been forced. Example: 1370 // 1371 // template <class T> struct Foo { T value; }; 1372 // Foo<int> *p = nullptr; 1373 // auto *d = __builtin_launder(p); 1374 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1375 diag::err_incomplete_type)) 1376 return ExprError(); 1377 1378 assert(ParamTy->getPointeeType()->isObjectType() && 1379 "Unhandled non-object pointer case"); 1380 1381 InitializedEntity Entity = 1382 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1383 ExprResult Arg = 1384 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1385 if (Arg.isInvalid()) 1386 return ExprError(); 1387 TheCall->setArg(0, Arg.get()); 1388 1389 return TheCall; 1390 } 1391 1392 // Emit an error and return true if the current architecture is not in the list 1393 // of supported architectures. 1394 static bool 1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1396 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1397 llvm::Triple::ArchType CurArch = 1398 S.getASTContext().getTargetInfo().getTriple().getArch(); 1399 if (llvm::is_contained(SupportedArchs, CurArch)) 1400 return false; 1401 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1402 << TheCall->getSourceRange(); 1403 return true; 1404 } 1405 1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1407 SourceLocation CallSiteLoc); 1408 1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1410 CallExpr *TheCall) { 1411 switch (TI.getTriple().getArch()) { 1412 default: 1413 // Some builtins don't require additional checking, so just consider these 1414 // acceptable. 1415 return false; 1416 case llvm::Triple::arm: 1417 case llvm::Triple::armeb: 1418 case llvm::Triple::thumb: 1419 case llvm::Triple::thumbeb: 1420 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::aarch64: 1422 case llvm::Triple::aarch64_32: 1423 case llvm::Triple::aarch64_be: 1424 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::bpfeb: 1426 case llvm::Triple::bpfel: 1427 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1428 case llvm::Triple::hexagon: 1429 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1430 case llvm::Triple::mips: 1431 case llvm::Triple::mipsel: 1432 case llvm::Triple::mips64: 1433 case llvm::Triple::mips64el: 1434 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 case llvm::Triple::systemz: 1436 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1437 case llvm::Triple::x86: 1438 case llvm::Triple::x86_64: 1439 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1440 case llvm::Triple::ppc: 1441 case llvm::Triple::ppcle: 1442 case llvm::Triple::ppc64: 1443 case llvm::Triple::ppc64le: 1444 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1445 case llvm::Triple::amdgcn: 1446 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1447 case llvm::Triple::riscv32: 1448 case llvm::Triple::riscv64: 1449 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1450 } 1451 } 1452 1453 ExprResult 1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1455 CallExpr *TheCall) { 1456 ExprResult TheCallResult(TheCall); 1457 1458 // Find out if any arguments are required to be integer constant expressions. 1459 unsigned ICEArguments = 0; 1460 ASTContext::GetBuiltinTypeError Error; 1461 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1462 if (Error != ASTContext::GE_None) 1463 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1464 1465 // If any arguments are required to be ICE's, check and diagnose. 1466 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1467 // Skip arguments not required to be ICE's. 1468 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1469 1470 llvm::APSInt Result; 1471 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1472 return true; 1473 ICEArguments &= ~(1 << ArgNo); 1474 } 1475 1476 switch (BuiltinID) { 1477 case Builtin::BI__builtin___CFStringMakeConstantString: 1478 assert(TheCall->getNumArgs() == 1 && 1479 "Wrong # arguments to builtin CFStringMakeConstantString"); 1480 if (CheckObjCString(TheCall->getArg(0))) 1481 return ExprError(); 1482 break; 1483 case Builtin::BI__builtin_ms_va_start: 1484 case Builtin::BI__builtin_stdarg_start: 1485 case Builtin::BI__builtin_va_start: 1486 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1487 return ExprError(); 1488 break; 1489 case Builtin::BI__va_start: { 1490 switch (Context.getTargetInfo().getTriple().getArch()) { 1491 case llvm::Triple::aarch64: 1492 case llvm::Triple::arm: 1493 case llvm::Triple::thumb: 1494 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1495 return ExprError(); 1496 break; 1497 default: 1498 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1499 return ExprError(); 1500 break; 1501 } 1502 break; 1503 } 1504 1505 // The acquire, release, and no fence variants are ARM and AArch64 only. 1506 case Builtin::BI_interlockedbittestandset_acq: 1507 case Builtin::BI_interlockedbittestandset_rel: 1508 case Builtin::BI_interlockedbittestandset_nf: 1509 case Builtin::BI_interlockedbittestandreset_acq: 1510 case Builtin::BI_interlockedbittestandreset_rel: 1511 case Builtin::BI_interlockedbittestandreset_nf: 1512 if (CheckBuiltinTargetSupport( 1513 *this, BuiltinID, TheCall, 1514 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1515 return ExprError(); 1516 break; 1517 1518 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1519 case Builtin::BI_bittest64: 1520 case Builtin::BI_bittestandcomplement64: 1521 case Builtin::BI_bittestandreset64: 1522 case Builtin::BI_bittestandset64: 1523 case Builtin::BI_interlockedbittestandreset64: 1524 case Builtin::BI_interlockedbittestandset64: 1525 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1526 {llvm::Triple::x86_64, llvm::Triple::arm, 1527 llvm::Triple::thumb, llvm::Triple::aarch64})) 1528 return ExprError(); 1529 break; 1530 1531 case Builtin::BI__builtin_isgreater: 1532 case Builtin::BI__builtin_isgreaterequal: 1533 case Builtin::BI__builtin_isless: 1534 case Builtin::BI__builtin_islessequal: 1535 case Builtin::BI__builtin_islessgreater: 1536 case Builtin::BI__builtin_isunordered: 1537 if (SemaBuiltinUnorderedCompare(TheCall)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_fpclassify: 1541 if (SemaBuiltinFPClassification(TheCall, 6)) 1542 return ExprError(); 1543 break; 1544 case Builtin::BI__builtin_isfinite: 1545 case Builtin::BI__builtin_isinf: 1546 case Builtin::BI__builtin_isinf_sign: 1547 case Builtin::BI__builtin_isnan: 1548 case Builtin::BI__builtin_isnormal: 1549 case Builtin::BI__builtin_signbit: 1550 case Builtin::BI__builtin_signbitf: 1551 case Builtin::BI__builtin_signbitl: 1552 if (SemaBuiltinFPClassification(TheCall, 1)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_shufflevector: 1556 return SemaBuiltinShuffleVector(TheCall); 1557 // TheCall will be freed by the smart pointer here, but that's fine, since 1558 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1559 case Builtin::BI__builtin_prefetch: 1560 if (SemaBuiltinPrefetch(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_alloca_with_align: 1564 if (SemaBuiltinAllocaWithAlign(TheCall)) 1565 return ExprError(); 1566 LLVM_FALLTHROUGH; 1567 case Builtin::BI__builtin_alloca: 1568 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1569 << TheCall->getDirectCallee(); 1570 break; 1571 case Builtin::BI__arithmetic_fence: 1572 if (SemaBuiltinArithmeticFence(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__assume: 1576 case Builtin::BI__builtin_assume: 1577 if (SemaBuiltinAssume(TheCall)) 1578 return ExprError(); 1579 break; 1580 case Builtin::BI__builtin_assume_aligned: 1581 if (SemaBuiltinAssumeAligned(TheCall)) 1582 return ExprError(); 1583 break; 1584 case Builtin::BI__builtin_dynamic_object_size: 1585 case Builtin::BI__builtin_object_size: 1586 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BI__builtin_longjmp: 1590 if (SemaBuiltinLongjmp(TheCall)) 1591 return ExprError(); 1592 break; 1593 case Builtin::BI__builtin_setjmp: 1594 if (SemaBuiltinSetjmp(TheCall)) 1595 return ExprError(); 1596 break; 1597 case Builtin::BI__builtin_classify_type: 1598 if (checkArgCount(*this, TheCall, 1)) return true; 1599 TheCall->setType(Context.IntTy); 1600 break; 1601 case Builtin::BI__builtin_complex: 1602 if (SemaBuiltinComplex(TheCall)) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_constant_p: { 1606 if (checkArgCount(*this, TheCall, 1)) return true; 1607 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1608 if (Arg.isInvalid()) return true; 1609 TheCall->setArg(0, Arg.get()); 1610 TheCall->setType(Context.IntTy); 1611 break; 1612 } 1613 case Builtin::BI__builtin_launder: 1614 return SemaBuiltinLaunder(*this, TheCall); 1615 case Builtin::BI__sync_fetch_and_add: 1616 case Builtin::BI__sync_fetch_and_add_1: 1617 case Builtin::BI__sync_fetch_and_add_2: 1618 case Builtin::BI__sync_fetch_and_add_4: 1619 case Builtin::BI__sync_fetch_and_add_8: 1620 case Builtin::BI__sync_fetch_and_add_16: 1621 case Builtin::BI__sync_fetch_and_sub: 1622 case Builtin::BI__sync_fetch_and_sub_1: 1623 case Builtin::BI__sync_fetch_and_sub_2: 1624 case Builtin::BI__sync_fetch_and_sub_4: 1625 case Builtin::BI__sync_fetch_and_sub_8: 1626 case Builtin::BI__sync_fetch_and_sub_16: 1627 case Builtin::BI__sync_fetch_and_or: 1628 case Builtin::BI__sync_fetch_and_or_1: 1629 case Builtin::BI__sync_fetch_and_or_2: 1630 case Builtin::BI__sync_fetch_and_or_4: 1631 case Builtin::BI__sync_fetch_and_or_8: 1632 case Builtin::BI__sync_fetch_and_or_16: 1633 case Builtin::BI__sync_fetch_and_and: 1634 case Builtin::BI__sync_fetch_and_and_1: 1635 case Builtin::BI__sync_fetch_and_and_2: 1636 case Builtin::BI__sync_fetch_and_and_4: 1637 case Builtin::BI__sync_fetch_and_and_8: 1638 case Builtin::BI__sync_fetch_and_and_16: 1639 case Builtin::BI__sync_fetch_and_xor: 1640 case Builtin::BI__sync_fetch_and_xor_1: 1641 case Builtin::BI__sync_fetch_and_xor_2: 1642 case Builtin::BI__sync_fetch_and_xor_4: 1643 case Builtin::BI__sync_fetch_and_xor_8: 1644 case Builtin::BI__sync_fetch_and_xor_16: 1645 case Builtin::BI__sync_fetch_and_nand: 1646 case Builtin::BI__sync_fetch_and_nand_1: 1647 case Builtin::BI__sync_fetch_and_nand_2: 1648 case Builtin::BI__sync_fetch_and_nand_4: 1649 case Builtin::BI__sync_fetch_and_nand_8: 1650 case Builtin::BI__sync_fetch_and_nand_16: 1651 case Builtin::BI__sync_add_and_fetch: 1652 case Builtin::BI__sync_add_and_fetch_1: 1653 case Builtin::BI__sync_add_and_fetch_2: 1654 case Builtin::BI__sync_add_and_fetch_4: 1655 case Builtin::BI__sync_add_and_fetch_8: 1656 case Builtin::BI__sync_add_and_fetch_16: 1657 case Builtin::BI__sync_sub_and_fetch: 1658 case Builtin::BI__sync_sub_and_fetch_1: 1659 case Builtin::BI__sync_sub_and_fetch_2: 1660 case Builtin::BI__sync_sub_and_fetch_4: 1661 case Builtin::BI__sync_sub_and_fetch_8: 1662 case Builtin::BI__sync_sub_and_fetch_16: 1663 case Builtin::BI__sync_and_and_fetch: 1664 case Builtin::BI__sync_and_and_fetch_1: 1665 case Builtin::BI__sync_and_and_fetch_2: 1666 case Builtin::BI__sync_and_and_fetch_4: 1667 case Builtin::BI__sync_and_and_fetch_8: 1668 case Builtin::BI__sync_and_and_fetch_16: 1669 case Builtin::BI__sync_or_and_fetch: 1670 case Builtin::BI__sync_or_and_fetch_1: 1671 case Builtin::BI__sync_or_and_fetch_2: 1672 case Builtin::BI__sync_or_and_fetch_4: 1673 case Builtin::BI__sync_or_and_fetch_8: 1674 case Builtin::BI__sync_or_and_fetch_16: 1675 case Builtin::BI__sync_xor_and_fetch: 1676 case Builtin::BI__sync_xor_and_fetch_1: 1677 case Builtin::BI__sync_xor_and_fetch_2: 1678 case Builtin::BI__sync_xor_and_fetch_4: 1679 case Builtin::BI__sync_xor_and_fetch_8: 1680 case Builtin::BI__sync_xor_and_fetch_16: 1681 case Builtin::BI__sync_nand_and_fetch: 1682 case Builtin::BI__sync_nand_and_fetch_1: 1683 case Builtin::BI__sync_nand_and_fetch_2: 1684 case Builtin::BI__sync_nand_and_fetch_4: 1685 case Builtin::BI__sync_nand_and_fetch_8: 1686 case Builtin::BI__sync_nand_and_fetch_16: 1687 case Builtin::BI__sync_val_compare_and_swap: 1688 case Builtin::BI__sync_val_compare_and_swap_1: 1689 case Builtin::BI__sync_val_compare_and_swap_2: 1690 case Builtin::BI__sync_val_compare_and_swap_4: 1691 case Builtin::BI__sync_val_compare_and_swap_8: 1692 case Builtin::BI__sync_val_compare_and_swap_16: 1693 case Builtin::BI__sync_bool_compare_and_swap: 1694 case Builtin::BI__sync_bool_compare_and_swap_1: 1695 case Builtin::BI__sync_bool_compare_and_swap_2: 1696 case Builtin::BI__sync_bool_compare_and_swap_4: 1697 case Builtin::BI__sync_bool_compare_and_swap_8: 1698 case Builtin::BI__sync_bool_compare_and_swap_16: 1699 case Builtin::BI__sync_lock_test_and_set: 1700 case Builtin::BI__sync_lock_test_and_set_1: 1701 case Builtin::BI__sync_lock_test_and_set_2: 1702 case Builtin::BI__sync_lock_test_and_set_4: 1703 case Builtin::BI__sync_lock_test_and_set_8: 1704 case Builtin::BI__sync_lock_test_and_set_16: 1705 case Builtin::BI__sync_lock_release: 1706 case Builtin::BI__sync_lock_release_1: 1707 case Builtin::BI__sync_lock_release_2: 1708 case Builtin::BI__sync_lock_release_4: 1709 case Builtin::BI__sync_lock_release_8: 1710 case Builtin::BI__sync_lock_release_16: 1711 case Builtin::BI__sync_swap: 1712 case Builtin::BI__sync_swap_1: 1713 case Builtin::BI__sync_swap_2: 1714 case Builtin::BI__sync_swap_4: 1715 case Builtin::BI__sync_swap_8: 1716 case Builtin::BI__sync_swap_16: 1717 return SemaBuiltinAtomicOverloaded(TheCallResult); 1718 case Builtin::BI__sync_synchronize: 1719 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1720 << TheCall->getCallee()->getSourceRange(); 1721 break; 1722 case Builtin::BI__builtin_nontemporal_load: 1723 case Builtin::BI__builtin_nontemporal_store: 1724 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1725 case Builtin::BI__builtin_memcpy_inline: { 1726 clang::Expr *SizeOp = TheCall->getArg(2); 1727 // We warn about copying to or from `nullptr` pointers when `size` is 1728 // greater than 0. When `size` is value dependent we cannot evaluate its 1729 // value so we bail out. 1730 if (SizeOp->isValueDependent()) 1731 break; 1732 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1733 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1734 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1735 } 1736 break; 1737 } 1738 #define BUILTIN(ID, TYPE, ATTRS) 1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1740 case Builtin::BI##ID: \ 1741 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1742 #include "clang/Basic/Builtins.def" 1743 case Builtin::BI__annotation: 1744 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_annotation: 1748 if (SemaBuiltinAnnotation(*this, TheCall)) 1749 return ExprError(); 1750 break; 1751 case Builtin::BI__builtin_addressof: 1752 if (SemaBuiltinAddressof(*this, TheCall)) 1753 return ExprError(); 1754 break; 1755 case Builtin::BI__builtin_is_aligned: 1756 case Builtin::BI__builtin_align_up: 1757 case Builtin::BI__builtin_align_down: 1758 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_add_overflow: 1762 case Builtin::BI__builtin_sub_overflow: 1763 case Builtin::BI__builtin_mul_overflow: 1764 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__builtin_operator_new: 1768 case Builtin::BI__builtin_operator_delete: { 1769 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1770 ExprResult Res = 1771 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1772 if (Res.isInvalid()) 1773 CorrectDelayedTyposInExpr(TheCallResult.get()); 1774 return Res; 1775 } 1776 case Builtin::BI__builtin_dump_struct: { 1777 // We first want to ensure we are called with 2 arguments 1778 if (checkArgCount(*this, TheCall, 2)) 1779 return ExprError(); 1780 // Ensure that the first argument is of type 'struct XX *' 1781 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1782 const QualType PtrArgType = PtrArg->getType(); 1783 if (!PtrArgType->isPointerType() || 1784 !PtrArgType->getPointeeType()->isRecordType()) { 1785 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1786 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1787 << "structure pointer"; 1788 return ExprError(); 1789 } 1790 1791 // Ensure that the second argument is of type 'FunctionType' 1792 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1793 const QualType FnPtrArgType = FnPtrArg->getType(); 1794 if (!FnPtrArgType->isPointerType()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1797 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 1801 const auto *FuncType = 1802 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1803 1804 if (!FuncType) { 1805 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1806 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1807 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1808 return ExprError(); 1809 } 1810 1811 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1812 if (!FT->getNumParams()) { 1813 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1814 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1815 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1816 return ExprError(); 1817 } 1818 QualType PT = FT->getParamType(0); 1819 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1820 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1821 !PT->getPointeeType().isConstQualified()) { 1822 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1823 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1824 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1825 return ExprError(); 1826 } 1827 } 1828 1829 TheCall->setType(Context.IntTy); 1830 break; 1831 } 1832 case Builtin::BI__builtin_expect_with_probability: { 1833 // We first want to ensure we are called with 3 arguments 1834 if (checkArgCount(*this, TheCall, 3)) 1835 return ExprError(); 1836 // then check probability is constant float in range [0.0, 1.0] 1837 const Expr *ProbArg = TheCall->getArg(2); 1838 SmallVector<PartialDiagnosticAt, 8> Notes; 1839 Expr::EvalResult Eval; 1840 Eval.Diag = &Notes; 1841 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1842 !Eval.Val.isFloat()) { 1843 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1844 << ProbArg->getSourceRange(); 1845 for (const PartialDiagnosticAt &PDiag : Notes) 1846 Diag(PDiag.first, PDiag.second); 1847 return ExprError(); 1848 } 1849 llvm::APFloat Probability = Eval.Val.getFloat(); 1850 bool LoseInfo = false; 1851 Probability.convert(llvm::APFloat::IEEEdouble(), 1852 llvm::RoundingMode::Dynamic, &LoseInfo); 1853 if (!(Probability >= llvm::APFloat(0.0) && 1854 Probability <= llvm::APFloat(1.0))) { 1855 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1856 << ProbArg->getSourceRange(); 1857 return ExprError(); 1858 } 1859 break; 1860 } 1861 case Builtin::BI__builtin_preserve_access_index: 1862 if (SemaBuiltinPreserveAI(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BI__builtin_call_with_static_chain: 1866 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__exception_code: 1870 case Builtin::BI_exception_code: 1871 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1872 diag::err_seh___except_block)) 1873 return ExprError(); 1874 break; 1875 case Builtin::BI__exception_info: 1876 case Builtin::BI_exception_info: 1877 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1878 diag::err_seh___except_filter)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BI__GetExceptionInfo: 1882 if (checkArgCount(*this, TheCall, 1)) 1883 return ExprError(); 1884 1885 if (CheckCXXThrowOperand( 1886 TheCall->getBeginLoc(), 1887 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1888 TheCall)) 1889 return ExprError(); 1890 1891 TheCall->setType(Context.VoidPtrTy); 1892 break; 1893 // OpenCL v2.0, s6.13.16 - Pipe functions 1894 case Builtin::BIread_pipe: 1895 case Builtin::BIwrite_pipe: 1896 // Since those two functions are declared with var args, we need a semantic 1897 // check for the argument. 1898 if (SemaBuiltinRWPipe(*this, TheCall)) 1899 return ExprError(); 1900 break; 1901 case Builtin::BIreserve_read_pipe: 1902 case Builtin::BIreserve_write_pipe: 1903 case Builtin::BIwork_group_reserve_read_pipe: 1904 case Builtin::BIwork_group_reserve_write_pipe: 1905 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIsub_group_reserve_read_pipe: 1909 case Builtin::BIsub_group_reserve_write_pipe: 1910 if (checkOpenCLSubgroupExt(*this, TheCall) || 1911 SemaBuiltinReserveRWPipe(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIcommit_read_pipe: 1915 case Builtin::BIcommit_write_pipe: 1916 case Builtin::BIwork_group_commit_read_pipe: 1917 case Builtin::BIwork_group_commit_write_pipe: 1918 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1919 return ExprError(); 1920 break; 1921 case Builtin::BIsub_group_commit_read_pipe: 1922 case Builtin::BIsub_group_commit_write_pipe: 1923 if (checkOpenCLSubgroupExt(*this, TheCall) || 1924 SemaBuiltinCommitRWPipe(*this, TheCall)) 1925 return ExprError(); 1926 break; 1927 case Builtin::BIget_pipe_num_packets: 1928 case Builtin::BIget_pipe_max_packets: 1929 if (SemaBuiltinPipePackets(*this, TheCall)) 1930 return ExprError(); 1931 break; 1932 case Builtin::BIto_global: 1933 case Builtin::BIto_local: 1934 case Builtin::BIto_private: 1935 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1936 return ExprError(); 1937 break; 1938 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1939 case Builtin::BIenqueue_kernel: 1940 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1941 return ExprError(); 1942 break; 1943 case Builtin::BIget_kernel_work_group_size: 1944 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1945 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1946 return ExprError(); 1947 break; 1948 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1949 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1950 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1951 return ExprError(); 1952 break; 1953 case Builtin::BI__builtin_os_log_format: 1954 Cleanup.setExprNeedsCleanups(true); 1955 LLVM_FALLTHROUGH; 1956 case Builtin::BI__builtin_os_log_format_buffer_size: 1957 if (SemaBuiltinOSLogFormat(TheCall)) 1958 return ExprError(); 1959 break; 1960 case Builtin::BI__builtin_frame_address: 1961 case Builtin::BI__builtin_return_address: { 1962 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1963 return ExprError(); 1964 1965 // -Wframe-address warning if non-zero passed to builtin 1966 // return/frame address. 1967 Expr::EvalResult Result; 1968 if (!TheCall->getArg(0)->isValueDependent() && 1969 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1970 Result.Val.getInt() != 0) 1971 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1972 << ((BuiltinID == Builtin::BI__builtin_return_address) 1973 ? "__builtin_return_address" 1974 : "__builtin_frame_address") 1975 << TheCall->getSourceRange(); 1976 break; 1977 } 1978 1979 case Builtin::BI__builtin_matrix_transpose: 1980 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1981 1982 case Builtin::BI__builtin_matrix_column_major_load: 1983 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1984 1985 case Builtin::BI__builtin_matrix_column_major_store: 1986 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1987 1988 case Builtin::BI__builtin_get_device_side_mangled_name: { 1989 auto Check = [](CallExpr *TheCall) { 1990 if (TheCall->getNumArgs() != 1) 1991 return false; 1992 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1993 if (!DRE) 1994 return false; 1995 auto *D = DRE->getDecl(); 1996 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1997 return false; 1998 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1999 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2000 }; 2001 if (!Check(TheCall)) { 2002 Diag(TheCall->getBeginLoc(), 2003 diag::err_hip_invalid_args_builtin_mangled_name); 2004 return ExprError(); 2005 } 2006 } 2007 } 2008 2009 // Since the target specific builtins for each arch overlap, only check those 2010 // of the arch we are compiling for. 2011 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2012 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2013 assert(Context.getAuxTargetInfo() && 2014 "Aux Target Builtin, but not an aux target?"); 2015 2016 if (CheckTSBuiltinFunctionCall( 2017 *Context.getAuxTargetInfo(), 2018 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2019 return ExprError(); 2020 } else { 2021 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2022 TheCall)) 2023 return ExprError(); 2024 } 2025 } 2026 2027 return TheCallResult; 2028 } 2029 2030 // Get the valid immediate range for the specified NEON type code. 2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2032 NeonTypeFlags Type(t); 2033 int IsQuad = ForceQuad ? true : Type.isQuad(); 2034 switch (Type.getEltType()) { 2035 case NeonTypeFlags::Int8: 2036 case NeonTypeFlags::Poly8: 2037 return shift ? 7 : (8 << IsQuad) - 1; 2038 case NeonTypeFlags::Int16: 2039 case NeonTypeFlags::Poly16: 2040 return shift ? 15 : (4 << IsQuad) - 1; 2041 case NeonTypeFlags::Int32: 2042 return shift ? 31 : (2 << IsQuad) - 1; 2043 case NeonTypeFlags::Int64: 2044 case NeonTypeFlags::Poly64: 2045 return shift ? 63 : (1 << IsQuad) - 1; 2046 case NeonTypeFlags::Poly128: 2047 return shift ? 127 : (1 << IsQuad) - 1; 2048 case NeonTypeFlags::Float16: 2049 assert(!shift && "cannot shift float types!"); 2050 return (4 << IsQuad) - 1; 2051 case NeonTypeFlags::Float32: 2052 assert(!shift && "cannot shift float types!"); 2053 return (2 << IsQuad) - 1; 2054 case NeonTypeFlags::Float64: 2055 assert(!shift && "cannot shift float types!"); 2056 return (1 << IsQuad) - 1; 2057 case NeonTypeFlags::BFloat16: 2058 assert(!shift && "cannot shift float types!"); 2059 return (4 << IsQuad) - 1; 2060 } 2061 llvm_unreachable("Invalid NeonTypeFlag!"); 2062 } 2063 2064 /// getNeonEltType - Return the QualType corresponding to the elements of 2065 /// the vector type specified by the NeonTypeFlags. This is used to check 2066 /// the pointer arguments for Neon load/store intrinsics. 2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2068 bool IsPolyUnsigned, bool IsInt64Long) { 2069 switch (Flags.getEltType()) { 2070 case NeonTypeFlags::Int8: 2071 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2072 case NeonTypeFlags::Int16: 2073 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2074 case NeonTypeFlags::Int32: 2075 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2076 case NeonTypeFlags::Int64: 2077 if (IsInt64Long) 2078 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2079 else 2080 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2081 : Context.LongLongTy; 2082 case NeonTypeFlags::Poly8: 2083 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2084 case NeonTypeFlags::Poly16: 2085 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2086 case NeonTypeFlags::Poly64: 2087 if (IsInt64Long) 2088 return Context.UnsignedLongTy; 2089 else 2090 return Context.UnsignedLongLongTy; 2091 case NeonTypeFlags::Poly128: 2092 break; 2093 case NeonTypeFlags::Float16: 2094 return Context.HalfTy; 2095 case NeonTypeFlags::Float32: 2096 return Context.FloatTy; 2097 case NeonTypeFlags::Float64: 2098 return Context.DoubleTy; 2099 case NeonTypeFlags::BFloat16: 2100 return Context.BFloat16Ty; 2101 } 2102 llvm_unreachable("Invalid NeonTypeFlag!"); 2103 } 2104 2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2106 // Range check SVE intrinsics that take immediate values. 2107 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2108 2109 switch (BuiltinID) { 2110 default: 2111 return false; 2112 #define GET_SVE_IMMEDIATE_CHECK 2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2114 #undef GET_SVE_IMMEDIATE_CHECK 2115 } 2116 2117 // Perform all the immediate checks for this builtin call. 2118 bool HasError = false; 2119 for (auto &I : ImmChecks) { 2120 int ArgNum, CheckTy, ElementSizeInBits; 2121 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2122 2123 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2124 2125 // Function that checks whether the operand (ArgNum) is an immediate 2126 // that is one of the predefined values. 2127 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2128 int ErrDiag) -> bool { 2129 // We can't check the value of a dependent argument. 2130 Expr *Arg = TheCall->getArg(ArgNum); 2131 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2132 return false; 2133 2134 // Check constant-ness first. 2135 llvm::APSInt Imm; 2136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2137 return true; 2138 2139 if (!CheckImm(Imm.getSExtValue())) 2140 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2141 return false; 2142 }; 2143 2144 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2145 case SVETypeFlags::ImmCheck0_31: 2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheck0_13: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2151 HasError = true; 2152 break; 2153 case SVETypeFlags::ImmCheck1_16: 2154 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheck0_7: 2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckExtract: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 (2048 / ElementSizeInBits) - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckShiftRight: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2168 HasError = true; 2169 break; 2170 case SVETypeFlags::ImmCheckShiftRightNarrow: 2171 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2172 ElementSizeInBits / 2)) 2173 HasError = true; 2174 break; 2175 case SVETypeFlags::ImmCheckShiftLeft: 2176 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2177 ElementSizeInBits - 1)) 2178 HasError = true; 2179 break; 2180 case SVETypeFlags::ImmCheckLaneIndex: 2181 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2182 (128 / (1 * ElementSizeInBits)) - 1)) 2183 HasError = true; 2184 break; 2185 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2186 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2187 (128 / (2 * ElementSizeInBits)) - 1)) 2188 HasError = true; 2189 break; 2190 case SVETypeFlags::ImmCheckLaneIndexDot: 2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2192 (128 / (4 * ElementSizeInBits)) - 1)) 2193 HasError = true; 2194 break; 2195 case SVETypeFlags::ImmCheckComplexRot90_270: 2196 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2197 diag::err_rotation_argument_to_cadd)) 2198 HasError = true; 2199 break; 2200 case SVETypeFlags::ImmCheckComplexRotAll90: 2201 if (CheckImmediateInSet( 2202 [](int64_t V) { 2203 return V == 0 || V == 90 || V == 180 || V == 270; 2204 }, 2205 diag::err_rotation_argument_to_cmla)) 2206 HasError = true; 2207 break; 2208 case SVETypeFlags::ImmCheck0_1: 2209 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2210 HasError = true; 2211 break; 2212 case SVETypeFlags::ImmCheck0_2: 2213 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2214 HasError = true; 2215 break; 2216 case SVETypeFlags::ImmCheck0_3: 2217 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2218 HasError = true; 2219 break; 2220 } 2221 } 2222 2223 return HasError; 2224 } 2225 2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2227 unsigned BuiltinID, CallExpr *TheCall) { 2228 llvm::APSInt Result; 2229 uint64_t mask = 0; 2230 unsigned TV = 0; 2231 int PtrArgNum = -1; 2232 bool HasConstPtr = false; 2233 switch (BuiltinID) { 2234 #define GET_NEON_OVERLOAD_CHECK 2235 #include "clang/Basic/arm_neon.inc" 2236 #include "clang/Basic/arm_fp16.inc" 2237 #undef GET_NEON_OVERLOAD_CHECK 2238 } 2239 2240 // For NEON intrinsics which are overloaded on vector element type, validate 2241 // the immediate which specifies which variant to emit. 2242 unsigned ImmArg = TheCall->getNumArgs()-1; 2243 if (mask) { 2244 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2245 return true; 2246 2247 TV = Result.getLimitedValue(64); 2248 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2249 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2250 << TheCall->getArg(ImmArg)->getSourceRange(); 2251 } 2252 2253 if (PtrArgNum >= 0) { 2254 // Check that pointer arguments have the specified type. 2255 Expr *Arg = TheCall->getArg(PtrArgNum); 2256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2257 Arg = ICE->getSubExpr(); 2258 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2259 QualType RHSTy = RHS.get()->getType(); 2260 2261 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2262 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2263 Arch == llvm::Triple::aarch64_32 || 2264 Arch == llvm::Triple::aarch64_be; 2265 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2266 QualType EltTy = 2267 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2268 if (HasConstPtr) 2269 EltTy = EltTy.withConst(); 2270 QualType LHSTy = Context.getPointerType(EltTy); 2271 AssignConvertType ConvTy; 2272 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2273 if (RHS.isInvalid()) 2274 return true; 2275 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2276 RHS.get(), AA_Assigning)) 2277 return true; 2278 } 2279 2280 // For NEON intrinsics which take an immediate value as part of the 2281 // instruction, range check them here. 2282 unsigned i = 0, l = 0, u = 0; 2283 switch (BuiltinID) { 2284 default: 2285 return false; 2286 #define GET_NEON_IMMEDIATE_CHECK 2287 #include "clang/Basic/arm_neon.inc" 2288 #include "clang/Basic/arm_fp16.inc" 2289 #undef GET_NEON_IMMEDIATE_CHECK 2290 } 2291 2292 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2293 } 2294 2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2296 switch (BuiltinID) { 2297 default: 2298 return false; 2299 #include "clang/Basic/arm_mve_builtin_sema.inc" 2300 } 2301 } 2302 2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2304 CallExpr *TheCall) { 2305 bool Err = false; 2306 switch (BuiltinID) { 2307 default: 2308 return false; 2309 #include "clang/Basic/arm_cde_builtin_sema.inc" 2310 } 2311 2312 if (Err) 2313 return true; 2314 2315 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2316 } 2317 2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2319 const Expr *CoprocArg, bool WantCDE) { 2320 if (isConstantEvaluated()) 2321 return false; 2322 2323 // We can't check the value of a dependent argument. 2324 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2325 return false; 2326 2327 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2328 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2329 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2330 2331 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2332 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2333 2334 if (IsCDECoproc != WantCDE) 2335 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2336 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2337 2338 return false; 2339 } 2340 2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2342 unsigned MaxWidth) { 2343 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2344 BuiltinID == ARM::BI__builtin_arm_ldaex || 2345 BuiltinID == ARM::BI__builtin_arm_strex || 2346 BuiltinID == ARM::BI__builtin_arm_stlex || 2347 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2348 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2349 BuiltinID == AArch64::BI__builtin_arm_strex || 2350 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2351 "unexpected ARM builtin"); 2352 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2353 BuiltinID == ARM::BI__builtin_arm_ldaex || 2354 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2355 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2356 2357 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2358 2359 // Ensure that we have the proper number of arguments. 2360 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2361 return true; 2362 2363 // Inspect the pointer argument of the atomic builtin. This should always be 2364 // a pointer type, whose element is an integral scalar or pointer type. 2365 // Because it is a pointer type, we don't have to worry about any implicit 2366 // casts here. 2367 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2368 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2369 if (PointerArgRes.isInvalid()) 2370 return true; 2371 PointerArg = PointerArgRes.get(); 2372 2373 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2374 if (!pointerType) { 2375 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2376 << PointerArg->getType() << PointerArg->getSourceRange(); 2377 return true; 2378 } 2379 2380 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2381 // task is to insert the appropriate casts into the AST. First work out just 2382 // what the appropriate type is. 2383 QualType ValType = pointerType->getPointeeType(); 2384 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2385 if (IsLdrex) 2386 AddrType.addConst(); 2387 2388 // Issue a warning if the cast is dodgy. 2389 CastKind CastNeeded = CK_NoOp; 2390 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2391 CastNeeded = CK_BitCast; 2392 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2393 << PointerArg->getType() << Context.getPointerType(AddrType) 2394 << AA_Passing << PointerArg->getSourceRange(); 2395 } 2396 2397 // Finally, do the cast and replace the argument with the corrected version. 2398 AddrType = Context.getPointerType(AddrType); 2399 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2400 if (PointerArgRes.isInvalid()) 2401 return true; 2402 PointerArg = PointerArgRes.get(); 2403 2404 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2405 2406 // In general, we allow ints, floats and pointers to be loaded and stored. 2407 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2408 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2409 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2410 << PointerArg->getType() << PointerArg->getSourceRange(); 2411 return true; 2412 } 2413 2414 // But ARM doesn't have instructions to deal with 128-bit versions. 2415 if (Context.getTypeSize(ValType) > MaxWidth) { 2416 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2417 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2418 << PointerArg->getType() << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 switch (ValType.getObjCLifetime()) { 2423 case Qualifiers::OCL_None: 2424 case Qualifiers::OCL_ExplicitNone: 2425 // okay 2426 break; 2427 2428 case Qualifiers::OCL_Weak: 2429 case Qualifiers::OCL_Strong: 2430 case Qualifiers::OCL_Autoreleasing: 2431 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2432 << ValType << PointerArg->getSourceRange(); 2433 return true; 2434 } 2435 2436 if (IsLdrex) { 2437 TheCall->setType(ValType); 2438 return false; 2439 } 2440 2441 // Initialize the argument to be stored. 2442 ExprResult ValArg = TheCall->getArg(0); 2443 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2444 Context, ValType, /*consume*/ false); 2445 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2446 if (ValArg.isInvalid()) 2447 return true; 2448 TheCall->setArg(0, ValArg.get()); 2449 2450 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2451 // but the custom checker bypasses all default analysis. 2452 TheCall->setType(Context.IntTy); 2453 return false; 2454 } 2455 2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2457 CallExpr *TheCall) { 2458 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2459 BuiltinID == ARM::BI__builtin_arm_ldaex || 2460 BuiltinID == ARM::BI__builtin_arm_strex || 2461 BuiltinID == ARM::BI__builtin_arm_stlex) { 2462 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2463 } 2464 2465 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2466 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2467 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2468 } 2469 2470 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2471 BuiltinID == ARM::BI__builtin_arm_wsr64) 2472 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2473 2474 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2475 BuiltinID == ARM::BI__builtin_arm_rsrp || 2476 BuiltinID == ARM::BI__builtin_arm_wsr || 2477 BuiltinID == ARM::BI__builtin_arm_wsrp) 2478 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2479 2480 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2481 return true; 2482 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2483 return true; 2484 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2485 return true; 2486 2487 // For intrinsics which take an immediate value as part of the instruction, 2488 // range check them here. 2489 // FIXME: VFP Intrinsics should error if VFP not present. 2490 switch (BuiltinID) { 2491 default: return false; 2492 case ARM::BI__builtin_arm_ssat: 2493 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2494 case ARM::BI__builtin_arm_usat: 2495 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2496 case ARM::BI__builtin_arm_ssat16: 2497 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2498 case ARM::BI__builtin_arm_usat16: 2499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2500 case ARM::BI__builtin_arm_vcvtr_f: 2501 case ARM::BI__builtin_arm_vcvtr_d: 2502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2503 case ARM::BI__builtin_arm_dmb: 2504 case ARM::BI__builtin_arm_dsb: 2505 case ARM::BI__builtin_arm_isb: 2506 case ARM::BI__builtin_arm_dbg: 2507 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2508 case ARM::BI__builtin_arm_cdp: 2509 case ARM::BI__builtin_arm_cdp2: 2510 case ARM::BI__builtin_arm_mcr: 2511 case ARM::BI__builtin_arm_mcr2: 2512 case ARM::BI__builtin_arm_mrc: 2513 case ARM::BI__builtin_arm_mrc2: 2514 case ARM::BI__builtin_arm_mcrr: 2515 case ARM::BI__builtin_arm_mcrr2: 2516 case ARM::BI__builtin_arm_mrrc: 2517 case ARM::BI__builtin_arm_mrrc2: 2518 case ARM::BI__builtin_arm_ldc: 2519 case ARM::BI__builtin_arm_ldcl: 2520 case ARM::BI__builtin_arm_ldc2: 2521 case ARM::BI__builtin_arm_ldc2l: 2522 case ARM::BI__builtin_arm_stc: 2523 case ARM::BI__builtin_arm_stcl: 2524 case ARM::BI__builtin_arm_stc2: 2525 case ARM::BI__builtin_arm_stc2l: 2526 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2527 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2528 /*WantCDE*/ false); 2529 } 2530 } 2531 2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2533 unsigned BuiltinID, 2534 CallExpr *TheCall) { 2535 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2536 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2537 BuiltinID == AArch64::BI__builtin_arm_strex || 2538 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2539 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2540 } 2541 2542 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2543 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2544 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2545 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2546 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2550 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2551 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2552 2553 // Memory Tagging Extensions (MTE) Intrinsics 2554 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2555 BuiltinID == AArch64::BI__builtin_arm_addg || 2556 BuiltinID == AArch64::BI__builtin_arm_gmi || 2557 BuiltinID == AArch64::BI__builtin_arm_ldg || 2558 BuiltinID == AArch64::BI__builtin_arm_stg || 2559 BuiltinID == AArch64::BI__builtin_arm_subp) { 2560 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2561 } 2562 2563 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2564 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2565 BuiltinID == AArch64::BI__builtin_arm_wsr || 2566 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2567 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2568 2569 // Only check the valid encoding range. Any constant in this range would be 2570 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2571 // an exception for incorrect registers. This matches MSVC behavior. 2572 if (BuiltinID == AArch64::BI_ReadStatusReg || 2573 BuiltinID == AArch64::BI_WriteStatusReg) 2574 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2575 2576 if (BuiltinID == AArch64::BI__getReg) 2577 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2578 2579 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2580 return true; 2581 2582 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2583 return true; 2584 2585 // For intrinsics which take an immediate value as part of the instruction, 2586 // range check them here. 2587 unsigned i = 0, l = 0, u = 0; 2588 switch (BuiltinID) { 2589 default: return false; 2590 case AArch64::BI__builtin_arm_dmb: 2591 case AArch64::BI__builtin_arm_dsb: 2592 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2593 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2594 } 2595 2596 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2597 } 2598 2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2600 if (Arg->getType()->getAsPlaceholderType()) 2601 return false; 2602 2603 // The first argument needs to be a record field access. 2604 // If it is an array element access, we delay decision 2605 // to BPF backend to check whether the access is a 2606 // field access or not. 2607 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2608 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2609 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2610 } 2611 2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2613 QualType VectorTy, QualType EltTy) { 2614 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2615 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2616 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2617 << Call->getSourceRange() << VectorEltTy << EltTy; 2618 return false; 2619 } 2620 return true; 2621 } 2622 2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2624 QualType ArgType = Arg->getType(); 2625 if (ArgType->getAsPlaceholderType()) 2626 return false; 2627 2628 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2629 // format: 2630 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2631 // 2. <type> var; 2632 // __builtin_preserve_type_info(var, flag); 2633 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2634 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2635 return false; 2636 2637 // Typedef type. 2638 if (ArgType->getAs<TypedefType>()) 2639 return true; 2640 2641 // Record type or Enum type. 2642 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2643 if (const auto *RT = Ty->getAs<RecordType>()) { 2644 if (!RT->getDecl()->getDeclName().isEmpty()) 2645 return true; 2646 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2647 if (!ET->getDecl()->getDeclName().isEmpty()) 2648 return true; 2649 } 2650 2651 return false; 2652 } 2653 2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2655 QualType ArgType = Arg->getType(); 2656 if (ArgType->getAsPlaceholderType()) 2657 return false; 2658 2659 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2660 // format: 2661 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2662 // flag); 2663 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2664 if (!UO) 2665 return false; 2666 2667 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2668 if (!CE) 2669 return false; 2670 if (CE->getCastKind() != CK_IntegralToPointer && 2671 CE->getCastKind() != CK_NullToPointer) 2672 return false; 2673 2674 // The integer must be from an EnumConstantDecl. 2675 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2676 if (!DR) 2677 return false; 2678 2679 const EnumConstantDecl *Enumerator = 2680 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2681 if (!Enumerator) 2682 return false; 2683 2684 // The type must be EnumType. 2685 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2686 const auto *ET = Ty->getAs<EnumType>(); 2687 if (!ET) 2688 return false; 2689 2690 // The enum value must be supported. 2691 for (auto *EDI : ET->getDecl()->enumerators()) { 2692 if (EDI == Enumerator) 2693 return true; 2694 } 2695 2696 return false; 2697 } 2698 2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2700 CallExpr *TheCall) { 2701 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2702 BuiltinID == BPF::BI__builtin_btf_type_id || 2703 BuiltinID == BPF::BI__builtin_preserve_type_info || 2704 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2705 "unexpected BPF builtin"); 2706 2707 if (checkArgCount(*this, TheCall, 2)) 2708 return true; 2709 2710 // The second argument needs to be a constant int 2711 Expr *Arg = TheCall->getArg(1); 2712 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2713 diag::kind kind; 2714 if (!Value) { 2715 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2716 kind = diag::err_preserve_field_info_not_const; 2717 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2718 kind = diag::err_btf_type_id_not_const; 2719 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2720 kind = diag::err_preserve_type_info_not_const; 2721 else 2722 kind = diag::err_preserve_enum_value_not_const; 2723 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2724 return true; 2725 } 2726 2727 // The first argument 2728 Arg = TheCall->getArg(0); 2729 bool InvalidArg = false; 2730 bool ReturnUnsignedInt = true; 2731 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2732 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2733 InvalidArg = true; 2734 kind = diag::err_preserve_field_info_not_field; 2735 } 2736 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2737 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2738 InvalidArg = true; 2739 kind = diag::err_preserve_type_info_invalid; 2740 } 2741 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2742 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2743 InvalidArg = true; 2744 kind = diag::err_preserve_enum_value_invalid; 2745 } 2746 ReturnUnsignedInt = false; 2747 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2748 ReturnUnsignedInt = false; 2749 } 2750 2751 if (InvalidArg) { 2752 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2753 return true; 2754 } 2755 2756 if (ReturnUnsignedInt) 2757 TheCall->setType(Context.UnsignedIntTy); 2758 else 2759 TheCall->setType(Context.UnsignedLongTy); 2760 return false; 2761 } 2762 2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2764 struct ArgInfo { 2765 uint8_t OpNum; 2766 bool IsSigned; 2767 uint8_t BitWidth; 2768 uint8_t Align; 2769 }; 2770 struct BuiltinInfo { 2771 unsigned BuiltinID; 2772 ArgInfo Infos[2]; 2773 }; 2774 2775 static BuiltinInfo Infos[] = { 2776 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2777 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2778 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2779 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2780 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2782 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2783 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2784 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2785 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2786 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2787 2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2799 2800 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2852 {{ 1, false, 6, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2860 {{ 1, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2867 { 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2869 { 2, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2871 { 3, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2873 { 3, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2890 {{ 2, false, 4, 0 }, 2891 { 3, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2893 {{ 2, false, 4, 0 }, 2894 { 3, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2896 {{ 2, false, 4, 0 }, 2897 { 3, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2899 {{ 2, false, 4, 0 }, 2900 { 3, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2912 { 2, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2914 { 2, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2924 {{ 1, false, 4, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2927 {{ 1, false, 4, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2948 {{ 3, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2953 {{ 3, false, 1, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2958 {{ 3, false, 1, 0 }} }, 2959 }; 2960 2961 // Use a dynamically initialized static to sort the table exactly once on 2962 // first run. 2963 static const bool SortOnce = 2964 (llvm::sort(Infos, 2965 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2966 return LHS.BuiltinID < RHS.BuiltinID; 2967 }), 2968 true); 2969 (void)SortOnce; 2970 2971 const BuiltinInfo *F = llvm::partition_point( 2972 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2973 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2974 return false; 2975 2976 bool Error = false; 2977 2978 for (const ArgInfo &A : F->Infos) { 2979 // Ignore empty ArgInfo elements. 2980 if (A.BitWidth == 0) 2981 continue; 2982 2983 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2984 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2985 if (!A.Align) { 2986 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2987 } else { 2988 unsigned M = 1 << A.Align; 2989 Min *= M; 2990 Max *= M; 2991 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2992 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2993 } 2994 } 2995 return Error; 2996 } 2997 2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2999 CallExpr *TheCall) { 3000 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3001 } 3002 3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3004 unsigned BuiltinID, CallExpr *TheCall) { 3005 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3006 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3007 } 3008 3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3010 CallExpr *TheCall) { 3011 3012 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3013 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3014 if (!TI.hasFeature("dsp")) 3015 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3016 } 3017 3018 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3019 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3020 if (!TI.hasFeature("dspr2")) 3021 return Diag(TheCall->getBeginLoc(), 3022 diag::err_mips_builtin_requires_dspr2); 3023 } 3024 3025 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3026 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3027 if (!TI.hasFeature("msa")) 3028 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3029 } 3030 3031 return false; 3032 } 3033 3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3036 // ordering for DSP is unspecified. MSA is ordered by the data format used 3037 // by the underlying instruction i.e., df/m, df/n and then by size. 3038 // 3039 // FIXME: The size tests here should instead be tablegen'd along with the 3040 // definitions from include/clang/Basic/BuiltinsMips.def. 3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3042 // be too. 3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3044 unsigned i = 0, l = 0, u = 0, m = 0; 3045 switch (BuiltinID) { 3046 default: return false; 3047 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3048 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3049 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3050 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3051 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3052 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3053 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3054 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3055 // df/m field. 3056 // These intrinsics take an unsigned 3 bit immediate. 3057 case Mips::BI__builtin_msa_bclri_b: 3058 case Mips::BI__builtin_msa_bnegi_b: 3059 case Mips::BI__builtin_msa_bseti_b: 3060 case Mips::BI__builtin_msa_sat_s_b: 3061 case Mips::BI__builtin_msa_sat_u_b: 3062 case Mips::BI__builtin_msa_slli_b: 3063 case Mips::BI__builtin_msa_srai_b: 3064 case Mips::BI__builtin_msa_srari_b: 3065 case Mips::BI__builtin_msa_srli_b: 3066 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3067 case Mips::BI__builtin_msa_binsli_b: 3068 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3069 // These intrinsics take an unsigned 4 bit immediate. 3070 case Mips::BI__builtin_msa_bclri_h: 3071 case Mips::BI__builtin_msa_bnegi_h: 3072 case Mips::BI__builtin_msa_bseti_h: 3073 case Mips::BI__builtin_msa_sat_s_h: 3074 case Mips::BI__builtin_msa_sat_u_h: 3075 case Mips::BI__builtin_msa_slli_h: 3076 case Mips::BI__builtin_msa_srai_h: 3077 case Mips::BI__builtin_msa_srari_h: 3078 case Mips::BI__builtin_msa_srli_h: 3079 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3080 case Mips::BI__builtin_msa_binsli_h: 3081 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3082 // These intrinsics take an unsigned 5 bit immediate. 3083 // The first block of intrinsics actually have an unsigned 5 bit field, 3084 // not a df/n field. 3085 case Mips::BI__builtin_msa_cfcmsa: 3086 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3087 case Mips::BI__builtin_msa_clei_u_b: 3088 case Mips::BI__builtin_msa_clei_u_h: 3089 case Mips::BI__builtin_msa_clei_u_w: 3090 case Mips::BI__builtin_msa_clei_u_d: 3091 case Mips::BI__builtin_msa_clti_u_b: 3092 case Mips::BI__builtin_msa_clti_u_h: 3093 case Mips::BI__builtin_msa_clti_u_w: 3094 case Mips::BI__builtin_msa_clti_u_d: 3095 case Mips::BI__builtin_msa_maxi_u_b: 3096 case Mips::BI__builtin_msa_maxi_u_h: 3097 case Mips::BI__builtin_msa_maxi_u_w: 3098 case Mips::BI__builtin_msa_maxi_u_d: 3099 case Mips::BI__builtin_msa_mini_u_b: 3100 case Mips::BI__builtin_msa_mini_u_h: 3101 case Mips::BI__builtin_msa_mini_u_w: 3102 case Mips::BI__builtin_msa_mini_u_d: 3103 case Mips::BI__builtin_msa_addvi_b: 3104 case Mips::BI__builtin_msa_addvi_h: 3105 case Mips::BI__builtin_msa_addvi_w: 3106 case Mips::BI__builtin_msa_addvi_d: 3107 case Mips::BI__builtin_msa_bclri_w: 3108 case Mips::BI__builtin_msa_bnegi_w: 3109 case Mips::BI__builtin_msa_bseti_w: 3110 case Mips::BI__builtin_msa_sat_s_w: 3111 case Mips::BI__builtin_msa_sat_u_w: 3112 case Mips::BI__builtin_msa_slli_w: 3113 case Mips::BI__builtin_msa_srai_w: 3114 case Mips::BI__builtin_msa_srari_w: 3115 case Mips::BI__builtin_msa_srli_w: 3116 case Mips::BI__builtin_msa_srlri_w: 3117 case Mips::BI__builtin_msa_subvi_b: 3118 case Mips::BI__builtin_msa_subvi_h: 3119 case Mips::BI__builtin_msa_subvi_w: 3120 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3121 case Mips::BI__builtin_msa_binsli_w: 3122 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3123 // These intrinsics take an unsigned 6 bit immediate. 3124 case Mips::BI__builtin_msa_bclri_d: 3125 case Mips::BI__builtin_msa_bnegi_d: 3126 case Mips::BI__builtin_msa_bseti_d: 3127 case Mips::BI__builtin_msa_sat_s_d: 3128 case Mips::BI__builtin_msa_sat_u_d: 3129 case Mips::BI__builtin_msa_slli_d: 3130 case Mips::BI__builtin_msa_srai_d: 3131 case Mips::BI__builtin_msa_srari_d: 3132 case Mips::BI__builtin_msa_srli_d: 3133 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3134 case Mips::BI__builtin_msa_binsli_d: 3135 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3136 // These intrinsics take a signed 5 bit immediate. 3137 case Mips::BI__builtin_msa_ceqi_b: 3138 case Mips::BI__builtin_msa_ceqi_h: 3139 case Mips::BI__builtin_msa_ceqi_w: 3140 case Mips::BI__builtin_msa_ceqi_d: 3141 case Mips::BI__builtin_msa_clti_s_b: 3142 case Mips::BI__builtin_msa_clti_s_h: 3143 case Mips::BI__builtin_msa_clti_s_w: 3144 case Mips::BI__builtin_msa_clti_s_d: 3145 case Mips::BI__builtin_msa_clei_s_b: 3146 case Mips::BI__builtin_msa_clei_s_h: 3147 case Mips::BI__builtin_msa_clei_s_w: 3148 case Mips::BI__builtin_msa_clei_s_d: 3149 case Mips::BI__builtin_msa_maxi_s_b: 3150 case Mips::BI__builtin_msa_maxi_s_h: 3151 case Mips::BI__builtin_msa_maxi_s_w: 3152 case Mips::BI__builtin_msa_maxi_s_d: 3153 case Mips::BI__builtin_msa_mini_s_b: 3154 case Mips::BI__builtin_msa_mini_s_h: 3155 case Mips::BI__builtin_msa_mini_s_w: 3156 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3157 // These intrinsics take an unsigned 8 bit immediate. 3158 case Mips::BI__builtin_msa_andi_b: 3159 case Mips::BI__builtin_msa_nori_b: 3160 case Mips::BI__builtin_msa_ori_b: 3161 case Mips::BI__builtin_msa_shf_b: 3162 case Mips::BI__builtin_msa_shf_h: 3163 case Mips::BI__builtin_msa_shf_w: 3164 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3165 case Mips::BI__builtin_msa_bseli_b: 3166 case Mips::BI__builtin_msa_bmnzi_b: 3167 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3168 // df/n format 3169 // These intrinsics take an unsigned 4 bit immediate. 3170 case Mips::BI__builtin_msa_copy_s_b: 3171 case Mips::BI__builtin_msa_copy_u_b: 3172 case Mips::BI__builtin_msa_insve_b: 3173 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3174 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3175 // These intrinsics take an unsigned 3 bit immediate. 3176 case Mips::BI__builtin_msa_copy_s_h: 3177 case Mips::BI__builtin_msa_copy_u_h: 3178 case Mips::BI__builtin_msa_insve_h: 3179 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3180 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3181 // These intrinsics take an unsigned 2 bit immediate. 3182 case Mips::BI__builtin_msa_copy_s_w: 3183 case Mips::BI__builtin_msa_copy_u_w: 3184 case Mips::BI__builtin_msa_insve_w: 3185 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3186 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3187 // These intrinsics take an unsigned 1 bit immediate. 3188 case Mips::BI__builtin_msa_copy_s_d: 3189 case Mips::BI__builtin_msa_copy_u_d: 3190 case Mips::BI__builtin_msa_insve_d: 3191 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3192 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3193 // Memory offsets and immediate loads. 3194 // These intrinsics take a signed 10 bit immediate. 3195 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3196 case Mips::BI__builtin_msa_ldi_h: 3197 case Mips::BI__builtin_msa_ldi_w: 3198 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3199 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3200 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3201 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3202 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3203 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3204 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3205 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3206 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3207 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3208 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3209 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3210 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3211 } 3212 3213 if (!m) 3214 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3215 3216 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3217 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3218 } 3219 3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3221 /// advancing the pointer over the consumed characters. The decoded type is 3222 /// returned. If the decoded type represents a constant integer with a 3223 /// constraint on its value then Mask is set to that value. The type descriptors 3224 /// used in Str are specific to PPC MMA builtins and are documented in the file 3225 /// defining the PPC builtins. 3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3227 unsigned &Mask) { 3228 bool RequireICE = false; 3229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3230 switch (*Str++) { 3231 case 'V': 3232 return Context.getVectorType(Context.UnsignedCharTy, 16, 3233 VectorType::VectorKind::AltiVecVector); 3234 case 'i': { 3235 char *End; 3236 unsigned size = strtoul(Str, &End, 10); 3237 assert(End != Str && "Missing constant parameter constraint"); 3238 Str = End; 3239 Mask = size; 3240 return Context.IntTy; 3241 } 3242 case 'W': { 3243 char *End; 3244 unsigned size = strtoul(Str, &End, 10); 3245 assert(End != Str && "Missing PowerPC MMA type size"); 3246 Str = End; 3247 QualType Type; 3248 switch (size) { 3249 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3250 case size: Type = Context.Id##Ty; break; 3251 #include "clang/Basic/PPCTypes.def" 3252 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3253 } 3254 bool CheckVectorArgs = false; 3255 while (!CheckVectorArgs) { 3256 switch (*Str++) { 3257 case '*': 3258 Type = Context.getPointerType(Type); 3259 break; 3260 case 'C': 3261 Type = Type.withConst(); 3262 break; 3263 default: 3264 CheckVectorArgs = true; 3265 --Str; 3266 break; 3267 } 3268 } 3269 return Type; 3270 } 3271 default: 3272 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3273 } 3274 } 3275 3276 static bool isPPC_64Builtin(unsigned BuiltinID) { 3277 // These builtins only work on PPC 64bit targets. 3278 switch (BuiltinID) { 3279 case PPC::BI__builtin_divde: 3280 case PPC::BI__builtin_divdeu: 3281 case PPC::BI__builtin_bpermd: 3282 case PPC::BI__builtin_ppc_ldarx: 3283 case PPC::BI__builtin_ppc_stdcx: 3284 case PPC::BI__builtin_ppc_tdw: 3285 case PPC::BI__builtin_ppc_trapd: 3286 case PPC::BI__builtin_ppc_cmpeqb: 3287 case PPC::BI__builtin_ppc_setb: 3288 case PPC::BI__builtin_ppc_mulhd: 3289 case PPC::BI__builtin_ppc_mulhdu: 3290 case PPC::BI__builtin_ppc_maddhd: 3291 case PPC::BI__builtin_ppc_maddhdu: 3292 case PPC::BI__builtin_ppc_maddld: 3293 case PPC::BI__builtin_ppc_load8r: 3294 case PPC::BI__builtin_ppc_store8r: 3295 case PPC::BI__builtin_ppc_insert_exp: 3296 case PPC::BI__builtin_ppc_extract_sig: 3297 return true; 3298 } 3299 return false; 3300 } 3301 3302 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3303 StringRef FeatureToCheck, unsigned DiagID, 3304 StringRef DiagArg = "") { 3305 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3306 return false; 3307 3308 if (DiagArg.empty()) 3309 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3310 else 3311 S.Diag(TheCall->getBeginLoc(), DiagID) 3312 << DiagArg << TheCall->getSourceRange(); 3313 3314 return true; 3315 } 3316 3317 /// Returns true if the argument consists of one contiguous run of 1s with any 3318 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3319 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3320 /// since all 1s are not contiguous. 3321 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3322 llvm::APSInt Result; 3323 // We can't check the value of a dependent argument. 3324 Expr *Arg = TheCall->getArg(ArgNum); 3325 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3326 return false; 3327 3328 // Check constant-ness first. 3329 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3330 return true; 3331 3332 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3333 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3334 return false; 3335 3336 return Diag(TheCall->getBeginLoc(), 3337 diag::err_argument_not_contiguous_bit_field) 3338 << ArgNum << Arg->getSourceRange(); 3339 } 3340 3341 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3342 CallExpr *TheCall) { 3343 unsigned i = 0, l = 0, u = 0; 3344 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3345 llvm::APSInt Result; 3346 3347 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3348 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3349 << TheCall->getSourceRange(); 3350 3351 switch (BuiltinID) { 3352 default: return false; 3353 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3354 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3355 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3356 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3357 case PPC::BI__builtin_altivec_dss: 3358 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3359 case PPC::BI__builtin_tbegin: 3360 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3361 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3362 case PPC::BI__builtin_tabortwc: 3363 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3364 case PPC::BI__builtin_tabortwci: 3365 case PPC::BI__builtin_tabortdci: 3366 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3367 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3368 case PPC::BI__builtin_altivec_dst: 3369 case PPC::BI__builtin_altivec_dstt: 3370 case PPC::BI__builtin_altivec_dstst: 3371 case PPC::BI__builtin_altivec_dststt: 3372 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3373 case PPC::BI__builtin_vsx_xxpermdi: 3374 case PPC::BI__builtin_vsx_xxsldwi: 3375 return SemaBuiltinVSX(TheCall); 3376 case PPC::BI__builtin_divwe: 3377 case PPC::BI__builtin_divweu: 3378 case PPC::BI__builtin_divde: 3379 case PPC::BI__builtin_divdeu: 3380 return SemaFeatureCheck(*this, TheCall, "extdiv", 3381 diag::err_ppc_builtin_only_on_arch, "7"); 3382 case PPC::BI__builtin_bpermd: 3383 return SemaFeatureCheck(*this, TheCall, "bpermd", 3384 diag::err_ppc_builtin_only_on_arch, "7"); 3385 case PPC::BI__builtin_unpack_vector_int128: 3386 return SemaFeatureCheck(*this, TheCall, "vsx", 3387 diag::err_ppc_builtin_only_on_arch, "7") || 3388 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3389 case PPC::BI__builtin_pack_vector_int128: 3390 return SemaFeatureCheck(*this, TheCall, "vsx", 3391 diag::err_ppc_builtin_only_on_arch, "7"); 3392 case PPC::BI__builtin_altivec_vgnb: 3393 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3394 case PPC::BI__builtin_altivec_vec_replace_elt: 3395 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3396 QualType VecTy = TheCall->getArg(0)->getType(); 3397 QualType EltTy = TheCall->getArg(1)->getType(); 3398 unsigned Width = Context.getIntWidth(EltTy); 3399 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3400 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3401 } 3402 case PPC::BI__builtin_vsx_xxeval: 3403 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3404 case PPC::BI__builtin_altivec_vsldbi: 3405 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3406 case PPC::BI__builtin_altivec_vsrdbi: 3407 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3408 case PPC::BI__builtin_vsx_xxpermx: 3409 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3410 case PPC::BI__builtin_ppc_tw: 3411 case PPC::BI__builtin_ppc_tdw: 3412 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3413 case PPC::BI__builtin_ppc_cmpeqb: 3414 case PPC::BI__builtin_ppc_setb: 3415 case PPC::BI__builtin_ppc_maddhd: 3416 case PPC::BI__builtin_ppc_maddhdu: 3417 case PPC::BI__builtin_ppc_maddld: 3418 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3419 diag::err_ppc_builtin_only_on_arch, "9"); 3420 case PPC::BI__builtin_ppc_cmprb: 3421 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3422 diag::err_ppc_builtin_only_on_arch, "9") || 3423 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3424 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3425 // be a constant that represents a contiguous bit field. 3426 case PPC::BI__builtin_ppc_rlwnm: 3427 return SemaBuiltinConstantArg(TheCall, 1, Result) || 3428 SemaValueIsRunOfOnes(TheCall, 2); 3429 case PPC::BI__builtin_ppc_rlwimi: 3430 case PPC::BI__builtin_ppc_rldimi: 3431 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3432 SemaValueIsRunOfOnes(TheCall, 3); 3433 case PPC::BI__builtin_ppc_extract_exp: 3434 case PPC::BI__builtin_ppc_extract_sig: 3435 case PPC::BI__builtin_ppc_insert_exp: 3436 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3437 diag::err_ppc_builtin_only_on_arch, "9"); 3438 case PPC::BI__builtin_ppc_mtfsb0: 3439 case PPC::BI__builtin_ppc_mtfsb1: 3440 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3441 case PPC::BI__builtin_ppc_mtfsf: 3442 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3443 case PPC::BI__builtin_ppc_mtfsfi: 3444 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3445 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3446 case PPC::BI__builtin_ppc_alignx: 3447 return SemaBuiltinConstantArgPower2(TheCall, 0); 3448 case PPC::BI__builtin_ppc_rdlam: 3449 return SemaValueIsRunOfOnes(TheCall, 2); 3450 case PPC::BI__builtin_ppc_icbt: 3451 case PPC::BI__builtin_ppc_sthcx: 3452 case PPC::BI__builtin_ppc_stbcx: 3453 case PPC::BI__builtin_ppc_lharx: 3454 case PPC::BI__builtin_ppc_lbarx: 3455 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3456 diag::err_ppc_builtin_only_on_arch, "8"); 3457 case PPC::BI__builtin_vsx_ldrmb: 3458 case PPC::BI__builtin_vsx_strmb: 3459 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3460 diag::err_ppc_builtin_only_on_arch, "8") || 3461 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3462 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3463 case PPC::BI__builtin_##Name: \ 3464 return SemaBuiltinPPCMMACall(TheCall, Types); 3465 #include "clang/Basic/BuiltinsPPC.def" 3466 } 3467 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3468 } 3469 3470 // Check if the given type is a non-pointer PPC MMA type. This function is used 3471 // in Sema to prevent invalid uses of restricted PPC MMA types. 3472 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3473 if (Type->isPointerType() || Type->isArrayType()) 3474 return false; 3475 3476 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3477 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3478 if (false 3479 #include "clang/Basic/PPCTypes.def" 3480 ) { 3481 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3482 return true; 3483 } 3484 return false; 3485 } 3486 3487 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3488 CallExpr *TheCall) { 3489 // position of memory order and scope arguments in the builtin 3490 unsigned OrderIndex, ScopeIndex; 3491 switch (BuiltinID) { 3492 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3493 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3494 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3495 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3496 OrderIndex = 2; 3497 ScopeIndex = 3; 3498 break; 3499 case AMDGPU::BI__builtin_amdgcn_fence: 3500 OrderIndex = 0; 3501 ScopeIndex = 1; 3502 break; 3503 default: 3504 return false; 3505 } 3506 3507 ExprResult Arg = TheCall->getArg(OrderIndex); 3508 auto ArgExpr = Arg.get(); 3509 Expr::EvalResult ArgResult; 3510 3511 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3512 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3513 << ArgExpr->getType(); 3514 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3515 3516 // Check valididty of memory ordering as per C11 / C++11's memody model. 3517 // Only fence needs check. Atomic dec/inc allow all memory orders. 3518 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3519 return Diag(ArgExpr->getBeginLoc(), 3520 diag::warn_atomic_op_has_invalid_memory_order) 3521 << ArgExpr->getSourceRange(); 3522 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3523 case llvm::AtomicOrderingCABI::relaxed: 3524 case llvm::AtomicOrderingCABI::consume: 3525 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3526 return Diag(ArgExpr->getBeginLoc(), 3527 diag::warn_atomic_op_has_invalid_memory_order) 3528 << ArgExpr->getSourceRange(); 3529 break; 3530 case llvm::AtomicOrderingCABI::acquire: 3531 case llvm::AtomicOrderingCABI::release: 3532 case llvm::AtomicOrderingCABI::acq_rel: 3533 case llvm::AtomicOrderingCABI::seq_cst: 3534 break; 3535 } 3536 3537 Arg = TheCall->getArg(ScopeIndex); 3538 ArgExpr = Arg.get(); 3539 Expr::EvalResult ArgResult1; 3540 // Check that sync scope is a constant literal 3541 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3542 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3543 << ArgExpr->getType(); 3544 3545 return false; 3546 } 3547 3548 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3549 llvm::APSInt Result; 3550 3551 // We can't check the value of a dependent argument. 3552 Expr *Arg = TheCall->getArg(ArgNum); 3553 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3554 return false; 3555 3556 // Check constant-ness first. 3557 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3558 return true; 3559 3560 int64_t Val = Result.getSExtValue(); 3561 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3562 return false; 3563 3564 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3565 << Arg->getSourceRange(); 3566 } 3567 3568 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3569 unsigned BuiltinID, 3570 CallExpr *TheCall) { 3571 // CodeGenFunction can also detect this, but this gives a better error 3572 // message. 3573 bool FeatureMissing = false; 3574 SmallVector<StringRef> ReqFeatures; 3575 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3576 Features.split(ReqFeatures, ','); 3577 3578 // Check if each required feature is included 3579 for (StringRef F : ReqFeatures) { 3580 if (TI.hasFeature(F)) 3581 continue; 3582 3583 // If the feature is 64bit, alter the string so it will print better in 3584 // the diagnostic. 3585 if (F == "64bit") 3586 F = "RV64"; 3587 3588 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3589 F.consume_front("experimental-"); 3590 std::string FeatureStr = F.str(); 3591 FeatureStr[0] = std::toupper(FeatureStr[0]); 3592 3593 // Error message 3594 FeatureMissing = true; 3595 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3596 << TheCall->getSourceRange() << StringRef(FeatureStr); 3597 } 3598 3599 if (FeatureMissing) 3600 return true; 3601 3602 switch (BuiltinID) { 3603 case RISCV::BI__builtin_rvv_vsetvli: 3604 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3605 CheckRISCVLMUL(TheCall, 2); 3606 case RISCV::BI__builtin_rvv_vsetvlimax: 3607 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3608 CheckRISCVLMUL(TheCall, 1); 3609 case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1: 3610 case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1: 3611 case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1: 3612 case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1: 3613 case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1: 3614 case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1: 3615 case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1: 3616 case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1: 3617 case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1: 3618 case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1: 3619 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2: 3620 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2: 3621 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2: 3622 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2: 3623 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2: 3624 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2: 3625 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2: 3626 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2: 3627 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2: 3628 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2: 3629 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4: 3630 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4: 3631 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4: 3632 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4: 3633 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4: 3634 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4: 3635 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4: 3636 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4: 3637 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4: 3638 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4: 3639 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3640 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1: 3641 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1: 3642 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1: 3643 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1: 3644 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1: 3645 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1: 3646 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1: 3647 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1: 3648 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1: 3649 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1: 3650 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2: 3651 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2: 3652 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2: 3653 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2: 3654 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2: 3655 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2: 3656 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2: 3657 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2: 3658 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2: 3659 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2: 3660 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3661 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1: 3662 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1: 3663 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1: 3664 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1: 3665 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1: 3666 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1: 3667 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1: 3668 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1: 3669 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1: 3670 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1: 3671 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3672 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2: 3673 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2: 3674 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2: 3675 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2: 3676 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2: 3677 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2: 3678 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2: 3679 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2: 3680 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2: 3681 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2: 3682 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4: 3683 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4: 3684 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4: 3685 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4: 3686 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4: 3687 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4: 3688 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4: 3689 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4: 3690 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4: 3691 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4: 3692 case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8: 3693 case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8: 3694 case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8: 3695 case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8: 3696 case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8: 3697 case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8: 3698 case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8: 3699 case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8: 3700 case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8: 3701 case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8: 3702 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3703 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4: 3704 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4: 3705 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4: 3706 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4: 3707 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4: 3708 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4: 3709 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4: 3710 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4: 3711 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4: 3712 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4: 3713 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8: 3714 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8: 3715 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8: 3716 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8: 3717 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8: 3718 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8: 3719 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8: 3720 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8: 3721 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8: 3722 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8: 3723 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3724 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8: 3725 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8: 3726 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8: 3727 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8: 3728 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8: 3729 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8: 3730 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8: 3731 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8: 3732 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8: 3733 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8: 3734 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3735 } 3736 3737 return false; 3738 } 3739 3740 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3741 CallExpr *TheCall) { 3742 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3743 Expr *Arg = TheCall->getArg(0); 3744 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3745 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3746 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3747 << Arg->getSourceRange(); 3748 } 3749 3750 // For intrinsics which take an immediate value as part of the instruction, 3751 // range check them here. 3752 unsigned i = 0, l = 0, u = 0; 3753 switch (BuiltinID) { 3754 default: return false; 3755 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3756 case SystemZ::BI__builtin_s390_verimb: 3757 case SystemZ::BI__builtin_s390_verimh: 3758 case SystemZ::BI__builtin_s390_verimf: 3759 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3760 case SystemZ::BI__builtin_s390_vfaeb: 3761 case SystemZ::BI__builtin_s390_vfaeh: 3762 case SystemZ::BI__builtin_s390_vfaef: 3763 case SystemZ::BI__builtin_s390_vfaebs: 3764 case SystemZ::BI__builtin_s390_vfaehs: 3765 case SystemZ::BI__builtin_s390_vfaefs: 3766 case SystemZ::BI__builtin_s390_vfaezb: 3767 case SystemZ::BI__builtin_s390_vfaezh: 3768 case SystemZ::BI__builtin_s390_vfaezf: 3769 case SystemZ::BI__builtin_s390_vfaezbs: 3770 case SystemZ::BI__builtin_s390_vfaezhs: 3771 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3772 case SystemZ::BI__builtin_s390_vfisb: 3773 case SystemZ::BI__builtin_s390_vfidb: 3774 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3775 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3776 case SystemZ::BI__builtin_s390_vftcisb: 3777 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3778 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3779 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3780 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3781 case SystemZ::BI__builtin_s390_vstrcb: 3782 case SystemZ::BI__builtin_s390_vstrch: 3783 case SystemZ::BI__builtin_s390_vstrcf: 3784 case SystemZ::BI__builtin_s390_vstrczb: 3785 case SystemZ::BI__builtin_s390_vstrczh: 3786 case SystemZ::BI__builtin_s390_vstrczf: 3787 case SystemZ::BI__builtin_s390_vstrcbs: 3788 case SystemZ::BI__builtin_s390_vstrchs: 3789 case SystemZ::BI__builtin_s390_vstrcfs: 3790 case SystemZ::BI__builtin_s390_vstrczbs: 3791 case SystemZ::BI__builtin_s390_vstrczhs: 3792 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3793 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3794 case SystemZ::BI__builtin_s390_vfminsb: 3795 case SystemZ::BI__builtin_s390_vfmaxsb: 3796 case SystemZ::BI__builtin_s390_vfmindb: 3797 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3798 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3799 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3800 case SystemZ::BI__builtin_s390_vclfnhs: 3801 case SystemZ::BI__builtin_s390_vclfnls: 3802 case SystemZ::BI__builtin_s390_vcfn: 3803 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3804 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3805 } 3806 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3807 } 3808 3809 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3810 /// This checks that the target supports __builtin_cpu_supports and 3811 /// that the string argument is constant and valid. 3812 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3813 CallExpr *TheCall) { 3814 Expr *Arg = TheCall->getArg(0); 3815 3816 // Check if the argument is a string literal. 3817 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3818 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3819 << Arg->getSourceRange(); 3820 3821 // Check the contents of the string. 3822 StringRef Feature = 3823 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3824 if (!TI.validateCpuSupports(Feature)) 3825 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3826 << Arg->getSourceRange(); 3827 return false; 3828 } 3829 3830 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3831 /// This checks that the target supports __builtin_cpu_is and 3832 /// that the string argument is constant and valid. 3833 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3834 Expr *Arg = TheCall->getArg(0); 3835 3836 // Check if the argument is a string literal. 3837 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3838 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3839 << Arg->getSourceRange(); 3840 3841 // Check the contents of the string. 3842 StringRef Feature = 3843 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3844 if (!TI.validateCpuIs(Feature)) 3845 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3846 << Arg->getSourceRange(); 3847 return false; 3848 } 3849 3850 // Check if the rounding mode is legal. 3851 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3852 // Indicates if this instruction has rounding control or just SAE. 3853 bool HasRC = false; 3854 3855 unsigned ArgNum = 0; 3856 switch (BuiltinID) { 3857 default: 3858 return false; 3859 case X86::BI__builtin_ia32_vcvttsd2si32: 3860 case X86::BI__builtin_ia32_vcvttsd2si64: 3861 case X86::BI__builtin_ia32_vcvttsd2usi32: 3862 case X86::BI__builtin_ia32_vcvttsd2usi64: 3863 case X86::BI__builtin_ia32_vcvttss2si32: 3864 case X86::BI__builtin_ia32_vcvttss2si64: 3865 case X86::BI__builtin_ia32_vcvttss2usi32: 3866 case X86::BI__builtin_ia32_vcvttss2usi64: 3867 ArgNum = 1; 3868 break; 3869 case X86::BI__builtin_ia32_maxpd512: 3870 case X86::BI__builtin_ia32_maxps512: 3871 case X86::BI__builtin_ia32_minpd512: 3872 case X86::BI__builtin_ia32_minps512: 3873 ArgNum = 2; 3874 break; 3875 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3876 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3877 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3878 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3879 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3880 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3881 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3882 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3883 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3884 case X86::BI__builtin_ia32_exp2pd_mask: 3885 case X86::BI__builtin_ia32_exp2ps_mask: 3886 case X86::BI__builtin_ia32_getexppd512_mask: 3887 case X86::BI__builtin_ia32_getexpps512_mask: 3888 case X86::BI__builtin_ia32_rcp28pd_mask: 3889 case X86::BI__builtin_ia32_rcp28ps_mask: 3890 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3891 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3892 case X86::BI__builtin_ia32_vcomisd: 3893 case X86::BI__builtin_ia32_vcomiss: 3894 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3895 ArgNum = 3; 3896 break; 3897 case X86::BI__builtin_ia32_cmppd512_mask: 3898 case X86::BI__builtin_ia32_cmpps512_mask: 3899 case X86::BI__builtin_ia32_cmpsd_mask: 3900 case X86::BI__builtin_ia32_cmpss_mask: 3901 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3902 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3903 case X86::BI__builtin_ia32_getexpss128_round_mask: 3904 case X86::BI__builtin_ia32_getmantpd512_mask: 3905 case X86::BI__builtin_ia32_getmantps512_mask: 3906 case X86::BI__builtin_ia32_maxsd_round_mask: 3907 case X86::BI__builtin_ia32_maxss_round_mask: 3908 case X86::BI__builtin_ia32_minsd_round_mask: 3909 case X86::BI__builtin_ia32_minss_round_mask: 3910 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3911 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3912 case X86::BI__builtin_ia32_reducepd512_mask: 3913 case X86::BI__builtin_ia32_reduceps512_mask: 3914 case X86::BI__builtin_ia32_rndscalepd_mask: 3915 case X86::BI__builtin_ia32_rndscaleps_mask: 3916 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3917 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3918 ArgNum = 4; 3919 break; 3920 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3921 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3922 case X86::BI__builtin_ia32_fixupimmps512_mask: 3923 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3924 case X86::BI__builtin_ia32_fixupimmsd_mask: 3925 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3926 case X86::BI__builtin_ia32_fixupimmss_mask: 3927 case X86::BI__builtin_ia32_fixupimmss_maskz: 3928 case X86::BI__builtin_ia32_getmantsd_round_mask: 3929 case X86::BI__builtin_ia32_getmantss_round_mask: 3930 case X86::BI__builtin_ia32_rangepd512_mask: 3931 case X86::BI__builtin_ia32_rangeps512_mask: 3932 case X86::BI__builtin_ia32_rangesd128_round_mask: 3933 case X86::BI__builtin_ia32_rangess128_round_mask: 3934 case X86::BI__builtin_ia32_reducesd_mask: 3935 case X86::BI__builtin_ia32_reducess_mask: 3936 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3937 case X86::BI__builtin_ia32_rndscaless_round_mask: 3938 ArgNum = 5; 3939 break; 3940 case X86::BI__builtin_ia32_vcvtsd2si64: 3941 case X86::BI__builtin_ia32_vcvtsd2si32: 3942 case X86::BI__builtin_ia32_vcvtsd2usi32: 3943 case X86::BI__builtin_ia32_vcvtsd2usi64: 3944 case X86::BI__builtin_ia32_vcvtss2si32: 3945 case X86::BI__builtin_ia32_vcvtss2si64: 3946 case X86::BI__builtin_ia32_vcvtss2usi32: 3947 case X86::BI__builtin_ia32_vcvtss2usi64: 3948 case X86::BI__builtin_ia32_sqrtpd512: 3949 case X86::BI__builtin_ia32_sqrtps512: 3950 ArgNum = 1; 3951 HasRC = true; 3952 break; 3953 case X86::BI__builtin_ia32_addpd512: 3954 case X86::BI__builtin_ia32_addps512: 3955 case X86::BI__builtin_ia32_divpd512: 3956 case X86::BI__builtin_ia32_divps512: 3957 case X86::BI__builtin_ia32_mulpd512: 3958 case X86::BI__builtin_ia32_mulps512: 3959 case X86::BI__builtin_ia32_subpd512: 3960 case X86::BI__builtin_ia32_subps512: 3961 case X86::BI__builtin_ia32_cvtsi2sd64: 3962 case X86::BI__builtin_ia32_cvtsi2ss32: 3963 case X86::BI__builtin_ia32_cvtsi2ss64: 3964 case X86::BI__builtin_ia32_cvtusi2sd64: 3965 case X86::BI__builtin_ia32_cvtusi2ss32: 3966 case X86::BI__builtin_ia32_cvtusi2ss64: 3967 ArgNum = 2; 3968 HasRC = true; 3969 break; 3970 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3971 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3972 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3973 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3974 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3975 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3976 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3977 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3978 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3979 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3980 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3981 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3982 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3983 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3984 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3985 ArgNum = 3; 3986 HasRC = true; 3987 break; 3988 case X86::BI__builtin_ia32_addss_round_mask: 3989 case X86::BI__builtin_ia32_addsd_round_mask: 3990 case X86::BI__builtin_ia32_divss_round_mask: 3991 case X86::BI__builtin_ia32_divsd_round_mask: 3992 case X86::BI__builtin_ia32_mulss_round_mask: 3993 case X86::BI__builtin_ia32_mulsd_round_mask: 3994 case X86::BI__builtin_ia32_subss_round_mask: 3995 case X86::BI__builtin_ia32_subsd_round_mask: 3996 case X86::BI__builtin_ia32_scalefpd512_mask: 3997 case X86::BI__builtin_ia32_scalefps512_mask: 3998 case X86::BI__builtin_ia32_scalefsd_round_mask: 3999 case X86::BI__builtin_ia32_scalefss_round_mask: 4000 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4001 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4002 case X86::BI__builtin_ia32_sqrtss_round_mask: 4003 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4004 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4005 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4006 case X86::BI__builtin_ia32_vfmaddss3_mask: 4007 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4008 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4009 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4010 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4011 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4012 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4013 case X86::BI__builtin_ia32_vfmaddps512_mask: 4014 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4015 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4016 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4017 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4018 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4019 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4020 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4021 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4022 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4023 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4024 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4025 ArgNum = 4; 4026 HasRC = true; 4027 break; 4028 } 4029 4030 llvm::APSInt Result; 4031 4032 // We can't check the value of a dependent argument. 4033 Expr *Arg = TheCall->getArg(ArgNum); 4034 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4035 return false; 4036 4037 // Check constant-ness first. 4038 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4039 return true; 4040 4041 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4042 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4043 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4044 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4045 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4046 Result == 8/*ROUND_NO_EXC*/ || 4047 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4048 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4049 return false; 4050 4051 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4052 << Arg->getSourceRange(); 4053 } 4054 4055 // Check if the gather/scatter scale is legal. 4056 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4057 CallExpr *TheCall) { 4058 unsigned ArgNum = 0; 4059 switch (BuiltinID) { 4060 default: 4061 return false; 4062 case X86::BI__builtin_ia32_gatherpfdpd: 4063 case X86::BI__builtin_ia32_gatherpfdps: 4064 case X86::BI__builtin_ia32_gatherpfqpd: 4065 case X86::BI__builtin_ia32_gatherpfqps: 4066 case X86::BI__builtin_ia32_scatterpfdpd: 4067 case X86::BI__builtin_ia32_scatterpfdps: 4068 case X86::BI__builtin_ia32_scatterpfqpd: 4069 case X86::BI__builtin_ia32_scatterpfqps: 4070 ArgNum = 3; 4071 break; 4072 case X86::BI__builtin_ia32_gatherd_pd: 4073 case X86::BI__builtin_ia32_gatherd_pd256: 4074 case X86::BI__builtin_ia32_gatherq_pd: 4075 case X86::BI__builtin_ia32_gatherq_pd256: 4076 case X86::BI__builtin_ia32_gatherd_ps: 4077 case X86::BI__builtin_ia32_gatherd_ps256: 4078 case X86::BI__builtin_ia32_gatherq_ps: 4079 case X86::BI__builtin_ia32_gatherq_ps256: 4080 case X86::BI__builtin_ia32_gatherd_q: 4081 case X86::BI__builtin_ia32_gatherd_q256: 4082 case X86::BI__builtin_ia32_gatherq_q: 4083 case X86::BI__builtin_ia32_gatherq_q256: 4084 case X86::BI__builtin_ia32_gatherd_d: 4085 case X86::BI__builtin_ia32_gatherd_d256: 4086 case X86::BI__builtin_ia32_gatherq_d: 4087 case X86::BI__builtin_ia32_gatherq_d256: 4088 case X86::BI__builtin_ia32_gather3div2df: 4089 case X86::BI__builtin_ia32_gather3div2di: 4090 case X86::BI__builtin_ia32_gather3div4df: 4091 case X86::BI__builtin_ia32_gather3div4di: 4092 case X86::BI__builtin_ia32_gather3div4sf: 4093 case X86::BI__builtin_ia32_gather3div4si: 4094 case X86::BI__builtin_ia32_gather3div8sf: 4095 case X86::BI__builtin_ia32_gather3div8si: 4096 case X86::BI__builtin_ia32_gather3siv2df: 4097 case X86::BI__builtin_ia32_gather3siv2di: 4098 case X86::BI__builtin_ia32_gather3siv4df: 4099 case X86::BI__builtin_ia32_gather3siv4di: 4100 case X86::BI__builtin_ia32_gather3siv4sf: 4101 case X86::BI__builtin_ia32_gather3siv4si: 4102 case X86::BI__builtin_ia32_gather3siv8sf: 4103 case X86::BI__builtin_ia32_gather3siv8si: 4104 case X86::BI__builtin_ia32_gathersiv8df: 4105 case X86::BI__builtin_ia32_gathersiv16sf: 4106 case X86::BI__builtin_ia32_gatherdiv8df: 4107 case X86::BI__builtin_ia32_gatherdiv16sf: 4108 case X86::BI__builtin_ia32_gathersiv8di: 4109 case X86::BI__builtin_ia32_gathersiv16si: 4110 case X86::BI__builtin_ia32_gatherdiv8di: 4111 case X86::BI__builtin_ia32_gatherdiv16si: 4112 case X86::BI__builtin_ia32_scatterdiv2df: 4113 case X86::BI__builtin_ia32_scatterdiv2di: 4114 case X86::BI__builtin_ia32_scatterdiv4df: 4115 case X86::BI__builtin_ia32_scatterdiv4di: 4116 case X86::BI__builtin_ia32_scatterdiv4sf: 4117 case X86::BI__builtin_ia32_scatterdiv4si: 4118 case X86::BI__builtin_ia32_scatterdiv8sf: 4119 case X86::BI__builtin_ia32_scatterdiv8si: 4120 case X86::BI__builtin_ia32_scattersiv2df: 4121 case X86::BI__builtin_ia32_scattersiv2di: 4122 case X86::BI__builtin_ia32_scattersiv4df: 4123 case X86::BI__builtin_ia32_scattersiv4di: 4124 case X86::BI__builtin_ia32_scattersiv4sf: 4125 case X86::BI__builtin_ia32_scattersiv4si: 4126 case X86::BI__builtin_ia32_scattersiv8sf: 4127 case X86::BI__builtin_ia32_scattersiv8si: 4128 case X86::BI__builtin_ia32_scattersiv8df: 4129 case X86::BI__builtin_ia32_scattersiv16sf: 4130 case X86::BI__builtin_ia32_scatterdiv8df: 4131 case X86::BI__builtin_ia32_scatterdiv16sf: 4132 case X86::BI__builtin_ia32_scattersiv8di: 4133 case X86::BI__builtin_ia32_scattersiv16si: 4134 case X86::BI__builtin_ia32_scatterdiv8di: 4135 case X86::BI__builtin_ia32_scatterdiv16si: 4136 ArgNum = 4; 4137 break; 4138 } 4139 4140 llvm::APSInt Result; 4141 4142 // We can't check the value of a dependent argument. 4143 Expr *Arg = TheCall->getArg(ArgNum); 4144 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4145 return false; 4146 4147 // Check constant-ness first. 4148 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4149 return true; 4150 4151 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4152 return false; 4153 4154 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4155 << Arg->getSourceRange(); 4156 } 4157 4158 enum { TileRegLow = 0, TileRegHigh = 7 }; 4159 4160 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4161 ArrayRef<int> ArgNums) { 4162 for (int ArgNum : ArgNums) { 4163 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4164 return true; 4165 } 4166 return false; 4167 } 4168 4169 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4170 ArrayRef<int> ArgNums) { 4171 // Because the max number of tile register is TileRegHigh + 1, so here we use 4172 // each bit to represent the usage of them in bitset. 4173 std::bitset<TileRegHigh + 1> ArgValues; 4174 for (int ArgNum : ArgNums) { 4175 Expr *Arg = TheCall->getArg(ArgNum); 4176 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4177 continue; 4178 4179 llvm::APSInt Result; 4180 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4181 return true; 4182 int ArgExtValue = Result.getExtValue(); 4183 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4184 "Incorrect tile register num."); 4185 if (ArgValues.test(ArgExtValue)) 4186 return Diag(TheCall->getBeginLoc(), 4187 diag::err_x86_builtin_tile_arg_duplicate) 4188 << TheCall->getArg(ArgNum)->getSourceRange(); 4189 ArgValues.set(ArgExtValue); 4190 } 4191 return false; 4192 } 4193 4194 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4195 ArrayRef<int> ArgNums) { 4196 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4197 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4198 } 4199 4200 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4201 switch (BuiltinID) { 4202 default: 4203 return false; 4204 case X86::BI__builtin_ia32_tileloadd64: 4205 case X86::BI__builtin_ia32_tileloaddt164: 4206 case X86::BI__builtin_ia32_tilestored64: 4207 case X86::BI__builtin_ia32_tilezero: 4208 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4209 case X86::BI__builtin_ia32_tdpbssd: 4210 case X86::BI__builtin_ia32_tdpbsud: 4211 case X86::BI__builtin_ia32_tdpbusd: 4212 case X86::BI__builtin_ia32_tdpbuud: 4213 case X86::BI__builtin_ia32_tdpbf16ps: 4214 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4215 } 4216 } 4217 static bool isX86_32Builtin(unsigned BuiltinID) { 4218 // These builtins only work on x86-32 targets. 4219 switch (BuiltinID) { 4220 case X86::BI__builtin_ia32_readeflags_u32: 4221 case X86::BI__builtin_ia32_writeeflags_u32: 4222 return true; 4223 } 4224 4225 return false; 4226 } 4227 4228 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4229 CallExpr *TheCall) { 4230 if (BuiltinID == X86::BI__builtin_cpu_supports) 4231 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4232 4233 if (BuiltinID == X86::BI__builtin_cpu_is) 4234 return SemaBuiltinCpuIs(*this, TI, TheCall); 4235 4236 // Check for 32-bit only builtins on a 64-bit target. 4237 const llvm::Triple &TT = TI.getTriple(); 4238 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4239 return Diag(TheCall->getCallee()->getBeginLoc(), 4240 diag::err_32_bit_builtin_64_bit_tgt); 4241 4242 // If the intrinsic has rounding or SAE make sure its valid. 4243 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4244 return true; 4245 4246 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4247 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4248 return true; 4249 4250 // If the intrinsic has a tile arguments, make sure they are valid. 4251 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4252 return true; 4253 4254 // For intrinsics which take an immediate value as part of the instruction, 4255 // range check them here. 4256 int i = 0, l = 0, u = 0; 4257 switch (BuiltinID) { 4258 default: 4259 return false; 4260 case X86::BI__builtin_ia32_vec_ext_v2si: 4261 case X86::BI__builtin_ia32_vec_ext_v2di: 4262 case X86::BI__builtin_ia32_vextractf128_pd256: 4263 case X86::BI__builtin_ia32_vextractf128_ps256: 4264 case X86::BI__builtin_ia32_vextractf128_si256: 4265 case X86::BI__builtin_ia32_extract128i256: 4266 case X86::BI__builtin_ia32_extractf64x4_mask: 4267 case X86::BI__builtin_ia32_extracti64x4_mask: 4268 case X86::BI__builtin_ia32_extractf32x8_mask: 4269 case X86::BI__builtin_ia32_extracti32x8_mask: 4270 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4271 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4272 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4273 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4274 i = 1; l = 0; u = 1; 4275 break; 4276 case X86::BI__builtin_ia32_vec_set_v2di: 4277 case X86::BI__builtin_ia32_vinsertf128_pd256: 4278 case X86::BI__builtin_ia32_vinsertf128_ps256: 4279 case X86::BI__builtin_ia32_vinsertf128_si256: 4280 case X86::BI__builtin_ia32_insert128i256: 4281 case X86::BI__builtin_ia32_insertf32x8: 4282 case X86::BI__builtin_ia32_inserti32x8: 4283 case X86::BI__builtin_ia32_insertf64x4: 4284 case X86::BI__builtin_ia32_inserti64x4: 4285 case X86::BI__builtin_ia32_insertf64x2_256: 4286 case X86::BI__builtin_ia32_inserti64x2_256: 4287 case X86::BI__builtin_ia32_insertf32x4_256: 4288 case X86::BI__builtin_ia32_inserti32x4_256: 4289 i = 2; l = 0; u = 1; 4290 break; 4291 case X86::BI__builtin_ia32_vpermilpd: 4292 case X86::BI__builtin_ia32_vec_ext_v4hi: 4293 case X86::BI__builtin_ia32_vec_ext_v4si: 4294 case X86::BI__builtin_ia32_vec_ext_v4sf: 4295 case X86::BI__builtin_ia32_vec_ext_v4di: 4296 case X86::BI__builtin_ia32_extractf32x4_mask: 4297 case X86::BI__builtin_ia32_extracti32x4_mask: 4298 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4299 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4300 i = 1; l = 0; u = 3; 4301 break; 4302 case X86::BI_mm_prefetch: 4303 case X86::BI__builtin_ia32_vec_ext_v8hi: 4304 case X86::BI__builtin_ia32_vec_ext_v8si: 4305 i = 1; l = 0; u = 7; 4306 break; 4307 case X86::BI__builtin_ia32_sha1rnds4: 4308 case X86::BI__builtin_ia32_blendpd: 4309 case X86::BI__builtin_ia32_shufpd: 4310 case X86::BI__builtin_ia32_vec_set_v4hi: 4311 case X86::BI__builtin_ia32_vec_set_v4si: 4312 case X86::BI__builtin_ia32_vec_set_v4di: 4313 case X86::BI__builtin_ia32_shuf_f32x4_256: 4314 case X86::BI__builtin_ia32_shuf_f64x2_256: 4315 case X86::BI__builtin_ia32_shuf_i32x4_256: 4316 case X86::BI__builtin_ia32_shuf_i64x2_256: 4317 case X86::BI__builtin_ia32_insertf64x2_512: 4318 case X86::BI__builtin_ia32_inserti64x2_512: 4319 case X86::BI__builtin_ia32_insertf32x4: 4320 case X86::BI__builtin_ia32_inserti32x4: 4321 i = 2; l = 0; u = 3; 4322 break; 4323 case X86::BI__builtin_ia32_vpermil2pd: 4324 case X86::BI__builtin_ia32_vpermil2pd256: 4325 case X86::BI__builtin_ia32_vpermil2ps: 4326 case X86::BI__builtin_ia32_vpermil2ps256: 4327 i = 3; l = 0; u = 3; 4328 break; 4329 case X86::BI__builtin_ia32_cmpb128_mask: 4330 case X86::BI__builtin_ia32_cmpw128_mask: 4331 case X86::BI__builtin_ia32_cmpd128_mask: 4332 case X86::BI__builtin_ia32_cmpq128_mask: 4333 case X86::BI__builtin_ia32_cmpb256_mask: 4334 case X86::BI__builtin_ia32_cmpw256_mask: 4335 case X86::BI__builtin_ia32_cmpd256_mask: 4336 case X86::BI__builtin_ia32_cmpq256_mask: 4337 case X86::BI__builtin_ia32_cmpb512_mask: 4338 case X86::BI__builtin_ia32_cmpw512_mask: 4339 case X86::BI__builtin_ia32_cmpd512_mask: 4340 case X86::BI__builtin_ia32_cmpq512_mask: 4341 case X86::BI__builtin_ia32_ucmpb128_mask: 4342 case X86::BI__builtin_ia32_ucmpw128_mask: 4343 case X86::BI__builtin_ia32_ucmpd128_mask: 4344 case X86::BI__builtin_ia32_ucmpq128_mask: 4345 case X86::BI__builtin_ia32_ucmpb256_mask: 4346 case X86::BI__builtin_ia32_ucmpw256_mask: 4347 case X86::BI__builtin_ia32_ucmpd256_mask: 4348 case X86::BI__builtin_ia32_ucmpq256_mask: 4349 case X86::BI__builtin_ia32_ucmpb512_mask: 4350 case X86::BI__builtin_ia32_ucmpw512_mask: 4351 case X86::BI__builtin_ia32_ucmpd512_mask: 4352 case X86::BI__builtin_ia32_ucmpq512_mask: 4353 case X86::BI__builtin_ia32_vpcomub: 4354 case X86::BI__builtin_ia32_vpcomuw: 4355 case X86::BI__builtin_ia32_vpcomud: 4356 case X86::BI__builtin_ia32_vpcomuq: 4357 case X86::BI__builtin_ia32_vpcomb: 4358 case X86::BI__builtin_ia32_vpcomw: 4359 case X86::BI__builtin_ia32_vpcomd: 4360 case X86::BI__builtin_ia32_vpcomq: 4361 case X86::BI__builtin_ia32_vec_set_v8hi: 4362 case X86::BI__builtin_ia32_vec_set_v8si: 4363 i = 2; l = 0; u = 7; 4364 break; 4365 case X86::BI__builtin_ia32_vpermilpd256: 4366 case X86::BI__builtin_ia32_roundps: 4367 case X86::BI__builtin_ia32_roundpd: 4368 case X86::BI__builtin_ia32_roundps256: 4369 case X86::BI__builtin_ia32_roundpd256: 4370 case X86::BI__builtin_ia32_getmantpd128_mask: 4371 case X86::BI__builtin_ia32_getmantpd256_mask: 4372 case X86::BI__builtin_ia32_getmantps128_mask: 4373 case X86::BI__builtin_ia32_getmantps256_mask: 4374 case X86::BI__builtin_ia32_getmantpd512_mask: 4375 case X86::BI__builtin_ia32_getmantps512_mask: 4376 case X86::BI__builtin_ia32_vec_ext_v16qi: 4377 case X86::BI__builtin_ia32_vec_ext_v16hi: 4378 i = 1; l = 0; u = 15; 4379 break; 4380 case X86::BI__builtin_ia32_pblendd128: 4381 case X86::BI__builtin_ia32_blendps: 4382 case X86::BI__builtin_ia32_blendpd256: 4383 case X86::BI__builtin_ia32_shufpd256: 4384 case X86::BI__builtin_ia32_roundss: 4385 case X86::BI__builtin_ia32_roundsd: 4386 case X86::BI__builtin_ia32_rangepd128_mask: 4387 case X86::BI__builtin_ia32_rangepd256_mask: 4388 case X86::BI__builtin_ia32_rangepd512_mask: 4389 case X86::BI__builtin_ia32_rangeps128_mask: 4390 case X86::BI__builtin_ia32_rangeps256_mask: 4391 case X86::BI__builtin_ia32_rangeps512_mask: 4392 case X86::BI__builtin_ia32_getmantsd_round_mask: 4393 case X86::BI__builtin_ia32_getmantss_round_mask: 4394 case X86::BI__builtin_ia32_vec_set_v16qi: 4395 case X86::BI__builtin_ia32_vec_set_v16hi: 4396 i = 2; l = 0; u = 15; 4397 break; 4398 case X86::BI__builtin_ia32_vec_ext_v32qi: 4399 i = 1; l = 0; u = 31; 4400 break; 4401 case X86::BI__builtin_ia32_cmpps: 4402 case X86::BI__builtin_ia32_cmpss: 4403 case X86::BI__builtin_ia32_cmppd: 4404 case X86::BI__builtin_ia32_cmpsd: 4405 case X86::BI__builtin_ia32_cmpps256: 4406 case X86::BI__builtin_ia32_cmppd256: 4407 case X86::BI__builtin_ia32_cmpps128_mask: 4408 case X86::BI__builtin_ia32_cmppd128_mask: 4409 case X86::BI__builtin_ia32_cmpps256_mask: 4410 case X86::BI__builtin_ia32_cmppd256_mask: 4411 case X86::BI__builtin_ia32_cmpps512_mask: 4412 case X86::BI__builtin_ia32_cmppd512_mask: 4413 case X86::BI__builtin_ia32_cmpsd_mask: 4414 case X86::BI__builtin_ia32_cmpss_mask: 4415 case X86::BI__builtin_ia32_vec_set_v32qi: 4416 i = 2; l = 0; u = 31; 4417 break; 4418 case X86::BI__builtin_ia32_permdf256: 4419 case X86::BI__builtin_ia32_permdi256: 4420 case X86::BI__builtin_ia32_permdf512: 4421 case X86::BI__builtin_ia32_permdi512: 4422 case X86::BI__builtin_ia32_vpermilps: 4423 case X86::BI__builtin_ia32_vpermilps256: 4424 case X86::BI__builtin_ia32_vpermilpd512: 4425 case X86::BI__builtin_ia32_vpermilps512: 4426 case X86::BI__builtin_ia32_pshufd: 4427 case X86::BI__builtin_ia32_pshufd256: 4428 case X86::BI__builtin_ia32_pshufd512: 4429 case X86::BI__builtin_ia32_pshufhw: 4430 case X86::BI__builtin_ia32_pshufhw256: 4431 case X86::BI__builtin_ia32_pshufhw512: 4432 case X86::BI__builtin_ia32_pshuflw: 4433 case X86::BI__builtin_ia32_pshuflw256: 4434 case X86::BI__builtin_ia32_pshuflw512: 4435 case X86::BI__builtin_ia32_vcvtps2ph: 4436 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4437 case X86::BI__builtin_ia32_vcvtps2ph256: 4438 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4439 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4440 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4441 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4442 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4443 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4444 case X86::BI__builtin_ia32_rndscaleps_mask: 4445 case X86::BI__builtin_ia32_rndscalepd_mask: 4446 case X86::BI__builtin_ia32_reducepd128_mask: 4447 case X86::BI__builtin_ia32_reducepd256_mask: 4448 case X86::BI__builtin_ia32_reducepd512_mask: 4449 case X86::BI__builtin_ia32_reduceps128_mask: 4450 case X86::BI__builtin_ia32_reduceps256_mask: 4451 case X86::BI__builtin_ia32_reduceps512_mask: 4452 case X86::BI__builtin_ia32_prold512: 4453 case X86::BI__builtin_ia32_prolq512: 4454 case X86::BI__builtin_ia32_prold128: 4455 case X86::BI__builtin_ia32_prold256: 4456 case X86::BI__builtin_ia32_prolq128: 4457 case X86::BI__builtin_ia32_prolq256: 4458 case X86::BI__builtin_ia32_prord512: 4459 case X86::BI__builtin_ia32_prorq512: 4460 case X86::BI__builtin_ia32_prord128: 4461 case X86::BI__builtin_ia32_prord256: 4462 case X86::BI__builtin_ia32_prorq128: 4463 case X86::BI__builtin_ia32_prorq256: 4464 case X86::BI__builtin_ia32_fpclasspd128_mask: 4465 case X86::BI__builtin_ia32_fpclasspd256_mask: 4466 case X86::BI__builtin_ia32_fpclassps128_mask: 4467 case X86::BI__builtin_ia32_fpclassps256_mask: 4468 case X86::BI__builtin_ia32_fpclassps512_mask: 4469 case X86::BI__builtin_ia32_fpclasspd512_mask: 4470 case X86::BI__builtin_ia32_fpclasssd_mask: 4471 case X86::BI__builtin_ia32_fpclassss_mask: 4472 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4473 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4474 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4475 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4476 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4477 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4478 case X86::BI__builtin_ia32_kshiftliqi: 4479 case X86::BI__builtin_ia32_kshiftlihi: 4480 case X86::BI__builtin_ia32_kshiftlisi: 4481 case X86::BI__builtin_ia32_kshiftlidi: 4482 case X86::BI__builtin_ia32_kshiftriqi: 4483 case X86::BI__builtin_ia32_kshiftrihi: 4484 case X86::BI__builtin_ia32_kshiftrisi: 4485 case X86::BI__builtin_ia32_kshiftridi: 4486 i = 1; l = 0; u = 255; 4487 break; 4488 case X86::BI__builtin_ia32_vperm2f128_pd256: 4489 case X86::BI__builtin_ia32_vperm2f128_ps256: 4490 case X86::BI__builtin_ia32_vperm2f128_si256: 4491 case X86::BI__builtin_ia32_permti256: 4492 case X86::BI__builtin_ia32_pblendw128: 4493 case X86::BI__builtin_ia32_pblendw256: 4494 case X86::BI__builtin_ia32_blendps256: 4495 case X86::BI__builtin_ia32_pblendd256: 4496 case X86::BI__builtin_ia32_palignr128: 4497 case X86::BI__builtin_ia32_palignr256: 4498 case X86::BI__builtin_ia32_palignr512: 4499 case X86::BI__builtin_ia32_alignq512: 4500 case X86::BI__builtin_ia32_alignd512: 4501 case X86::BI__builtin_ia32_alignd128: 4502 case X86::BI__builtin_ia32_alignd256: 4503 case X86::BI__builtin_ia32_alignq128: 4504 case X86::BI__builtin_ia32_alignq256: 4505 case X86::BI__builtin_ia32_vcomisd: 4506 case X86::BI__builtin_ia32_vcomiss: 4507 case X86::BI__builtin_ia32_shuf_f32x4: 4508 case X86::BI__builtin_ia32_shuf_f64x2: 4509 case X86::BI__builtin_ia32_shuf_i32x4: 4510 case X86::BI__builtin_ia32_shuf_i64x2: 4511 case X86::BI__builtin_ia32_shufpd512: 4512 case X86::BI__builtin_ia32_shufps: 4513 case X86::BI__builtin_ia32_shufps256: 4514 case X86::BI__builtin_ia32_shufps512: 4515 case X86::BI__builtin_ia32_dbpsadbw128: 4516 case X86::BI__builtin_ia32_dbpsadbw256: 4517 case X86::BI__builtin_ia32_dbpsadbw512: 4518 case X86::BI__builtin_ia32_vpshldd128: 4519 case X86::BI__builtin_ia32_vpshldd256: 4520 case X86::BI__builtin_ia32_vpshldd512: 4521 case X86::BI__builtin_ia32_vpshldq128: 4522 case X86::BI__builtin_ia32_vpshldq256: 4523 case X86::BI__builtin_ia32_vpshldq512: 4524 case X86::BI__builtin_ia32_vpshldw128: 4525 case X86::BI__builtin_ia32_vpshldw256: 4526 case X86::BI__builtin_ia32_vpshldw512: 4527 case X86::BI__builtin_ia32_vpshrdd128: 4528 case X86::BI__builtin_ia32_vpshrdd256: 4529 case X86::BI__builtin_ia32_vpshrdd512: 4530 case X86::BI__builtin_ia32_vpshrdq128: 4531 case X86::BI__builtin_ia32_vpshrdq256: 4532 case X86::BI__builtin_ia32_vpshrdq512: 4533 case X86::BI__builtin_ia32_vpshrdw128: 4534 case X86::BI__builtin_ia32_vpshrdw256: 4535 case X86::BI__builtin_ia32_vpshrdw512: 4536 i = 2; l = 0; u = 255; 4537 break; 4538 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4539 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4540 case X86::BI__builtin_ia32_fixupimmps512_mask: 4541 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4542 case X86::BI__builtin_ia32_fixupimmsd_mask: 4543 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4544 case X86::BI__builtin_ia32_fixupimmss_mask: 4545 case X86::BI__builtin_ia32_fixupimmss_maskz: 4546 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4547 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4548 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4549 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4550 case X86::BI__builtin_ia32_fixupimmps128_mask: 4551 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4552 case X86::BI__builtin_ia32_fixupimmps256_mask: 4553 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4554 case X86::BI__builtin_ia32_pternlogd512_mask: 4555 case X86::BI__builtin_ia32_pternlogd512_maskz: 4556 case X86::BI__builtin_ia32_pternlogq512_mask: 4557 case X86::BI__builtin_ia32_pternlogq512_maskz: 4558 case X86::BI__builtin_ia32_pternlogd128_mask: 4559 case X86::BI__builtin_ia32_pternlogd128_maskz: 4560 case X86::BI__builtin_ia32_pternlogd256_mask: 4561 case X86::BI__builtin_ia32_pternlogd256_maskz: 4562 case X86::BI__builtin_ia32_pternlogq128_mask: 4563 case X86::BI__builtin_ia32_pternlogq128_maskz: 4564 case X86::BI__builtin_ia32_pternlogq256_mask: 4565 case X86::BI__builtin_ia32_pternlogq256_maskz: 4566 i = 3; l = 0; u = 255; 4567 break; 4568 case X86::BI__builtin_ia32_gatherpfdpd: 4569 case X86::BI__builtin_ia32_gatherpfdps: 4570 case X86::BI__builtin_ia32_gatherpfqpd: 4571 case X86::BI__builtin_ia32_gatherpfqps: 4572 case X86::BI__builtin_ia32_scatterpfdpd: 4573 case X86::BI__builtin_ia32_scatterpfdps: 4574 case X86::BI__builtin_ia32_scatterpfqpd: 4575 case X86::BI__builtin_ia32_scatterpfqps: 4576 i = 4; l = 2; u = 3; 4577 break; 4578 case X86::BI__builtin_ia32_reducesd_mask: 4579 case X86::BI__builtin_ia32_reducess_mask: 4580 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4581 case X86::BI__builtin_ia32_rndscaless_round_mask: 4582 i = 4; l = 0; u = 255; 4583 break; 4584 } 4585 4586 // Note that we don't force a hard error on the range check here, allowing 4587 // template-generated or macro-generated dead code to potentially have out-of- 4588 // range values. These need to code generate, but don't need to necessarily 4589 // make any sense. We use a warning that defaults to an error. 4590 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4591 } 4592 4593 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4594 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4595 /// Returns true when the format fits the function and the FormatStringInfo has 4596 /// been populated. 4597 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4598 FormatStringInfo *FSI) { 4599 FSI->HasVAListArg = Format->getFirstArg() == 0; 4600 FSI->FormatIdx = Format->getFormatIdx() - 1; 4601 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4602 4603 // The way the format attribute works in GCC, the implicit this argument 4604 // of member functions is counted. However, it doesn't appear in our own 4605 // lists, so decrement format_idx in that case. 4606 if (IsCXXMember) { 4607 if(FSI->FormatIdx == 0) 4608 return false; 4609 --FSI->FormatIdx; 4610 if (FSI->FirstDataArg != 0) 4611 --FSI->FirstDataArg; 4612 } 4613 return true; 4614 } 4615 4616 /// Checks if a the given expression evaluates to null. 4617 /// 4618 /// Returns true if the value evaluates to null. 4619 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4620 // If the expression has non-null type, it doesn't evaluate to null. 4621 if (auto nullability 4622 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4623 if (*nullability == NullabilityKind::NonNull) 4624 return false; 4625 } 4626 4627 // As a special case, transparent unions initialized with zero are 4628 // considered null for the purposes of the nonnull attribute. 4629 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4630 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4631 if (const CompoundLiteralExpr *CLE = 4632 dyn_cast<CompoundLiteralExpr>(Expr)) 4633 if (const InitListExpr *ILE = 4634 dyn_cast<InitListExpr>(CLE->getInitializer())) 4635 Expr = ILE->getInit(0); 4636 } 4637 4638 bool Result; 4639 return (!Expr->isValueDependent() && 4640 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4641 !Result); 4642 } 4643 4644 static void CheckNonNullArgument(Sema &S, 4645 const Expr *ArgExpr, 4646 SourceLocation CallSiteLoc) { 4647 if (CheckNonNullExpr(S, ArgExpr)) 4648 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4649 S.PDiag(diag::warn_null_arg) 4650 << ArgExpr->getSourceRange()); 4651 } 4652 4653 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4654 FormatStringInfo FSI; 4655 if ((GetFormatStringType(Format) == FST_NSString) && 4656 getFormatStringInfo(Format, false, &FSI)) { 4657 Idx = FSI.FormatIdx; 4658 return true; 4659 } 4660 return false; 4661 } 4662 4663 /// Diagnose use of %s directive in an NSString which is being passed 4664 /// as formatting string to formatting method. 4665 static void 4666 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4667 const NamedDecl *FDecl, 4668 Expr **Args, 4669 unsigned NumArgs) { 4670 unsigned Idx = 0; 4671 bool Format = false; 4672 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4673 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4674 Idx = 2; 4675 Format = true; 4676 } 4677 else 4678 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4679 if (S.GetFormatNSStringIdx(I, Idx)) { 4680 Format = true; 4681 break; 4682 } 4683 } 4684 if (!Format || NumArgs <= Idx) 4685 return; 4686 const Expr *FormatExpr = Args[Idx]; 4687 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4688 FormatExpr = CSCE->getSubExpr(); 4689 const StringLiteral *FormatString; 4690 if (const ObjCStringLiteral *OSL = 4691 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4692 FormatString = OSL->getString(); 4693 else 4694 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4695 if (!FormatString) 4696 return; 4697 if (S.FormatStringHasSArg(FormatString)) { 4698 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4699 << "%s" << 1 << 1; 4700 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4701 << FDecl->getDeclName(); 4702 } 4703 } 4704 4705 /// Determine whether the given type has a non-null nullability annotation. 4706 static bool isNonNullType(ASTContext &ctx, QualType type) { 4707 if (auto nullability = type->getNullability(ctx)) 4708 return *nullability == NullabilityKind::NonNull; 4709 4710 return false; 4711 } 4712 4713 static void CheckNonNullArguments(Sema &S, 4714 const NamedDecl *FDecl, 4715 const FunctionProtoType *Proto, 4716 ArrayRef<const Expr *> Args, 4717 SourceLocation CallSiteLoc) { 4718 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4719 4720 // Already checked by by constant evaluator. 4721 if (S.isConstantEvaluated()) 4722 return; 4723 // Check the attributes attached to the method/function itself. 4724 llvm::SmallBitVector NonNullArgs; 4725 if (FDecl) { 4726 // Handle the nonnull attribute on the function/method declaration itself. 4727 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4728 if (!NonNull->args_size()) { 4729 // Easy case: all pointer arguments are nonnull. 4730 for (const auto *Arg : Args) 4731 if (S.isValidPointerAttrType(Arg->getType())) 4732 CheckNonNullArgument(S, Arg, CallSiteLoc); 4733 return; 4734 } 4735 4736 for (const ParamIdx &Idx : NonNull->args()) { 4737 unsigned IdxAST = Idx.getASTIndex(); 4738 if (IdxAST >= Args.size()) 4739 continue; 4740 if (NonNullArgs.empty()) 4741 NonNullArgs.resize(Args.size()); 4742 NonNullArgs.set(IdxAST); 4743 } 4744 } 4745 } 4746 4747 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4748 // Handle the nonnull attribute on the parameters of the 4749 // function/method. 4750 ArrayRef<ParmVarDecl*> parms; 4751 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4752 parms = FD->parameters(); 4753 else 4754 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4755 4756 unsigned ParamIndex = 0; 4757 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4758 I != E; ++I, ++ParamIndex) { 4759 const ParmVarDecl *PVD = *I; 4760 if (PVD->hasAttr<NonNullAttr>() || 4761 isNonNullType(S.Context, PVD->getType())) { 4762 if (NonNullArgs.empty()) 4763 NonNullArgs.resize(Args.size()); 4764 4765 NonNullArgs.set(ParamIndex); 4766 } 4767 } 4768 } else { 4769 // If we have a non-function, non-method declaration but no 4770 // function prototype, try to dig out the function prototype. 4771 if (!Proto) { 4772 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4773 QualType type = VD->getType().getNonReferenceType(); 4774 if (auto pointerType = type->getAs<PointerType>()) 4775 type = pointerType->getPointeeType(); 4776 else if (auto blockType = type->getAs<BlockPointerType>()) 4777 type = blockType->getPointeeType(); 4778 // FIXME: data member pointers? 4779 4780 // Dig out the function prototype, if there is one. 4781 Proto = type->getAs<FunctionProtoType>(); 4782 } 4783 } 4784 4785 // Fill in non-null argument information from the nullability 4786 // information on the parameter types (if we have them). 4787 if (Proto) { 4788 unsigned Index = 0; 4789 for (auto paramType : Proto->getParamTypes()) { 4790 if (isNonNullType(S.Context, paramType)) { 4791 if (NonNullArgs.empty()) 4792 NonNullArgs.resize(Args.size()); 4793 4794 NonNullArgs.set(Index); 4795 } 4796 4797 ++Index; 4798 } 4799 } 4800 } 4801 4802 // Check for non-null arguments. 4803 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4804 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4805 if (NonNullArgs[ArgIndex]) 4806 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4807 } 4808 } 4809 4810 /// Warn if a pointer or reference argument passed to a function points to an 4811 /// object that is less aligned than the parameter. This can happen when 4812 /// creating a typedef with a lower alignment than the original type and then 4813 /// calling functions defined in terms of the original type. 4814 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4815 StringRef ParamName, QualType ArgTy, 4816 QualType ParamTy) { 4817 4818 // If a function accepts a pointer or reference type 4819 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4820 return; 4821 4822 // If the parameter is a pointer type, get the pointee type for the 4823 // argument too. If the parameter is a reference type, don't try to get 4824 // the pointee type for the argument. 4825 if (ParamTy->isPointerType()) 4826 ArgTy = ArgTy->getPointeeType(); 4827 4828 // Remove reference or pointer 4829 ParamTy = ParamTy->getPointeeType(); 4830 4831 // Find expected alignment, and the actual alignment of the passed object. 4832 // getTypeAlignInChars requires complete types 4833 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4834 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4835 ArgTy->isUndeducedType()) 4836 return; 4837 4838 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4839 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4840 4841 // If the argument is less aligned than the parameter, there is a 4842 // potential alignment issue. 4843 if (ArgAlign < ParamAlign) 4844 Diag(Loc, diag::warn_param_mismatched_alignment) 4845 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4846 << ParamName << FDecl; 4847 } 4848 4849 /// Handles the checks for format strings, non-POD arguments to vararg 4850 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4851 /// attributes. 4852 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4853 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4854 bool IsMemberFunction, SourceLocation Loc, 4855 SourceRange Range, VariadicCallType CallType) { 4856 // FIXME: We should check as much as we can in the template definition. 4857 if (CurContext->isDependentContext()) 4858 return; 4859 4860 // Printf and scanf checking. 4861 llvm::SmallBitVector CheckedVarArgs; 4862 if (FDecl) { 4863 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4864 // Only create vector if there are format attributes. 4865 CheckedVarArgs.resize(Args.size()); 4866 4867 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4868 CheckedVarArgs); 4869 } 4870 } 4871 4872 // Refuse POD arguments that weren't caught by the format string 4873 // checks above. 4874 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4875 if (CallType != VariadicDoesNotApply && 4876 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4877 unsigned NumParams = Proto ? Proto->getNumParams() 4878 : FDecl && isa<FunctionDecl>(FDecl) 4879 ? cast<FunctionDecl>(FDecl)->getNumParams() 4880 : FDecl && isa<ObjCMethodDecl>(FDecl) 4881 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4882 : 0; 4883 4884 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4885 // Args[ArgIdx] can be null in malformed code. 4886 if (const Expr *Arg = Args[ArgIdx]) { 4887 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4888 checkVariadicArgument(Arg, CallType); 4889 } 4890 } 4891 } 4892 4893 if (FDecl || Proto) { 4894 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4895 4896 // Type safety checking. 4897 if (FDecl) { 4898 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4899 CheckArgumentWithTypeTag(I, Args, Loc); 4900 } 4901 } 4902 4903 // Check that passed arguments match the alignment of original arguments. 4904 // Try to get the missing prototype from the declaration. 4905 if (!Proto && FDecl) { 4906 const auto *FT = FDecl->getFunctionType(); 4907 if (isa_and_nonnull<FunctionProtoType>(FT)) 4908 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4909 } 4910 if (Proto) { 4911 // For variadic functions, we may have more args than parameters. 4912 // For some K&R functions, we may have less args than parameters. 4913 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4914 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4915 // Args[ArgIdx] can be null in malformed code. 4916 if (const Expr *Arg = Args[ArgIdx]) { 4917 if (Arg->containsErrors()) 4918 continue; 4919 4920 QualType ParamTy = Proto->getParamType(ArgIdx); 4921 QualType ArgTy = Arg->getType(); 4922 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4923 ArgTy, ParamTy); 4924 } 4925 } 4926 } 4927 4928 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4929 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4930 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4931 if (!Arg->isValueDependent()) { 4932 Expr::EvalResult Align; 4933 if (Arg->EvaluateAsInt(Align, Context)) { 4934 const llvm::APSInt &I = Align.Val.getInt(); 4935 if (!I.isPowerOf2()) 4936 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4937 << Arg->getSourceRange(); 4938 4939 if (I > Sema::MaximumAlignment) 4940 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4941 << Arg->getSourceRange() << Sema::MaximumAlignment; 4942 } 4943 } 4944 } 4945 4946 if (FD) 4947 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4948 } 4949 4950 /// CheckConstructorCall - Check a constructor call for correctness and safety 4951 /// properties not enforced by the C type system. 4952 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4953 ArrayRef<const Expr *> Args, 4954 const FunctionProtoType *Proto, 4955 SourceLocation Loc) { 4956 VariadicCallType CallType = 4957 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4958 4959 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4960 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4961 Context.getPointerType(Ctor->getThisObjectType())); 4962 4963 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4964 Loc, SourceRange(), CallType); 4965 } 4966 4967 /// CheckFunctionCall - Check a direct function call for various correctness 4968 /// and safety properties not strictly enforced by the C type system. 4969 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4970 const FunctionProtoType *Proto) { 4971 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4972 isa<CXXMethodDecl>(FDecl); 4973 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4974 IsMemberOperatorCall; 4975 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4976 TheCall->getCallee()); 4977 Expr** Args = TheCall->getArgs(); 4978 unsigned NumArgs = TheCall->getNumArgs(); 4979 4980 Expr *ImplicitThis = nullptr; 4981 if (IsMemberOperatorCall) { 4982 // If this is a call to a member operator, hide the first argument 4983 // from checkCall. 4984 // FIXME: Our choice of AST representation here is less than ideal. 4985 ImplicitThis = Args[0]; 4986 ++Args; 4987 --NumArgs; 4988 } else if (IsMemberFunction) 4989 ImplicitThis = 4990 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4991 4992 if (ImplicitThis) { 4993 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4994 // used. 4995 QualType ThisType = ImplicitThis->getType(); 4996 if (!ThisType->isPointerType()) { 4997 assert(!ThisType->isReferenceType()); 4998 ThisType = Context.getPointerType(ThisType); 4999 } 5000 5001 QualType ThisTypeFromDecl = 5002 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5003 5004 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5005 ThisTypeFromDecl); 5006 } 5007 5008 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5009 IsMemberFunction, TheCall->getRParenLoc(), 5010 TheCall->getCallee()->getSourceRange(), CallType); 5011 5012 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5013 // None of the checks below are needed for functions that don't have 5014 // simple names (e.g., C++ conversion functions). 5015 if (!FnInfo) 5016 return false; 5017 5018 CheckTCBEnforcement(TheCall, FDecl); 5019 5020 CheckAbsoluteValueFunction(TheCall, FDecl); 5021 CheckMaxUnsignedZero(TheCall, FDecl); 5022 5023 if (getLangOpts().ObjC) 5024 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5025 5026 unsigned CMId = FDecl->getMemoryFunctionKind(); 5027 5028 // Handle memory setting and copying functions. 5029 switch (CMId) { 5030 case 0: 5031 return false; 5032 case Builtin::BIstrlcpy: // fallthrough 5033 case Builtin::BIstrlcat: 5034 CheckStrlcpycatArguments(TheCall, FnInfo); 5035 break; 5036 case Builtin::BIstrncat: 5037 CheckStrncatArguments(TheCall, FnInfo); 5038 break; 5039 case Builtin::BIfree: 5040 CheckFreeArguments(TheCall); 5041 break; 5042 default: 5043 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5044 } 5045 5046 return false; 5047 } 5048 5049 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5050 ArrayRef<const Expr *> Args) { 5051 VariadicCallType CallType = 5052 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5053 5054 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5055 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5056 CallType); 5057 5058 return false; 5059 } 5060 5061 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5062 const FunctionProtoType *Proto) { 5063 QualType Ty; 5064 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5065 Ty = V->getType().getNonReferenceType(); 5066 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5067 Ty = F->getType().getNonReferenceType(); 5068 else 5069 return false; 5070 5071 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5072 !Ty->isFunctionProtoType()) 5073 return false; 5074 5075 VariadicCallType CallType; 5076 if (!Proto || !Proto->isVariadic()) { 5077 CallType = VariadicDoesNotApply; 5078 } else if (Ty->isBlockPointerType()) { 5079 CallType = VariadicBlock; 5080 } else { // Ty->isFunctionPointerType() 5081 CallType = VariadicFunction; 5082 } 5083 5084 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5085 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5086 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5087 TheCall->getCallee()->getSourceRange(), CallType); 5088 5089 return false; 5090 } 5091 5092 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5093 /// such as function pointers returned from functions. 5094 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5095 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5096 TheCall->getCallee()); 5097 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5098 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5099 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5100 TheCall->getCallee()->getSourceRange(), CallType); 5101 5102 return false; 5103 } 5104 5105 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5106 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5107 return false; 5108 5109 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5110 switch (Op) { 5111 case AtomicExpr::AO__c11_atomic_init: 5112 case AtomicExpr::AO__opencl_atomic_init: 5113 llvm_unreachable("There is no ordering argument for an init"); 5114 5115 case AtomicExpr::AO__c11_atomic_load: 5116 case AtomicExpr::AO__opencl_atomic_load: 5117 case AtomicExpr::AO__atomic_load_n: 5118 case AtomicExpr::AO__atomic_load: 5119 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5120 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5121 5122 case AtomicExpr::AO__c11_atomic_store: 5123 case AtomicExpr::AO__opencl_atomic_store: 5124 case AtomicExpr::AO__atomic_store: 5125 case AtomicExpr::AO__atomic_store_n: 5126 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5127 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5128 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5129 5130 default: 5131 return true; 5132 } 5133 } 5134 5135 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5136 AtomicExpr::AtomicOp Op) { 5137 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5138 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5139 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5140 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5141 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5142 Op); 5143 } 5144 5145 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5146 SourceLocation RParenLoc, MultiExprArg Args, 5147 AtomicExpr::AtomicOp Op, 5148 AtomicArgumentOrder ArgOrder) { 5149 // All the non-OpenCL operations take one of the following forms. 5150 // The OpenCL operations take the __c11 forms with one extra argument for 5151 // synchronization scope. 5152 enum { 5153 // C __c11_atomic_init(A *, C) 5154 Init, 5155 5156 // C __c11_atomic_load(A *, int) 5157 Load, 5158 5159 // void __atomic_load(A *, CP, int) 5160 LoadCopy, 5161 5162 // void __atomic_store(A *, CP, int) 5163 Copy, 5164 5165 // C __c11_atomic_add(A *, M, int) 5166 Arithmetic, 5167 5168 // C __atomic_exchange_n(A *, CP, int) 5169 Xchg, 5170 5171 // void __atomic_exchange(A *, C *, CP, int) 5172 GNUXchg, 5173 5174 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5175 C11CmpXchg, 5176 5177 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5178 GNUCmpXchg 5179 } Form = Init; 5180 5181 const unsigned NumForm = GNUCmpXchg + 1; 5182 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5183 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5184 // where: 5185 // C is an appropriate type, 5186 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5187 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5188 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5189 // the int parameters are for orderings. 5190 5191 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5192 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5193 "need to update code for modified forms"); 5194 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5195 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5196 AtomicExpr::AO__atomic_load, 5197 "need to update code for modified C11 atomics"); 5198 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5199 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5200 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5201 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5202 IsOpenCL; 5203 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5204 Op == AtomicExpr::AO__atomic_store_n || 5205 Op == AtomicExpr::AO__atomic_exchange_n || 5206 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5207 bool IsAddSub = false; 5208 5209 switch (Op) { 5210 case AtomicExpr::AO__c11_atomic_init: 5211 case AtomicExpr::AO__opencl_atomic_init: 5212 Form = Init; 5213 break; 5214 5215 case AtomicExpr::AO__c11_atomic_load: 5216 case AtomicExpr::AO__opencl_atomic_load: 5217 case AtomicExpr::AO__atomic_load_n: 5218 Form = Load; 5219 break; 5220 5221 case AtomicExpr::AO__atomic_load: 5222 Form = LoadCopy; 5223 break; 5224 5225 case AtomicExpr::AO__c11_atomic_store: 5226 case AtomicExpr::AO__opencl_atomic_store: 5227 case AtomicExpr::AO__atomic_store: 5228 case AtomicExpr::AO__atomic_store_n: 5229 Form = Copy; 5230 break; 5231 5232 case AtomicExpr::AO__c11_atomic_fetch_add: 5233 case AtomicExpr::AO__c11_atomic_fetch_sub: 5234 case AtomicExpr::AO__opencl_atomic_fetch_add: 5235 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5236 case AtomicExpr::AO__atomic_fetch_add: 5237 case AtomicExpr::AO__atomic_fetch_sub: 5238 case AtomicExpr::AO__atomic_add_fetch: 5239 case AtomicExpr::AO__atomic_sub_fetch: 5240 IsAddSub = true; 5241 Form = Arithmetic; 5242 break; 5243 case AtomicExpr::AO__c11_atomic_fetch_and: 5244 case AtomicExpr::AO__c11_atomic_fetch_or: 5245 case AtomicExpr::AO__c11_atomic_fetch_xor: 5246 case AtomicExpr::AO__opencl_atomic_fetch_and: 5247 case AtomicExpr::AO__opencl_atomic_fetch_or: 5248 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5249 case AtomicExpr::AO__atomic_fetch_and: 5250 case AtomicExpr::AO__atomic_fetch_or: 5251 case AtomicExpr::AO__atomic_fetch_xor: 5252 case AtomicExpr::AO__atomic_fetch_nand: 5253 case AtomicExpr::AO__atomic_and_fetch: 5254 case AtomicExpr::AO__atomic_or_fetch: 5255 case AtomicExpr::AO__atomic_xor_fetch: 5256 case AtomicExpr::AO__atomic_nand_fetch: 5257 Form = Arithmetic; 5258 break; 5259 case AtomicExpr::AO__c11_atomic_fetch_min: 5260 case AtomicExpr::AO__c11_atomic_fetch_max: 5261 case AtomicExpr::AO__opencl_atomic_fetch_min: 5262 case AtomicExpr::AO__opencl_atomic_fetch_max: 5263 case AtomicExpr::AO__atomic_min_fetch: 5264 case AtomicExpr::AO__atomic_max_fetch: 5265 case AtomicExpr::AO__atomic_fetch_min: 5266 case AtomicExpr::AO__atomic_fetch_max: 5267 Form = Arithmetic; 5268 break; 5269 5270 case AtomicExpr::AO__c11_atomic_exchange: 5271 case AtomicExpr::AO__opencl_atomic_exchange: 5272 case AtomicExpr::AO__atomic_exchange_n: 5273 Form = Xchg; 5274 break; 5275 5276 case AtomicExpr::AO__atomic_exchange: 5277 Form = GNUXchg; 5278 break; 5279 5280 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5281 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5282 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5283 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5284 Form = C11CmpXchg; 5285 break; 5286 5287 case AtomicExpr::AO__atomic_compare_exchange: 5288 case AtomicExpr::AO__atomic_compare_exchange_n: 5289 Form = GNUCmpXchg; 5290 break; 5291 } 5292 5293 unsigned AdjustedNumArgs = NumArgs[Form]; 5294 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5295 ++AdjustedNumArgs; 5296 // Check we have the right number of arguments. 5297 if (Args.size() < AdjustedNumArgs) { 5298 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5299 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5300 << ExprRange; 5301 return ExprError(); 5302 } else if (Args.size() > AdjustedNumArgs) { 5303 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5304 diag::err_typecheck_call_too_many_args) 5305 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5306 << ExprRange; 5307 return ExprError(); 5308 } 5309 5310 // Inspect the first argument of the atomic operation. 5311 Expr *Ptr = Args[0]; 5312 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5313 if (ConvertedPtr.isInvalid()) 5314 return ExprError(); 5315 5316 Ptr = ConvertedPtr.get(); 5317 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5318 if (!pointerType) { 5319 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5320 << Ptr->getType() << Ptr->getSourceRange(); 5321 return ExprError(); 5322 } 5323 5324 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5325 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5326 QualType ValType = AtomTy; // 'C' 5327 if (IsC11) { 5328 if (!AtomTy->isAtomicType()) { 5329 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5330 << Ptr->getType() << Ptr->getSourceRange(); 5331 return ExprError(); 5332 } 5333 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5334 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5335 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5336 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5337 << Ptr->getSourceRange(); 5338 return ExprError(); 5339 } 5340 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5341 } else if (Form != Load && Form != LoadCopy) { 5342 if (ValType.isConstQualified()) { 5343 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5344 << Ptr->getType() << Ptr->getSourceRange(); 5345 return ExprError(); 5346 } 5347 } 5348 5349 // For an arithmetic operation, the implied arithmetic must be well-formed. 5350 if (Form == Arithmetic) { 5351 // gcc does not enforce these rules for GNU atomics, but we do so for 5352 // sanity. 5353 auto IsAllowedValueType = [&](QualType ValType) { 5354 if (ValType->isIntegerType()) 5355 return true; 5356 if (ValType->isPointerType()) 5357 return true; 5358 if (!ValType->isFloatingType()) 5359 return false; 5360 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5361 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5362 &Context.getTargetInfo().getLongDoubleFormat() == 5363 &llvm::APFloat::x87DoubleExtended()) 5364 return false; 5365 return true; 5366 }; 5367 if (IsAddSub && !IsAllowedValueType(ValType)) { 5368 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5369 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5370 return ExprError(); 5371 } 5372 if (!IsAddSub && !ValType->isIntegerType()) { 5373 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5374 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5375 return ExprError(); 5376 } 5377 if (IsC11 && ValType->isPointerType() && 5378 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5379 diag::err_incomplete_type)) { 5380 return ExprError(); 5381 } 5382 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5383 // For __atomic_*_n operations, the value type must be a scalar integral or 5384 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5385 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5386 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5387 return ExprError(); 5388 } 5389 5390 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5391 !AtomTy->isScalarType()) { 5392 // For GNU atomics, require a trivially-copyable type. This is not part of 5393 // the GNU atomics specification, but we enforce it for sanity. 5394 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5395 << Ptr->getType() << Ptr->getSourceRange(); 5396 return ExprError(); 5397 } 5398 5399 switch (ValType.getObjCLifetime()) { 5400 case Qualifiers::OCL_None: 5401 case Qualifiers::OCL_ExplicitNone: 5402 // okay 5403 break; 5404 5405 case Qualifiers::OCL_Weak: 5406 case Qualifiers::OCL_Strong: 5407 case Qualifiers::OCL_Autoreleasing: 5408 // FIXME: Can this happen? By this point, ValType should be known 5409 // to be trivially copyable. 5410 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5411 << ValType << Ptr->getSourceRange(); 5412 return ExprError(); 5413 } 5414 5415 // All atomic operations have an overload which takes a pointer to a volatile 5416 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5417 // into the result or the other operands. Similarly atomic_load takes a 5418 // pointer to a const 'A'. 5419 ValType.removeLocalVolatile(); 5420 ValType.removeLocalConst(); 5421 QualType ResultType = ValType; 5422 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5423 Form == Init) 5424 ResultType = Context.VoidTy; 5425 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5426 ResultType = Context.BoolTy; 5427 5428 // The type of a parameter passed 'by value'. In the GNU atomics, such 5429 // arguments are actually passed as pointers. 5430 QualType ByValType = ValType; // 'CP' 5431 bool IsPassedByAddress = false; 5432 if (!IsC11 && !IsN) { 5433 ByValType = Ptr->getType(); 5434 IsPassedByAddress = true; 5435 } 5436 5437 SmallVector<Expr *, 5> APIOrderedArgs; 5438 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5439 APIOrderedArgs.push_back(Args[0]); 5440 switch (Form) { 5441 case Init: 5442 case Load: 5443 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5444 break; 5445 case LoadCopy: 5446 case Copy: 5447 case Arithmetic: 5448 case Xchg: 5449 APIOrderedArgs.push_back(Args[2]); // Val1 5450 APIOrderedArgs.push_back(Args[1]); // Order 5451 break; 5452 case GNUXchg: 5453 APIOrderedArgs.push_back(Args[2]); // Val1 5454 APIOrderedArgs.push_back(Args[3]); // Val2 5455 APIOrderedArgs.push_back(Args[1]); // Order 5456 break; 5457 case C11CmpXchg: 5458 APIOrderedArgs.push_back(Args[2]); // Val1 5459 APIOrderedArgs.push_back(Args[4]); // Val2 5460 APIOrderedArgs.push_back(Args[1]); // Order 5461 APIOrderedArgs.push_back(Args[3]); // OrderFail 5462 break; 5463 case GNUCmpXchg: 5464 APIOrderedArgs.push_back(Args[2]); // Val1 5465 APIOrderedArgs.push_back(Args[4]); // Val2 5466 APIOrderedArgs.push_back(Args[5]); // Weak 5467 APIOrderedArgs.push_back(Args[1]); // Order 5468 APIOrderedArgs.push_back(Args[3]); // OrderFail 5469 break; 5470 } 5471 } else 5472 APIOrderedArgs.append(Args.begin(), Args.end()); 5473 5474 // The first argument's non-CV pointer type is used to deduce the type of 5475 // subsequent arguments, except for: 5476 // - weak flag (always converted to bool) 5477 // - memory order (always converted to int) 5478 // - scope (always converted to int) 5479 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5480 QualType Ty; 5481 if (i < NumVals[Form] + 1) { 5482 switch (i) { 5483 case 0: 5484 // The first argument is always a pointer. It has a fixed type. 5485 // It is always dereferenced, a nullptr is undefined. 5486 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5487 // Nothing else to do: we already know all we want about this pointer. 5488 continue; 5489 case 1: 5490 // The second argument is the non-atomic operand. For arithmetic, this 5491 // is always passed by value, and for a compare_exchange it is always 5492 // passed by address. For the rest, GNU uses by-address and C11 uses 5493 // by-value. 5494 assert(Form != Load); 5495 if (Form == Arithmetic && ValType->isPointerType()) 5496 Ty = Context.getPointerDiffType(); 5497 else if (Form == Init || Form == Arithmetic) 5498 Ty = ValType; 5499 else if (Form == Copy || Form == Xchg) { 5500 if (IsPassedByAddress) { 5501 // The value pointer is always dereferenced, a nullptr is undefined. 5502 CheckNonNullArgument(*this, APIOrderedArgs[i], 5503 ExprRange.getBegin()); 5504 } 5505 Ty = ByValType; 5506 } else { 5507 Expr *ValArg = APIOrderedArgs[i]; 5508 // The value pointer is always dereferenced, a nullptr is undefined. 5509 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5510 LangAS AS = LangAS::Default; 5511 // Keep address space of non-atomic pointer type. 5512 if (const PointerType *PtrTy = 5513 ValArg->getType()->getAs<PointerType>()) { 5514 AS = PtrTy->getPointeeType().getAddressSpace(); 5515 } 5516 Ty = Context.getPointerType( 5517 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5518 } 5519 break; 5520 case 2: 5521 // The third argument to compare_exchange / GNU exchange is the desired 5522 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5523 if (IsPassedByAddress) 5524 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5525 Ty = ByValType; 5526 break; 5527 case 3: 5528 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5529 Ty = Context.BoolTy; 5530 break; 5531 } 5532 } else { 5533 // The order(s) and scope are always converted to int. 5534 Ty = Context.IntTy; 5535 } 5536 5537 InitializedEntity Entity = 5538 InitializedEntity::InitializeParameter(Context, Ty, false); 5539 ExprResult Arg = APIOrderedArgs[i]; 5540 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5541 if (Arg.isInvalid()) 5542 return true; 5543 APIOrderedArgs[i] = Arg.get(); 5544 } 5545 5546 // Permute the arguments into a 'consistent' order. 5547 SmallVector<Expr*, 5> SubExprs; 5548 SubExprs.push_back(Ptr); 5549 switch (Form) { 5550 case Init: 5551 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5552 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5553 break; 5554 case Load: 5555 SubExprs.push_back(APIOrderedArgs[1]); // Order 5556 break; 5557 case LoadCopy: 5558 case Copy: 5559 case Arithmetic: 5560 case Xchg: 5561 SubExprs.push_back(APIOrderedArgs[2]); // Order 5562 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5563 break; 5564 case GNUXchg: 5565 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5566 SubExprs.push_back(APIOrderedArgs[3]); // Order 5567 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5568 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5569 break; 5570 case C11CmpXchg: 5571 SubExprs.push_back(APIOrderedArgs[3]); // Order 5572 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5573 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5574 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5575 break; 5576 case GNUCmpXchg: 5577 SubExprs.push_back(APIOrderedArgs[4]); // Order 5578 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5579 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5580 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5581 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5582 break; 5583 } 5584 5585 if (SubExprs.size() >= 2 && Form != Init) { 5586 if (Optional<llvm::APSInt> Result = 5587 SubExprs[1]->getIntegerConstantExpr(Context)) 5588 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5589 Diag(SubExprs[1]->getBeginLoc(), 5590 diag::warn_atomic_op_has_invalid_memory_order) 5591 << SubExprs[1]->getSourceRange(); 5592 } 5593 5594 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5595 auto *Scope = Args[Args.size() - 1]; 5596 if (Optional<llvm::APSInt> Result = 5597 Scope->getIntegerConstantExpr(Context)) { 5598 if (!ScopeModel->isValid(Result->getZExtValue())) 5599 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5600 << Scope->getSourceRange(); 5601 } 5602 SubExprs.push_back(Scope); 5603 } 5604 5605 AtomicExpr *AE = new (Context) 5606 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5607 5608 if ((Op == AtomicExpr::AO__c11_atomic_load || 5609 Op == AtomicExpr::AO__c11_atomic_store || 5610 Op == AtomicExpr::AO__opencl_atomic_load || 5611 Op == AtomicExpr::AO__opencl_atomic_store ) && 5612 Context.AtomicUsesUnsupportedLibcall(AE)) 5613 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5614 << ((Op == AtomicExpr::AO__c11_atomic_load || 5615 Op == AtomicExpr::AO__opencl_atomic_load) 5616 ? 0 5617 : 1); 5618 5619 if (ValType->isExtIntType()) { 5620 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5621 return ExprError(); 5622 } 5623 5624 return AE; 5625 } 5626 5627 /// checkBuiltinArgument - Given a call to a builtin function, perform 5628 /// normal type-checking on the given argument, updating the call in 5629 /// place. This is useful when a builtin function requires custom 5630 /// type-checking for some of its arguments but not necessarily all of 5631 /// them. 5632 /// 5633 /// Returns true on error. 5634 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5635 FunctionDecl *Fn = E->getDirectCallee(); 5636 assert(Fn && "builtin call without direct callee!"); 5637 5638 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5639 InitializedEntity Entity = 5640 InitializedEntity::InitializeParameter(S.Context, Param); 5641 5642 ExprResult Arg = E->getArg(0); 5643 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5644 if (Arg.isInvalid()) 5645 return true; 5646 5647 E->setArg(ArgIndex, Arg.get()); 5648 return false; 5649 } 5650 5651 /// We have a call to a function like __sync_fetch_and_add, which is an 5652 /// overloaded function based on the pointer type of its first argument. 5653 /// The main BuildCallExpr routines have already promoted the types of 5654 /// arguments because all of these calls are prototyped as void(...). 5655 /// 5656 /// This function goes through and does final semantic checking for these 5657 /// builtins, as well as generating any warnings. 5658 ExprResult 5659 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5660 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5661 Expr *Callee = TheCall->getCallee(); 5662 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5663 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5664 5665 // Ensure that we have at least one argument to do type inference from. 5666 if (TheCall->getNumArgs() < 1) { 5667 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5668 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5669 return ExprError(); 5670 } 5671 5672 // Inspect the first argument of the atomic builtin. This should always be 5673 // a pointer type, whose element is an integral scalar or pointer type. 5674 // Because it is a pointer type, we don't have to worry about any implicit 5675 // casts here. 5676 // FIXME: We don't allow floating point scalars as input. 5677 Expr *FirstArg = TheCall->getArg(0); 5678 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5679 if (FirstArgResult.isInvalid()) 5680 return ExprError(); 5681 FirstArg = FirstArgResult.get(); 5682 TheCall->setArg(0, FirstArg); 5683 5684 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5685 if (!pointerType) { 5686 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5687 << FirstArg->getType() << FirstArg->getSourceRange(); 5688 return ExprError(); 5689 } 5690 5691 QualType ValType = pointerType->getPointeeType(); 5692 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5693 !ValType->isBlockPointerType()) { 5694 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5695 << FirstArg->getType() << FirstArg->getSourceRange(); 5696 return ExprError(); 5697 } 5698 5699 if (ValType.isConstQualified()) { 5700 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5701 << FirstArg->getType() << FirstArg->getSourceRange(); 5702 return ExprError(); 5703 } 5704 5705 switch (ValType.getObjCLifetime()) { 5706 case Qualifiers::OCL_None: 5707 case Qualifiers::OCL_ExplicitNone: 5708 // okay 5709 break; 5710 5711 case Qualifiers::OCL_Weak: 5712 case Qualifiers::OCL_Strong: 5713 case Qualifiers::OCL_Autoreleasing: 5714 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5715 << ValType << FirstArg->getSourceRange(); 5716 return ExprError(); 5717 } 5718 5719 // Strip any qualifiers off ValType. 5720 ValType = ValType.getUnqualifiedType(); 5721 5722 // The majority of builtins return a value, but a few have special return 5723 // types, so allow them to override appropriately below. 5724 QualType ResultType = ValType; 5725 5726 // We need to figure out which concrete builtin this maps onto. For example, 5727 // __sync_fetch_and_add with a 2 byte object turns into 5728 // __sync_fetch_and_add_2. 5729 #define BUILTIN_ROW(x) \ 5730 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5731 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5732 5733 static const unsigned BuiltinIndices[][5] = { 5734 BUILTIN_ROW(__sync_fetch_and_add), 5735 BUILTIN_ROW(__sync_fetch_and_sub), 5736 BUILTIN_ROW(__sync_fetch_and_or), 5737 BUILTIN_ROW(__sync_fetch_and_and), 5738 BUILTIN_ROW(__sync_fetch_and_xor), 5739 BUILTIN_ROW(__sync_fetch_and_nand), 5740 5741 BUILTIN_ROW(__sync_add_and_fetch), 5742 BUILTIN_ROW(__sync_sub_and_fetch), 5743 BUILTIN_ROW(__sync_and_and_fetch), 5744 BUILTIN_ROW(__sync_or_and_fetch), 5745 BUILTIN_ROW(__sync_xor_and_fetch), 5746 BUILTIN_ROW(__sync_nand_and_fetch), 5747 5748 BUILTIN_ROW(__sync_val_compare_and_swap), 5749 BUILTIN_ROW(__sync_bool_compare_and_swap), 5750 BUILTIN_ROW(__sync_lock_test_and_set), 5751 BUILTIN_ROW(__sync_lock_release), 5752 BUILTIN_ROW(__sync_swap) 5753 }; 5754 #undef BUILTIN_ROW 5755 5756 // Determine the index of the size. 5757 unsigned SizeIndex; 5758 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5759 case 1: SizeIndex = 0; break; 5760 case 2: SizeIndex = 1; break; 5761 case 4: SizeIndex = 2; break; 5762 case 8: SizeIndex = 3; break; 5763 case 16: SizeIndex = 4; break; 5764 default: 5765 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5766 << FirstArg->getType() << FirstArg->getSourceRange(); 5767 return ExprError(); 5768 } 5769 5770 // Each of these builtins has one pointer argument, followed by some number of 5771 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5772 // that we ignore. Find out which row of BuiltinIndices to read from as well 5773 // as the number of fixed args. 5774 unsigned BuiltinID = FDecl->getBuiltinID(); 5775 unsigned BuiltinIndex, NumFixed = 1; 5776 bool WarnAboutSemanticsChange = false; 5777 switch (BuiltinID) { 5778 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5779 case Builtin::BI__sync_fetch_and_add: 5780 case Builtin::BI__sync_fetch_and_add_1: 5781 case Builtin::BI__sync_fetch_and_add_2: 5782 case Builtin::BI__sync_fetch_and_add_4: 5783 case Builtin::BI__sync_fetch_and_add_8: 5784 case Builtin::BI__sync_fetch_and_add_16: 5785 BuiltinIndex = 0; 5786 break; 5787 5788 case Builtin::BI__sync_fetch_and_sub: 5789 case Builtin::BI__sync_fetch_and_sub_1: 5790 case Builtin::BI__sync_fetch_and_sub_2: 5791 case Builtin::BI__sync_fetch_and_sub_4: 5792 case Builtin::BI__sync_fetch_and_sub_8: 5793 case Builtin::BI__sync_fetch_and_sub_16: 5794 BuiltinIndex = 1; 5795 break; 5796 5797 case Builtin::BI__sync_fetch_and_or: 5798 case Builtin::BI__sync_fetch_and_or_1: 5799 case Builtin::BI__sync_fetch_and_or_2: 5800 case Builtin::BI__sync_fetch_and_or_4: 5801 case Builtin::BI__sync_fetch_and_or_8: 5802 case Builtin::BI__sync_fetch_and_or_16: 5803 BuiltinIndex = 2; 5804 break; 5805 5806 case Builtin::BI__sync_fetch_and_and: 5807 case Builtin::BI__sync_fetch_and_and_1: 5808 case Builtin::BI__sync_fetch_and_and_2: 5809 case Builtin::BI__sync_fetch_and_and_4: 5810 case Builtin::BI__sync_fetch_and_and_8: 5811 case Builtin::BI__sync_fetch_and_and_16: 5812 BuiltinIndex = 3; 5813 break; 5814 5815 case Builtin::BI__sync_fetch_and_xor: 5816 case Builtin::BI__sync_fetch_and_xor_1: 5817 case Builtin::BI__sync_fetch_and_xor_2: 5818 case Builtin::BI__sync_fetch_and_xor_4: 5819 case Builtin::BI__sync_fetch_and_xor_8: 5820 case Builtin::BI__sync_fetch_and_xor_16: 5821 BuiltinIndex = 4; 5822 break; 5823 5824 case Builtin::BI__sync_fetch_and_nand: 5825 case Builtin::BI__sync_fetch_and_nand_1: 5826 case Builtin::BI__sync_fetch_and_nand_2: 5827 case Builtin::BI__sync_fetch_and_nand_4: 5828 case Builtin::BI__sync_fetch_and_nand_8: 5829 case Builtin::BI__sync_fetch_and_nand_16: 5830 BuiltinIndex = 5; 5831 WarnAboutSemanticsChange = true; 5832 break; 5833 5834 case Builtin::BI__sync_add_and_fetch: 5835 case Builtin::BI__sync_add_and_fetch_1: 5836 case Builtin::BI__sync_add_and_fetch_2: 5837 case Builtin::BI__sync_add_and_fetch_4: 5838 case Builtin::BI__sync_add_and_fetch_8: 5839 case Builtin::BI__sync_add_and_fetch_16: 5840 BuiltinIndex = 6; 5841 break; 5842 5843 case Builtin::BI__sync_sub_and_fetch: 5844 case Builtin::BI__sync_sub_and_fetch_1: 5845 case Builtin::BI__sync_sub_and_fetch_2: 5846 case Builtin::BI__sync_sub_and_fetch_4: 5847 case Builtin::BI__sync_sub_and_fetch_8: 5848 case Builtin::BI__sync_sub_and_fetch_16: 5849 BuiltinIndex = 7; 5850 break; 5851 5852 case Builtin::BI__sync_and_and_fetch: 5853 case Builtin::BI__sync_and_and_fetch_1: 5854 case Builtin::BI__sync_and_and_fetch_2: 5855 case Builtin::BI__sync_and_and_fetch_4: 5856 case Builtin::BI__sync_and_and_fetch_8: 5857 case Builtin::BI__sync_and_and_fetch_16: 5858 BuiltinIndex = 8; 5859 break; 5860 5861 case Builtin::BI__sync_or_and_fetch: 5862 case Builtin::BI__sync_or_and_fetch_1: 5863 case Builtin::BI__sync_or_and_fetch_2: 5864 case Builtin::BI__sync_or_and_fetch_4: 5865 case Builtin::BI__sync_or_and_fetch_8: 5866 case Builtin::BI__sync_or_and_fetch_16: 5867 BuiltinIndex = 9; 5868 break; 5869 5870 case Builtin::BI__sync_xor_and_fetch: 5871 case Builtin::BI__sync_xor_and_fetch_1: 5872 case Builtin::BI__sync_xor_and_fetch_2: 5873 case Builtin::BI__sync_xor_and_fetch_4: 5874 case Builtin::BI__sync_xor_and_fetch_8: 5875 case Builtin::BI__sync_xor_and_fetch_16: 5876 BuiltinIndex = 10; 5877 break; 5878 5879 case Builtin::BI__sync_nand_and_fetch: 5880 case Builtin::BI__sync_nand_and_fetch_1: 5881 case Builtin::BI__sync_nand_and_fetch_2: 5882 case Builtin::BI__sync_nand_and_fetch_4: 5883 case Builtin::BI__sync_nand_and_fetch_8: 5884 case Builtin::BI__sync_nand_and_fetch_16: 5885 BuiltinIndex = 11; 5886 WarnAboutSemanticsChange = true; 5887 break; 5888 5889 case Builtin::BI__sync_val_compare_and_swap: 5890 case Builtin::BI__sync_val_compare_and_swap_1: 5891 case Builtin::BI__sync_val_compare_and_swap_2: 5892 case Builtin::BI__sync_val_compare_and_swap_4: 5893 case Builtin::BI__sync_val_compare_and_swap_8: 5894 case Builtin::BI__sync_val_compare_and_swap_16: 5895 BuiltinIndex = 12; 5896 NumFixed = 2; 5897 break; 5898 5899 case Builtin::BI__sync_bool_compare_and_swap: 5900 case Builtin::BI__sync_bool_compare_and_swap_1: 5901 case Builtin::BI__sync_bool_compare_and_swap_2: 5902 case Builtin::BI__sync_bool_compare_and_swap_4: 5903 case Builtin::BI__sync_bool_compare_and_swap_8: 5904 case Builtin::BI__sync_bool_compare_and_swap_16: 5905 BuiltinIndex = 13; 5906 NumFixed = 2; 5907 ResultType = Context.BoolTy; 5908 break; 5909 5910 case Builtin::BI__sync_lock_test_and_set: 5911 case Builtin::BI__sync_lock_test_and_set_1: 5912 case Builtin::BI__sync_lock_test_and_set_2: 5913 case Builtin::BI__sync_lock_test_and_set_4: 5914 case Builtin::BI__sync_lock_test_and_set_8: 5915 case Builtin::BI__sync_lock_test_and_set_16: 5916 BuiltinIndex = 14; 5917 break; 5918 5919 case Builtin::BI__sync_lock_release: 5920 case Builtin::BI__sync_lock_release_1: 5921 case Builtin::BI__sync_lock_release_2: 5922 case Builtin::BI__sync_lock_release_4: 5923 case Builtin::BI__sync_lock_release_8: 5924 case Builtin::BI__sync_lock_release_16: 5925 BuiltinIndex = 15; 5926 NumFixed = 0; 5927 ResultType = Context.VoidTy; 5928 break; 5929 5930 case Builtin::BI__sync_swap: 5931 case Builtin::BI__sync_swap_1: 5932 case Builtin::BI__sync_swap_2: 5933 case Builtin::BI__sync_swap_4: 5934 case Builtin::BI__sync_swap_8: 5935 case Builtin::BI__sync_swap_16: 5936 BuiltinIndex = 16; 5937 break; 5938 } 5939 5940 // Now that we know how many fixed arguments we expect, first check that we 5941 // have at least that many. 5942 if (TheCall->getNumArgs() < 1+NumFixed) { 5943 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5944 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5945 << Callee->getSourceRange(); 5946 return ExprError(); 5947 } 5948 5949 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5950 << Callee->getSourceRange(); 5951 5952 if (WarnAboutSemanticsChange) { 5953 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5954 << Callee->getSourceRange(); 5955 } 5956 5957 // Get the decl for the concrete builtin from this, we can tell what the 5958 // concrete integer type we should convert to is. 5959 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5960 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5961 FunctionDecl *NewBuiltinDecl; 5962 if (NewBuiltinID == BuiltinID) 5963 NewBuiltinDecl = FDecl; 5964 else { 5965 // Perform builtin lookup to avoid redeclaring it. 5966 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5967 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5968 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5969 assert(Res.getFoundDecl()); 5970 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5971 if (!NewBuiltinDecl) 5972 return ExprError(); 5973 } 5974 5975 // The first argument --- the pointer --- has a fixed type; we 5976 // deduce the types of the rest of the arguments accordingly. Walk 5977 // the remaining arguments, converting them to the deduced value type. 5978 for (unsigned i = 0; i != NumFixed; ++i) { 5979 ExprResult Arg = TheCall->getArg(i+1); 5980 5981 // GCC does an implicit conversion to the pointer or integer ValType. This 5982 // can fail in some cases (1i -> int**), check for this error case now. 5983 // Initialize the argument. 5984 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5985 ValType, /*consume*/ false); 5986 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5987 if (Arg.isInvalid()) 5988 return ExprError(); 5989 5990 // Okay, we have something that *can* be converted to the right type. Check 5991 // to see if there is a potentially weird extension going on here. This can 5992 // happen when you do an atomic operation on something like an char* and 5993 // pass in 42. The 42 gets converted to char. This is even more strange 5994 // for things like 45.123 -> char, etc. 5995 // FIXME: Do this check. 5996 TheCall->setArg(i+1, Arg.get()); 5997 } 5998 5999 // Create a new DeclRefExpr to refer to the new decl. 6000 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6001 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6002 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6003 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6004 6005 // Set the callee in the CallExpr. 6006 // FIXME: This loses syntactic information. 6007 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6008 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6009 CK_BuiltinFnToFnPtr); 6010 TheCall->setCallee(PromotedCall.get()); 6011 6012 // Change the result type of the call to match the original value type. This 6013 // is arbitrary, but the codegen for these builtins ins design to handle it 6014 // gracefully. 6015 TheCall->setType(ResultType); 6016 6017 // Prohibit use of _ExtInt with atomic builtins. 6018 // The arguments would have already been converted to the first argument's 6019 // type, so only need to check the first argument. 6020 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6021 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6022 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6023 return ExprError(); 6024 } 6025 6026 return TheCallResult; 6027 } 6028 6029 /// SemaBuiltinNontemporalOverloaded - We have a call to 6030 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6031 /// overloaded function based on the pointer type of its last argument. 6032 /// 6033 /// This function goes through and does final semantic checking for these 6034 /// builtins. 6035 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6036 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6037 DeclRefExpr *DRE = 6038 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6039 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6040 unsigned BuiltinID = FDecl->getBuiltinID(); 6041 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6042 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6043 "Unexpected nontemporal load/store builtin!"); 6044 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6045 unsigned numArgs = isStore ? 2 : 1; 6046 6047 // Ensure that we have the proper number of arguments. 6048 if (checkArgCount(*this, TheCall, numArgs)) 6049 return ExprError(); 6050 6051 // Inspect the last argument of the nontemporal builtin. This should always 6052 // be a pointer type, from which we imply the type of the memory access. 6053 // Because it is a pointer type, we don't have to worry about any implicit 6054 // casts here. 6055 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6056 ExprResult PointerArgResult = 6057 DefaultFunctionArrayLvalueConversion(PointerArg); 6058 6059 if (PointerArgResult.isInvalid()) 6060 return ExprError(); 6061 PointerArg = PointerArgResult.get(); 6062 TheCall->setArg(numArgs - 1, PointerArg); 6063 6064 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6065 if (!pointerType) { 6066 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6067 << PointerArg->getType() << PointerArg->getSourceRange(); 6068 return ExprError(); 6069 } 6070 6071 QualType ValType = pointerType->getPointeeType(); 6072 6073 // Strip any qualifiers off ValType. 6074 ValType = ValType.getUnqualifiedType(); 6075 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6076 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6077 !ValType->isVectorType()) { 6078 Diag(DRE->getBeginLoc(), 6079 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6080 << PointerArg->getType() << PointerArg->getSourceRange(); 6081 return ExprError(); 6082 } 6083 6084 if (!isStore) { 6085 TheCall->setType(ValType); 6086 return TheCallResult; 6087 } 6088 6089 ExprResult ValArg = TheCall->getArg(0); 6090 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6091 Context, ValType, /*consume*/ false); 6092 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6093 if (ValArg.isInvalid()) 6094 return ExprError(); 6095 6096 TheCall->setArg(0, ValArg.get()); 6097 TheCall->setType(Context.VoidTy); 6098 return TheCallResult; 6099 } 6100 6101 /// CheckObjCString - Checks that the argument to the builtin 6102 /// CFString constructor is correct 6103 /// Note: It might also make sense to do the UTF-16 conversion here (would 6104 /// simplify the backend). 6105 bool Sema::CheckObjCString(Expr *Arg) { 6106 Arg = Arg->IgnoreParenCasts(); 6107 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6108 6109 if (!Literal || !Literal->isAscii()) { 6110 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6111 << Arg->getSourceRange(); 6112 return true; 6113 } 6114 6115 if (Literal->containsNonAsciiOrNull()) { 6116 StringRef String = Literal->getString(); 6117 unsigned NumBytes = String.size(); 6118 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6119 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6120 llvm::UTF16 *ToPtr = &ToBuf[0]; 6121 6122 llvm::ConversionResult Result = 6123 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6124 ToPtr + NumBytes, llvm::strictConversion); 6125 // Check for conversion failure. 6126 if (Result != llvm::conversionOK) 6127 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6128 << Arg->getSourceRange(); 6129 } 6130 return false; 6131 } 6132 6133 /// CheckObjCString - Checks that the format string argument to the os_log() 6134 /// and os_trace() functions is correct, and converts it to const char *. 6135 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6136 Arg = Arg->IgnoreParenCasts(); 6137 auto *Literal = dyn_cast<StringLiteral>(Arg); 6138 if (!Literal) { 6139 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6140 Literal = ObjcLiteral->getString(); 6141 } 6142 } 6143 6144 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6145 return ExprError( 6146 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6147 << Arg->getSourceRange()); 6148 } 6149 6150 ExprResult Result(Literal); 6151 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6152 InitializedEntity Entity = 6153 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6154 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6155 return Result; 6156 } 6157 6158 /// Check that the user is calling the appropriate va_start builtin for the 6159 /// target and calling convention. 6160 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6161 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6162 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6163 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6164 TT.getArch() == llvm::Triple::aarch64_32); 6165 bool IsWindows = TT.isOSWindows(); 6166 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6167 if (IsX64 || IsAArch64) { 6168 CallingConv CC = CC_C; 6169 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6170 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6171 if (IsMSVAStart) { 6172 // Don't allow this in System V ABI functions. 6173 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6174 return S.Diag(Fn->getBeginLoc(), 6175 diag::err_ms_va_start_used_in_sysv_function); 6176 } else { 6177 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6178 // On x64 Windows, don't allow this in System V ABI functions. 6179 // (Yes, that means there's no corresponding way to support variadic 6180 // System V ABI functions on Windows.) 6181 if ((IsWindows && CC == CC_X86_64SysV) || 6182 (!IsWindows && CC == CC_Win64)) 6183 return S.Diag(Fn->getBeginLoc(), 6184 diag::err_va_start_used_in_wrong_abi_function) 6185 << !IsWindows; 6186 } 6187 return false; 6188 } 6189 6190 if (IsMSVAStart) 6191 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6192 return false; 6193 } 6194 6195 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6196 ParmVarDecl **LastParam = nullptr) { 6197 // Determine whether the current function, block, or obj-c method is variadic 6198 // and get its parameter list. 6199 bool IsVariadic = false; 6200 ArrayRef<ParmVarDecl *> Params; 6201 DeclContext *Caller = S.CurContext; 6202 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6203 IsVariadic = Block->isVariadic(); 6204 Params = Block->parameters(); 6205 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6206 IsVariadic = FD->isVariadic(); 6207 Params = FD->parameters(); 6208 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6209 IsVariadic = MD->isVariadic(); 6210 // FIXME: This isn't correct for methods (results in bogus warning). 6211 Params = MD->parameters(); 6212 } else if (isa<CapturedDecl>(Caller)) { 6213 // We don't support va_start in a CapturedDecl. 6214 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6215 return true; 6216 } else { 6217 // This must be some other declcontext that parses exprs. 6218 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6219 return true; 6220 } 6221 6222 if (!IsVariadic) { 6223 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6224 return true; 6225 } 6226 6227 if (LastParam) 6228 *LastParam = Params.empty() ? nullptr : Params.back(); 6229 6230 return false; 6231 } 6232 6233 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6234 /// for validity. Emit an error and return true on failure; return false 6235 /// on success. 6236 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6237 Expr *Fn = TheCall->getCallee(); 6238 6239 if (checkVAStartABI(*this, BuiltinID, Fn)) 6240 return true; 6241 6242 if (checkArgCount(*this, TheCall, 2)) 6243 return true; 6244 6245 // Type-check the first argument normally. 6246 if (checkBuiltinArgument(*this, TheCall, 0)) 6247 return true; 6248 6249 // Check that the current function is variadic, and get its last parameter. 6250 ParmVarDecl *LastParam; 6251 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6252 return true; 6253 6254 // Verify that the second argument to the builtin is the last argument of the 6255 // current function or method. 6256 bool SecondArgIsLastNamedArgument = false; 6257 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6258 6259 // These are valid if SecondArgIsLastNamedArgument is false after the next 6260 // block. 6261 QualType Type; 6262 SourceLocation ParamLoc; 6263 bool IsCRegister = false; 6264 6265 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6266 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6267 SecondArgIsLastNamedArgument = PV == LastParam; 6268 6269 Type = PV->getType(); 6270 ParamLoc = PV->getLocation(); 6271 IsCRegister = 6272 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6273 } 6274 } 6275 6276 if (!SecondArgIsLastNamedArgument) 6277 Diag(TheCall->getArg(1)->getBeginLoc(), 6278 diag::warn_second_arg_of_va_start_not_last_named_param); 6279 else if (IsCRegister || Type->isReferenceType() || 6280 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6281 // Promotable integers are UB, but enumerations need a bit of 6282 // extra checking to see what their promotable type actually is. 6283 if (!Type->isPromotableIntegerType()) 6284 return false; 6285 if (!Type->isEnumeralType()) 6286 return true; 6287 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6288 return !(ED && 6289 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6290 }()) { 6291 unsigned Reason = 0; 6292 if (Type->isReferenceType()) Reason = 1; 6293 else if (IsCRegister) Reason = 2; 6294 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6295 Diag(ParamLoc, diag::note_parameter_type) << Type; 6296 } 6297 6298 TheCall->setType(Context.VoidTy); 6299 return false; 6300 } 6301 6302 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6303 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6304 // const char *named_addr); 6305 6306 Expr *Func = Call->getCallee(); 6307 6308 if (Call->getNumArgs() < 3) 6309 return Diag(Call->getEndLoc(), 6310 diag::err_typecheck_call_too_few_args_at_least) 6311 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6312 6313 // Type-check the first argument normally. 6314 if (checkBuiltinArgument(*this, Call, 0)) 6315 return true; 6316 6317 // Check that the current function is variadic. 6318 if (checkVAStartIsInVariadicFunction(*this, Func)) 6319 return true; 6320 6321 // __va_start on Windows does not validate the parameter qualifiers 6322 6323 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6324 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6325 6326 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6327 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6328 6329 const QualType &ConstCharPtrTy = 6330 Context.getPointerType(Context.CharTy.withConst()); 6331 if (!Arg1Ty->isPointerType() || 6332 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 6333 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6334 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6335 << 0 /* qualifier difference */ 6336 << 3 /* parameter mismatch */ 6337 << 2 << Arg1->getType() << ConstCharPtrTy; 6338 6339 const QualType SizeTy = Context.getSizeType(); 6340 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6341 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6342 << Arg2->getType() << SizeTy << 1 /* different class */ 6343 << 0 /* qualifier difference */ 6344 << 3 /* parameter mismatch */ 6345 << 3 << Arg2->getType() << SizeTy; 6346 6347 return false; 6348 } 6349 6350 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6351 /// friends. This is declared to take (...), so we have to check everything. 6352 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6353 if (checkArgCount(*this, TheCall, 2)) 6354 return true; 6355 6356 ExprResult OrigArg0 = TheCall->getArg(0); 6357 ExprResult OrigArg1 = TheCall->getArg(1); 6358 6359 // Do standard promotions between the two arguments, returning their common 6360 // type. 6361 QualType Res = UsualArithmeticConversions( 6362 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6363 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6364 return true; 6365 6366 // Make sure any conversions are pushed back into the call; this is 6367 // type safe since unordered compare builtins are declared as "_Bool 6368 // foo(...)". 6369 TheCall->setArg(0, OrigArg0.get()); 6370 TheCall->setArg(1, OrigArg1.get()); 6371 6372 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6373 return false; 6374 6375 // If the common type isn't a real floating type, then the arguments were 6376 // invalid for this operation. 6377 if (Res.isNull() || !Res->isRealFloatingType()) 6378 return Diag(OrigArg0.get()->getBeginLoc(), 6379 diag::err_typecheck_call_invalid_ordered_compare) 6380 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6381 << SourceRange(OrigArg0.get()->getBeginLoc(), 6382 OrigArg1.get()->getEndLoc()); 6383 6384 return false; 6385 } 6386 6387 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6388 /// __builtin_isnan and friends. This is declared to take (...), so we have 6389 /// to check everything. We expect the last argument to be a floating point 6390 /// value. 6391 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6392 if (checkArgCount(*this, TheCall, NumArgs)) 6393 return true; 6394 6395 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6396 // on all preceding parameters just being int. Try all of those. 6397 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6398 Expr *Arg = TheCall->getArg(i); 6399 6400 if (Arg->isTypeDependent()) 6401 return false; 6402 6403 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6404 6405 if (Res.isInvalid()) 6406 return true; 6407 TheCall->setArg(i, Res.get()); 6408 } 6409 6410 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6411 6412 if (OrigArg->isTypeDependent()) 6413 return false; 6414 6415 // Usual Unary Conversions will convert half to float, which we want for 6416 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6417 // type how it is, but do normal L->Rvalue conversions. 6418 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6419 OrigArg = UsualUnaryConversions(OrigArg).get(); 6420 else 6421 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6422 TheCall->setArg(NumArgs - 1, OrigArg); 6423 6424 // This operation requires a non-_Complex floating-point number. 6425 if (!OrigArg->getType()->isRealFloatingType()) 6426 return Diag(OrigArg->getBeginLoc(), 6427 diag::err_typecheck_call_invalid_unary_fp) 6428 << OrigArg->getType() << OrigArg->getSourceRange(); 6429 6430 return false; 6431 } 6432 6433 /// Perform semantic analysis for a call to __builtin_complex. 6434 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6435 if (checkArgCount(*this, TheCall, 2)) 6436 return true; 6437 6438 bool Dependent = false; 6439 for (unsigned I = 0; I != 2; ++I) { 6440 Expr *Arg = TheCall->getArg(I); 6441 QualType T = Arg->getType(); 6442 if (T->isDependentType()) { 6443 Dependent = true; 6444 continue; 6445 } 6446 6447 // Despite supporting _Complex int, GCC requires a real floating point type 6448 // for the operands of __builtin_complex. 6449 if (!T->isRealFloatingType()) { 6450 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6451 << Arg->getType() << Arg->getSourceRange(); 6452 } 6453 6454 ExprResult Converted = DefaultLvalueConversion(Arg); 6455 if (Converted.isInvalid()) 6456 return true; 6457 TheCall->setArg(I, Converted.get()); 6458 } 6459 6460 if (Dependent) { 6461 TheCall->setType(Context.DependentTy); 6462 return false; 6463 } 6464 6465 Expr *Real = TheCall->getArg(0); 6466 Expr *Imag = TheCall->getArg(1); 6467 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6468 return Diag(Real->getBeginLoc(), 6469 diag::err_typecheck_call_different_arg_types) 6470 << Real->getType() << Imag->getType() 6471 << Real->getSourceRange() << Imag->getSourceRange(); 6472 } 6473 6474 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6475 // don't allow this builtin to form those types either. 6476 // FIXME: Should we allow these types? 6477 if (Real->getType()->isFloat16Type()) 6478 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6479 << "_Float16"; 6480 if (Real->getType()->isHalfType()) 6481 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6482 << "half"; 6483 6484 TheCall->setType(Context.getComplexType(Real->getType())); 6485 return false; 6486 } 6487 6488 // Customized Sema Checking for VSX builtins that have the following signature: 6489 // vector [...] builtinName(vector [...], vector [...], const int); 6490 // Which takes the same type of vectors (any legal vector type) for the first 6491 // two arguments and takes compile time constant for the third argument. 6492 // Example builtins are : 6493 // vector double vec_xxpermdi(vector double, vector double, int); 6494 // vector short vec_xxsldwi(vector short, vector short, int); 6495 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6496 unsigned ExpectedNumArgs = 3; 6497 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6498 return true; 6499 6500 // Check the third argument is a compile time constant 6501 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6502 return Diag(TheCall->getBeginLoc(), 6503 diag::err_vsx_builtin_nonconstant_argument) 6504 << 3 /* argument index */ << TheCall->getDirectCallee() 6505 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6506 TheCall->getArg(2)->getEndLoc()); 6507 6508 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6509 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6510 6511 // Check the type of argument 1 and argument 2 are vectors. 6512 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6513 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6514 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6515 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6516 << TheCall->getDirectCallee() 6517 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6518 TheCall->getArg(1)->getEndLoc()); 6519 } 6520 6521 // Check the first two arguments are the same type. 6522 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6523 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6524 << TheCall->getDirectCallee() 6525 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6526 TheCall->getArg(1)->getEndLoc()); 6527 } 6528 6529 // When default clang type checking is turned off and the customized type 6530 // checking is used, the returning type of the function must be explicitly 6531 // set. Otherwise it is _Bool by default. 6532 TheCall->setType(Arg1Ty); 6533 6534 return false; 6535 } 6536 6537 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6538 // This is declared to take (...), so we have to check everything. 6539 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6540 if (TheCall->getNumArgs() < 2) 6541 return ExprError(Diag(TheCall->getEndLoc(), 6542 diag::err_typecheck_call_too_few_args_at_least) 6543 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6544 << TheCall->getSourceRange()); 6545 6546 // Determine which of the following types of shufflevector we're checking: 6547 // 1) unary, vector mask: (lhs, mask) 6548 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6549 QualType resType = TheCall->getArg(0)->getType(); 6550 unsigned numElements = 0; 6551 6552 if (!TheCall->getArg(0)->isTypeDependent() && 6553 !TheCall->getArg(1)->isTypeDependent()) { 6554 QualType LHSType = TheCall->getArg(0)->getType(); 6555 QualType RHSType = TheCall->getArg(1)->getType(); 6556 6557 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6558 return ExprError( 6559 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6560 << TheCall->getDirectCallee() 6561 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6562 TheCall->getArg(1)->getEndLoc())); 6563 6564 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6565 unsigned numResElements = TheCall->getNumArgs() - 2; 6566 6567 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6568 // with mask. If so, verify that RHS is an integer vector type with the 6569 // same number of elts as lhs. 6570 if (TheCall->getNumArgs() == 2) { 6571 if (!RHSType->hasIntegerRepresentation() || 6572 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6573 return ExprError(Diag(TheCall->getBeginLoc(), 6574 diag::err_vec_builtin_incompatible_vector) 6575 << TheCall->getDirectCallee() 6576 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6577 TheCall->getArg(1)->getEndLoc())); 6578 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6579 return ExprError(Diag(TheCall->getBeginLoc(), 6580 diag::err_vec_builtin_incompatible_vector) 6581 << TheCall->getDirectCallee() 6582 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6583 TheCall->getArg(1)->getEndLoc())); 6584 } else if (numElements != numResElements) { 6585 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6586 resType = Context.getVectorType(eltType, numResElements, 6587 VectorType::GenericVector); 6588 } 6589 } 6590 6591 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6592 if (TheCall->getArg(i)->isTypeDependent() || 6593 TheCall->getArg(i)->isValueDependent()) 6594 continue; 6595 6596 Optional<llvm::APSInt> Result; 6597 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6598 return ExprError(Diag(TheCall->getBeginLoc(), 6599 diag::err_shufflevector_nonconstant_argument) 6600 << TheCall->getArg(i)->getSourceRange()); 6601 6602 // Allow -1 which will be translated to undef in the IR. 6603 if (Result->isSigned() && Result->isAllOnesValue()) 6604 continue; 6605 6606 if (Result->getActiveBits() > 64 || 6607 Result->getZExtValue() >= numElements * 2) 6608 return ExprError(Diag(TheCall->getBeginLoc(), 6609 diag::err_shufflevector_argument_too_large) 6610 << TheCall->getArg(i)->getSourceRange()); 6611 } 6612 6613 SmallVector<Expr*, 32> exprs; 6614 6615 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6616 exprs.push_back(TheCall->getArg(i)); 6617 TheCall->setArg(i, nullptr); 6618 } 6619 6620 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6621 TheCall->getCallee()->getBeginLoc(), 6622 TheCall->getRParenLoc()); 6623 } 6624 6625 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6626 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6627 SourceLocation BuiltinLoc, 6628 SourceLocation RParenLoc) { 6629 ExprValueKind VK = VK_PRValue; 6630 ExprObjectKind OK = OK_Ordinary; 6631 QualType DstTy = TInfo->getType(); 6632 QualType SrcTy = E->getType(); 6633 6634 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6635 return ExprError(Diag(BuiltinLoc, 6636 diag::err_convertvector_non_vector) 6637 << E->getSourceRange()); 6638 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6639 return ExprError(Diag(BuiltinLoc, 6640 diag::err_convertvector_non_vector_type)); 6641 6642 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6643 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6644 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6645 if (SrcElts != DstElts) 6646 return ExprError(Diag(BuiltinLoc, 6647 diag::err_convertvector_incompatible_vector) 6648 << E->getSourceRange()); 6649 } 6650 6651 return new (Context) 6652 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6653 } 6654 6655 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6656 // This is declared to take (const void*, ...) and can take two 6657 // optional constant int args. 6658 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6659 unsigned NumArgs = TheCall->getNumArgs(); 6660 6661 if (NumArgs > 3) 6662 return Diag(TheCall->getEndLoc(), 6663 diag::err_typecheck_call_too_many_args_at_most) 6664 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6665 6666 // Argument 0 is checked for us and the remaining arguments must be 6667 // constant integers. 6668 for (unsigned i = 1; i != NumArgs; ++i) 6669 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6670 return true; 6671 6672 return false; 6673 } 6674 6675 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6676 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6677 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6678 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6679 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6680 if (checkArgCount(*this, TheCall, 1)) 6681 return true; 6682 Expr *Arg = TheCall->getArg(0); 6683 if (Arg->isInstantiationDependent()) 6684 return false; 6685 6686 QualType ArgTy = Arg->getType(); 6687 if (!ArgTy->hasFloatingRepresentation()) 6688 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6689 << ArgTy; 6690 if (Arg->isLValue()) { 6691 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6692 TheCall->setArg(0, FirstArg.get()); 6693 } 6694 TheCall->setType(TheCall->getArg(0)->getType()); 6695 return false; 6696 } 6697 6698 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6699 // __assume does not evaluate its arguments, and should warn if its argument 6700 // has side effects. 6701 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6702 Expr *Arg = TheCall->getArg(0); 6703 if (Arg->isInstantiationDependent()) return false; 6704 6705 if (Arg->HasSideEffects(Context)) 6706 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6707 << Arg->getSourceRange() 6708 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6709 6710 return false; 6711 } 6712 6713 /// Handle __builtin_alloca_with_align. This is declared 6714 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6715 /// than 8. 6716 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6717 // The alignment must be a constant integer. 6718 Expr *Arg = TheCall->getArg(1); 6719 6720 // We can't check the value of a dependent argument. 6721 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6722 if (const auto *UE = 6723 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6724 if (UE->getKind() == UETT_AlignOf || 6725 UE->getKind() == UETT_PreferredAlignOf) 6726 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6727 << Arg->getSourceRange(); 6728 6729 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6730 6731 if (!Result.isPowerOf2()) 6732 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6733 << Arg->getSourceRange(); 6734 6735 if (Result < Context.getCharWidth()) 6736 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6737 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6738 6739 if (Result > std::numeric_limits<int32_t>::max()) 6740 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6741 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6742 } 6743 6744 return false; 6745 } 6746 6747 /// Handle __builtin_assume_aligned. This is declared 6748 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6749 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6750 unsigned NumArgs = TheCall->getNumArgs(); 6751 6752 if (NumArgs > 3) 6753 return Diag(TheCall->getEndLoc(), 6754 diag::err_typecheck_call_too_many_args_at_most) 6755 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6756 6757 // The alignment must be a constant integer. 6758 Expr *Arg = TheCall->getArg(1); 6759 6760 // We can't check the value of a dependent argument. 6761 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6762 llvm::APSInt Result; 6763 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6764 return true; 6765 6766 if (!Result.isPowerOf2()) 6767 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6768 << Arg->getSourceRange(); 6769 6770 if (Result > Sema::MaximumAlignment) 6771 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6772 << Arg->getSourceRange() << Sema::MaximumAlignment; 6773 } 6774 6775 if (NumArgs > 2) { 6776 ExprResult Arg(TheCall->getArg(2)); 6777 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6778 Context.getSizeType(), false); 6779 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6780 if (Arg.isInvalid()) return true; 6781 TheCall->setArg(2, Arg.get()); 6782 } 6783 6784 return false; 6785 } 6786 6787 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6788 unsigned BuiltinID = 6789 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6790 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6791 6792 unsigned NumArgs = TheCall->getNumArgs(); 6793 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6794 if (NumArgs < NumRequiredArgs) { 6795 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6796 << 0 /* function call */ << NumRequiredArgs << NumArgs 6797 << TheCall->getSourceRange(); 6798 } 6799 if (NumArgs >= NumRequiredArgs + 0x100) { 6800 return Diag(TheCall->getEndLoc(), 6801 diag::err_typecheck_call_too_many_args_at_most) 6802 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6803 << TheCall->getSourceRange(); 6804 } 6805 unsigned i = 0; 6806 6807 // For formatting call, check buffer arg. 6808 if (!IsSizeCall) { 6809 ExprResult Arg(TheCall->getArg(i)); 6810 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6811 Context, Context.VoidPtrTy, false); 6812 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6813 if (Arg.isInvalid()) 6814 return true; 6815 TheCall->setArg(i, Arg.get()); 6816 i++; 6817 } 6818 6819 // Check string literal arg. 6820 unsigned FormatIdx = i; 6821 { 6822 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6823 if (Arg.isInvalid()) 6824 return true; 6825 TheCall->setArg(i, Arg.get()); 6826 i++; 6827 } 6828 6829 // Make sure variadic args are scalar. 6830 unsigned FirstDataArg = i; 6831 while (i < NumArgs) { 6832 ExprResult Arg = DefaultVariadicArgumentPromotion( 6833 TheCall->getArg(i), VariadicFunction, nullptr); 6834 if (Arg.isInvalid()) 6835 return true; 6836 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6837 if (ArgSize.getQuantity() >= 0x100) { 6838 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6839 << i << (int)ArgSize.getQuantity() << 0xff 6840 << TheCall->getSourceRange(); 6841 } 6842 TheCall->setArg(i, Arg.get()); 6843 i++; 6844 } 6845 6846 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6847 // call to avoid duplicate diagnostics. 6848 if (!IsSizeCall) { 6849 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6850 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6851 bool Success = CheckFormatArguments( 6852 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6853 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6854 CheckedVarArgs); 6855 if (!Success) 6856 return true; 6857 } 6858 6859 if (IsSizeCall) { 6860 TheCall->setType(Context.getSizeType()); 6861 } else { 6862 TheCall->setType(Context.VoidPtrTy); 6863 } 6864 return false; 6865 } 6866 6867 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6868 /// TheCall is a constant expression. 6869 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6870 llvm::APSInt &Result) { 6871 Expr *Arg = TheCall->getArg(ArgNum); 6872 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6873 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6874 6875 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6876 6877 Optional<llvm::APSInt> R; 6878 if (!(R = Arg->getIntegerConstantExpr(Context))) 6879 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6880 << FDecl->getDeclName() << Arg->getSourceRange(); 6881 Result = *R; 6882 return false; 6883 } 6884 6885 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6886 /// TheCall is a constant expression in the range [Low, High]. 6887 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6888 int Low, int High, bool RangeIsError) { 6889 if (isConstantEvaluated()) 6890 return false; 6891 llvm::APSInt Result; 6892 6893 // We can't check the value of a dependent argument. 6894 Expr *Arg = TheCall->getArg(ArgNum); 6895 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6896 return false; 6897 6898 // Check constant-ness first. 6899 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6900 return true; 6901 6902 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6903 if (RangeIsError) 6904 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6905 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 6906 else 6907 // Defer the warning until we know if the code will be emitted so that 6908 // dead code can ignore this. 6909 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6910 PDiag(diag::warn_argument_invalid_range) 6911 << toString(Result, 10) << Low << High 6912 << Arg->getSourceRange()); 6913 } 6914 6915 return false; 6916 } 6917 6918 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6919 /// TheCall is a constant expression is a multiple of Num.. 6920 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6921 unsigned Num) { 6922 llvm::APSInt Result; 6923 6924 // We can't check the value of a dependent argument. 6925 Expr *Arg = TheCall->getArg(ArgNum); 6926 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6927 return false; 6928 6929 // Check constant-ness first. 6930 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6931 return true; 6932 6933 if (Result.getSExtValue() % Num != 0) 6934 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6935 << Num << Arg->getSourceRange(); 6936 6937 return false; 6938 } 6939 6940 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6941 /// constant expression representing a power of 2. 6942 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6943 llvm::APSInt Result; 6944 6945 // We can't check the value of a dependent argument. 6946 Expr *Arg = TheCall->getArg(ArgNum); 6947 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6948 return false; 6949 6950 // Check constant-ness first. 6951 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6952 return true; 6953 6954 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6955 // and only if x is a power of 2. 6956 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6957 return false; 6958 6959 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6960 << Arg->getSourceRange(); 6961 } 6962 6963 static bool IsShiftedByte(llvm::APSInt Value) { 6964 if (Value.isNegative()) 6965 return false; 6966 6967 // Check if it's a shifted byte, by shifting it down 6968 while (true) { 6969 // If the value fits in the bottom byte, the check passes. 6970 if (Value < 0x100) 6971 return true; 6972 6973 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6974 // fails. 6975 if ((Value & 0xFF) != 0) 6976 return false; 6977 6978 // If the bottom 8 bits are all 0, but something above that is nonzero, 6979 // then shifting the value right by 8 bits won't affect whether it's a 6980 // shifted byte or not. So do that, and go round again. 6981 Value >>= 8; 6982 } 6983 } 6984 6985 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6986 /// a constant expression representing an arbitrary byte value shifted left by 6987 /// a multiple of 8 bits. 6988 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6989 unsigned ArgBits) { 6990 llvm::APSInt Result; 6991 6992 // We can't check the value of a dependent argument. 6993 Expr *Arg = TheCall->getArg(ArgNum); 6994 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6995 return false; 6996 6997 // Check constant-ness first. 6998 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6999 return true; 7000 7001 // Truncate to the given size. 7002 Result = Result.getLoBits(ArgBits); 7003 Result.setIsUnsigned(true); 7004 7005 if (IsShiftedByte(Result)) 7006 return false; 7007 7008 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7009 << Arg->getSourceRange(); 7010 } 7011 7012 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7013 /// TheCall is a constant expression representing either a shifted byte value, 7014 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7015 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7016 /// Arm MVE intrinsics. 7017 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7018 int ArgNum, 7019 unsigned ArgBits) { 7020 llvm::APSInt Result; 7021 7022 // We can't check the value of a dependent argument. 7023 Expr *Arg = TheCall->getArg(ArgNum); 7024 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7025 return false; 7026 7027 // Check constant-ness first. 7028 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7029 return true; 7030 7031 // Truncate to the given size. 7032 Result = Result.getLoBits(ArgBits); 7033 Result.setIsUnsigned(true); 7034 7035 // Check to see if it's in either of the required forms. 7036 if (IsShiftedByte(Result) || 7037 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7038 return false; 7039 7040 return Diag(TheCall->getBeginLoc(), 7041 diag::err_argument_not_shifted_byte_or_xxff) 7042 << Arg->getSourceRange(); 7043 } 7044 7045 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7046 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7047 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7048 if (checkArgCount(*this, TheCall, 2)) 7049 return true; 7050 Expr *Arg0 = TheCall->getArg(0); 7051 Expr *Arg1 = TheCall->getArg(1); 7052 7053 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7054 if (FirstArg.isInvalid()) 7055 return true; 7056 QualType FirstArgType = FirstArg.get()->getType(); 7057 if (!FirstArgType->isAnyPointerType()) 7058 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7059 << "first" << FirstArgType << Arg0->getSourceRange(); 7060 TheCall->setArg(0, FirstArg.get()); 7061 7062 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7063 if (SecArg.isInvalid()) 7064 return true; 7065 QualType SecArgType = SecArg.get()->getType(); 7066 if (!SecArgType->isIntegerType()) 7067 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7068 << "second" << SecArgType << Arg1->getSourceRange(); 7069 7070 // Derive the return type from the pointer argument. 7071 TheCall->setType(FirstArgType); 7072 return false; 7073 } 7074 7075 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7076 if (checkArgCount(*this, TheCall, 2)) 7077 return true; 7078 7079 Expr *Arg0 = TheCall->getArg(0); 7080 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7081 if (FirstArg.isInvalid()) 7082 return true; 7083 QualType FirstArgType = FirstArg.get()->getType(); 7084 if (!FirstArgType->isAnyPointerType()) 7085 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7086 << "first" << FirstArgType << Arg0->getSourceRange(); 7087 TheCall->setArg(0, FirstArg.get()); 7088 7089 // Derive the return type from the pointer argument. 7090 TheCall->setType(FirstArgType); 7091 7092 // Second arg must be an constant in range [0,15] 7093 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7094 } 7095 7096 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7097 if (checkArgCount(*this, TheCall, 2)) 7098 return true; 7099 Expr *Arg0 = TheCall->getArg(0); 7100 Expr *Arg1 = TheCall->getArg(1); 7101 7102 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7103 if (FirstArg.isInvalid()) 7104 return true; 7105 QualType FirstArgType = FirstArg.get()->getType(); 7106 if (!FirstArgType->isAnyPointerType()) 7107 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7108 << "first" << FirstArgType << Arg0->getSourceRange(); 7109 7110 QualType SecArgType = Arg1->getType(); 7111 if (!SecArgType->isIntegerType()) 7112 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7113 << "second" << SecArgType << Arg1->getSourceRange(); 7114 TheCall->setType(Context.IntTy); 7115 return false; 7116 } 7117 7118 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7119 BuiltinID == AArch64::BI__builtin_arm_stg) { 7120 if (checkArgCount(*this, TheCall, 1)) 7121 return true; 7122 Expr *Arg0 = TheCall->getArg(0); 7123 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7124 if (FirstArg.isInvalid()) 7125 return true; 7126 7127 QualType FirstArgType = FirstArg.get()->getType(); 7128 if (!FirstArgType->isAnyPointerType()) 7129 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7130 << "first" << FirstArgType << Arg0->getSourceRange(); 7131 TheCall->setArg(0, FirstArg.get()); 7132 7133 // Derive the return type from the pointer argument. 7134 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7135 TheCall->setType(FirstArgType); 7136 return false; 7137 } 7138 7139 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7140 Expr *ArgA = TheCall->getArg(0); 7141 Expr *ArgB = TheCall->getArg(1); 7142 7143 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7144 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7145 7146 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7147 return true; 7148 7149 QualType ArgTypeA = ArgExprA.get()->getType(); 7150 QualType ArgTypeB = ArgExprB.get()->getType(); 7151 7152 auto isNull = [&] (Expr *E) -> bool { 7153 return E->isNullPointerConstant( 7154 Context, Expr::NPC_ValueDependentIsNotNull); }; 7155 7156 // argument should be either a pointer or null 7157 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7158 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7159 << "first" << ArgTypeA << ArgA->getSourceRange(); 7160 7161 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7162 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7163 << "second" << ArgTypeB << ArgB->getSourceRange(); 7164 7165 // Ensure Pointee types are compatible 7166 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7167 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7168 QualType pointeeA = ArgTypeA->getPointeeType(); 7169 QualType pointeeB = ArgTypeB->getPointeeType(); 7170 if (!Context.typesAreCompatible( 7171 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7172 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7173 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7174 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7175 << ArgB->getSourceRange(); 7176 } 7177 } 7178 7179 // at least one argument should be pointer type 7180 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7181 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7182 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7183 7184 if (isNull(ArgA)) // adopt type of the other pointer 7185 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7186 7187 if (isNull(ArgB)) 7188 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7189 7190 TheCall->setArg(0, ArgExprA.get()); 7191 TheCall->setArg(1, ArgExprB.get()); 7192 TheCall->setType(Context.LongLongTy); 7193 return false; 7194 } 7195 assert(false && "Unhandled ARM MTE intrinsic"); 7196 return true; 7197 } 7198 7199 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7200 /// TheCall is an ARM/AArch64 special register string literal. 7201 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7202 int ArgNum, unsigned ExpectedFieldNum, 7203 bool AllowName) { 7204 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7205 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7206 BuiltinID == ARM::BI__builtin_arm_rsr || 7207 BuiltinID == ARM::BI__builtin_arm_rsrp || 7208 BuiltinID == ARM::BI__builtin_arm_wsr || 7209 BuiltinID == ARM::BI__builtin_arm_wsrp; 7210 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7211 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7212 BuiltinID == AArch64::BI__builtin_arm_rsr || 7213 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7214 BuiltinID == AArch64::BI__builtin_arm_wsr || 7215 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7216 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7217 7218 // We can't check the value of a dependent argument. 7219 Expr *Arg = TheCall->getArg(ArgNum); 7220 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7221 return false; 7222 7223 // Check if the argument is a string literal. 7224 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7225 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7226 << Arg->getSourceRange(); 7227 7228 // Check the type of special register given. 7229 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7230 SmallVector<StringRef, 6> Fields; 7231 Reg.split(Fields, ":"); 7232 7233 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7234 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7235 << Arg->getSourceRange(); 7236 7237 // If the string is the name of a register then we cannot check that it is 7238 // valid here but if the string is of one the forms described in ACLE then we 7239 // can check that the supplied fields are integers and within the valid 7240 // ranges. 7241 if (Fields.size() > 1) { 7242 bool FiveFields = Fields.size() == 5; 7243 7244 bool ValidString = true; 7245 if (IsARMBuiltin) { 7246 ValidString &= Fields[0].startswith_insensitive("cp") || 7247 Fields[0].startswith_insensitive("p"); 7248 if (ValidString) 7249 Fields[0] = Fields[0].drop_front( 7250 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7251 7252 ValidString &= Fields[2].startswith_insensitive("c"); 7253 if (ValidString) 7254 Fields[2] = Fields[2].drop_front(1); 7255 7256 if (FiveFields) { 7257 ValidString &= Fields[3].startswith_insensitive("c"); 7258 if (ValidString) 7259 Fields[3] = Fields[3].drop_front(1); 7260 } 7261 } 7262 7263 SmallVector<int, 5> Ranges; 7264 if (FiveFields) 7265 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7266 else 7267 Ranges.append({15, 7, 15}); 7268 7269 for (unsigned i=0; i<Fields.size(); ++i) { 7270 int IntField; 7271 ValidString &= !Fields[i].getAsInteger(10, IntField); 7272 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7273 } 7274 7275 if (!ValidString) 7276 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7277 << Arg->getSourceRange(); 7278 } else if (IsAArch64Builtin && Fields.size() == 1) { 7279 // If the register name is one of those that appear in the condition below 7280 // and the special register builtin being used is one of the write builtins, 7281 // then we require that the argument provided for writing to the register 7282 // is an integer constant expression. This is because it will be lowered to 7283 // an MSR (immediate) instruction, so we need to know the immediate at 7284 // compile time. 7285 if (TheCall->getNumArgs() != 2) 7286 return false; 7287 7288 std::string RegLower = Reg.lower(); 7289 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7290 RegLower != "pan" && RegLower != "uao") 7291 return false; 7292 7293 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7294 } 7295 7296 return false; 7297 } 7298 7299 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7300 /// Emit an error and return true on failure; return false on success. 7301 /// TypeStr is a string containing the type descriptor of the value returned by 7302 /// the builtin and the descriptors of the expected type of the arguments. 7303 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 7304 7305 assert((TypeStr[0] != '\0') && 7306 "Invalid types in PPC MMA builtin declaration"); 7307 7308 unsigned Mask = 0; 7309 unsigned ArgNum = 0; 7310 7311 // The first type in TypeStr is the type of the value returned by the 7312 // builtin. So we first read that type and change the type of TheCall. 7313 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7314 TheCall->setType(type); 7315 7316 while (*TypeStr != '\0') { 7317 Mask = 0; 7318 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7319 if (ArgNum >= TheCall->getNumArgs()) { 7320 ArgNum++; 7321 break; 7322 } 7323 7324 Expr *Arg = TheCall->getArg(ArgNum); 7325 QualType ArgType = Arg->getType(); 7326 7327 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7328 (!ExpectedType->isVoidPointerType() && 7329 ArgType.getCanonicalType() != ExpectedType)) 7330 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7331 << ArgType << ExpectedType << 1 << 0 << 0; 7332 7333 // If the value of the Mask is not 0, we have a constraint in the size of 7334 // the integer argument so here we ensure the argument is a constant that 7335 // is in the valid range. 7336 if (Mask != 0 && 7337 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7338 return true; 7339 7340 ArgNum++; 7341 } 7342 7343 // In case we exited early from the previous loop, there are other types to 7344 // read from TypeStr. So we need to read them all to ensure we have the right 7345 // number of arguments in TheCall and if it is not the case, to display a 7346 // better error message. 7347 while (*TypeStr != '\0') { 7348 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7349 ArgNum++; 7350 } 7351 if (checkArgCount(*this, TheCall, ArgNum)) 7352 return true; 7353 7354 return false; 7355 } 7356 7357 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7358 /// This checks that the target supports __builtin_longjmp and 7359 /// that val is a constant 1. 7360 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7361 if (!Context.getTargetInfo().hasSjLjLowering()) 7362 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7363 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7364 7365 Expr *Arg = TheCall->getArg(1); 7366 llvm::APSInt Result; 7367 7368 // TODO: This is less than ideal. Overload this to take a value. 7369 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7370 return true; 7371 7372 if (Result != 1) 7373 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7374 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7375 7376 return false; 7377 } 7378 7379 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7380 /// This checks that the target supports __builtin_setjmp. 7381 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7382 if (!Context.getTargetInfo().hasSjLjLowering()) 7383 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7384 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7385 return false; 7386 } 7387 7388 namespace { 7389 7390 class UncoveredArgHandler { 7391 enum { Unknown = -1, AllCovered = -2 }; 7392 7393 signed FirstUncoveredArg = Unknown; 7394 SmallVector<const Expr *, 4> DiagnosticExprs; 7395 7396 public: 7397 UncoveredArgHandler() = default; 7398 7399 bool hasUncoveredArg() const { 7400 return (FirstUncoveredArg >= 0); 7401 } 7402 7403 unsigned getUncoveredArg() const { 7404 assert(hasUncoveredArg() && "no uncovered argument"); 7405 return FirstUncoveredArg; 7406 } 7407 7408 void setAllCovered() { 7409 // A string has been found with all arguments covered, so clear out 7410 // the diagnostics. 7411 DiagnosticExprs.clear(); 7412 FirstUncoveredArg = AllCovered; 7413 } 7414 7415 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7416 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7417 7418 // Don't update if a previous string covers all arguments. 7419 if (FirstUncoveredArg == AllCovered) 7420 return; 7421 7422 // UncoveredArgHandler tracks the highest uncovered argument index 7423 // and with it all the strings that match this index. 7424 if (NewFirstUncoveredArg == FirstUncoveredArg) 7425 DiagnosticExprs.push_back(StrExpr); 7426 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7427 DiagnosticExprs.clear(); 7428 DiagnosticExprs.push_back(StrExpr); 7429 FirstUncoveredArg = NewFirstUncoveredArg; 7430 } 7431 } 7432 7433 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7434 }; 7435 7436 enum StringLiteralCheckType { 7437 SLCT_NotALiteral, 7438 SLCT_UncheckedLiteral, 7439 SLCT_CheckedLiteral 7440 }; 7441 7442 } // namespace 7443 7444 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7445 BinaryOperatorKind BinOpKind, 7446 bool AddendIsRight) { 7447 unsigned BitWidth = Offset.getBitWidth(); 7448 unsigned AddendBitWidth = Addend.getBitWidth(); 7449 // There might be negative interim results. 7450 if (Addend.isUnsigned()) { 7451 Addend = Addend.zext(++AddendBitWidth); 7452 Addend.setIsSigned(true); 7453 } 7454 // Adjust the bit width of the APSInts. 7455 if (AddendBitWidth > BitWidth) { 7456 Offset = Offset.sext(AddendBitWidth); 7457 BitWidth = AddendBitWidth; 7458 } else if (BitWidth > AddendBitWidth) { 7459 Addend = Addend.sext(BitWidth); 7460 } 7461 7462 bool Ov = false; 7463 llvm::APSInt ResOffset = Offset; 7464 if (BinOpKind == BO_Add) 7465 ResOffset = Offset.sadd_ov(Addend, Ov); 7466 else { 7467 assert(AddendIsRight && BinOpKind == BO_Sub && 7468 "operator must be add or sub with addend on the right"); 7469 ResOffset = Offset.ssub_ov(Addend, Ov); 7470 } 7471 7472 // We add an offset to a pointer here so we should support an offset as big as 7473 // possible. 7474 if (Ov) { 7475 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7476 "index (intermediate) result too big"); 7477 Offset = Offset.sext(2 * BitWidth); 7478 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7479 return; 7480 } 7481 7482 Offset = ResOffset; 7483 } 7484 7485 namespace { 7486 7487 // This is a wrapper class around StringLiteral to support offsetted string 7488 // literals as format strings. It takes the offset into account when returning 7489 // the string and its length or the source locations to display notes correctly. 7490 class FormatStringLiteral { 7491 const StringLiteral *FExpr; 7492 int64_t Offset; 7493 7494 public: 7495 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7496 : FExpr(fexpr), Offset(Offset) {} 7497 7498 StringRef getString() const { 7499 return FExpr->getString().drop_front(Offset); 7500 } 7501 7502 unsigned getByteLength() const { 7503 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7504 } 7505 7506 unsigned getLength() const { return FExpr->getLength() - Offset; } 7507 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7508 7509 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7510 7511 QualType getType() const { return FExpr->getType(); } 7512 7513 bool isAscii() const { return FExpr->isAscii(); } 7514 bool isWide() const { return FExpr->isWide(); } 7515 bool isUTF8() const { return FExpr->isUTF8(); } 7516 bool isUTF16() const { return FExpr->isUTF16(); } 7517 bool isUTF32() const { return FExpr->isUTF32(); } 7518 bool isPascal() const { return FExpr->isPascal(); } 7519 7520 SourceLocation getLocationOfByte( 7521 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7522 const TargetInfo &Target, unsigned *StartToken = nullptr, 7523 unsigned *StartTokenByteOffset = nullptr) const { 7524 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7525 StartToken, StartTokenByteOffset); 7526 } 7527 7528 SourceLocation getBeginLoc() const LLVM_READONLY { 7529 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7530 } 7531 7532 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7533 }; 7534 7535 } // namespace 7536 7537 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7538 const Expr *OrigFormatExpr, 7539 ArrayRef<const Expr *> Args, 7540 bool HasVAListArg, unsigned format_idx, 7541 unsigned firstDataArg, 7542 Sema::FormatStringType Type, 7543 bool inFunctionCall, 7544 Sema::VariadicCallType CallType, 7545 llvm::SmallBitVector &CheckedVarArgs, 7546 UncoveredArgHandler &UncoveredArg, 7547 bool IgnoreStringsWithoutSpecifiers); 7548 7549 // Determine if an expression is a string literal or constant string. 7550 // If this function returns false on the arguments to a function expecting a 7551 // format string, we will usually need to emit a warning. 7552 // True string literals are then checked by CheckFormatString. 7553 static StringLiteralCheckType 7554 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7555 bool HasVAListArg, unsigned format_idx, 7556 unsigned firstDataArg, Sema::FormatStringType Type, 7557 Sema::VariadicCallType CallType, bool InFunctionCall, 7558 llvm::SmallBitVector &CheckedVarArgs, 7559 UncoveredArgHandler &UncoveredArg, 7560 llvm::APSInt Offset, 7561 bool IgnoreStringsWithoutSpecifiers = false) { 7562 if (S.isConstantEvaluated()) 7563 return SLCT_NotALiteral; 7564 tryAgain: 7565 assert(Offset.isSigned() && "invalid offset"); 7566 7567 if (E->isTypeDependent() || E->isValueDependent()) 7568 return SLCT_NotALiteral; 7569 7570 E = E->IgnoreParenCasts(); 7571 7572 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7573 // Technically -Wformat-nonliteral does not warn about this case. 7574 // The behavior of printf and friends in this case is implementation 7575 // dependent. Ideally if the format string cannot be null then 7576 // it should have a 'nonnull' attribute in the function prototype. 7577 return SLCT_UncheckedLiteral; 7578 7579 switch (E->getStmtClass()) { 7580 case Stmt::BinaryConditionalOperatorClass: 7581 case Stmt::ConditionalOperatorClass: { 7582 // The expression is a literal if both sub-expressions were, and it was 7583 // completely checked only if both sub-expressions were checked. 7584 const AbstractConditionalOperator *C = 7585 cast<AbstractConditionalOperator>(E); 7586 7587 // Determine whether it is necessary to check both sub-expressions, for 7588 // example, because the condition expression is a constant that can be 7589 // evaluated at compile time. 7590 bool CheckLeft = true, CheckRight = true; 7591 7592 bool Cond; 7593 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7594 S.isConstantEvaluated())) { 7595 if (Cond) 7596 CheckRight = false; 7597 else 7598 CheckLeft = false; 7599 } 7600 7601 // We need to maintain the offsets for the right and the left hand side 7602 // separately to check if every possible indexed expression is a valid 7603 // string literal. They might have different offsets for different string 7604 // literals in the end. 7605 StringLiteralCheckType Left; 7606 if (!CheckLeft) 7607 Left = SLCT_UncheckedLiteral; 7608 else { 7609 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7610 HasVAListArg, format_idx, firstDataArg, 7611 Type, CallType, InFunctionCall, 7612 CheckedVarArgs, UncoveredArg, Offset, 7613 IgnoreStringsWithoutSpecifiers); 7614 if (Left == SLCT_NotALiteral || !CheckRight) { 7615 return Left; 7616 } 7617 } 7618 7619 StringLiteralCheckType Right = checkFormatStringExpr( 7620 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7621 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7622 IgnoreStringsWithoutSpecifiers); 7623 7624 return (CheckLeft && Left < Right) ? Left : Right; 7625 } 7626 7627 case Stmt::ImplicitCastExprClass: 7628 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7629 goto tryAgain; 7630 7631 case Stmt::OpaqueValueExprClass: 7632 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7633 E = src; 7634 goto tryAgain; 7635 } 7636 return SLCT_NotALiteral; 7637 7638 case Stmt::PredefinedExprClass: 7639 // While __func__, etc., are technically not string literals, they 7640 // cannot contain format specifiers and thus are not a security 7641 // liability. 7642 return SLCT_UncheckedLiteral; 7643 7644 case Stmt::DeclRefExprClass: { 7645 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7646 7647 // As an exception, do not flag errors for variables binding to 7648 // const string literals. 7649 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7650 bool isConstant = false; 7651 QualType T = DR->getType(); 7652 7653 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7654 isConstant = AT->getElementType().isConstant(S.Context); 7655 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7656 isConstant = T.isConstant(S.Context) && 7657 PT->getPointeeType().isConstant(S.Context); 7658 } else if (T->isObjCObjectPointerType()) { 7659 // In ObjC, there is usually no "const ObjectPointer" type, 7660 // so don't check if the pointee type is constant. 7661 isConstant = T.isConstant(S.Context); 7662 } 7663 7664 if (isConstant) { 7665 if (const Expr *Init = VD->getAnyInitializer()) { 7666 // Look through initializers like const char c[] = { "foo" } 7667 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7668 if (InitList->isStringLiteralInit()) 7669 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7670 } 7671 return checkFormatStringExpr(S, Init, Args, 7672 HasVAListArg, format_idx, 7673 firstDataArg, Type, CallType, 7674 /*InFunctionCall*/ false, CheckedVarArgs, 7675 UncoveredArg, Offset); 7676 } 7677 } 7678 7679 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7680 // special check to see if the format string is a function parameter 7681 // of the function calling the printf function. If the function 7682 // has an attribute indicating it is a printf-like function, then we 7683 // should suppress warnings concerning non-literals being used in a call 7684 // to a vprintf function. For example: 7685 // 7686 // void 7687 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7688 // va_list ap; 7689 // va_start(ap, fmt); 7690 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7691 // ... 7692 // } 7693 if (HasVAListArg) { 7694 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7695 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7696 int PVIndex = PV->getFunctionScopeIndex() + 1; 7697 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7698 // adjust for implicit parameter 7699 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7700 if (MD->isInstance()) 7701 ++PVIndex; 7702 // We also check if the formats are compatible. 7703 // We can't pass a 'scanf' string to a 'printf' function. 7704 if (PVIndex == PVFormat->getFormatIdx() && 7705 Type == S.GetFormatStringType(PVFormat)) 7706 return SLCT_UncheckedLiteral; 7707 } 7708 } 7709 } 7710 } 7711 } 7712 7713 return SLCT_NotALiteral; 7714 } 7715 7716 case Stmt::CallExprClass: 7717 case Stmt::CXXMemberCallExprClass: { 7718 const CallExpr *CE = cast<CallExpr>(E); 7719 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7720 bool IsFirst = true; 7721 StringLiteralCheckType CommonResult; 7722 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7723 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7724 StringLiteralCheckType Result = checkFormatStringExpr( 7725 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7726 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7727 IgnoreStringsWithoutSpecifiers); 7728 if (IsFirst) { 7729 CommonResult = Result; 7730 IsFirst = false; 7731 } 7732 } 7733 if (!IsFirst) 7734 return CommonResult; 7735 7736 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7737 unsigned BuiltinID = FD->getBuiltinID(); 7738 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7739 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7740 const Expr *Arg = CE->getArg(0); 7741 return checkFormatStringExpr(S, Arg, Args, 7742 HasVAListArg, format_idx, 7743 firstDataArg, Type, CallType, 7744 InFunctionCall, CheckedVarArgs, 7745 UncoveredArg, Offset, 7746 IgnoreStringsWithoutSpecifiers); 7747 } 7748 } 7749 } 7750 7751 return SLCT_NotALiteral; 7752 } 7753 case Stmt::ObjCMessageExprClass: { 7754 const auto *ME = cast<ObjCMessageExpr>(E); 7755 if (const auto *MD = ME->getMethodDecl()) { 7756 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7757 // As a special case heuristic, if we're using the method -[NSBundle 7758 // localizedStringForKey:value:table:], ignore any key strings that lack 7759 // format specifiers. The idea is that if the key doesn't have any 7760 // format specifiers then its probably just a key to map to the 7761 // localized strings. If it does have format specifiers though, then its 7762 // likely that the text of the key is the format string in the 7763 // programmer's language, and should be checked. 7764 const ObjCInterfaceDecl *IFace; 7765 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7766 IFace->getIdentifier()->isStr("NSBundle") && 7767 MD->getSelector().isKeywordSelector( 7768 {"localizedStringForKey", "value", "table"})) { 7769 IgnoreStringsWithoutSpecifiers = true; 7770 } 7771 7772 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7773 return checkFormatStringExpr( 7774 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7775 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7776 IgnoreStringsWithoutSpecifiers); 7777 } 7778 } 7779 7780 return SLCT_NotALiteral; 7781 } 7782 case Stmt::ObjCStringLiteralClass: 7783 case Stmt::StringLiteralClass: { 7784 const StringLiteral *StrE = nullptr; 7785 7786 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7787 StrE = ObjCFExpr->getString(); 7788 else 7789 StrE = cast<StringLiteral>(E); 7790 7791 if (StrE) { 7792 if (Offset.isNegative() || Offset > StrE->getLength()) { 7793 // TODO: It would be better to have an explicit warning for out of 7794 // bounds literals. 7795 return SLCT_NotALiteral; 7796 } 7797 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7798 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7799 firstDataArg, Type, InFunctionCall, CallType, 7800 CheckedVarArgs, UncoveredArg, 7801 IgnoreStringsWithoutSpecifiers); 7802 return SLCT_CheckedLiteral; 7803 } 7804 7805 return SLCT_NotALiteral; 7806 } 7807 case Stmt::BinaryOperatorClass: { 7808 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7809 7810 // A string literal + an int offset is still a string literal. 7811 if (BinOp->isAdditiveOp()) { 7812 Expr::EvalResult LResult, RResult; 7813 7814 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7815 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7816 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7817 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7818 7819 if (LIsInt != RIsInt) { 7820 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7821 7822 if (LIsInt) { 7823 if (BinOpKind == BO_Add) { 7824 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7825 E = BinOp->getRHS(); 7826 goto tryAgain; 7827 } 7828 } else { 7829 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7830 E = BinOp->getLHS(); 7831 goto tryAgain; 7832 } 7833 } 7834 } 7835 7836 return SLCT_NotALiteral; 7837 } 7838 case Stmt::UnaryOperatorClass: { 7839 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7840 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7841 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7842 Expr::EvalResult IndexResult; 7843 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7844 Expr::SE_NoSideEffects, 7845 S.isConstantEvaluated())) { 7846 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7847 /*RHS is int*/ true); 7848 E = ASE->getBase(); 7849 goto tryAgain; 7850 } 7851 } 7852 7853 return SLCT_NotALiteral; 7854 } 7855 7856 default: 7857 return SLCT_NotALiteral; 7858 } 7859 } 7860 7861 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7862 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7863 .Case("scanf", FST_Scanf) 7864 .Cases("printf", "printf0", FST_Printf) 7865 .Cases("NSString", "CFString", FST_NSString) 7866 .Case("strftime", FST_Strftime) 7867 .Case("strfmon", FST_Strfmon) 7868 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7869 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7870 .Case("os_trace", FST_OSLog) 7871 .Case("os_log", FST_OSLog) 7872 .Default(FST_Unknown); 7873 } 7874 7875 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7876 /// functions) for correct use of format strings. 7877 /// Returns true if a format string has been fully checked. 7878 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7879 ArrayRef<const Expr *> Args, 7880 bool IsCXXMember, 7881 VariadicCallType CallType, 7882 SourceLocation Loc, SourceRange Range, 7883 llvm::SmallBitVector &CheckedVarArgs) { 7884 FormatStringInfo FSI; 7885 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7886 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7887 FSI.FirstDataArg, GetFormatStringType(Format), 7888 CallType, Loc, Range, CheckedVarArgs); 7889 return false; 7890 } 7891 7892 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7893 bool HasVAListArg, unsigned format_idx, 7894 unsigned firstDataArg, FormatStringType Type, 7895 VariadicCallType CallType, 7896 SourceLocation Loc, SourceRange Range, 7897 llvm::SmallBitVector &CheckedVarArgs) { 7898 // CHECK: printf/scanf-like function is called with no format string. 7899 if (format_idx >= Args.size()) { 7900 Diag(Loc, diag::warn_missing_format_string) << Range; 7901 return false; 7902 } 7903 7904 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7905 7906 // CHECK: format string is not a string literal. 7907 // 7908 // Dynamically generated format strings are difficult to 7909 // automatically vet at compile time. Requiring that format strings 7910 // are string literals: (1) permits the checking of format strings by 7911 // the compiler and thereby (2) can practically remove the source of 7912 // many format string exploits. 7913 7914 // Format string can be either ObjC string (e.g. @"%d") or 7915 // C string (e.g. "%d") 7916 // ObjC string uses the same format specifiers as C string, so we can use 7917 // the same format string checking logic for both ObjC and C strings. 7918 UncoveredArgHandler UncoveredArg; 7919 StringLiteralCheckType CT = 7920 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7921 format_idx, firstDataArg, Type, CallType, 7922 /*IsFunctionCall*/ true, CheckedVarArgs, 7923 UncoveredArg, 7924 /*no string offset*/ llvm::APSInt(64, false) = 0); 7925 7926 // Generate a diagnostic where an uncovered argument is detected. 7927 if (UncoveredArg.hasUncoveredArg()) { 7928 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7929 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7930 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7931 } 7932 7933 if (CT != SLCT_NotALiteral) 7934 // Literal format string found, check done! 7935 return CT == SLCT_CheckedLiteral; 7936 7937 // Strftime is particular as it always uses a single 'time' argument, 7938 // so it is safe to pass a non-literal string. 7939 if (Type == FST_Strftime) 7940 return false; 7941 7942 // Do not emit diag when the string param is a macro expansion and the 7943 // format is either NSString or CFString. This is a hack to prevent 7944 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7945 // which are usually used in place of NS and CF string literals. 7946 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7947 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7948 return false; 7949 7950 // If there are no arguments specified, warn with -Wformat-security, otherwise 7951 // warn only with -Wformat-nonliteral. 7952 if (Args.size() == firstDataArg) { 7953 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7954 << OrigFormatExpr->getSourceRange(); 7955 switch (Type) { 7956 default: 7957 break; 7958 case FST_Kprintf: 7959 case FST_FreeBSDKPrintf: 7960 case FST_Printf: 7961 Diag(FormatLoc, diag::note_format_security_fixit) 7962 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7963 break; 7964 case FST_NSString: 7965 Diag(FormatLoc, diag::note_format_security_fixit) 7966 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7967 break; 7968 } 7969 } else { 7970 Diag(FormatLoc, diag::warn_format_nonliteral) 7971 << OrigFormatExpr->getSourceRange(); 7972 } 7973 return false; 7974 } 7975 7976 namespace { 7977 7978 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7979 protected: 7980 Sema &S; 7981 const FormatStringLiteral *FExpr; 7982 const Expr *OrigFormatExpr; 7983 const Sema::FormatStringType FSType; 7984 const unsigned FirstDataArg; 7985 const unsigned NumDataArgs; 7986 const char *Beg; // Start of format string. 7987 const bool HasVAListArg; 7988 ArrayRef<const Expr *> Args; 7989 unsigned FormatIdx; 7990 llvm::SmallBitVector CoveredArgs; 7991 bool usesPositionalArgs = false; 7992 bool atFirstArg = true; 7993 bool inFunctionCall; 7994 Sema::VariadicCallType CallType; 7995 llvm::SmallBitVector &CheckedVarArgs; 7996 UncoveredArgHandler &UncoveredArg; 7997 7998 public: 7999 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8000 const Expr *origFormatExpr, 8001 const Sema::FormatStringType type, unsigned firstDataArg, 8002 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8003 ArrayRef<const Expr *> Args, unsigned formatIdx, 8004 bool inFunctionCall, Sema::VariadicCallType callType, 8005 llvm::SmallBitVector &CheckedVarArgs, 8006 UncoveredArgHandler &UncoveredArg) 8007 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8008 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8009 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8010 inFunctionCall(inFunctionCall), CallType(callType), 8011 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8012 CoveredArgs.resize(numDataArgs); 8013 CoveredArgs.reset(); 8014 } 8015 8016 void DoneProcessing(); 8017 8018 void HandleIncompleteSpecifier(const char *startSpecifier, 8019 unsigned specifierLen) override; 8020 8021 void HandleInvalidLengthModifier( 8022 const analyze_format_string::FormatSpecifier &FS, 8023 const analyze_format_string::ConversionSpecifier &CS, 8024 const char *startSpecifier, unsigned specifierLen, 8025 unsigned DiagID); 8026 8027 void HandleNonStandardLengthModifier( 8028 const analyze_format_string::FormatSpecifier &FS, 8029 const char *startSpecifier, unsigned specifierLen); 8030 8031 void HandleNonStandardConversionSpecifier( 8032 const analyze_format_string::ConversionSpecifier &CS, 8033 const char *startSpecifier, unsigned specifierLen); 8034 8035 void HandlePosition(const char *startPos, unsigned posLen) override; 8036 8037 void HandleInvalidPosition(const char *startSpecifier, 8038 unsigned specifierLen, 8039 analyze_format_string::PositionContext p) override; 8040 8041 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8042 8043 void HandleNullChar(const char *nullCharacter) override; 8044 8045 template <typename Range> 8046 static void 8047 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8048 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8049 bool IsStringLocation, Range StringRange, 8050 ArrayRef<FixItHint> Fixit = None); 8051 8052 protected: 8053 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8054 const char *startSpec, 8055 unsigned specifierLen, 8056 const char *csStart, unsigned csLen); 8057 8058 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8059 const char *startSpec, 8060 unsigned specifierLen); 8061 8062 SourceRange getFormatStringRange(); 8063 CharSourceRange getSpecifierRange(const char *startSpecifier, 8064 unsigned specifierLen); 8065 SourceLocation getLocationOfByte(const char *x); 8066 8067 const Expr *getDataArg(unsigned i) const; 8068 8069 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8070 const analyze_format_string::ConversionSpecifier &CS, 8071 const char *startSpecifier, unsigned specifierLen, 8072 unsigned argIndex); 8073 8074 template <typename Range> 8075 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8076 bool IsStringLocation, Range StringRange, 8077 ArrayRef<FixItHint> Fixit = None); 8078 }; 8079 8080 } // namespace 8081 8082 SourceRange CheckFormatHandler::getFormatStringRange() { 8083 return OrigFormatExpr->getSourceRange(); 8084 } 8085 8086 CharSourceRange CheckFormatHandler:: 8087 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8088 SourceLocation Start = getLocationOfByte(startSpecifier); 8089 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8090 8091 // Advance the end SourceLocation by one due to half-open ranges. 8092 End = End.getLocWithOffset(1); 8093 8094 return CharSourceRange::getCharRange(Start, End); 8095 } 8096 8097 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8098 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8099 S.getLangOpts(), S.Context.getTargetInfo()); 8100 } 8101 8102 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8103 unsigned specifierLen){ 8104 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8105 getLocationOfByte(startSpecifier), 8106 /*IsStringLocation*/true, 8107 getSpecifierRange(startSpecifier, specifierLen)); 8108 } 8109 8110 void CheckFormatHandler::HandleInvalidLengthModifier( 8111 const analyze_format_string::FormatSpecifier &FS, 8112 const analyze_format_string::ConversionSpecifier &CS, 8113 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8114 using namespace analyze_format_string; 8115 8116 const LengthModifier &LM = FS.getLengthModifier(); 8117 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8118 8119 // See if we know how to fix this length modifier. 8120 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8121 if (FixedLM) { 8122 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8123 getLocationOfByte(LM.getStart()), 8124 /*IsStringLocation*/true, 8125 getSpecifierRange(startSpecifier, specifierLen)); 8126 8127 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8128 << FixedLM->toString() 8129 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8130 8131 } else { 8132 FixItHint Hint; 8133 if (DiagID == diag::warn_format_nonsensical_length) 8134 Hint = FixItHint::CreateRemoval(LMRange); 8135 8136 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8137 getLocationOfByte(LM.getStart()), 8138 /*IsStringLocation*/true, 8139 getSpecifierRange(startSpecifier, specifierLen), 8140 Hint); 8141 } 8142 } 8143 8144 void CheckFormatHandler::HandleNonStandardLengthModifier( 8145 const analyze_format_string::FormatSpecifier &FS, 8146 const char *startSpecifier, unsigned specifierLen) { 8147 using namespace analyze_format_string; 8148 8149 const LengthModifier &LM = FS.getLengthModifier(); 8150 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8151 8152 // See if we know how to fix this length modifier. 8153 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8154 if (FixedLM) { 8155 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8156 << LM.toString() << 0, 8157 getLocationOfByte(LM.getStart()), 8158 /*IsStringLocation*/true, 8159 getSpecifierRange(startSpecifier, specifierLen)); 8160 8161 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8162 << FixedLM->toString() 8163 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8164 8165 } else { 8166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8167 << LM.toString() << 0, 8168 getLocationOfByte(LM.getStart()), 8169 /*IsStringLocation*/true, 8170 getSpecifierRange(startSpecifier, specifierLen)); 8171 } 8172 } 8173 8174 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8175 const analyze_format_string::ConversionSpecifier &CS, 8176 const char *startSpecifier, unsigned specifierLen) { 8177 using namespace analyze_format_string; 8178 8179 // See if we know how to fix this conversion specifier. 8180 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8181 if (FixedCS) { 8182 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8183 << CS.toString() << /*conversion specifier*/1, 8184 getLocationOfByte(CS.getStart()), 8185 /*IsStringLocation*/true, 8186 getSpecifierRange(startSpecifier, specifierLen)); 8187 8188 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8189 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8190 << FixedCS->toString() 8191 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8192 } else { 8193 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8194 << CS.toString() << /*conversion specifier*/1, 8195 getLocationOfByte(CS.getStart()), 8196 /*IsStringLocation*/true, 8197 getSpecifierRange(startSpecifier, specifierLen)); 8198 } 8199 } 8200 8201 void CheckFormatHandler::HandlePosition(const char *startPos, 8202 unsigned posLen) { 8203 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8204 getLocationOfByte(startPos), 8205 /*IsStringLocation*/true, 8206 getSpecifierRange(startPos, posLen)); 8207 } 8208 8209 void 8210 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8211 analyze_format_string::PositionContext p) { 8212 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8213 << (unsigned) p, 8214 getLocationOfByte(startPos), /*IsStringLocation*/true, 8215 getSpecifierRange(startPos, posLen)); 8216 } 8217 8218 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8219 unsigned posLen) { 8220 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8221 getLocationOfByte(startPos), 8222 /*IsStringLocation*/true, 8223 getSpecifierRange(startPos, posLen)); 8224 } 8225 8226 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8227 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8228 // The presence of a null character is likely an error. 8229 EmitFormatDiagnostic( 8230 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8231 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8232 getFormatStringRange()); 8233 } 8234 } 8235 8236 // Note that this may return NULL if there was an error parsing or building 8237 // one of the argument expressions. 8238 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8239 return Args[FirstDataArg + i]; 8240 } 8241 8242 void CheckFormatHandler::DoneProcessing() { 8243 // Does the number of data arguments exceed the number of 8244 // format conversions in the format string? 8245 if (!HasVAListArg) { 8246 // Find any arguments that weren't covered. 8247 CoveredArgs.flip(); 8248 signed notCoveredArg = CoveredArgs.find_first(); 8249 if (notCoveredArg >= 0) { 8250 assert((unsigned)notCoveredArg < NumDataArgs); 8251 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8252 } else { 8253 UncoveredArg.setAllCovered(); 8254 } 8255 } 8256 } 8257 8258 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8259 const Expr *ArgExpr) { 8260 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8261 "Invalid state"); 8262 8263 if (!ArgExpr) 8264 return; 8265 8266 SourceLocation Loc = ArgExpr->getBeginLoc(); 8267 8268 if (S.getSourceManager().isInSystemMacro(Loc)) 8269 return; 8270 8271 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8272 for (auto E : DiagnosticExprs) 8273 PDiag << E->getSourceRange(); 8274 8275 CheckFormatHandler::EmitFormatDiagnostic( 8276 S, IsFunctionCall, DiagnosticExprs[0], 8277 PDiag, Loc, /*IsStringLocation*/false, 8278 DiagnosticExprs[0]->getSourceRange()); 8279 } 8280 8281 bool 8282 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8283 SourceLocation Loc, 8284 const char *startSpec, 8285 unsigned specifierLen, 8286 const char *csStart, 8287 unsigned csLen) { 8288 bool keepGoing = true; 8289 if (argIndex < NumDataArgs) { 8290 // Consider the argument coverered, even though the specifier doesn't 8291 // make sense. 8292 CoveredArgs.set(argIndex); 8293 } 8294 else { 8295 // If argIndex exceeds the number of data arguments we 8296 // don't issue a warning because that is just a cascade of warnings (and 8297 // they may have intended '%%' anyway). We don't want to continue processing 8298 // the format string after this point, however, as we will like just get 8299 // gibberish when trying to match arguments. 8300 keepGoing = false; 8301 } 8302 8303 StringRef Specifier(csStart, csLen); 8304 8305 // If the specifier in non-printable, it could be the first byte of a UTF-8 8306 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8307 // hex value. 8308 std::string CodePointStr; 8309 if (!llvm::sys::locale::isPrint(*csStart)) { 8310 llvm::UTF32 CodePoint; 8311 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8312 const llvm::UTF8 *E = 8313 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8314 llvm::ConversionResult Result = 8315 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8316 8317 if (Result != llvm::conversionOK) { 8318 unsigned char FirstChar = *csStart; 8319 CodePoint = (llvm::UTF32)FirstChar; 8320 } 8321 8322 llvm::raw_string_ostream OS(CodePointStr); 8323 if (CodePoint < 256) 8324 OS << "\\x" << llvm::format("%02x", CodePoint); 8325 else if (CodePoint <= 0xFFFF) 8326 OS << "\\u" << llvm::format("%04x", CodePoint); 8327 else 8328 OS << "\\U" << llvm::format("%08x", CodePoint); 8329 OS.flush(); 8330 Specifier = CodePointStr; 8331 } 8332 8333 EmitFormatDiagnostic( 8334 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8335 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8336 8337 return keepGoing; 8338 } 8339 8340 void 8341 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8342 const char *startSpec, 8343 unsigned specifierLen) { 8344 EmitFormatDiagnostic( 8345 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8346 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8347 } 8348 8349 bool 8350 CheckFormatHandler::CheckNumArgs( 8351 const analyze_format_string::FormatSpecifier &FS, 8352 const analyze_format_string::ConversionSpecifier &CS, 8353 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8354 8355 if (argIndex >= NumDataArgs) { 8356 PartialDiagnostic PDiag = FS.usesPositionalArg() 8357 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8358 << (argIndex+1) << NumDataArgs) 8359 : S.PDiag(diag::warn_printf_insufficient_data_args); 8360 EmitFormatDiagnostic( 8361 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8362 getSpecifierRange(startSpecifier, specifierLen)); 8363 8364 // Since more arguments than conversion tokens are given, by extension 8365 // all arguments are covered, so mark this as so. 8366 UncoveredArg.setAllCovered(); 8367 return false; 8368 } 8369 return true; 8370 } 8371 8372 template<typename Range> 8373 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8374 SourceLocation Loc, 8375 bool IsStringLocation, 8376 Range StringRange, 8377 ArrayRef<FixItHint> FixIt) { 8378 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8379 Loc, IsStringLocation, StringRange, FixIt); 8380 } 8381 8382 /// If the format string is not within the function call, emit a note 8383 /// so that the function call and string are in diagnostic messages. 8384 /// 8385 /// \param InFunctionCall if true, the format string is within the function 8386 /// call and only one diagnostic message will be produced. Otherwise, an 8387 /// extra note will be emitted pointing to location of the format string. 8388 /// 8389 /// \param ArgumentExpr the expression that is passed as the format string 8390 /// argument in the function call. Used for getting locations when two 8391 /// diagnostics are emitted. 8392 /// 8393 /// \param PDiag the callee should already have provided any strings for the 8394 /// diagnostic message. This function only adds locations and fixits 8395 /// to diagnostics. 8396 /// 8397 /// \param Loc primary location for diagnostic. If two diagnostics are 8398 /// required, one will be at Loc and a new SourceLocation will be created for 8399 /// the other one. 8400 /// 8401 /// \param IsStringLocation if true, Loc points to the format string should be 8402 /// used for the note. Otherwise, Loc points to the argument list and will 8403 /// be used with PDiag. 8404 /// 8405 /// \param StringRange some or all of the string to highlight. This is 8406 /// templated so it can accept either a CharSourceRange or a SourceRange. 8407 /// 8408 /// \param FixIt optional fix it hint for the format string. 8409 template <typename Range> 8410 void CheckFormatHandler::EmitFormatDiagnostic( 8411 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8412 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8413 Range StringRange, ArrayRef<FixItHint> FixIt) { 8414 if (InFunctionCall) { 8415 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8416 D << StringRange; 8417 D << FixIt; 8418 } else { 8419 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8420 << ArgumentExpr->getSourceRange(); 8421 8422 const Sema::SemaDiagnosticBuilder &Note = 8423 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8424 diag::note_format_string_defined); 8425 8426 Note << StringRange; 8427 Note << FixIt; 8428 } 8429 } 8430 8431 //===--- CHECK: Printf format string checking ------------------------------===// 8432 8433 namespace { 8434 8435 class CheckPrintfHandler : public CheckFormatHandler { 8436 public: 8437 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8438 const Expr *origFormatExpr, 8439 const Sema::FormatStringType type, unsigned firstDataArg, 8440 unsigned numDataArgs, bool isObjC, const char *beg, 8441 bool hasVAListArg, ArrayRef<const Expr *> Args, 8442 unsigned formatIdx, bool inFunctionCall, 8443 Sema::VariadicCallType CallType, 8444 llvm::SmallBitVector &CheckedVarArgs, 8445 UncoveredArgHandler &UncoveredArg) 8446 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8447 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8448 inFunctionCall, CallType, CheckedVarArgs, 8449 UncoveredArg) {} 8450 8451 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8452 8453 /// Returns true if '%@' specifiers are allowed in the format string. 8454 bool allowsObjCArg() const { 8455 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8456 FSType == Sema::FST_OSTrace; 8457 } 8458 8459 bool HandleInvalidPrintfConversionSpecifier( 8460 const analyze_printf::PrintfSpecifier &FS, 8461 const char *startSpecifier, 8462 unsigned specifierLen) override; 8463 8464 void handleInvalidMaskType(StringRef MaskType) override; 8465 8466 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8467 const char *startSpecifier, 8468 unsigned specifierLen) override; 8469 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8470 const char *StartSpecifier, 8471 unsigned SpecifierLen, 8472 const Expr *E); 8473 8474 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8475 const char *startSpecifier, unsigned specifierLen); 8476 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8477 const analyze_printf::OptionalAmount &Amt, 8478 unsigned type, 8479 const char *startSpecifier, unsigned specifierLen); 8480 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8481 const analyze_printf::OptionalFlag &flag, 8482 const char *startSpecifier, unsigned specifierLen); 8483 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8484 const analyze_printf::OptionalFlag &ignoredFlag, 8485 const analyze_printf::OptionalFlag &flag, 8486 const char *startSpecifier, unsigned specifierLen); 8487 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8488 const Expr *E); 8489 8490 void HandleEmptyObjCModifierFlag(const char *startFlag, 8491 unsigned flagLen) override; 8492 8493 void HandleInvalidObjCModifierFlag(const char *startFlag, 8494 unsigned flagLen) override; 8495 8496 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8497 const char *flagsEnd, 8498 const char *conversionPosition) 8499 override; 8500 }; 8501 8502 } // namespace 8503 8504 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8505 const analyze_printf::PrintfSpecifier &FS, 8506 const char *startSpecifier, 8507 unsigned specifierLen) { 8508 const analyze_printf::PrintfConversionSpecifier &CS = 8509 FS.getConversionSpecifier(); 8510 8511 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8512 getLocationOfByte(CS.getStart()), 8513 startSpecifier, specifierLen, 8514 CS.getStart(), CS.getLength()); 8515 } 8516 8517 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8518 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8519 } 8520 8521 bool CheckPrintfHandler::HandleAmount( 8522 const analyze_format_string::OptionalAmount &Amt, 8523 unsigned k, const char *startSpecifier, 8524 unsigned specifierLen) { 8525 if (Amt.hasDataArgument()) { 8526 if (!HasVAListArg) { 8527 unsigned argIndex = Amt.getArgIndex(); 8528 if (argIndex >= NumDataArgs) { 8529 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8530 << k, 8531 getLocationOfByte(Amt.getStart()), 8532 /*IsStringLocation*/true, 8533 getSpecifierRange(startSpecifier, specifierLen)); 8534 // Don't do any more checking. We will just emit 8535 // spurious errors. 8536 return false; 8537 } 8538 8539 // Type check the data argument. It should be an 'int'. 8540 // Although not in conformance with C99, we also allow the argument to be 8541 // an 'unsigned int' as that is a reasonably safe case. GCC also 8542 // doesn't emit a warning for that case. 8543 CoveredArgs.set(argIndex); 8544 const Expr *Arg = getDataArg(argIndex); 8545 if (!Arg) 8546 return false; 8547 8548 QualType T = Arg->getType(); 8549 8550 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8551 assert(AT.isValid()); 8552 8553 if (!AT.matchesType(S.Context, T)) { 8554 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8555 << k << AT.getRepresentativeTypeName(S.Context) 8556 << T << Arg->getSourceRange(), 8557 getLocationOfByte(Amt.getStart()), 8558 /*IsStringLocation*/true, 8559 getSpecifierRange(startSpecifier, specifierLen)); 8560 // Don't do any more checking. We will just emit 8561 // spurious errors. 8562 return false; 8563 } 8564 } 8565 } 8566 return true; 8567 } 8568 8569 void CheckPrintfHandler::HandleInvalidAmount( 8570 const analyze_printf::PrintfSpecifier &FS, 8571 const analyze_printf::OptionalAmount &Amt, 8572 unsigned type, 8573 const char *startSpecifier, 8574 unsigned specifierLen) { 8575 const analyze_printf::PrintfConversionSpecifier &CS = 8576 FS.getConversionSpecifier(); 8577 8578 FixItHint fixit = 8579 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8580 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8581 Amt.getConstantLength())) 8582 : FixItHint(); 8583 8584 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8585 << type << CS.toString(), 8586 getLocationOfByte(Amt.getStart()), 8587 /*IsStringLocation*/true, 8588 getSpecifierRange(startSpecifier, specifierLen), 8589 fixit); 8590 } 8591 8592 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8593 const analyze_printf::OptionalFlag &flag, 8594 const char *startSpecifier, 8595 unsigned specifierLen) { 8596 // Warn about pointless flag with a fixit removal. 8597 const analyze_printf::PrintfConversionSpecifier &CS = 8598 FS.getConversionSpecifier(); 8599 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8600 << flag.toString() << CS.toString(), 8601 getLocationOfByte(flag.getPosition()), 8602 /*IsStringLocation*/true, 8603 getSpecifierRange(startSpecifier, specifierLen), 8604 FixItHint::CreateRemoval( 8605 getSpecifierRange(flag.getPosition(), 1))); 8606 } 8607 8608 void CheckPrintfHandler::HandleIgnoredFlag( 8609 const analyze_printf::PrintfSpecifier &FS, 8610 const analyze_printf::OptionalFlag &ignoredFlag, 8611 const analyze_printf::OptionalFlag &flag, 8612 const char *startSpecifier, 8613 unsigned specifierLen) { 8614 // Warn about ignored flag with a fixit removal. 8615 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8616 << ignoredFlag.toString() << flag.toString(), 8617 getLocationOfByte(ignoredFlag.getPosition()), 8618 /*IsStringLocation*/true, 8619 getSpecifierRange(startSpecifier, specifierLen), 8620 FixItHint::CreateRemoval( 8621 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8622 } 8623 8624 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8625 unsigned flagLen) { 8626 // Warn about an empty flag. 8627 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8628 getLocationOfByte(startFlag), 8629 /*IsStringLocation*/true, 8630 getSpecifierRange(startFlag, flagLen)); 8631 } 8632 8633 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8634 unsigned flagLen) { 8635 // Warn about an invalid flag. 8636 auto Range = getSpecifierRange(startFlag, flagLen); 8637 StringRef flag(startFlag, flagLen); 8638 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8639 getLocationOfByte(startFlag), 8640 /*IsStringLocation*/true, 8641 Range, FixItHint::CreateRemoval(Range)); 8642 } 8643 8644 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8645 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8646 // Warn about using '[...]' without a '@' conversion. 8647 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8648 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8649 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8650 getLocationOfByte(conversionPosition), 8651 /*IsStringLocation*/true, 8652 Range, FixItHint::CreateRemoval(Range)); 8653 } 8654 8655 // Determines if the specified is a C++ class or struct containing 8656 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8657 // "c_str()"). 8658 template<typename MemberKind> 8659 static llvm::SmallPtrSet<MemberKind*, 1> 8660 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8661 const RecordType *RT = Ty->getAs<RecordType>(); 8662 llvm::SmallPtrSet<MemberKind*, 1> Results; 8663 8664 if (!RT) 8665 return Results; 8666 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8667 if (!RD || !RD->getDefinition()) 8668 return Results; 8669 8670 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8671 Sema::LookupMemberName); 8672 R.suppressDiagnostics(); 8673 8674 // We just need to include all members of the right kind turned up by the 8675 // filter, at this point. 8676 if (S.LookupQualifiedName(R, RT->getDecl())) 8677 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8678 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8679 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8680 Results.insert(FK); 8681 } 8682 return Results; 8683 } 8684 8685 /// Check if we could call '.c_str()' on an object. 8686 /// 8687 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8688 /// allow the call, or if it would be ambiguous). 8689 bool Sema::hasCStrMethod(const Expr *E) { 8690 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8691 8692 MethodSet Results = 8693 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8694 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8695 MI != ME; ++MI) 8696 if ((*MI)->getMinRequiredArguments() == 0) 8697 return true; 8698 return false; 8699 } 8700 8701 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8702 // better diagnostic if so. AT is assumed to be valid. 8703 // Returns true when a c_str() conversion method is found. 8704 bool CheckPrintfHandler::checkForCStrMembers( 8705 const analyze_printf::ArgType &AT, const Expr *E) { 8706 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8707 8708 MethodSet Results = 8709 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8710 8711 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8712 MI != ME; ++MI) { 8713 const CXXMethodDecl *Method = *MI; 8714 if (Method->getMinRequiredArguments() == 0 && 8715 AT.matchesType(S.Context, Method->getReturnType())) { 8716 // FIXME: Suggest parens if the expression needs them. 8717 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8718 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8719 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8720 return true; 8721 } 8722 } 8723 8724 return false; 8725 } 8726 8727 bool 8728 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8729 &FS, 8730 const char *startSpecifier, 8731 unsigned specifierLen) { 8732 using namespace analyze_format_string; 8733 using namespace analyze_printf; 8734 8735 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8736 8737 if (FS.consumesDataArgument()) { 8738 if (atFirstArg) { 8739 atFirstArg = false; 8740 usesPositionalArgs = FS.usesPositionalArg(); 8741 } 8742 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8743 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8744 startSpecifier, specifierLen); 8745 return false; 8746 } 8747 } 8748 8749 // First check if the field width, precision, and conversion specifier 8750 // have matching data arguments. 8751 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8752 startSpecifier, specifierLen)) { 8753 return false; 8754 } 8755 8756 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8757 startSpecifier, specifierLen)) { 8758 return false; 8759 } 8760 8761 if (!CS.consumesDataArgument()) { 8762 // FIXME: Technically specifying a precision or field width here 8763 // makes no sense. Worth issuing a warning at some point. 8764 return true; 8765 } 8766 8767 // Consume the argument. 8768 unsigned argIndex = FS.getArgIndex(); 8769 if (argIndex < NumDataArgs) { 8770 // The check to see if the argIndex is valid will come later. 8771 // We set the bit here because we may exit early from this 8772 // function if we encounter some other error. 8773 CoveredArgs.set(argIndex); 8774 } 8775 8776 // FreeBSD kernel extensions. 8777 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8778 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8779 // We need at least two arguments. 8780 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8781 return false; 8782 8783 // Claim the second argument. 8784 CoveredArgs.set(argIndex + 1); 8785 8786 // Type check the first argument (int for %b, pointer for %D) 8787 const Expr *Ex = getDataArg(argIndex); 8788 const analyze_printf::ArgType &AT = 8789 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8790 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8791 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8792 EmitFormatDiagnostic( 8793 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8794 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8795 << false << Ex->getSourceRange(), 8796 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8797 getSpecifierRange(startSpecifier, specifierLen)); 8798 8799 // Type check the second argument (char * for both %b and %D) 8800 Ex = getDataArg(argIndex + 1); 8801 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8802 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8803 EmitFormatDiagnostic( 8804 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8805 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8806 << false << Ex->getSourceRange(), 8807 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8808 getSpecifierRange(startSpecifier, specifierLen)); 8809 8810 return true; 8811 } 8812 8813 // Check for using an Objective-C specific conversion specifier 8814 // in a non-ObjC literal. 8815 if (!allowsObjCArg() && CS.isObjCArg()) { 8816 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8817 specifierLen); 8818 } 8819 8820 // %P can only be used with os_log. 8821 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8822 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8823 specifierLen); 8824 } 8825 8826 // %n is not allowed with os_log. 8827 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8828 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8829 getLocationOfByte(CS.getStart()), 8830 /*IsStringLocation*/ false, 8831 getSpecifierRange(startSpecifier, specifierLen)); 8832 8833 return true; 8834 } 8835 8836 // Only scalars are allowed for os_trace. 8837 if (FSType == Sema::FST_OSTrace && 8838 (CS.getKind() == ConversionSpecifier::PArg || 8839 CS.getKind() == ConversionSpecifier::sArg || 8840 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8841 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8842 specifierLen); 8843 } 8844 8845 // Check for use of public/private annotation outside of os_log(). 8846 if (FSType != Sema::FST_OSLog) { 8847 if (FS.isPublic().isSet()) { 8848 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8849 << "public", 8850 getLocationOfByte(FS.isPublic().getPosition()), 8851 /*IsStringLocation*/ false, 8852 getSpecifierRange(startSpecifier, specifierLen)); 8853 } 8854 if (FS.isPrivate().isSet()) { 8855 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8856 << "private", 8857 getLocationOfByte(FS.isPrivate().getPosition()), 8858 /*IsStringLocation*/ false, 8859 getSpecifierRange(startSpecifier, specifierLen)); 8860 } 8861 } 8862 8863 // Check for invalid use of field width 8864 if (!FS.hasValidFieldWidth()) { 8865 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8866 startSpecifier, specifierLen); 8867 } 8868 8869 // Check for invalid use of precision 8870 if (!FS.hasValidPrecision()) { 8871 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8872 startSpecifier, specifierLen); 8873 } 8874 8875 // Precision is mandatory for %P specifier. 8876 if (CS.getKind() == ConversionSpecifier::PArg && 8877 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8878 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8879 getLocationOfByte(startSpecifier), 8880 /*IsStringLocation*/ false, 8881 getSpecifierRange(startSpecifier, specifierLen)); 8882 } 8883 8884 // Check each flag does not conflict with any other component. 8885 if (!FS.hasValidThousandsGroupingPrefix()) 8886 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8887 if (!FS.hasValidLeadingZeros()) 8888 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8889 if (!FS.hasValidPlusPrefix()) 8890 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8891 if (!FS.hasValidSpacePrefix()) 8892 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8893 if (!FS.hasValidAlternativeForm()) 8894 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8895 if (!FS.hasValidLeftJustified()) 8896 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8897 8898 // Check that flags are not ignored by another flag 8899 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8900 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8901 startSpecifier, specifierLen); 8902 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8903 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8904 startSpecifier, specifierLen); 8905 8906 // Check the length modifier is valid with the given conversion specifier. 8907 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8908 S.getLangOpts())) 8909 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8910 diag::warn_format_nonsensical_length); 8911 else if (!FS.hasStandardLengthModifier()) 8912 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8913 else if (!FS.hasStandardLengthConversionCombination()) 8914 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8915 diag::warn_format_non_standard_conversion_spec); 8916 8917 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8918 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8919 8920 // The remaining checks depend on the data arguments. 8921 if (HasVAListArg) 8922 return true; 8923 8924 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8925 return false; 8926 8927 const Expr *Arg = getDataArg(argIndex); 8928 if (!Arg) 8929 return true; 8930 8931 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8932 } 8933 8934 static bool requiresParensToAddCast(const Expr *E) { 8935 // FIXME: We should have a general way to reason about operator 8936 // precedence and whether parens are actually needed here. 8937 // Take care of a few common cases where they aren't. 8938 const Expr *Inside = E->IgnoreImpCasts(); 8939 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8940 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8941 8942 switch (Inside->getStmtClass()) { 8943 case Stmt::ArraySubscriptExprClass: 8944 case Stmt::CallExprClass: 8945 case Stmt::CharacterLiteralClass: 8946 case Stmt::CXXBoolLiteralExprClass: 8947 case Stmt::DeclRefExprClass: 8948 case Stmt::FloatingLiteralClass: 8949 case Stmt::IntegerLiteralClass: 8950 case Stmt::MemberExprClass: 8951 case Stmt::ObjCArrayLiteralClass: 8952 case Stmt::ObjCBoolLiteralExprClass: 8953 case Stmt::ObjCBoxedExprClass: 8954 case Stmt::ObjCDictionaryLiteralClass: 8955 case Stmt::ObjCEncodeExprClass: 8956 case Stmt::ObjCIvarRefExprClass: 8957 case Stmt::ObjCMessageExprClass: 8958 case Stmt::ObjCPropertyRefExprClass: 8959 case Stmt::ObjCStringLiteralClass: 8960 case Stmt::ObjCSubscriptRefExprClass: 8961 case Stmt::ParenExprClass: 8962 case Stmt::StringLiteralClass: 8963 case Stmt::UnaryOperatorClass: 8964 return false; 8965 default: 8966 return true; 8967 } 8968 } 8969 8970 static std::pair<QualType, StringRef> 8971 shouldNotPrintDirectly(const ASTContext &Context, 8972 QualType IntendedTy, 8973 const Expr *E) { 8974 // Use a 'while' to peel off layers of typedefs. 8975 QualType TyTy = IntendedTy; 8976 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8977 StringRef Name = UserTy->getDecl()->getName(); 8978 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8979 .Case("CFIndex", Context.getNSIntegerType()) 8980 .Case("NSInteger", Context.getNSIntegerType()) 8981 .Case("NSUInteger", Context.getNSUIntegerType()) 8982 .Case("SInt32", Context.IntTy) 8983 .Case("UInt32", Context.UnsignedIntTy) 8984 .Default(QualType()); 8985 8986 if (!CastTy.isNull()) 8987 return std::make_pair(CastTy, Name); 8988 8989 TyTy = UserTy->desugar(); 8990 } 8991 8992 // Strip parens if necessary. 8993 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8994 return shouldNotPrintDirectly(Context, 8995 PE->getSubExpr()->getType(), 8996 PE->getSubExpr()); 8997 8998 // If this is a conditional expression, then its result type is constructed 8999 // via usual arithmetic conversions and thus there might be no necessary 9000 // typedef sugar there. Recurse to operands to check for NSInteger & 9001 // Co. usage condition. 9002 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9003 QualType TrueTy, FalseTy; 9004 StringRef TrueName, FalseName; 9005 9006 std::tie(TrueTy, TrueName) = 9007 shouldNotPrintDirectly(Context, 9008 CO->getTrueExpr()->getType(), 9009 CO->getTrueExpr()); 9010 std::tie(FalseTy, FalseName) = 9011 shouldNotPrintDirectly(Context, 9012 CO->getFalseExpr()->getType(), 9013 CO->getFalseExpr()); 9014 9015 if (TrueTy == FalseTy) 9016 return std::make_pair(TrueTy, TrueName); 9017 else if (TrueTy.isNull()) 9018 return std::make_pair(FalseTy, FalseName); 9019 else if (FalseTy.isNull()) 9020 return std::make_pair(TrueTy, TrueName); 9021 } 9022 9023 return std::make_pair(QualType(), StringRef()); 9024 } 9025 9026 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9027 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9028 /// type do not count. 9029 static bool 9030 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9031 QualType From = ICE->getSubExpr()->getType(); 9032 QualType To = ICE->getType(); 9033 // It's an integer promotion if the destination type is the promoted 9034 // source type. 9035 if (ICE->getCastKind() == CK_IntegralCast && 9036 From->isPromotableIntegerType() && 9037 S.Context.getPromotedIntegerType(From) == To) 9038 return true; 9039 // Look through vector types, since we do default argument promotion for 9040 // those in OpenCL. 9041 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9042 From = VecTy->getElementType(); 9043 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9044 To = VecTy->getElementType(); 9045 // It's a floating promotion if the source type is a lower rank. 9046 return ICE->getCastKind() == CK_FloatingCast && 9047 S.Context.getFloatingTypeOrder(From, To) < 0; 9048 } 9049 9050 bool 9051 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9052 const char *StartSpecifier, 9053 unsigned SpecifierLen, 9054 const Expr *E) { 9055 using namespace analyze_format_string; 9056 using namespace analyze_printf; 9057 9058 // Now type check the data expression that matches the 9059 // format specifier. 9060 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9061 if (!AT.isValid()) 9062 return true; 9063 9064 QualType ExprTy = E->getType(); 9065 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9066 ExprTy = TET->getUnderlyingExpr()->getType(); 9067 } 9068 9069 // Diagnose attempts to print a boolean value as a character. Unlike other 9070 // -Wformat diagnostics, this is fine from a type perspective, but it still 9071 // doesn't make sense. 9072 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9073 E->isKnownToHaveBooleanValue()) { 9074 const CharSourceRange &CSR = 9075 getSpecifierRange(StartSpecifier, SpecifierLen); 9076 SmallString<4> FSString; 9077 llvm::raw_svector_ostream os(FSString); 9078 FS.toString(os); 9079 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9080 << FSString, 9081 E->getExprLoc(), false, CSR); 9082 return true; 9083 } 9084 9085 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9086 if (Match == analyze_printf::ArgType::Match) 9087 return true; 9088 9089 // Look through argument promotions for our error message's reported type. 9090 // This includes the integral and floating promotions, but excludes array 9091 // and function pointer decay (seeing that an argument intended to be a 9092 // string has type 'char [6]' is probably more confusing than 'char *') and 9093 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9094 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9095 if (isArithmeticArgumentPromotion(S, ICE)) { 9096 E = ICE->getSubExpr(); 9097 ExprTy = E->getType(); 9098 9099 // Check if we didn't match because of an implicit cast from a 'char' 9100 // or 'short' to an 'int'. This is done because printf is a varargs 9101 // function. 9102 if (ICE->getType() == S.Context.IntTy || 9103 ICE->getType() == S.Context.UnsignedIntTy) { 9104 // All further checking is done on the subexpression 9105 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9106 AT.matchesType(S.Context, ExprTy); 9107 if (ImplicitMatch == analyze_printf::ArgType::Match) 9108 return true; 9109 if (ImplicitMatch == ArgType::NoMatchPedantic || 9110 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9111 Match = ImplicitMatch; 9112 } 9113 } 9114 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9115 // Special case for 'a', which has type 'int' in C. 9116 // Note, however, that we do /not/ want to treat multibyte constants like 9117 // 'MooV' as characters! This form is deprecated but still exists. In 9118 // addition, don't treat expressions as of type 'char' if one byte length 9119 // modifier is provided. 9120 if (ExprTy == S.Context.IntTy && 9121 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9122 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9123 ExprTy = S.Context.CharTy; 9124 } 9125 9126 // Look through enums to their underlying type. 9127 bool IsEnum = false; 9128 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9129 ExprTy = EnumTy->getDecl()->getIntegerType(); 9130 IsEnum = true; 9131 } 9132 9133 // %C in an Objective-C context prints a unichar, not a wchar_t. 9134 // If the argument is an integer of some kind, believe the %C and suggest 9135 // a cast instead of changing the conversion specifier. 9136 QualType IntendedTy = ExprTy; 9137 if (isObjCContext() && 9138 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9139 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9140 !ExprTy->isCharType()) { 9141 // 'unichar' is defined as a typedef of unsigned short, but we should 9142 // prefer using the typedef if it is visible. 9143 IntendedTy = S.Context.UnsignedShortTy; 9144 9145 // While we are here, check if the value is an IntegerLiteral that happens 9146 // to be within the valid range. 9147 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9148 const llvm::APInt &V = IL->getValue(); 9149 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9150 return true; 9151 } 9152 9153 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9154 Sema::LookupOrdinaryName); 9155 if (S.LookupName(Result, S.getCurScope())) { 9156 NamedDecl *ND = Result.getFoundDecl(); 9157 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9158 if (TD->getUnderlyingType() == IntendedTy) 9159 IntendedTy = S.Context.getTypedefType(TD); 9160 } 9161 } 9162 } 9163 9164 // Special-case some of Darwin's platform-independence types by suggesting 9165 // casts to primitive types that are known to be large enough. 9166 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9167 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9168 QualType CastTy; 9169 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9170 if (!CastTy.isNull()) { 9171 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9172 // (long in ASTContext). Only complain to pedants. 9173 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9174 (AT.isSizeT() || AT.isPtrdiffT()) && 9175 AT.matchesType(S.Context, CastTy)) 9176 Match = ArgType::NoMatchPedantic; 9177 IntendedTy = CastTy; 9178 ShouldNotPrintDirectly = true; 9179 } 9180 } 9181 9182 // We may be able to offer a FixItHint if it is a supported type. 9183 PrintfSpecifier fixedFS = FS; 9184 bool Success = 9185 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9186 9187 if (Success) { 9188 // Get the fix string from the fixed format specifier 9189 SmallString<16> buf; 9190 llvm::raw_svector_ostream os(buf); 9191 fixedFS.toString(os); 9192 9193 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9194 9195 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9196 unsigned Diag; 9197 switch (Match) { 9198 case ArgType::Match: llvm_unreachable("expected non-matching"); 9199 case ArgType::NoMatchPedantic: 9200 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9201 break; 9202 case ArgType::NoMatchTypeConfusion: 9203 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9204 break; 9205 case ArgType::NoMatch: 9206 Diag = diag::warn_format_conversion_argument_type_mismatch; 9207 break; 9208 } 9209 9210 // In this case, the specifier is wrong and should be changed to match 9211 // the argument. 9212 EmitFormatDiagnostic(S.PDiag(Diag) 9213 << AT.getRepresentativeTypeName(S.Context) 9214 << IntendedTy << IsEnum << E->getSourceRange(), 9215 E->getBeginLoc(), 9216 /*IsStringLocation*/ false, SpecRange, 9217 FixItHint::CreateReplacement(SpecRange, os.str())); 9218 } else { 9219 // The canonical type for formatting this value is different from the 9220 // actual type of the expression. (This occurs, for example, with Darwin's 9221 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9222 // should be printed as 'long' for 64-bit compatibility.) 9223 // Rather than emitting a normal format/argument mismatch, we want to 9224 // add a cast to the recommended type (and correct the format string 9225 // if necessary). 9226 SmallString<16> CastBuf; 9227 llvm::raw_svector_ostream CastFix(CastBuf); 9228 CastFix << "("; 9229 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9230 CastFix << ")"; 9231 9232 SmallVector<FixItHint,4> Hints; 9233 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9234 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9235 9236 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9237 // If there's already a cast present, just replace it. 9238 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9239 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9240 9241 } else if (!requiresParensToAddCast(E)) { 9242 // If the expression has high enough precedence, 9243 // just write the C-style cast. 9244 Hints.push_back( 9245 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9246 } else { 9247 // Otherwise, add parens around the expression as well as the cast. 9248 CastFix << "("; 9249 Hints.push_back( 9250 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9251 9252 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9253 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9254 } 9255 9256 if (ShouldNotPrintDirectly) { 9257 // The expression has a type that should not be printed directly. 9258 // We extract the name from the typedef because we don't want to show 9259 // the underlying type in the diagnostic. 9260 StringRef Name; 9261 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9262 Name = TypedefTy->getDecl()->getName(); 9263 else 9264 Name = CastTyName; 9265 unsigned Diag = Match == ArgType::NoMatchPedantic 9266 ? diag::warn_format_argument_needs_cast_pedantic 9267 : diag::warn_format_argument_needs_cast; 9268 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9269 << E->getSourceRange(), 9270 E->getBeginLoc(), /*IsStringLocation=*/false, 9271 SpecRange, Hints); 9272 } else { 9273 // In this case, the expression could be printed using a different 9274 // specifier, but we've decided that the specifier is probably correct 9275 // and we should cast instead. Just use the normal warning message. 9276 EmitFormatDiagnostic( 9277 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9278 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9279 << E->getSourceRange(), 9280 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9281 } 9282 } 9283 } else { 9284 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9285 SpecifierLen); 9286 // Since the warning for passing non-POD types to variadic functions 9287 // was deferred until now, we emit a warning for non-POD 9288 // arguments here. 9289 switch (S.isValidVarArgType(ExprTy)) { 9290 case Sema::VAK_Valid: 9291 case Sema::VAK_ValidInCXX11: { 9292 unsigned Diag; 9293 switch (Match) { 9294 case ArgType::Match: llvm_unreachable("expected non-matching"); 9295 case ArgType::NoMatchPedantic: 9296 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9297 break; 9298 case ArgType::NoMatchTypeConfusion: 9299 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9300 break; 9301 case ArgType::NoMatch: 9302 Diag = diag::warn_format_conversion_argument_type_mismatch; 9303 break; 9304 } 9305 9306 EmitFormatDiagnostic( 9307 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9308 << IsEnum << CSR << E->getSourceRange(), 9309 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9310 break; 9311 } 9312 case Sema::VAK_Undefined: 9313 case Sema::VAK_MSVCUndefined: 9314 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9315 << S.getLangOpts().CPlusPlus11 << ExprTy 9316 << CallType 9317 << AT.getRepresentativeTypeName(S.Context) << CSR 9318 << E->getSourceRange(), 9319 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9320 checkForCStrMembers(AT, E); 9321 break; 9322 9323 case Sema::VAK_Invalid: 9324 if (ExprTy->isObjCObjectType()) 9325 EmitFormatDiagnostic( 9326 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9327 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9328 << AT.getRepresentativeTypeName(S.Context) << CSR 9329 << E->getSourceRange(), 9330 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9331 else 9332 // FIXME: If this is an initializer list, suggest removing the braces 9333 // or inserting a cast to the target type. 9334 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9335 << isa<InitListExpr>(E) << ExprTy << CallType 9336 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9337 break; 9338 } 9339 9340 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9341 "format string specifier index out of range"); 9342 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9343 } 9344 9345 return true; 9346 } 9347 9348 //===--- CHECK: Scanf format string checking ------------------------------===// 9349 9350 namespace { 9351 9352 class CheckScanfHandler : public CheckFormatHandler { 9353 public: 9354 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9355 const Expr *origFormatExpr, Sema::FormatStringType type, 9356 unsigned firstDataArg, unsigned numDataArgs, 9357 const char *beg, bool hasVAListArg, 9358 ArrayRef<const Expr *> Args, unsigned formatIdx, 9359 bool inFunctionCall, Sema::VariadicCallType CallType, 9360 llvm::SmallBitVector &CheckedVarArgs, 9361 UncoveredArgHandler &UncoveredArg) 9362 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9363 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9364 inFunctionCall, CallType, CheckedVarArgs, 9365 UncoveredArg) {} 9366 9367 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9368 const char *startSpecifier, 9369 unsigned specifierLen) override; 9370 9371 bool HandleInvalidScanfConversionSpecifier( 9372 const analyze_scanf::ScanfSpecifier &FS, 9373 const char *startSpecifier, 9374 unsigned specifierLen) override; 9375 9376 void HandleIncompleteScanList(const char *start, const char *end) override; 9377 }; 9378 9379 } // namespace 9380 9381 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9382 const char *end) { 9383 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9384 getLocationOfByte(end), /*IsStringLocation*/true, 9385 getSpecifierRange(start, end - start)); 9386 } 9387 9388 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9389 const analyze_scanf::ScanfSpecifier &FS, 9390 const char *startSpecifier, 9391 unsigned specifierLen) { 9392 const analyze_scanf::ScanfConversionSpecifier &CS = 9393 FS.getConversionSpecifier(); 9394 9395 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9396 getLocationOfByte(CS.getStart()), 9397 startSpecifier, specifierLen, 9398 CS.getStart(), CS.getLength()); 9399 } 9400 9401 bool CheckScanfHandler::HandleScanfSpecifier( 9402 const analyze_scanf::ScanfSpecifier &FS, 9403 const char *startSpecifier, 9404 unsigned specifierLen) { 9405 using namespace analyze_scanf; 9406 using namespace analyze_format_string; 9407 9408 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9409 9410 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9411 // be used to decide if we are using positional arguments consistently. 9412 if (FS.consumesDataArgument()) { 9413 if (atFirstArg) { 9414 atFirstArg = false; 9415 usesPositionalArgs = FS.usesPositionalArg(); 9416 } 9417 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9418 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9419 startSpecifier, specifierLen); 9420 return false; 9421 } 9422 } 9423 9424 // Check if the field with is non-zero. 9425 const OptionalAmount &Amt = FS.getFieldWidth(); 9426 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9427 if (Amt.getConstantAmount() == 0) { 9428 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9429 Amt.getConstantLength()); 9430 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9431 getLocationOfByte(Amt.getStart()), 9432 /*IsStringLocation*/true, R, 9433 FixItHint::CreateRemoval(R)); 9434 } 9435 } 9436 9437 if (!FS.consumesDataArgument()) { 9438 // FIXME: Technically specifying a precision or field width here 9439 // makes no sense. Worth issuing a warning at some point. 9440 return true; 9441 } 9442 9443 // Consume the argument. 9444 unsigned argIndex = FS.getArgIndex(); 9445 if (argIndex < NumDataArgs) { 9446 // The check to see if the argIndex is valid will come later. 9447 // We set the bit here because we may exit early from this 9448 // function if we encounter some other error. 9449 CoveredArgs.set(argIndex); 9450 } 9451 9452 // Check the length modifier is valid with the given conversion specifier. 9453 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9454 S.getLangOpts())) 9455 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9456 diag::warn_format_nonsensical_length); 9457 else if (!FS.hasStandardLengthModifier()) 9458 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9459 else if (!FS.hasStandardLengthConversionCombination()) 9460 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9461 diag::warn_format_non_standard_conversion_spec); 9462 9463 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9464 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9465 9466 // The remaining checks depend on the data arguments. 9467 if (HasVAListArg) 9468 return true; 9469 9470 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9471 return false; 9472 9473 // Check that the argument type matches the format specifier. 9474 const Expr *Ex = getDataArg(argIndex); 9475 if (!Ex) 9476 return true; 9477 9478 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9479 9480 if (!AT.isValid()) { 9481 return true; 9482 } 9483 9484 analyze_format_string::ArgType::MatchKind Match = 9485 AT.matchesType(S.Context, Ex->getType()); 9486 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9487 if (Match == analyze_format_string::ArgType::Match) 9488 return true; 9489 9490 ScanfSpecifier fixedFS = FS; 9491 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9492 S.getLangOpts(), S.Context); 9493 9494 unsigned Diag = 9495 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9496 : diag::warn_format_conversion_argument_type_mismatch; 9497 9498 if (Success) { 9499 // Get the fix string from the fixed format specifier. 9500 SmallString<128> buf; 9501 llvm::raw_svector_ostream os(buf); 9502 fixedFS.toString(os); 9503 9504 EmitFormatDiagnostic( 9505 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9506 << Ex->getType() << false << Ex->getSourceRange(), 9507 Ex->getBeginLoc(), 9508 /*IsStringLocation*/ false, 9509 getSpecifierRange(startSpecifier, specifierLen), 9510 FixItHint::CreateReplacement( 9511 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9512 } else { 9513 EmitFormatDiagnostic(S.PDiag(Diag) 9514 << AT.getRepresentativeTypeName(S.Context) 9515 << Ex->getType() << false << Ex->getSourceRange(), 9516 Ex->getBeginLoc(), 9517 /*IsStringLocation*/ false, 9518 getSpecifierRange(startSpecifier, specifierLen)); 9519 } 9520 9521 return true; 9522 } 9523 9524 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9525 const Expr *OrigFormatExpr, 9526 ArrayRef<const Expr *> Args, 9527 bool HasVAListArg, unsigned format_idx, 9528 unsigned firstDataArg, 9529 Sema::FormatStringType Type, 9530 bool inFunctionCall, 9531 Sema::VariadicCallType CallType, 9532 llvm::SmallBitVector &CheckedVarArgs, 9533 UncoveredArgHandler &UncoveredArg, 9534 bool IgnoreStringsWithoutSpecifiers) { 9535 // CHECK: is the format string a wide literal? 9536 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9537 CheckFormatHandler::EmitFormatDiagnostic( 9538 S, inFunctionCall, Args[format_idx], 9539 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9540 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9541 return; 9542 } 9543 9544 // Str - The format string. NOTE: this is NOT null-terminated! 9545 StringRef StrRef = FExpr->getString(); 9546 const char *Str = StrRef.data(); 9547 // Account for cases where the string literal is truncated in a declaration. 9548 const ConstantArrayType *T = 9549 S.Context.getAsConstantArrayType(FExpr->getType()); 9550 assert(T && "String literal not of constant array type!"); 9551 size_t TypeSize = T->getSize().getZExtValue(); 9552 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9553 const unsigned numDataArgs = Args.size() - firstDataArg; 9554 9555 if (IgnoreStringsWithoutSpecifiers && 9556 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9557 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9558 return; 9559 9560 // Emit a warning if the string literal is truncated and does not contain an 9561 // embedded null character. 9562 if (TypeSize <= StrRef.size() && 9563 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9564 CheckFormatHandler::EmitFormatDiagnostic( 9565 S, inFunctionCall, Args[format_idx], 9566 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9567 FExpr->getBeginLoc(), 9568 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9569 return; 9570 } 9571 9572 // CHECK: empty format string? 9573 if (StrLen == 0 && numDataArgs > 0) { 9574 CheckFormatHandler::EmitFormatDiagnostic( 9575 S, inFunctionCall, Args[format_idx], 9576 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9577 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9578 return; 9579 } 9580 9581 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9582 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9583 Type == Sema::FST_OSTrace) { 9584 CheckPrintfHandler H( 9585 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9586 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9587 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9588 CheckedVarArgs, UncoveredArg); 9589 9590 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9591 S.getLangOpts(), 9592 S.Context.getTargetInfo(), 9593 Type == Sema::FST_FreeBSDKPrintf)) 9594 H.DoneProcessing(); 9595 } else if (Type == Sema::FST_Scanf) { 9596 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9597 numDataArgs, Str, HasVAListArg, Args, format_idx, 9598 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9599 9600 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9601 S.getLangOpts(), 9602 S.Context.getTargetInfo())) 9603 H.DoneProcessing(); 9604 } // TODO: handle other formats 9605 } 9606 9607 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9608 // Str - The format string. NOTE: this is NOT null-terminated! 9609 StringRef StrRef = FExpr->getString(); 9610 const char *Str = StrRef.data(); 9611 // Account for cases where the string literal is truncated in a declaration. 9612 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9613 assert(T && "String literal not of constant array type!"); 9614 size_t TypeSize = T->getSize().getZExtValue(); 9615 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9616 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9617 getLangOpts(), 9618 Context.getTargetInfo()); 9619 } 9620 9621 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9622 9623 // Returns the related absolute value function that is larger, of 0 if one 9624 // does not exist. 9625 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9626 switch (AbsFunction) { 9627 default: 9628 return 0; 9629 9630 case Builtin::BI__builtin_abs: 9631 return Builtin::BI__builtin_labs; 9632 case Builtin::BI__builtin_labs: 9633 return Builtin::BI__builtin_llabs; 9634 case Builtin::BI__builtin_llabs: 9635 return 0; 9636 9637 case Builtin::BI__builtin_fabsf: 9638 return Builtin::BI__builtin_fabs; 9639 case Builtin::BI__builtin_fabs: 9640 return Builtin::BI__builtin_fabsl; 9641 case Builtin::BI__builtin_fabsl: 9642 return 0; 9643 9644 case Builtin::BI__builtin_cabsf: 9645 return Builtin::BI__builtin_cabs; 9646 case Builtin::BI__builtin_cabs: 9647 return Builtin::BI__builtin_cabsl; 9648 case Builtin::BI__builtin_cabsl: 9649 return 0; 9650 9651 case Builtin::BIabs: 9652 return Builtin::BIlabs; 9653 case Builtin::BIlabs: 9654 return Builtin::BIllabs; 9655 case Builtin::BIllabs: 9656 return 0; 9657 9658 case Builtin::BIfabsf: 9659 return Builtin::BIfabs; 9660 case Builtin::BIfabs: 9661 return Builtin::BIfabsl; 9662 case Builtin::BIfabsl: 9663 return 0; 9664 9665 case Builtin::BIcabsf: 9666 return Builtin::BIcabs; 9667 case Builtin::BIcabs: 9668 return Builtin::BIcabsl; 9669 case Builtin::BIcabsl: 9670 return 0; 9671 } 9672 } 9673 9674 // Returns the argument type of the absolute value function. 9675 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9676 unsigned AbsType) { 9677 if (AbsType == 0) 9678 return QualType(); 9679 9680 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9681 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9682 if (Error != ASTContext::GE_None) 9683 return QualType(); 9684 9685 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9686 if (!FT) 9687 return QualType(); 9688 9689 if (FT->getNumParams() != 1) 9690 return QualType(); 9691 9692 return FT->getParamType(0); 9693 } 9694 9695 // Returns the best absolute value function, or zero, based on type and 9696 // current absolute value function. 9697 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9698 unsigned AbsFunctionKind) { 9699 unsigned BestKind = 0; 9700 uint64_t ArgSize = Context.getTypeSize(ArgType); 9701 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9702 Kind = getLargerAbsoluteValueFunction(Kind)) { 9703 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9704 if (Context.getTypeSize(ParamType) >= ArgSize) { 9705 if (BestKind == 0) 9706 BestKind = Kind; 9707 else if (Context.hasSameType(ParamType, ArgType)) { 9708 BestKind = Kind; 9709 break; 9710 } 9711 } 9712 } 9713 return BestKind; 9714 } 9715 9716 enum AbsoluteValueKind { 9717 AVK_Integer, 9718 AVK_Floating, 9719 AVK_Complex 9720 }; 9721 9722 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9723 if (T->isIntegralOrEnumerationType()) 9724 return AVK_Integer; 9725 if (T->isRealFloatingType()) 9726 return AVK_Floating; 9727 if (T->isAnyComplexType()) 9728 return AVK_Complex; 9729 9730 llvm_unreachable("Type not integer, floating, or complex"); 9731 } 9732 9733 // Changes the absolute value function to a different type. Preserves whether 9734 // the function is a builtin. 9735 static unsigned changeAbsFunction(unsigned AbsKind, 9736 AbsoluteValueKind ValueKind) { 9737 switch (ValueKind) { 9738 case AVK_Integer: 9739 switch (AbsKind) { 9740 default: 9741 return 0; 9742 case Builtin::BI__builtin_fabsf: 9743 case Builtin::BI__builtin_fabs: 9744 case Builtin::BI__builtin_fabsl: 9745 case Builtin::BI__builtin_cabsf: 9746 case Builtin::BI__builtin_cabs: 9747 case Builtin::BI__builtin_cabsl: 9748 return Builtin::BI__builtin_abs; 9749 case Builtin::BIfabsf: 9750 case Builtin::BIfabs: 9751 case Builtin::BIfabsl: 9752 case Builtin::BIcabsf: 9753 case Builtin::BIcabs: 9754 case Builtin::BIcabsl: 9755 return Builtin::BIabs; 9756 } 9757 case AVK_Floating: 9758 switch (AbsKind) { 9759 default: 9760 return 0; 9761 case Builtin::BI__builtin_abs: 9762 case Builtin::BI__builtin_labs: 9763 case Builtin::BI__builtin_llabs: 9764 case Builtin::BI__builtin_cabsf: 9765 case Builtin::BI__builtin_cabs: 9766 case Builtin::BI__builtin_cabsl: 9767 return Builtin::BI__builtin_fabsf; 9768 case Builtin::BIabs: 9769 case Builtin::BIlabs: 9770 case Builtin::BIllabs: 9771 case Builtin::BIcabsf: 9772 case Builtin::BIcabs: 9773 case Builtin::BIcabsl: 9774 return Builtin::BIfabsf; 9775 } 9776 case AVK_Complex: 9777 switch (AbsKind) { 9778 default: 9779 return 0; 9780 case Builtin::BI__builtin_abs: 9781 case Builtin::BI__builtin_labs: 9782 case Builtin::BI__builtin_llabs: 9783 case Builtin::BI__builtin_fabsf: 9784 case Builtin::BI__builtin_fabs: 9785 case Builtin::BI__builtin_fabsl: 9786 return Builtin::BI__builtin_cabsf; 9787 case Builtin::BIabs: 9788 case Builtin::BIlabs: 9789 case Builtin::BIllabs: 9790 case Builtin::BIfabsf: 9791 case Builtin::BIfabs: 9792 case Builtin::BIfabsl: 9793 return Builtin::BIcabsf; 9794 } 9795 } 9796 llvm_unreachable("Unable to convert function"); 9797 } 9798 9799 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9800 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9801 if (!FnInfo) 9802 return 0; 9803 9804 switch (FDecl->getBuiltinID()) { 9805 default: 9806 return 0; 9807 case Builtin::BI__builtin_abs: 9808 case Builtin::BI__builtin_fabs: 9809 case Builtin::BI__builtin_fabsf: 9810 case Builtin::BI__builtin_fabsl: 9811 case Builtin::BI__builtin_labs: 9812 case Builtin::BI__builtin_llabs: 9813 case Builtin::BI__builtin_cabs: 9814 case Builtin::BI__builtin_cabsf: 9815 case Builtin::BI__builtin_cabsl: 9816 case Builtin::BIabs: 9817 case Builtin::BIlabs: 9818 case Builtin::BIllabs: 9819 case Builtin::BIfabs: 9820 case Builtin::BIfabsf: 9821 case Builtin::BIfabsl: 9822 case Builtin::BIcabs: 9823 case Builtin::BIcabsf: 9824 case Builtin::BIcabsl: 9825 return FDecl->getBuiltinID(); 9826 } 9827 llvm_unreachable("Unknown Builtin type"); 9828 } 9829 9830 // If the replacement is valid, emit a note with replacement function. 9831 // Additionally, suggest including the proper header if not already included. 9832 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9833 unsigned AbsKind, QualType ArgType) { 9834 bool EmitHeaderHint = true; 9835 const char *HeaderName = nullptr; 9836 const char *FunctionName = nullptr; 9837 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9838 FunctionName = "std::abs"; 9839 if (ArgType->isIntegralOrEnumerationType()) { 9840 HeaderName = "cstdlib"; 9841 } else if (ArgType->isRealFloatingType()) { 9842 HeaderName = "cmath"; 9843 } else { 9844 llvm_unreachable("Invalid Type"); 9845 } 9846 9847 // Lookup all std::abs 9848 if (NamespaceDecl *Std = S.getStdNamespace()) { 9849 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9850 R.suppressDiagnostics(); 9851 S.LookupQualifiedName(R, Std); 9852 9853 for (const auto *I : R) { 9854 const FunctionDecl *FDecl = nullptr; 9855 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9856 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9857 } else { 9858 FDecl = dyn_cast<FunctionDecl>(I); 9859 } 9860 if (!FDecl) 9861 continue; 9862 9863 // Found std::abs(), check that they are the right ones. 9864 if (FDecl->getNumParams() != 1) 9865 continue; 9866 9867 // Check that the parameter type can handle the argument. 9868 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9869 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9870 S.Context.getTypeSize(ArgType) <= 9871 S.Context.getTypeSize(ParamType)) { 9872 // Found a function, don't need the header hint. 9873 EmitHeaderHint = false; 9874 break; 9875 } 9876 } 9877 } 9878 } else { 9879 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9880 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9881 9882 if (HeaderName) { 9883 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9884 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9885 R.suppressDiagnostics(); 9886 S.LookupName(R, S.getCurScope()); 9887 9888 if (R.isSingleResult()) { 9889 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9890 if (FD && FD->getBuiltinID() == AbsKind) { 9891 EmitHeaderHint = false; 9892 } else { 9893 return; 9894 } 9895 } else if (!R.empty()) { 9896 return; 9897 } 9898 } 9899 } 9900 9901 S.Diag(Loc, diag::note_replace_abs_function) 9902 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9903 9904 if (!HeaderName) 9905 return; 9906 9907 if (!EmitHeaderHint) 9908 return; 9909 9910 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9911 << FunctionName; 9912 } 9913 9914 template <std::size_t StrLen> 9915 static bool IsStdFunction(const FunctionDecl *FDecl, 9916 const char (&Str)[StrLen]) { 9917 if (!FDecl) 9918 return false; 9919 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9920 return false; 9921 if (!FDecl->isInStdNamespace()) 9922 return false; 9923 9924 return true; 9925 } 9926 9927 // Warn when using the wrong abs() function. 9928 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9929 const FunctionDecl *FDecl) { 9930 if (Call->getNumArgs() != 1) 9931 return; 9932 9933 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9934 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9935 if (AbsKind == 0 && !IsStdAbs) 9936 return; 9937 9938 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9939 QualType ParamType = Call->getArg(0)->getType(); 9940 9941 // Unsigned types cannot be negative. Suggest removing the absolute value 9942 // function call. 9943 if (ArgType->isUnsignedIntegerType()) { 9944 const char *FunctionName = 9945 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9946 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9947 Diag(Call->getExprLoc(), diag::note_remove_abs) 9948 << FunctionName 9949 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9950 return; 9951 } 9952 9953 // Taking the absolute value of a pointer is very suspicious, they probably 9954 // wanted to index into an array, dereference a pointer, call a function, etc. 9955 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9956 unsigned DiagType = 0; 9957 if (ArgType->isFunctionType()) 9958 DiagType = 1; 9959 else if (ArgType->isArrayType()) 9960 DiagType = 2; 9961 9962 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9963 return; 9964 } 9965 9966 // std::abs has overloads which prevent most of the absolute value problems 9967 // from occurring. 9968 if (IsStdAbs) 9969 return; 9970 9971 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9972 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9973 9974 // The argument and parameter are the same kind. Check if they are the right 9975 // size. 9976 if (ArgValueKind == ParamValueKind) { 9977 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9978 return; 9979 9980 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9981 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9982 << FDecl << ArgType << ParamType; 9983 9984 if (NewAbsKind == 0) 9985 return; 9986 9987 emitReplacement(*this, Call->getExprLoc(), 9988 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9989 return; 9990 } 9991 9992 // ArgValueKind != ParamValueKind 9993 // The wrong type of absolute value function was used. Attempt to find the 9994 // proper one. 9995 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9996 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9997 if (NewAbsKind == 0) 9998 return; 9999 10000 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10001 << FDecl << ParamValueKind << ArgValueKind; 10002 10003 emitReplacement(*this, Call->getExprLoc(), 10004 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10005 } 10006 10007 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10008 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10009 const FunctionDecl *FDecl) { 10010 if (!Call || !FDecl) return; 10011 10012 // Ignore template specializations and macros. 10013 if (inTemplateInstantiation()) return; 10014 if (Call->getExprLoc().isMacroID()) return; 10015 10016 // Only care about the one template argument, two function parameter std::max 10017 if (Call->getNumArgs() != 2) return; 10018 if (!IsStdFunction(FDecl, "max")) return; 10019 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10020 if (!ArgList) return; 10021 if (ArgList->size() != 1) return; 10022 10023 // Check that template type argument is unsigned integer. 10024 const auto& TA = ArgList->get(0); 10025 if (TA.getKind() != TemplateArgument::Type) return; 10026 QualType ArgType = TA.getAsType(); 10027 if (!ArgType->isUnsignedIntegerType()) return; 10028 10029 // See if either argument is a literal zero. 10030 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10031 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10032 if (!MTE) return false; 10033 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10034 if (!Num) return false; 10035 if (Num->getValue() != 0) return false; 10036 return true; 10037 }; 10038 10039 const Expr *FirstArg = Call->getArg(0); 10040 const Expr *SecondArg = Call->getArg(1); 10041 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10042 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10043 10044 // Only warn when exactly one argument is zero. 10045 if (IsFirstArgZero == IsSecondArgZero) return; 10046 10047 SourceRange FirstRange = FirstArg->getSourceRange(); 10048 SourceRange SecondRange = SecondArg->getSourceRange(); 10049 10050 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10051 10052 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10053 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10054 10055 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10056 SourceRange RemovalRange; 10057 if (IsFirstArgZero) { 10058 RemovalRange = SourceRange(FirstRange.getBegin(), 10059 SecondRange.getBegin().getLocWithOffset(-1)); 10060 } else { 10061 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10062 SecondRange.getEnd()); 10063 } 10064 10065 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10066 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10067 << FixItHint::CreateRemoval(RemovalRange); 10068 } 10069 10070 //===--- CHECK: Standard memory functions ---------------------------------===// 10071 10072 /// Takes the expression passed to the size_t parameter of functions 10073 /// such as memcmp, strncat, etc and warns if it's a comparison. 10074 /// 10075 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10076 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10077 IdentifierInfo *FnName, 10078 SourceLocation FnLoc, 10079 SourceLocation RParenLoc) { 10080 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10081 if (!Size) 10082 return false; 10083 10084 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10085 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10086 return false; 10087 10088 SourceRange SizeRange = Size->getSourceRange(); 10089 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10090 << SizeRange << FnName; 10091 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10092 << FnName 10093 << FixItHint::CreateInsertion( 10094 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10095 << FixItHint::CreateRemoval(RParenLoc); 10096 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10097 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10098 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10099 ")"); 10100 10101 return true; 10102 } 10103 10104 /// Determine whether the given type is or contains a dynamic class type 10105 /// (e.g., whether it has a vtable). 10106 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10107 bool &IsContained) { 10108 // Look through array types while ignoring qualifiers. 10109 const Type *Ty = T->getBaseElementTypeUnsafe(); 10110 IsContained = false; 10111 10112 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10113 RD = RD ? RD->getDefinition() : nullptr; 10114 if (!RD || RD->isInvalidDecl()) 10115 return nullptr; 10116 10117 if (RD->isDynamicClass()) 10118 return RD; 10119 10120 // Check all the fields. If any bases were dynamic, the class is dynamic. 10121 // It's impossible for a class to transitively contain itself by value, so 10122 // infinite recursion is impossible. 10123 for (auto *FD : RD->fields()) { 10124 bool SubContained; 10125 if (const CXXRecordDecl *ContainedRD = 10126 getContainedDynamicClass(FD->getType(), SubContained)) { 10127 IsContained = true; 10128 return ContainedRD; 10129 } 10130 } 10131 10132 return nullptr; 10133 } 10134 10135 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10136 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10137 if (Unary->getKind() == UETT_SizeOf) 10138 return Unary; 10139 return nullptr; 10140 } 10141 10142 /// If E is a sizeof expression, returns its argument expression, 10143 /// otherwise returns NULL. 10144 static const Expr *getSizeOfExprArg(const Expr *E) { 10145 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10146 if (!SizeOf->isArgumentType()) 10147 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10148 return nullptr; 10149 } 10150 10151 /// If E is a sizeof expression, returns its argument type. 10152 static QualType getSizeOfArgType(const Expr *E) { 10153 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10154 return SizeOf->getTypeOfArgument(); 10155 return QualType(); 10156 } 10157 10158 namespace { 10159 10160 struct SearchNonTrivialToInitializeField 10161 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10162 using Super = 10163 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10164 10165 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10166 10167 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10168 SourceLocation SL) { 10169 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10170 asDerived().visitArray(PDIK, AT, SL); 10171 return; 10172 } 10173 10174 Super::visitWithKind(PDIK, FT, SL); 10175 } 10176 10177 void visitARCStrong(QualType FT, SourceLocation SL) { 10178 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10179 } 10180 void visitARCWeak(QualType FT, SourceLocation SL) { 10181 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10182 } 10183 void visitStruct(QualType FT, SourceLocation SL) { 10184 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10185 visit(FD->getType(), FD->getLocation()); 10186 } 10187 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10188 const ArrayType *AT, SourceLocation SL) { 10189 visit(getContext().getBaseElementType(AT), SL); 10190 } 10191 void visitTrivial(QualType FT, SourceLocation SL) {} 10192 10193 static void diag(QualType RT, const Expr *E, Sema &S) { 10194 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10195 } 10196 10197 ASTContext &getContext() { return S.getASTContext(); } 10198 10199 const Expr *E; 10200 Sema &S; 10201 }; 10202 10203 struct SearchNonTrivialToCopyField 10204 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10205 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10206 10207 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10208 10209 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10210 SourceLocation SL) { 10211 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10212 asDerived().visitArray(PCK, AT, SL); 10213 return; 10214 } 10215 10216 Super::visitWithKind(PCK, FT, SL); 10217 } 10218 10219 void visitARCStrong(QualType FT, SourceLocation SL) { 10220 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10221 } 10222 void visitARCWeak(QualType FT, SourceLocation SL) { 10223 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10224 } 10225 void visitStruct(QualType FT, SourceLocation SL) { 10226 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10227 visit(FD->getType(), FD->getLocation()); 10228 } 10229 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10230 SourceLocation SL) { 10231 visit(getContext().getBaseElementType(AT), SL); 10232 } 10233 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10234 SourceLocation SL) {} 10235 void visitTrivial(QualType FT, SourceLocation SL) {} 10236 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10237 10238 static void diag(QualType RT, const Expr *E, Sema &S) { 10239 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10240 } 10241 10242 ASTContext &getContext() { return S.getASTContext(); } 10243 10244 const Expr *E; 10245 Sema &S; 10246 }; 10247 10248 } 10249 10250 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10251 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10252 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10253 10254 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10255 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10256 return false; 10257 10258 return doesExprLikelyComputeSize(BO->getLHS()) || 10259 doesExprLikelyComputeSize(BO->getRHS()); 10260 } 10261 10262 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10263 } 10264 10265 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10266 /// 10267 /// \code 10268 /// #define MACRO 0 10269 /// foo(MACRO); 10270 /// foo(0); 10271 /// \endcode 10272 /// 10273 /// This should return true for the first call to foo, but not for the second 10274 /// (regardless of whether foo is a macro or function). 10275 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10276 SourceLocation CallLoc, 10277 SourceLocation ArgLoc) { 10278 if (!CallLoc.isMacroID()) 10279 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10280 10281 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10282 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10283 } 10284 10285 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10286 /// last two arguments transposed. 10287 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10288 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10289 return; 10290 10291 const Expr *SizeArg = 10292 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10293 10294 auto isLiteralZero = [](const Expr *E) { 10295 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10296 }; 10297 10298 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10299 SourceLocation CallLoc = Call->getRParenLoc(); 10300 SourceManager &SM = S.getSourceManager(); 10301 if (isLiteralZero(SizeArg) && 10302 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10303 10304 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10305 10306 // Some platforms #define bzero to __builtin_memset. See if this is the 10307 // case, and if so, emit a better diagnostic. 10308 if (BId == Builtin::BIbzero || 10309 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10310 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10311 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10312 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10313 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10314 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10315 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10316 } 10317 return; 10318 } 10319 10320 // If the second argument to a memset is a sizeof expression and the third 10321 // isn't, this is also likely an error. This should catch 10322 // 'memset(buf, sizeof(buf), 0xff)'. 10323 if (BId == Builtin::BImemset && 10324 doesExprLikelyComputeSize(Call->getArg(1)) && 10325 !doesExprLikelyComputeSize(Call->getArg(2))) { 10326 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10327 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10328 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10329 return; 10330 } 10331 } 10332 10333 /// Check for dangerous or invalid arguments to memset(). 10334 /// 10335 /// This issues warnings on known problematic, dangerous or unspecified 10336 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10337 /// function calls. 10338 /// 10339 /// \param Call The call expression to diagnose. 10340 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10341 unsigned BId, 10342 IdentifierInfo *FnName) { 10343 assert(BId != 0); 10344 10345 // It is possible to have a non-standard definition of memset. Validate 10346 // we have enough arguments, and if not, abort further checking. 10347 unsigned ExpectedNumArgs = 10348 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10349 if (Call->getNumArgs() < ExpectedNumArgs) 10350 return; 10351 10352 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10353 BId == Builtin::BIstrndup ? 1 : 2); 10354 unsigned LenArg = 10355 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10356 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10357 10358 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10359 Call->getBeginLoc(), Call->getRParenLoc())) 10360 return; 10361 10362 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10363 CheckMemaccessSize(*this, BId, Call); 10364 10365 // We have special checking when the length is a sizeof expression. 10366 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10367 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10368 llvm::FoldingSetNodeID SizeOfArgID; 10369 10370 // Although widely used, 'bzero' is not a standard function. Be more strict 10371 // with the argument types before allowing diagnostics and only allow the 10372 // form bzero(ptr, sizeof(...)). 10373 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10374 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10375 return; 10376 10377 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10378 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10379 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10380 10381 QualType DestTy = Dest->getType(); 10382 QualType PointeeTy; 10383 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10384 PointeeTy = DestPtrTy->getPointeeType(); 10385 10386 // Never warn about void type pointers. This can be used to suppress 10387 // false positives. 10388 if (PointeeTy->isVoidType()) 10389 continue; 10390 10391 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10392 // actually comparing the expressions for equality. Because computing the 10393 // expression IDs can be expensive, we only do this if the diagnostic is 10394 // enabled. 10395 if (SizeOfArg && 10396 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10397 SizeOfArg->getExprLoc())) { 10398 // We only compute IDs for expressions if the warning is enabled, and 10399 // cache the sizeof arg's ID. 10400 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10401 SizeOfArg->Profile(SizeOfArgID, Context, true); 10402 llvm::FoldingSetNodeID DestID; 10403 Dest->Profile(DestID, Context, true); 10404 if (DestID == SizeOfArgID) { 10405 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10406 // over sizeof(src) as well. 10407 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10408 StringRef ReadableName = FnName->getName(); 10409 10410 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10411 if (UnaryOp->getOpcode() == UO_AddrOf) 10412 ActionIdx = 1; // If its an address-of operator, just remove it. 10413 if (!PointeeTy->isIncompleteType() && 10414 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10415 ActionIdx = 2; // If the pointee's size is sizeof(char), 10416 // suggest an explicit length. 10417 10418 // If the function is defined as a builtin macro, do not show macro 10419 // expansion. 10420 SourceLocation SL = SizeOfArg->getExprLoc(); 10421 SourceRange DSR = Dest->getSourceRange(); 10422 SourceRange SSR = SizeOfArg->getSourceRange(); 10423 SourceManager &SM = getSourceManager(); 10424 10425 if (SM.isMacroArgExpansion(SL)) { 10426 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10427 SL = SM.getSpellingLoc(SL); 10428 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10429 SM.getSpellingLoc(DSR.getEnd())); 10430 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10431 SM.getSpellingLoc(SSR.getEnd())); 10432 } 10433 10434 DiagRuntimeBehavior(SL, SizeOfArg, 10435 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10436 << ReadableName 10437 << PointeeTy 10438 << DestTy 10439 << DSR 10440 << SSR); 10441 DiagRuntimeBehavior(SL, SizeOfArg, 10442 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10443 << ActionIdx 10444 << SSR); 10445 10446 break; 10447 } 10448 } 10449 10450 // Also check for cases where the sizeof argument is the exact same 10451 // type as the memory argument, and where it points to a user-defined 10452 // record type. 10453 if (SizeOfArgTy != QualType()) { 10454 if (PointeeTy->isRecordType() && 10455 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10456 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10457 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10458 << FnName << SizeOfArgTy << ArgIdx 10459 << PointeeTy << Dest->getSourceRange() 10460 << LenExpr->getSourceRange()); 10461 break; 10462 } 10463 } 10464 } else if (DestTy->isArrayType()) { 10465 PointeeTy = DestTy; 10466 } 10467 10468 if (PointeeTy == QualType()) 10469 continue; 10470 10471 // Always complain about dynamic classes. 10472 bool IsContained; 10473 if (const CXXRecordDecl *ContainedRD = 10474 getContainedDynamicClass(PointeeTy, IsContained)) { 10475 10476 unsigned OperationType = 0; 10477 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10478 // "overwritten" if we're warning about the destination for any call 10479 // but memcmp; otherwise a verb appropriate to the call. 10480 if (ArgIdx != 0 || IsCmp) { 10481 if (BId == Builtin::BImemcpy) 10482 OperationType = 1; 10483 else if(BId == Builtin::BImemmove) 10484 OperationType = 2; 10485 else if (IsCmp) 10486 OperationType = 3; 10487 } 10488 10489 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10490 PDiag(diag::warn_dyn_class_memaccess) 10491 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10492 << IsContained << ContainedRD << OperationType 10493 << Call->getCallee()->getSourceRange()); 10494 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10495 BId != Builtin::BImemset) 10496 DiagRuntimeBehavior( 10497 Dest->getExprLoc(), Dest, 10498 PDiag(diag::warn_arc_object_memaccess) 10499 << ArgIdx << FnName << PointeeTy 10500 << Call->getCallee()->getSourceRange()); 10501 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10502 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10503 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10504 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10505 PDiag(diag::warn_cstruct_memaccess) 10506 << ArgIdx << FnName << PointeeTy << 0); 10507 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10508 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10509 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10510 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10511 PDiag(diag::warn_cstruct_memaccess) 10512 << ArgIdx << FnName << PointeeTy << 1); 10513 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10514 } else { 10515 continue; 10516 } 10517 } else 10518 continue; 10519 10520 DiagRuntimeBehavior( 10521 Dest->getExprLoc(), Dest, 10522 PDiag(diag::note_bad_memaccess_silence) 10523 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10524 break; 10525 } 10526 } 10527 10528 // A little helper routine: ignore addition and subtraction of integer literals. 10529 // This intentionally does not ignore all integer constant expressions because 10530 // we don't want to remove sizeof(). 10531 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10532 Ex = Ex->IgnoreParenCasts(); 10533 10534 while (true) { 10535 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10536 if (!BO || !BO->isAdditiveOp()) 10537 break; 10538 10539 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10540 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10541 10542 if (isa<IntegerLiteral>(RHS)) 10543 Ex = LHS; 10544 else if (isa<IntegerLiteral>(LHS)) 10545 Ex = RHS; 10546 else 10547 break; 10548 } 10549 10550 return Ex; 10551 } 10552 10553 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10554 ASTContext &Context) { 10555 // Only handle constant-sized or VLAs, but not flexible members. 10556 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10557 // Only issue the FIXIT for arrays of size > 1. 10558 if (CAT->getSize().getSExtValue() <= 1) 10559 return false; 10560 } else if (!Ty->isVariableArrayType()) { 10561 return false; 10562 } 10563 return true; 10564 } 10565 10566 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10567 // be the size of the source, instead of the destination. 10568 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10569 IdentifierInfo *FnName) { 10570 10571 // Don't crash if the user has the wrong number of arguments 10572 unsigned NumArgs = Call->getNumArgs(); 10573 if ((NumArgs != 3) && (NumArgs != 4)) 10574 return; 10575 10576 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10577 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10578 const Expr *CompareWithSrc = nullptr; 10579 10580 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10581 Call->getBeginLoc(), Call->getRParenLoc())) 10582 return; 10583 10584 // Look for 'strlcpy(dst, x, sizeof(x))' 10585 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10586 CompareWithSrc = Ex; 10587 else { 10588 // Look for 'strlcpy(dst, x, strlen(x))' 10589 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10590 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10591 SizeCall->getNumArgs() == 1) 10592 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10593 } 10594 } 10595 10596 if (!CompareWithSrc) 10597 return; 10598 10599 // Determine if the argument to sizeof/strlen is equal to the source 10600 // argument. In principle there's all kinds of things you could do 10601 // here, for instance creating an == expression and evaluating it with 10602 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10603 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10604 if (!SrcArgDRE) 10605 return; 10606 10607 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10608 if (!CompareWithSrcDRE || 10609 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10610 return; 10611 10612 const Expr *OriginalSizeArg = Call->getArg(2); 10613 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10614 << OriginalSizeArg->getSourceRange() << FnName; 10615 10616 // Output a FIXIT hint if the destination is an array (rather than a 10617 // pointer to an array). This could be enhanced to handle some 10618 // pointers if we know the actual size, like if DstArg is 'array+2' 10619 // we could say 'sizeof(array)-2'. 10620 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10621 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10622 return; 10623 10624 SmallString<128> sizeString; 10625 llvm::raw_svector_ostream OS(sizeString); 10626 OS << "sizeof("; 10627 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10628 OS << ")"; 10629 10630 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10631 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10632 OS.str()); 10633 } 10634 10635 /// Check if two expressions refer to the same declaration. 10636 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10637 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10638 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10639 return D1->getDecl() == D2->getDecl(); 10640 return false; 10641 } 10642 10643 static const Expr *getStrlenExprArg(const Expr *E) { 10644 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10645 const FunctionDecl *FD = CE->getDirectCallee(); 10646 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10647 return nullptr; 10648 return CE->getArg(0)->IgnoreParenCasts(); 10649 } 10650 return nullptr; 10651 } 10652 10653 // Warn on anti-patterns as the 'size' argument to strncat. 10654 // The correct size argument should look like following: 10655 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10656 void Sema::CheckStrncatArguments(const CallExpr *CE, 10657 IdentifierInfo *FnName) { 10658 // Don't crash if the user has the wrong number of arguments. 10659 if (CE->getNumArgs() < 3) 10660 return; 10661 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10662 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10663 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10664 10665 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10666 CE->getRParenLoc())) 10667 return; 10668 10669 // Identify common expressions, which are wrongly used as the size argument 10670 // to strncat and may lead to buffer overflows. 10671 unsigned PatternType = 0; 10672 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10673 // - sizeof(dst) 10674 if (referToTheSameDecl(SizeOfArg, DstArg)) 10675 PatternType = 1; 10676 // - sizeof(src) 10677 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10678 PatternType = 2; 10679 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10680 if (BE->getOpcode() == BO_Sub) { 10681 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10682 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10683 // - sizeof(dst) - strlen(dst) 10684 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10685 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10686 PatternType = 1; 10687 // - sizeof(src) - (anything) 10688 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10689 PatternType = 2; 10690 } 10691 } 10692 10693 if (PatternType == 0) 10694 return; 10695 10696 // Generate the diagnostic. 10697 SourceLocation SL = LenArg->getBeginLoc(); 10698 SourceRange SR = LenArg->getSourceRange(); 10699 SourceManager &SM = getSourceManager(); 10700 10701 // If the function is defined as a builtin macro, do not show macro expansion. 10702 if (SM.isMacroArgExpansion(SL)) { 10703 SL = SM.getSpellingLoc(SL); 10704 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10705 SM.getSpellingLoc(SR.getEnd())); 10706 } 10707 10708 // Check if the destination is an array (rather than a pointer to an array). 10709 QualType DstTy = DstArg->getType(); 10710 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10711 Context); 10712 if (!isKnownSizeArray) { 10713 if (PatternType == 1) 10714 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10715 else 10716 Diag(SL, diag::warn_strncat_src_size) << SR; 10717 return; 10718 } 10719 10720 if (PatternType == 1) 10721 Diag(SL, diag::warn_strncat_large_size) << SR; 10722 else 10723 Diag(SL, diag::warn_strncat_src_size) << SR; 10724 10725 SmallString<128> sizeString; 10726 llvm::raw_svector_ostream OS(sizeString); 10727 OS << "sizeof("; 10728 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10729 OS << ") - "; 10730 OS << "strlen("; 10731 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10732 OS << ") - 1"; 10733 10734 Diag(SL, diag::note_strncat_wrong_size) 10735 << FixItHint::CreateReplacement(SR, OS.str()); 10736 } 10737 10738 namespace { 10739 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10740 const UnaryOperator *UnaryExpr, const Decl *D) { 10741 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10742 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10743 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10744 return; 10745 } 10746 } 10747 10748 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10749 const UnaryOperator *UnaryExpr) { 10750 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10751 const Decl *D = Lvalue->getDecl(); 10752 if (isa<DeclaratorDecl>(D)) 10753 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10754 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10755 } 10756 10757 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10758 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10759 Lvalue->getMemberDecl()); 10760 } 10761 10762 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10763 const UnaryOperator *UnaryExpr) { 10764 const auto *Lambda = dyn_cast<LambdaExpr>( 10765 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10766 if (!Lambda) 10767 return; 10768 10769 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10770 << CalleeName << 2 /*object: lambda expression*/; 10771 } 10772 10773 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10774 const DeclRefExpr *Lvalue) { 10775 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10776 if (Var == nullptr) 10777 return; 10778 10779 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10780 << CalleeName << 0 /*object: */ << Var; 10781 } 10782 10783 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10784 const CastExpr *Cast) { 10785 SmallString<128> SizeString; 10786 llvm::raw_svector_ostream OS(SizeString); 10787 10788 clang::CastKind Kind = Cast->getCastKind(); 10789 if (Kind == clang::CK_BitCast && 10790 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10791 return; 10792 if (Kind == clang::CK_IntegralToPointer && 10793 !isa<IntegerLiteral>( 10794 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10795 return; 10796 10797 switch (Cast->getCastKind()) { 10798 case clang::CK_BitCast: 10799 case clang::CK_IntegralToPointer: 10800 case clang::CK_FunctionToPointerDecay: 10801 OS << '\''; 10802 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10803 OS << '\''; 10804 break; 10805 default: 10806 return; 10807 } 10808 10809 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10810 << CalleeName << 0 /*object: */ << OS.str(); 10811 } 10812 } // namespace 10813 10814 /// Alerts the user that they are attempting to free a non-malloc'd object. 10815 void Sema::CheckFreeArguments(const CallExpr *E) { 10816 const std::string CalleeName = 10817 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10818 10819 { // Prefer something that doesn't involve a cast to make things simpler. 10820 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10821 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10822 switch (UnaryExpr->getOpcode()) { 10823 case UnaryOperator::Opcode::UO_AddrOf: 10824 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10825 case UnaryOperator::Opcode::UO_Plus: 10826 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10827 default: 10828 break; 10829 } 10830 10831 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10832 if (Lvalue->getType()->isArrayType()) 10833 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10834 10835 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10836 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10837 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10838 return; 10839 } 10840 10841 if (isa<BlockExpr>(Arg)) { 10842 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10843 << CalleeName << 1 /*object: block*/; 10844 return; 10845 } 10846 } 10847 // Maybe the cast was important, check after the other cases. 10848 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10849 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10850 } 10851 10852 void 10853 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10854 SourceLocation ReturnLoc, 10855 bool isObjCMethod, 10856 const AttrVec *Attrs, 10857 const FunctionDecl *FD) { 10858 // Check if the return value is null but should not be. 10859 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10860 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10861 CheckNonNullExpr(*this, RetValExp)) 10862 Diag(ReturnLoc, diag::warn_null_ret) 10863 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10864 10865 // C++11 [basic.stc.dynamic.allocation]p4: 10866 // If an allocation function declared with a non-throwing 10867 // exception-specification fails to allocate storage, it shall return 10868 // a null pointer. Any other allocation function that fails to allocate 10869 // storage shall indicate failure only by throwing an exception [...] 10870 if (FD) { 10871 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10872 if (Op == OO_New || Op == OO_Array_New) { 10873 const FunctionProtoType *Proto 10874 = FD->getType()->castAs<FunctionProtoType>(); 10875 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10876 CheckNonNullExpr(*this, RetValExp)) 10877 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10878 << FD << getLangOpts().CPlusPlus11; 10879 } 10880 } 10881 10882 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10883 // here prevent the user from using a PPC MMA type as trailing return type. 10884 if (Context.getTargetInfo().getTriple().isPPC64()) 10885 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10886 } 10887 10888 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10889 10890 /// Check for comparisons of floating point operands using != and ==. 10891 /// Issue a warning if these are no self-comparisons, as they are not likely 10892 /// to do what the programmer intended. 10893 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10894 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10895 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10896 10897 // Special case: check for x == x (which is OK). 10898 // Do not emit warnings for such cases. 10899 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10900 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10901 if (DRL->getDecl() == DRR->getDecl()) 10902 return; 10903 10904 // Special case: check for comparisons against literals that can be exactly 10905 // represented by APFloat. In such cases, do not emit a warning. This 10906 // is a heuristic: often comparison against such literals are used to 10907 // detect if a value in a variable has not changed. This clearly can 10908 // lead to false negatives. 10909 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10910 if (FLL->isExact()) 10911 return; 10912 } else 10913 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10914 if (FLR->isExact()) 10915 return; 10916 10917 // Check for comparisons with builtin types. 10918 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10919 if (CL->getBuiltinCallee()) 10920 return; 10921 10922 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10923 if (CR->getBuiltinCallee()) 10924 return; 10925 10926 // Emit the diagnostic. 10927 Diag(Loc, diag::warn_floatingpoint_eq) 10928 << LHS->getSourceRange() << RHS->getSourceRange(); 10929 } 10930 10931 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10932 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10933 10934 namespace { 10935 10936 /// Structure recording the 'active' range of an integer-valued 10937 /// expression. 10938 struct IntRange { 10939 /// The number of bits active in the int. Note that this includes exactly one 10940 /// sign bit if !NonNegative. 10941 unsigned Width; 10942 10943 /// True if the int is known not to have negative values. If so, all leading 10944 /// bits before Width are known zero, otherwise they are known to be the 10945 /// same as the MSB within Width. 10946 bool NonNegative; 10947 10948 IntRange(unsigned Width, bool NonNegative) 10949 : Width(Width), NonNegative(NonNegative) {} 10950 10951 /// Number of bits excluding the sign bit. 10952 unsigned valueBits() const { 10953 return NonNegative ? Width : Width - 1; 10954 } 10955 10956 /// Returns the range of the bool type. 10957 static IntRange forBoolType() { 10958 return IntRange(1, true); 10959 } 10960 10961 /// Returns the range of an opaque value of the given integral type. 10962 static IntRange forValueOfType(ASTContext &C, QualType T) { 10963 return forValueOfCanonicalType(C, 10964 T->getCanonicalTypeInternal().getTypePtr()); 10965 } 10966 10967 /// Returns the range of an opaque value of a canonical integral type. 10968 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10969 assert(T->isCanonicalUnqualified()); 10970 10971 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10972 T = VT->getElementType().getTypePtr(); 10973 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10974 T = CT->getElementType().getTypePtr(); 10975 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10976 T = AT->getValueType().getTypePtr(); 10977 10978 if (!C.getLangOpts().CPlusPlus) { 10979 // For enum types in C code, use the underlying datatype. 10980 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10981 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10982 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10983 // For enum types in C++, use the known bit width of the enumerators. 10984 EnumDecl *Enum = ET->getDecl(); 10985 // In C++11, enums can have a fixed underlying type. Use this type to 10986 // compute the range. 10987 if (Enum->isFixed()) { 10988 return IntRange(C.getIntWidth(QualType(T, 0)), 10989 !ET->isSignedIntegerOrEnumerationType()); 10990 } 10991 10992 unsigned NumPositive = Enum->getNumPositiveBits(); 10993 unsigned NumNegative = Enum->getNumNegativeBits(); 10994 10995 if (NumNegative == 0) 10996 return IntRange(NumPositive, true/*NonNegative*/); 10997 else 10998 return IntRange(std::max(NumPositive + 1, NumNegative), 10999 false/*NonNegative*/); 11000 } 11001 11002 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11003 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11004 11005 const BuiltinType *BT = cast<BuiltinType>(T); 11006 assert(BT->isInteger()); 11007 11008 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11009 } 11010 11011 /// Returns the "target" range of a canonical integral type, i.e. 11012 /// the range of values expressible in the type. 11013 /// 11014 /// This matches forValueOfCanonicalType except that enums have the 11015 /// full range of their type, not the range of their enumerators. 11016 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11017 assert(T->isCanonicalUnqualified()); 11018 11019 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11020 T = VT->getElementType().getTypePtr(); 11021 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11022 T = CT->getElementType().getTypePtr(); 11023 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11024 T = AT->getValueType().getTypePtr(); 11025 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11026 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11027 11028 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11029 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11030 11031 const BuiltinType *BT = cast<BuiltinType>(T); 11032 assert(BT->isInteger()); 11033 11034 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11035 } 11036 11037 /// Returns the supremum of two ranges: i.e. their conservative merge. 11038 static IntRange join(IntRange L, IntRange R) { 11039 bool Unsigned = L.NonNegative && R.NonNegative; 11040 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11041 L.NonNegative && R.NonNegative); 11042 } 11043 11044 /// Return the range of a bitwise-AND of the two ranges. 11045 static IntRange bit_and(IntRange L, IntRange R) { 11046 unsigned Bits = std::max(L.Width, R.Width); 11047 bool NonNegative = false; 11048 if (L.NonNegative) { 11049 Bits = std::min(Bits, L.Width); 11050 NonNegative = true; 11051 } 11052 if (R.NonNegative) { 11053 Bits = std::min(Bits, R.Width); 11054 NonNegative = true; 11055 } 11056 return IntRange(Bits, NonNegative); 11057 } 11058 11059 /// Return the range of a sum of the two ranges. 11060 static IntRange sum(IntRange L, IntRange R) { 11061 bool Unsigned = L.NonNegative && R.NonNegative; 11062 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11063 Unsigned); 11064 } 11065 11066 /// Return the range of a difference of the two ranges. 11067 static IntRange difference(IntRange L, IntRange R) { 11068 // We need a 1-bit-wider range if: 11069 // 1) LHS can be negative: least value can be reduced. 11070 // 2) RHS can be negative: greatest value can be increased. 11071 bool CanWiden = !L.NonNegative || !R.NonNegative; 11072 bool Unsigned = L.NonNegative && R.Width == 0; 11073 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11074 !Unsigned, 11075 Unsigned); 11076 } 11077 11078 /// Return the range of a product of the two ranges. 11079 static IntRange product(IntRange L, IntRange R) { 11080 // If both LHS and RHS can be negative, we can form 11081 // -2^L * -2^R = 2^(L + R) 11082 // which requires L + R + 1 value bits to represent. 11083 bool CanWiden = !L.NonNegative && !R.NonNegative; 11084 bool Unsigned = L.NonNegative && R.NonNegative; 11085 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11086 Unsigned); 11087 } 11088 11089 /// Return the range of a remainder operation between the two ranges. 11090 static IntRange rem(IntRange L, IntRange R) { 11091 // The result of a remainder can't be larger than the result of 11092 // either side. The sign of the result is the sign of the LHS. 11093 bool Unsigned = L.NonNegative; 11094 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11095 Unsigned); 11096 } 11097 }; 11098 11099 } // namespace 11100 11101 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11102 unsigned MaxWidth) { 11103 if (value.isSigned() && value.isNegative()) 11104 return IntRange(value.getMinSignedBits(), false); 11105 11106 if (value.getBitWidth() > MaxWidth) 11107 value = value.trunc(MaxWidth); 11108 11109 // isNonNegative() just checks the sign bit without considering 11110 // signedness. 11111 return IntRange(value.getActiveBits(), true); 11112 } 11113 11114 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11115 unsigned MaxWidth) { 11116 if (result.isInt()) 11117 return GetValueRange(C, result.getInt(), MaxWidth); 11118 11119 if (result.isVector()) { 11120 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11121 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11122 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11123 R = IntRange::join(R, El); 11124 } 11125 return R; 11126 } 11127 11128 if (result.isComplexInt()) { 11129 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11130 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11131 return IntRange::join(R, I); 11132 } 11133 11134 // This can happen with lossless casts to intptr_t of "based" lvalues. 11135 // Assume it might use arbitrary bits. 11136 // FIXME: The only reason we need to pass the type in here is to get 11137 // the sign right on this one case. It would be nice if APValue 11138 // preserved this. 11139 assert(result.isLValue() || result.isAddrLabelDiff()); 11140 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11141 } 11142 11143 static QualType GetExprType(const Expr *E) { 11144 QualType Ty = E->getType(); 11145 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11146 Ty = AtomicRHS->getValueType(); 11147 return Ty; 11148 } 11149 11150 /// Pseudo-evaluate the given integer expression, estimating the 11151 /// range of values it might take. 11152 /// 11153 /// \param MaxWidth The width to which the value will be truncated. 11154 /// \param Approximate If \c true, return a likely range for the result: in 11155 /// particular, assume that aritmetic on narrower types doesn't leave 11156 /// those types. If \c false, return a range including all possible 11157 /// result values. 11158 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11159 bool InConstantContext, bool Approximate) { 11160 E = E->IgnoreParens(); 11161 11162 // Try a full evaluation first. 11163 Expr::EvalResult result; 11164 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11165 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11166 11167 // I think we only want to look through implicit casts here; if the 11168 // user has an explicit widening cast, we should treat the value as 11169 // being of the new, wider type. 11170 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11171 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11172 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11173 Approximate); 11174 11175 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11176 11177 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11178 CE->getCastKind() == CK_BooleanToSignedIntegral; 11179 11180 // Assume that non-integer casts can span the full range of the type. 11181 if (!isIntegerCast) 11182 return OutputTypeRange; 11183 11184 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11185 std::min(MaxWidth, OutputTypeRange.Width), 11186 InConstantContext, Approximate); 11187 11188 // Bail out if the subexpr's range is as wide as the cast type. 11189 if (SubRange.Width >= OutputTypeRange.Width) 11190 return OutputTypeRange; 11191 11192 // Otherwise, we take the smaller width, and we're non-negative if 11193 // either the output type or the subexpr is. 11194 return IntRange(SubRange.Width, 11195 SubRange.NonNegative || OutputTypeRange.NonNegative); 11196 } 11197 11198 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11199 // If we can fold the condition, just take that operand. 11200 bool CondResult; 11201 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11202 return GetExprRange(C, 11203 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11204 MaxWidth, InConstantContext, Approximate); 11205 11206 // Otherwise, conservatively merge. 11207 // GetExprRange requires an integer expression, but a throw expression 11208 // results in a void type. 11209 Expr *E = CO->getTrueExpr(); 11210 IntRange L = E->getType()->isVoidType() 11211 ? IntRange{0, true} 11212 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11213 E = CO->getFalseExpr(); 11214 IntRange R = E->getType()->isVoidType() 11215 ? IntRange{0, true} 11216 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11217 return IntRange::join(L, R); 11218 } 11219 11220 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11221 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11222 11223 switch (BO->getOpcode()) { 11224 case BO_Cmp: 11225 llvm_unreachable("builtin <=> should have class type"); 11226 11227 // Boolean-valued operations are single-bit and positive. 11228 case BO_LAnd: 11229 case BO_LOr: 11230 case BO_LT: 11231 case BO_GT: 11232 case BO_LE: 11233 case BO_GE: 11234 case BO_EQ: 11235 case BO_NE: 11236 return IntRange::forBoolType(); 11237 11238 // The type of the assignments is the type of the LHS, so the RHS 11239 // is not necessarily the same type. 11240 case BO_MulAssign: 11241 case BO_DivAssign: 11242 case BO_RemAssign: 11243 case BO_AddAssign: 11244 case BO_SubAssign: 11245 case BO_XorAssign: 11246 case BO_OrAssign: 11247 // TODO: bitfields? 11248 return IntRange::forValueOfType(C, GetExprType(E)); 11249 11250 // Simple assignments just pass through the RHS, which will have 11251 // been coerced to the LHS type. 11252 case BO_Assign: 11253 // TODO: bitfields? 11254 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11255 Approximate); 11256 11257 // Operations with opaque sources are black-listed. 11258 case BO_PtrMemD: 11259 case BO_PtrMemI: 11260 return IntRange::forValueOfType(C, GetExprType(E)); 11261 11262 // Bitwise-and uses the *infinum* of the two source ranges. 11263 case BO_And: 11264 case BO_AndAssign: 11265 Combine = IntRange::bit_and; 11266 break; 11267 11268 // Left shift gets black-listed based on a judgement call. 11269 case BO_Shl: 11270 // ...except that we want to treat '1 << (blah)' as logically 11271 // positive. It's an important idiom. 11272 if (IntegerLiteral *I 11273 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11274 if (I->getValue() == 1) { 11275 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11276 return IntRange(R.Width, /*NonNegative*/ true); 11277 } 11278 } 11279 LLVM_FALLTHROUGH; 11280 11281 case BO_ShlAssign: 11282 return IntRange::forValueOfType(C, GetExprType(E)); 11283 11284 // Right shift by a constant can narrow its left argument. 11285 case BO_Shr: 11286 case BO_ShrAssign: { 11287 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11288 Approximate); 11289 11290 // If the shift amount is a positive constant, drop the width by 11291 // that much. 11292 if (Optional<llvm::APSInt> shift = 11293 BO->getRHS()->getIntegerConstantExpr(C)) { 11294 if (shift->isNonNegative()) { 11295 unsigned zext = shift->getZExtValue(); 11296 if (zext >= L.Width) 11297 L.Width = (L.NonNegative ? 0 : 1); 11298 else 11299 L.Width -= zext; 11300 } 11301 } 11302 11303 return L; 11304 } 11305 11306 // Comma acts as its right operand. 11307 case BO_Comma: 11308 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11309 Approximate); 11310 11311 case BO_Add: 11312 if (!Approximate) 11313 Combine = IntRange::sum; 11314 break; 11315 11316 case BO_Sub: 11317 if (BO->getLHS()->getType()->isPointerType()) 11318 return IntRange::forValueOfType(C, GetExprType(E)); 11319 if (!Approximate) 11320 Combine = IntRange::difference; 11321 break; 11322 11323 case BO_Mul: 11324 if (!Approximate) 11325 Combine = IntRange::product; 11326 break; 11327 11328 // The width of a division result is mostly determined by the size 11329 // of the LHS. 11330 case BO_Div: { 11331 // Don't 'pre-truncate' the operands. 11332 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11333 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11334 Approximate); 11335 11336 // If the divisor is constant, use that. 11337 if (Optional<llvm::APSInt> divisor = 11338 BO->getRHS()->getIntegerConstantExpr(C)) { 11339 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11340 if (log2 >= L.Width) 11341 L.Width = (L.NonNegative ? 0 : 1); 11342 else 11343 L.Width = std::min(L.Width - log2, MaxWidth); 11344 return L; 11345 } 11346 11347 // Otherwise, just use the LHS's width. 11348 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11349 // could be -1. 11350 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11351 Approximate); 11352 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11353 } 11354 11355 case BO_Rem: 11356 Combine = IntRange::rem; 11357 break; 11358 11359 // The default behavior is okay for these. 11360 case BO_Xor: 11361 case BO_Or: 11362 break; 11363 } 11364 11365 // Combine the two ranges, but limit the result to the type in which we 11366 // performed the computation. 11367 QualType T = GetExprType(E); 11368 unsigned opWidth = C.getIntWidth(T); 11369 IntRange L = 11370 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11371 IntRange R = 11372 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11373 IntRange C = Combine(L, R); 11374 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11375 C.Width = std::min(C.Width, MaxWidth); 11376 return C; 11377 } 11378 11379 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11380 switch (UO->getOpcode()) { 11381 // Boolean-valued operations are white-listed. 11382 case UO_LNot: 11383 return IntRange::forBoolType(); 11384 11385 // Operations with opaque sources are black-listed. 11386 case UO_Deref: 11387 case UO_AddrOf: // should be impossible 11388 return IntRange::forValueOfType(C, GetExprType(E)); 11389 11390 default: 11391 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11392 Approximate); 11393 } 11394 } 11395 11396 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11397 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11398 Approximate); 11399 11400 if (const auto *BitField = E->getSourceBitField()) 11401 return IntRange(BitField->getBitWidthValue(C), 11402 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11403 11404 return IntRange::forValueOfType(C, GetExprType(E)); 11405 } 11406 11407 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11408 bool InConstantContext, bool Approximate) { 11409 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11410 Approximate); 11411 } 11412 11413 /// Checks whether the given value, which currently has the given 11414 /// source semantics, has the same value when coerced through the 11415 /// target semantics. 11416 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11417 const llvm::fltSemantics &Src, 11418 const llvm::fltSemantics &Tgt) { 11419 llvm::APFloat truncated = value; 11420 11421 bool ignored; 11422 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11423 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11424 11425 return truncated.bitwiseIsEqual(value); 11426 } 11427 11428 /// Checks whether the given value, which currently has the given 11429 /// source semantics, has the same value when coerced through the 11430 /// target semantics. 11431 /// 11432 /// The value might be a vector of floats (or a complex number). 11433 static bool IsSameFloatAfterCast(const APValue &value, 11434 const llvm::fltSemantics &Src, 11435 const llvm::fltSemantics &Tgt) { 11436 if (value.isFloat()) 11437 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11438 11439 if (value.isVector()) { 11440 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11441 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11442 return false; 11443 return true; 11444 } 11445 11446 assert(value.isComplexFloat()); 11447 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11448 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11449 } 11450 11451 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11452 bool IsListInit = false); 11453 11454 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11455 // Suppress cases where we are comparing against an enum constant. 11456 if (const DeclRefExpr *DR = 11457 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11458 if (isa<EnumConstantDecl>(DR->getDecl())) 11459 return true; 11460 11461 // Suppress cases where the value is expanded from a macro, unless that macro 11462 // is how a language represents a boolean literal. This is the case in both C 11463 // and Objective-C. 11464 SourceLocation BeginLoc = E->getBeginLoc(); 11465 if (BeginLoc.isMacroID()) { 11466 StringRef MacroName = Lexer::getImmediateMacroName( 11467 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11468 return MacroName != "YES" && MacroName != "NO" && 11469 MacroName != "true" && MacroName != "false"; 11470 } 11471 11472 return false; 11473 } 11474 11475 static bool isKnownToHaveUnsignedValue(Expr *E) { 11476 return E->getType()->isIntegerType() && 11477 (!E->getType()->isSignedIntegerType() || 11478 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11479 } 11480 11481 namespace { 11482 /// The promoted range of values of a type. In general this has the 11483 /// following structure: 11484 /// 11485 /// |-----------| . . . |-----------| 11486 /// ^ ^ ^ ^ 11487 /// Min HoleMin HoleMax Max 11488 /// 11489 /// ... where there is only a hole if a signed type is promoted to unsigned 11490 /// (in which case Min and Max are the smallest and largest representable 11491 /// values). 11492 struct PromotedRange { 11493 // Min, or HoleMax if there is a hole. 11494 llvm::APSInt PromotedMin; 11495 // Max, or HoleMin if there is a hole. 11496 llvm::APSInt PromotedMax; 11497 11498 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11499 if (R.Width == 0) 11500 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11501 else if (R.Width >= BitWidth && !Unsigned) { 11502 // Promotion made the type *narrower*. This happens when promoting 11503 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11504 // Treat all values of 'signed int' as being in range for now. 11505 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11506 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11507 } else { 11508 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11509 .extOrTrunc(BitWidth); 11510 PromotedMin.setIsUnsigned(Unsigned); 11511 11512 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11513 .extOrTrunc(BitWidth); 11514 PromotedMax.setIsUnsigned(Unsigned); 11515 } 11516 } 11517 11518 // Determine whether this range is contiguous (has no hole). 11519 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11520 11521 // Where a constant value is within the range. 11522 enum ComparisonResult { 11523 LT = 0x1, 11524 LE = 0x2, 11525 GT = 0x4, 11526 GE = 0x8, 11527 EQ = 0x10, 11528 NE = 0x20, 11529 InRangeFlag = 0x40, 11530 11531 Less = LE | LT | NE, 11532 Min = LE | InRangeFlag, 11533 InRange = InRangeFlag, 11534 Max = GE | InRangeFlag, 11535 Greater = GE | GT | NE, 11536 11537 OnlyValue = LE | GE | EQ | InRangeFlag, 11538 InHole = NE 11539 }; 11540 11541 ComparisonResult compare(const llvm::APSInt &Value) const { 11542 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11543 Value.isUnsigned() == PromotedMin.isUnsigned()); 11544 if (!isContiguous()) { 11545 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11546 if (Value.isMinValue()) return Min; 11547 if (Value.isMaxValue()) return Max; 11548 if (Value >= PromotedMin) return InRange; 11549 if (Value <= PromotedMax) return InRange; 11550 return InHole; 11551 } 11552 11553 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11554 case -1: return Less; 11555 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11556 case 1: 11557 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11558 case -1: return InRange; 11559 case 0: return Max; 11560 case 1: return Greater; 11561 } 11562 } 11563 11564 llvm_unreachable("impossible compare result"); 11565 } 11566 11567 static llvm::Optional<StringRef> 11568 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11569 if (Op == BO_Cmp) { 11570 ComparisonResult LTFlag = LT, GTFlag = GT; 11571 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11572 11573 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11574 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11575 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11576 return llvm::None; 11577 } 11578 11579 ComparisonResult TrueFlag, FalseFlag; 11580 if (Op == BO_EQ) { 11581 TrueFlag = EQ; 11582 FalseFlag = NE; 11583 } else if (Op == BO_NE) { 11584 TrueFlag = NE; 11585 FalseFlag = EQ; 11586 } else { 11587 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11588 TrueFlag = LT; 11589 FalseFlag = GE; 11590 } else { 11591 TrueFlag = GT; 11592 FalseFlag = LE; 11593 } 11594 if (Op == BO_GE || Op == BO_LE) 11595 std::swap(TrueFlag, FalseFlag); 11596 } 11597 if (R & TrueFlag) 11598 return StringRef("true"); 11599 if (R & FalseFlag) 11600 return StringRef("false"); 11601 return llvm::None; 11602 } 11603 }; 11604 } 11605 11606 static bool HasEnumType(Expr *E) { 11607 // Strip off implicit integral promotions. 11608 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11609 if (ICE->getCastKind() != CK_IntegralCast && 11610 ICE->getCastKind() != CK_NoOp) 11611 break; 11612 E = ICE->getSubExpr(); 11613 } 11614 11615 return E->getType()->isEnumeralType(); 11616 } 11617 11618 static int classifyConstantValue(Expr *Constant) { 11619 // The values of this enumeration are used in the diagnostics 11620 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11621 enum ConstantValueKind { 11622 Miscellaneous = 0, 11623 LiteralTrue, 11624 LiteralFalse 11625 }; 11626 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11627 return BL->getValue() ? ConstantValueKind::LiteralTrue 11628 : ConstantValueKind::LiteralFalse; 11629 return ConstantValueKind::Miscellaneous; 11630 } 11631 11632 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11633 Expr *Constant, Expr *Other, 11634 const llvm::APSInt &Value, 11635 bool RhsConstant) { 11636 if (S.inTemplateInstantiation()) 11637 return false; 11638 11639 Expr *OriginalOther = Other; 11640 11641 Constant = Constant->IgnoreParenImpCasts(); 11642 Other = Other->IgnoreParenImpCasts(); 11643 11644 // Suppress warnings on tautological comparisons between values of the same 11645 // enumeration type. There are only two ways we could warn on this: 11646 // - If the constant is outside the range of representable values of 11647 // the enumeration. In such a case, we should warn about the cast 11648 // to enumeration type, not about the comparison. 11649 // - If the constant is the maximum / minimum in-range value. For an 11650 // enumeratin type, such comparisons can be meaningful and useful. 11651 if (Constant->getType()->isEnumeralType() && 11652 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11653 return false; 11654 11655 IntRange OtherValueRange = GetExprRange( 11656 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11657 11658 QualType OtherT = Other->getType(); 11659 if (const auto *AT = OtherT->getAs<AtomicType>()) 11660 OtherT = AT->getValueType(); 11661 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11662 11663 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11664 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11665 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11666 S.NSAPIObj->isObjCBOOLType(OtherT) && 11667 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11668 11669 // Whether we're treating Other as being a bool because of the form of 11670 // expression despite it having another type (typically 'int' in C). 11671 bool OtherIsBooleanDespiteType = 11672 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11673 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11674 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11675 11676 // Check if all values in the range of possible values of this expression 11677 // lead to the same comparison outcome. 11678 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11679 Value.isUnsigned()); 11680 auto Cmp = OtherPromotedValueRange.compare(Value); 11681 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11682 if (!Result) 11683 return false; 11684 11685 // Also consider the range determined by the type alone. This allows us to 11686 // classify the warning under the proper diagnostic group. 11687 bool TautologicalTypeCompare = false; 11688 { 11689 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11690 Value.isUnsigned()); 11691 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11692 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11693 RhsConstant)) { 11694 TautologicalTypeCompare = true; 11695 Cmp = TypeCmp; 11696 Result = TypeResult; 11697 } 11698 } 11699 11700 // Don't warn if the non-constant operand actually always evaluates to the 11701 // same value. 11702 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11703 return false; 11704 11705 // Suppress the diagnostic for an in-range comparison if the constant comes 11706 // from a macro or enumerator. We don't want to diagnose 11707 // 11708 // some_long_value <= INT_MAX 11709 // 11710 // when sizeof(int) == sizeof(long). 11711 bool InRange = Cmp & PromotedRange::InRangeFlag; 11712 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11713 return false; 11714 11715 // A comparison of an unsigned bit-field against 0 is really a type problem, 11716 // even though at the type level the bit-field might promote to 'signed int'. 11717 if (Other->refersToBitField() && InRange && Value == 0 && 11718 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11719 TautologicalTypeCompare = true; 11720 11721 // If this is a comparison to an enum constant, include that 11722 // constant in the diagnostic. 11723 const EnumConstantDecl *ED = nullptr; 11724 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11725 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11726 11727 // Should be enough for uint128 (39 decimal digits) 11728 SmallString<64> PrettySourceValue; 11729 llvm::raw_svector_ostream OS(PrettySourceValue); 11730 if (ED) { 11731 OS << '\'' << *ED << "' (" << Value << ")"; 11732 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11733 Constant->IgnoreParenImpCasts())) { 11734 OS << (BL->getValue() ? "YES" : "NO"); 11735 } else { 11736 OS << Value; 11737 } 11738 11739 if (!TautologicalTypeCompare) { 11740 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11741 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11742 << E->getOpcodeStr() << OS.str() << *Result 11743 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11744 return true; 11745 } 11746 11747 if (IsObjCSignedCharBool) { 11748 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11749 S.PDiag(diag::warn_tautological_compare_objc_bool) 11750 << OS.str() << *Result); 11751 return true; 11752 } 11753 11754 // FIXME: We use a somewhat different formatting for the in-range cases and 11755 // cases involving boolean values for historical reasons. We should pick a 11756 // consistent way of presenting these diagnostics. 11757 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11758 11759 S.DiagRuntimeBehavior( 11760 E->getOperatorLoc(), E, 11761 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11762 : diag::warn_tautological_bool_compare) 11763 << OS.str() << classifyConstantValue(Constant) << OtherT 11764 << OtherIsBooleanDespiteType << *Result 11765 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11766 } else { 11767 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11768 unsigned Diag = 11769 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11770 ? (HasEnumType(OriginalOther) 11771 ? diag::warn_unsigned_enum_always_true_comparison 11772 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11773 : diag::warn_unsigned_always_true_comparison) 11774 : diag::warn_tautological_constant_compare; 11775 11776 S.Diag(E->getOperatorLoc(), Diag) 11777 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11778 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11779 } 11780 11781 return true; 11782 } 11783 11784 /// Analyze the operands of the given comparison. Implements the 11785 /// fallback case from AnalyzeComparison. 11786 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11787 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11788 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11789 } 11790 11791 /// Implements -Wsign-compare. 11792 /// 11793 /// \param E the binary operator to check for warnings 11794 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11795 // The type the comparison is being performed in. 11796 QualType T = E->getLHS()->getType(); 11797 11798 // Only analyze comparison operators where both sides have been converted to 11799 // the same type. 11800 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11801 return AnalyzeImpConvsInComparison(S, E); 11802 11803 // Don't analyze value-dependent comparisons directly. 11804 if (E->isValueDependent()) 11805 return AnalyzeImpConvsInComparison(S, E); 11806 11807 Expr *LHS = E->getLHS(); 11808 Expr *RHS = E->getRHS(); 11809 11810 if (T->isIntegralType(S.Context)) { 11811 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11812 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11813 11814 // We don't care about expressions whose result is a constant. 11815 if (RHSValue && LHSValue) 11816 return AnalyzeImpConvsInComparison(S, E); 11817 11818 // We only care about expressions where just one side is literal 11819 if ((bool)RHSValue ^ (bool)LHSValue) { 11820 // Is the constant on the RHS or LHS? 11821 const bool RhsConstant = (bool)RHSValue; 11822 Expr *Const = RhsConstant ? RHS : LHS; 11823 Expr *Other = RhsConstant ? LHS : RHS; 11824 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11825 11826 // Check whether an integer constant comparison results in a value 11827 // of 'true' or 'false'. 11828 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11829 return AnalyzeImpConvsInComparison(S, E); 11830 } 11831 } 11832 11833 if (!T->hasUnsignedIntegerRepresentation()) { 11834 // We don't do anything special if this isn't an unsigned integral 11835 // comparison: we're only interested in integral comparisons, and 11836 // signed comparisons only happen in cases we don't care to warn about. 11837 return AnalyzeImpConvsInComparison(S, E); 11838 } 11839 11840 LHS = LHS->IgnoreParenImpCasts(); 11841 RHS = RHS->IgnoreParenImpCasts(); 11842 11843 if (!S.getLangOpts().CPlusPlus) { 11844 // Avoid warning about comparison of integers with different signs when 11845 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11846 // the type of `E`. 11847 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11848 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11849 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11850 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11851 } 11852 11853 // Check to see if one of the (unmodified) operands is of different 11854 // signedness. 11855 Expr *signedOperand, *unsignedOperand; 11856 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11857 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11858 "unsigned comparison between two signed integer expressions?"); 11859 signedOperand = LHS; 11860 unsignedOperand = RHS; 11861 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11862 signedOperand = RHS; 11863 unsignedOperand = LHS; 11864 } else { 11865 return AnalyzeImpConvsInComparison(S, E); 11866 } 11867 11868 // Otherwise, calculate the effective range of the signed operand. 11869 IntRange signedRange = GetExprRange( 11870 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11871 11872 // Go ahead and analyze implicit conversions in the operands. Note 11873 // that we skip the implicit conversions on both sides. 11874 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11875 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11876 11877 // If the signed range is non-negative, -Wsign-compare won't fire. 11878 if (signedRange.NonNegative) 11879 return; 11880 11881 // For (in)equality comparisons, if the unsigned operand is a 11882 // constant which cannot collide with a overflowed signed operand, 11883 // then reinterpreting the signed operand as unsigned will not 11884 // change the result of the comparison. 11885 if (E->isEqualityOp()) { 11886 unsigned comparisonWidth = S.Context.getIntWidth(T); 11887 IntRange unsignedRange = 11888 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11889 /*Approximate*/ true); 11890 11891 // We should never be unable to prove that the unsigned operand is 11892 // non-negative. 11893 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11894 11895 if (unsignedRange.Width < comparisonWidth) 11896 return; 11897 } 11898 11899 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11900 S.PDiag(diag::warn_mixed_sign_comparison) 11901 << LHS->getType() << RHS->getType() 11902 << LHS->getSourceRange() << RHS->getSourceRange()); 11903 } 11904 11905 /// Analyzes an attempt to assign the given value to a bitfield. 11906 /// 11907 /// Returns true if there was something fishy about the attempt. 11908 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11909 SourceLocation InitLoc) { 11910 assert(Bitfield->isBitField()); 11911 if (Bitfield->isInvalidDecl()) 11912 return false; 11913 11914 // White-list bool bitfields. 11915 QualType BitfieldType = Bitfield->getType(); 11916 if (BitfieldType->isBooleanType()) 11917 return false; 11918 11919 if (BitfieldType->isEnumeralType()) { 11920 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11921 // If the underlying enum type was not explicitly specified as an unsigned 11922 // type and the enum contain only positive values, MSVC++ will cause an 11923 // inconsistency by storing this as a signed type. 11924 if (S.getLangOpts().CPlusPlus11 && 11925 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11926 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11927 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11928 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11929 << BitfieldEnumDecl; 11930 } 11931 } 11932 11933 if (Bitfield->getType()->isBooleanType()) 11934 return false; 11935 11936 // Ignore value- or type-dependent expressions. 11937 if (Bitfield->getBitWidth()->isValueDependent() || 11938 Bitfield->getBitWidth()->isTypeDependent() || 11939 Init->isValueDependent() || 11940 Init->isTypeDependent()) 11941 return false; 11942 11943 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11944 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11945 11946 Expr::EvalResult Result; 11947 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11948 Expr::SE_AllowSideEffects)) { 11949 // The RHS is not constant. If the RHS has an enum type, make sure the 11950 // bitfield is wide enough to hold all the values of the enum without 11951 // truncation. 11952 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11953 EnumDecl *ED = EnumTy->getDecl(); 11954 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11955 11956 // Enum types are implicitly signed on Windows, so check if there are any 11957 // negative enumerators to see if the enum was intended to be signed or 11958 // not. 11959 bool SignedEnum = ED->getNumNegativeBits() > 0; 11960 11961 // Check for surprising sign changes when assigning enum values to a 11962 // bitfield of different signedness. If the bitfield is signed and we 11963 // have exactly the right number of bits to store this unsigned enum, 11964 // suggest changing the enum to an unsigned type. This typically happens 11965 // on Windows where unfixed enums always use an underlying type of 'int'. 11966 unsigned DiagID = 0; 11967 if (SignedEnum && !SignedBitfield) { 11968 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11969 } else if (SignedBitfield && !SignedEnum && 11970 ED->getNumPositiveBits() == FieldWidth) { 11971 DiagID = diag::warn_signed_bitfield_enum_conversion; 11972 } 11973 11974 if (DiagID) { 11975 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11976 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11977 SourceRange TypeRange = 11978 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11979 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11980 << SignedEnum << TypeRange; 11981 } 11982 11983 // Compute the required bitwidth. If the enum has negative values, we need 11984 // one more bit than the normal number of positive bits to represent the 11985 // sign bit. 11986 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11987 ED->getNumNegativeBits()) 11988 : ED->getNumPositiveBits(); 11989 11990 // Check the bitwidth. 11991 if (BitsNeeded > FieldWidth) { 11992 Expr *WidthExpr = Bitfield->getBitWidth(); 11993 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11994 << Bitfield << ED; 11995 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11996 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11997 } 11998 } 11999 12000 return false; 12001 } 12002 12003 llvm::APSInt Value = Result.Val.getInt(); 12004 12005 unsigned OriginalWidth = Value.getBitWidth(); 12006 12007 if (!Value.isSigned() || Value.isNegative()) 12008 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12009 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12010 OriginalWidth = Value.getMinSignedBits(); 12011 12012 if (OriginalWidth <= FieldWidth) 12013 return false; 12014 12015 // Compute the value which the bitfield will contain. 12016 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12017 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12018 12019 // Check whether the stored value is equal to the original value. 12020 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12021 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12022 return false; 12023 12024 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12025 // therefore don't strictly fit into a signed bitfield of width 1. 12026 if (FieldWidth == 1 && Value == 1) 12027 return false; 12028 12029 std::string PrettyValue = toString(Value, 10); 12030 std::string PrettyTrunc = toString(TruncatedValue, 10); 12031 12032 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12033 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12034 << Init->getSourceRange(); 12035 12036 return true; 12037 } 12038 12039 /// Analyze the given simple or compound assignment for warning-worthy 12040 /// operations. 12041 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12042 // Just recurse on the LHS. 12043 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12044 12045 // We want to recurse on the RHS as normal unless we're assigning to 12046 // a bitfield. 12047 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12048 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12049 E->getOperatorLoc())) { 12050 // Recurse, ignoring any implicit conversions on the RHS. 12051 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12052 E->getOperatorLoc()); 12053 } 12054 } 12055 12056 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12057 12058 // Diagnose implicitly sequentially-consistent atomic assignment. 12059 if (E->getLHS()->getType()->isAtomicType()) 12060 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12061 } 12062 12063 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12064 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12065 SourceLocation CContext, unsigned diag, 12066 bool pruneControlFlow = false) { 12067 if (pruneControlFlow) { 12068 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12069 S.PDiag(diag) 12070 << SourceType << T << E->getSourceRange() 12071 << SourceRange(CContext)); 12072 return; 12073 } 12074 S.Diag(E->getExprLoc(), diag) 12075 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12076 } 12077 12078 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12079 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12080 SourceLocation CContext, 12081 unsigned diag, bool pruneControlFlow = false) { 12082 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12083 } 12084 12085 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12086 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12087 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12088 } 12089 12090 static void adornObjCBoolConversionDiagWithTernaryFixit( 12091 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12092 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12093 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12094 Ignored = OVE->getSourceExpr(); 12095 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12096 isa<BinaryOperator>(Ignored) || 12097 isa<CXXOperatorCallExpr>(Ignored); 12098 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12099 if (NeedsParens) 12100 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12101 << FixItHint::CreateInsertion(EndLoc, ")"); 12102 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12103 } 12104 12105 /// Diagnose an implicit cast from a floating point value to an integer value. 12106 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12107 SourceLocation CContext) { 12108 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12109 const bool PruneWarnings = S.inTemplateInstantiation(); 12110 12111 Expr *InnerE = E->IgnoreParenImpCasts(); 12112 // We also want to warn on, e.g., "int i = -1.234" 12113 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12114 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12115 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12116 12117 const bool IsLiteral = 12118 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12119 12120 llvm::APFloat Value(0.0); 12121 bool IsConstant = 12122 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12123 if (!IsConstant) { 12124 if (isObjCSignedCharBool(S, T)) { 12125 return adornObjCBoolConversionDiagWithTernaryFixit( 12126 S, E, 12127 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12128 << E->getType()); 12129 } 12130 12131 return DiagnoseImpCast(S, E, T, CContext, 12132 diag::warn_impcast_float_integer, PruneWarnings); 12133 } 12134 12135 bool isExact = false; 12136 12137 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12138 T->hasUnsignedIntegerRepresentation()); 12139 llvm::APFloat::opStatus Result = Value.convertToInteger( 12140 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12141 12142 // FIXME: Force the precision of the source value down so we don't print 12143 // digits which are usually useless (we don't really care here if we 12144 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12145 // would automatically print the shortest representation, but it's a bit 12146 // tricky to implement. 12147 SmallString<16> PrettySourceValue; 12148 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12149 precision = (precision * 59 + 195) / 196; 12150 Value.toString(PrettySourceValue, precision); 12151 12152 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12153 return adornObjCBoolConversionDiagWithTernaryFixit( 12154 S, E, 12155 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12156 << PrettySourceValue); 12157 } 12158 12159 if (Result == llvm::APFloat::opOK && isExact) { 12160 if (IsLiteral) return; 12161 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12162 PruneWarnings); 12163 } 12164 12165 // Conversion of a floating-point value to a non-bool integer where the 12166 // integral part cannot be represented by the integer type is undefined. 12167 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12168 return DiagnoseImpCast( 12169 S, E, T, CContext, 12170 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12171 : diag::warn_impcast_float_to_integer_out_of_range, 12172 PruneWarnings); 12173 12174 unsigned DiagID = 0; 12175 if (IsLiteral) { 12176 // Warn on floating point literal to integer. 12177 DiagID = diag::warn_impcast_literal_float_to_integer; 12178 } else if (IntegerValue == 0) { 12179 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12180 return DiagnoseImpCast(S, E, T, CContext, 12181 diag::warn_impcast_float_integer, PruneWarnings); 12182 } 12183 // Warn on non-zero to zero conversion. 12184 DiagID = diag::warn_impcast_float_to_integer_zero; 12185 } else { 12186 if (IntegerValue.isUnsigned()) { 12187 if (!IntegerValue.isMaxValue()) { 12188 return DiagnoseImpCast(S, E, T, CContext, 12189 diag::warn_impcast_float_integer, PruneWarnings); 12190 } 12191 } else { // IntegerValue.isSigned() 12192 if (!IntegerValue.isMaxSignedValue() && 12193 !IntegerValue.isMinSignedValue()) { 12194 return DiagnoseImpCast(S, E, T, CContext, 12195 diag::warn_impcast_float_integer, PruneWarnings); 12196 } 12197 } 12198 // Warn on evaluatable floating point expression to integer conversion. 12199 DiagID = diag::warn_impcast_float_to_integer; 12200 } 12201 12202 SmallString<16> PrettyTargetValue; 12203 if (IsBool) 12204 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12205 else 12206 IntegerValue.toString(PrettyTargetValue); 12207 12208 if (PruneWarnings) { 12209 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12210 S.PDiag(DiagID) 12211 << E->getType() << T.getUnqualifiedType() 12212 << PrettySourceValue << PrettyTargetValue 12213 << E->getSourceRange() << SourceRange(CContext)); 12214 } else { 12215 S.Diag(E->getExprLoc(), DiagID) 12216 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12217 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12218 } 12219 } 12220 12221 /// Analyze the given compound assignment for the possible losing of 12222 /// floating-point precision. 12223 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12224 assert(isa<CompoundAssignOperator>(E) && 12225 "Must be compound assignment operation"); 12226 // Recurse on the LHS and RHS in here 12227 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12228 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12229 12230 if (E->getLHS()->getType()->isAtomicType()) 12231 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12232 12233 // Now check the outermost expression 12234 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12235 const auto *RBT = cast<CompoundAssignOperator>(E) 12236 ->getComputationResultType() 12237 ->getAs<BuiltinType>(); 12238 12239 // The below checks assume source is floating point. 12240 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12241 12242 // If source is floating point but target is an integer. 12243 if (ResultBT->isInteger()) 12244 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12245 E->getExprLoc(), diag::warn_impcast_float_integer); 12246 12247 if (!ResultBT->isFloatingPoint()) 12248 return; 12249 12250 // If both source and target are floating points, warn about losing precision. 12251 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12252 QualType(ResultBT, 0), QualType(RBT, 0)); 12253 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12254 // warn about dropping FP rank. 12255 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12256 diag::warn_impcast_float_result_precision); 12257 } 12258 12259 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12260 IntRange Range) { 12261 if (!Range.Width) return "0"; 12262 12263 llvm::APSInt ValueInRange = Value; 12264 ValueInRange.setIsSigned(!Range.NonNegative); 12265 ValueInRange = ValueInRange.trunc(Range.Width); 12266 return toString(ValueInRange, 10); 12267 } 12268 12269 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12270 if (!isa<ImplicitCastExpr>(Ex)) 12271 return false; 12272 12273 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12274 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12275 const Type *Source = 12276 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12277 if (Target->isDependentType()) 12278 return false; 12279 12280 const BuiltinType *FloatCandidateBT = 12281 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12282 const Type *BoolCandidateType = ToBool ? Target : Source; 12283 12284 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12285 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12286 } 12287 12288 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12289 SourceLocation CC) { 12290 unsigned NumArgs = TheCall->getNumArgs(); 12291 for (unsigned i = 0; i < NumArgs; ++i) { 12292 Expr *CurrA = TheCall->getArg(i); 12293 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12294 continue; 12295 12296 bool IsSwapped = ((i > 0) && 12297 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12298 IsSwapped |= ((i < (NumArgs - 1)) && 12299 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12300 if (IsSwapped) { 12301 // Warn on this floating-point to bool conversion. 12302 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12303 CurrA->getType(), CC, 12304 diag::warn_impcast_floating_point_to_bool); 12305 } 12306 } 12307 } 12308 12309 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12310 SourceLocation CC) { 12311 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12312 E->getExprLoc())) 12313 return; 12314 12315 // Don't warn on functions which have return type nullptr_t. 12316 if (isa<CallExpr>(E)) 12317 return; 12318 12319 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12320 const Expr::NullPointerConstantKind NullKind = 12321 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12322 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12323 return; 12324 12325 // Return if target type is a safe conversion. 12326 if (T->isAnyPointerType() || T->isBlockPointerType() || 12327 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12328 return; 12329 12330 SourceLocation Loc = E->getSourceRange().getBegin(); 12331 12332 // Venture through the macro stacks to get to the source of macro arguments. 12333 // The new location is a better location than the complete location that was 12334 // passed in. 12335 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12336 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12337 12338 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12339 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12340 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12341 Loc, S.SourceMgr, S.getLangOpts()); 12342 if (MacroName == "NULL") 12343 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12344 } 12345 12346 // Only warn if the null and context location are in the same macro expansion. 12347 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12348 return; 12349 12350 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12351 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12352 << FixItHint::CreateReplacement(Loc, 12353 S.getFixItZeroLiteralForType(T, Loc)); 12354 } 12355 12356 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12357 ObjCArrayLiteral *ArrayLiteral); 12358 12359 static void 12360 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12361 ObjCDictionaryLiteral *DictionaryLiteral); 12362 12363 /// Check a single element within a collection literal against the 12364 /// target element type. 12365 static void checkObjCCollectionLiteralElement(Sema &S, 12366 QualType TargetElementType, 12367 Expr *Element, 12368 unsigned ElementKind) { 12369 // Skip a bitcast to 'id' or qualified 'id'. 12370 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12371 if (ICE->getCastKind() == CK_BitCast && 12372 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12373 Element = ICE->getSubExpr(); 12374 } 12375 12376 QualType ElementType = Element->getType(); 12377 ExprResult ElementResult(Element); 12378 if (ElementType->getAs<ObjCObjectPointerType>() && 12379 S.CheckSingleAssignmentConstraints(TargetElementType, 12380 ElementResult, 12381 false, false) 12382 != Sema::Compatible) { 12383 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12384 << ElementType << ElementKind << TargetElementType 12385 << Element->getSourceRange(); 12386 } 12387 12388 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12389 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12390 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12391 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12392 } 12393 12394 /// Check an Objective-C array literal being converted to the given 12395 /// target type. 12396 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12397 ObjCArrayLiteral *ArrayLiteral) { 12398 if (!S.NSArrayDecl) 12399 return; 12400 12401 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12402 if (!TargetObjCPtr) 12403 return; 12404 12405 if (TargetObjCPtr->isUnspecialized() || 12406 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12407 != S.NSArrayDecl->getCanonicalDecl()) 12408 return; 12409 12410 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12411 if (TypeArgs.size() != 1) 12412 return; 12413 12414 QualType TargetElementType = TypeArgs[0]; 12415 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12416 checkObjCCollectionLiteralElement(S, TargetElementType, 12417 ArrayLiteral->getElement(I), 12418 0); 12419 } 12420 } 12421 12422 /// Check an Objective-C dictionary literal being converted to the given 12423 /// target type. 12424 static void 12425 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12426 ObjCDictionaryLiteral *DictionaryLiteral) { 12427 if (!S.NSDictionaryDecl) 12428 return; 12429 12430 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12431 if (!TargetObjCPtr) 12432 return; 12433 12434 if (TargetObjCPtr->isUnspecialized() || 12435 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12436 != S.NSDictionaryDecl->getCanonicalDecl()) 12437 return; 12438 12439 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12440 if (TypeArgs.size() != 2) 12441 return; 12442 12443 QualType TargetKeyType = TypeArgs[0]; 12444 QualType TargetObjectType = TypeArgs[1]; 12445 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12446 auto Element = DictionaryLiteral->getKeyValueElement(I); 12447 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12448 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12449 } 12450 } 12451 12452 // Helper function to filter out cases for constant width constant conversion. 12453 // Don't warn on char array initialization or for non-decimal values. 12454 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12455 SourceLocation CC) { 12456 // If initializing from a constant, and the constant starts with '0', 12457 // then it is a binary, octal, or hexadecimal. Allow these constants 12458 // to fill all the bits, even if there is a sign change. 12459 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12460 const char FirstLiteralCharacter = 12461 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12462 if (FirstLiteralCharacter == '0') 12463 return false; 12464 } 12465 12466 // If the CC location points to a '{', and the type is char, then assume 12467 // assume it is an array initialization. 12468 if (CC.isValid() && T->isCharType()) { 12469 const char FirstContextCharacter = 12470 S.getSourceManager().getCharacterData(CC)[0]; 12471 if (FirstContextCharacter == '{') 12472 return false; 12473 } 12474 12475 return true; 12476 } 12477 12478 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12479 const auto *IL = dyn_cast<IntegerLiteral>(E); 12480 if (!IL) { 12481 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12482 if (UO->getOpcode() == UO_Minus) 12483 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12484 } 12485 } 12486 12487 return IL; 12488 } 12489 12490 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12491 E = E->IgnoreParenImpCasts(); 12492 SourceLocation ExprLoc = E->getExprLoc(); 12493 12494 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12495 BinaryOperator::Opcode Opc = BO->getOpcode(); 12496 Expr::EvalResult Result; 12497 // Do not diagnose unsigned shifts. 12498 if (Opc == BO_Shl) { 12499 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12500 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12501 if (LHS && LHS->getValue() == 0) 12502 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12503 else if (!E->isValueDependent() && LHS && RHS && 12504 RHS->getValue().isNonNegative() && 12505 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12506 S.Diag(ExprLoc, diag::warn_left_shift_always) 12507 << (Result.Val.getInt() != 0); 12508 else if (E->getType()->isSignedIntegerType()) 12509 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12510 } 12511 } 12512 12513 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12514 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12515 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12516 if (!LHS || !RHS) 12517 return; 12518 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12519 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12520 // Do not diagnose common idioms. 12521 return; 12522 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12523 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12524 } 12525 } 12526 12527 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12528 SourceLocation CC, 12529 bool *ICContext = nullptr, 12530 bool IsListInit = false) { 12531 if (E->isTypeDependent() || E->isValueDependent()) return; 12532 12533 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12534 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12535 if (Source == Target) return; 12536 if (Target->isDependentType()) return; 12537 12538 // If the conversion context location is invalid don't complain. We also 12539 // don't want to emit a warning if the issue occurs from the expansion of 12540 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12541 // delay this check as long as possible. Once we detect we are in that 12542 // scenario, we just return. 12543 if (CC.isInvalid()) 12544 return; 12545 12546 if (Source->isAtomicType()) 12547 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12548 12549 // Diagnose implicit casts to bool. 12550 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12551 if (isa<StringLiteral>(E)) 12552 // Warn on string literal to bool. Checks for string literals in logical 12553 // and expressions, for instance, assert(0 && "error here"), are 12554 // prevented by a check in AnalyzeImplicitConversions(). 12555 return DiagnoseImpCast(S, E, T, CC, 12556 diag::warn_impcast_string_literal_to_bool); 12557 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12558 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12559 // This covers the literal expressions that evaluate to Objective-C 12560 // objects. 12561 return DiagnoseImpCast(S, E, T, CC, 12562 diag::warn_impcast_objective_c_literal_to_bool); 12563 } 12564 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12565 // Warn on pointer to bool conversion that is always true. 12566 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12567 SourceRange(CC)); 12568 } 12569 } 12570 12571 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12572 // is a typedef for signed char (macOS), then that constant value has to be 1 12573 // or 0. 12574 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12575 Expr::EvalResult Result; 12576 if (E->EvaluateAsInt(Result, S.getASTContext(), 12577 Expr::SE_AllowSideEffects)) { 12578 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12579 adornObjCBoolConversionDiagWithTernaryFixit( 12580 S, E, 12581 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12582 << toString(Result.Val.getInt(), 10)); 12583 } 12584 return; 12585 } 12586 } 12587 12588 // Check implicit casts from Objective-C collection literals to specialized 12589 // collection types, e.g., NSArray<NSString *> *. 12590 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12591 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12592 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12593 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12594 12595 // Strip vector types. 12596 if (isa<VectorType>(Source)) { 12597 if (Target->isVLSTBuiltinType() && 12598 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12599 QualType(Source, 0)) || 12600 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12601 QualType(Source, 0)))) 12602 return; 12603 12604 if (!isa<VectorType>(Target)) { 12605 if (S.SourceMgr.isInSystemMacro(CC)) 12606 return; 12607 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12608 } 12609 12610 // If the vector cast is cast between two vectors of the same size, it is 12611 // a bitcast, not a conversion. 12612 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12613 return; 12614 12615 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12616 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12617 } 12618 if (auto VecTy = dyn_cast<VectorType>(Target)) 12619 Target = VecTy->getElementType().getTypePtr(); 12620 12621 // Strip complex types. 12622 if (isa<ComplexType>(Source)) { 12623 if (!isa<ComplexType>(Target)) { 12624 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12625 return; 12626 12627 return DiagnoseImpCast(S, E, T, CC, 12628 S.getLangOpts().CPlusPlus 12629 ? diag::err_impcast_complex_scalar 12630 : diag::warn_impcast_complex_scalar); 12631 } 12632 12633 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12634 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12635 } 12636 12637 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12638 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12639 12640 // If the source is floating point... 12641 if (SourceBT && SourceBT->isFloatingPoint()) { 12642 // ...and the target is floating point... 12643 if (TargetBT && TargetBT->isFloatingPoint()) { 12644 // ...then warn if we're dropping FP rank. 12645 12646 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12647 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12648 if (Order > 0) { 12649 // Don't warn about float constants that are precisely 12650 // representable in the target type. 12651 Expr::EvalResult result; 12652 if (E->EvaluateAsRValue(result, S.Context)) { 12653 // Value might be a float, a float vector, or a float complex. 12654 if (IsSameFloatAfterCast(result.Val, 12655 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12656 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12657 return; 12658 } 12659 12660 if (S.SourceMgr.isInSystemMacro(CC)) 12661 return; 12662 12663 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12664 } 12665 // ... or possibly if we're increasing rank, too 12666 else if (Order < 0) { 12667 if (S.SourceMgr.isInSystemMacro(CC)) 12668 return; 12669 12670 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12671 } 12672 return; 12673 } 12674 12675 // If the target is integral, always warn. 12676 if (TargetBT && TargetBT->isInteger()) { 12677 if (S.SourceMgr.isInSystemMacro(CC)) 12678 return; 12679 12680 DiagnoseFloatingImpCast(S, E, T, CC); 12681 } 12682 12683 // Detect the case where a call result is converted from floating-point to 12684 // to bool, and the final argument to the call is converted from bool, to 12685 // discover this typo: 12686 // 12687 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12688 // 12689 // FIXME: This is an incredibly special case; is there some more general 12690 // way to detect this class of misplaced-parentheses bug? 12691 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12692 // Check last argument of function call to see if it is an 12693 // implicit cast from a type matching the type the result 12694 // is being cast to. 12695 CallExpr *CEx = cast<CallExpr>(E); 12696 if (unsigned NumArgs = CEx->getNumArgs()) { 12697 Expr *LastA = CEx->getArg(NumArgs - 1); 12698 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12699 if (isa<ImplicitCastExpr>(LastA) && 12700 InnerE->getType()->isBooleanType()) { 12701 // Warn on this floating-point to bool conversion 12702 DiagnoseImpCast(S, E, T, CC, 12703 diag::warn_impcast_floating_point_to_bool); 12704 } 12705 } 12706 } 12707 return; 12708 } 12709 12710 // Valid casts involving fixed point types should be accounted for here. 12711 if (Source->isFixedPointType()) { 12712 if (Target->isUnsaturatedFixedPointType()) { 12713 Expr::EvalResult Result; 12714 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12715 S.isConstantEvaluated())) { 12716 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12717 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12718 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12719 if (Value > MaxVal || Value < MinVal) { 12720 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12721 S.PDiag(diag::warn_impcast_fixed_point_range) 12722 << Value.toString() << T 12723 << E->getSourceRange() 12724 << clang::SourceRange(CC)); 12725 return; 12726 } 12727 } 12728 } else if (Target->isIntegerType()) { 12729 Expr::EvalResult Result; 12730 if (!S.isConstantEvaluated() && 12731 E->EvaluateAsFixedPoint(Result, S.Context, 12732 Expr::SE_AllowSideEffects)) { 12733 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12734 12735 bool Overflowed; 12736 llvm::APSInt IntResult = FXResult.convertToInt( 12737 S.Context.getIntWidth(T), 12738 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12739 12740 if (Overflowed) { 12741 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12742 S.PDiag(diag::warn_impcast_fixed_point_range) 12743 << FXResult.toString() << T 12744 << E->getSourceRange() 12745 << clang::SourceRange(CC)); 12746 return; 12747 } 12748 } 12749 } 12750 } else if (Target->isUnsaturatedFixedPointType()) { 12751 if (Source->isIntegerType()) { 12752 Expr::EvalResult Result; 12753 if (!S.isConstantEvaluated() && 12754 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12755 llvm::APSInt Value = Result.Val.getInt(); 12756 12757 bool Overflowed; 12758 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12759 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12760 12761 if (Overflowed) { 12762 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12763 S.PDiag(diag::warn_impcast_fixed_point_range) 12764 << toString(Value, /*Radix=*/10) << T 12765 << E->getSourceRange() 12766 << clang::SourceRange(CC)); 12767 return; 12768 } 12769 } 12770 } 12771 } 12772 12773 // If we are casting an integer type to a floating point type without 12774 // initialization-list syntax, we might lose accuracy if the floating 12775 // point type has a narrower significand than the integer type. 12776 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12777 TargetBT->isFloatingType() && !IsListInit) { 12778 // Determine the number of precision bits in the source integer type. 12779 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12780 /*Approximate*/ true); 12781 unsigned int SourcePrecision = SourceRange.Width; 12782 12783 // Determine the number of precision bits in the 12784 // target floating point type. 12785 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12786 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12787 12788 if (SourcePrecision > 0 && TargetPrecision > 0 && 12789 SourcePrecision > TargetPrecision) { 12790 12791 if (Optional<llvm::APSInt> SourceInt = 12792 E->getIntegerConstantExpr(S.Context)) { 12793 // If the source integer is a constant, convert it to the target 12794 // floating point type. Issue a warning if the value changes 12795 // during the whole conversion. 12796 llvm::APFloat TargetFloatValue( 12797 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12798 llvm::APFloat::opStatus ConversionStatus = 12799 TargetFloatValue.convertFromAPInt( 12800 *SourceInt, SourceBT->isSignedInteger(), 12801 llvm::APFloat::rmNearestTiesToEven); 12802 12803 if (ConversionStatus != llvm::APFloat::opOK) { 12804 SmallString<32> PrettySourceValue; 12805 SourceInt->toString(PrettySourceValue, 10); 12806 SmallString<32> PrettyTargetValue; 12807 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12808 12809 S.DiagRuntimeBehavior( 12810 E->getExprLoc(), E, 12811 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12812 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12813 << E->getSourceRange() << clang::SourceRange(CC)); 12814 } 12815 } else { 12816 // Otherwise, the implicit conversion may lose precision. 12817 DiagnoseImpCast(S, E, T, CC, 12818 diag::warn_impcast_integer_float_precision); 12819 } 12820 } 12821 } 12822 12823 DiagnoseNullConversion(S, E, T, CC); 12824 12825 S.DiscardMisalignedMemberAddress(Target, E); 12826 12827 if (Target->isBooleanType()) 12828 DiagnoseIntInBoolContext(S, E); 12829 12830 if (!Source->isIntegerType() || !Target->isIntegerType()) 12831 return; 12832 12833 // TODO: remove this early return once the false positives for constant->bool 12834 // in templates, macros, etc, are reduced or removed. 12835 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12836 return; 12837 12838 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12839 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12840 return adornObjCBoolConversionDiagWithTernaryFixit( 12841 S, E, 12842 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12843 << E->getType()); 12844 } 12845 12846 IntRange SourceTypeRange = 12847 IntRange::forTargetOfCanonicalType(S.Context, Source); 12848 IntRange LikelySourceRange = 12849 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12850 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12851 12852 if (LikelySourceRange.Width > TargetRange.Width) { 12853 // If the source is a constant, use a default-on diagnostic. 12854 // TODO: this should happen for bitfield stores, too. 12855 Expr::EvalResult Result; 12856 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12857 S.isConstantEvaluated())) { 12858 llvm::APSInt Value(32); 12859 Value = Result.Val.getInt(); 12860 12861 if (S.SourceMgr.isInSystemMacro(CC)) 12862 return; 12863 12864 std::string PrettySourceValue = toString(Value, 10); 12865 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12866 12867 S.DiagRuntimeBehavior( 12868 E->getExprLoc(), E, 12869 S.PDiag(diag::warn_impcast_integer_precision_constant) 12870 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12871 << E->getSourceRange() << SourceRange(CC)); 12872 return; 12873 } 12874 12875 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12876 if (S.SourceMgr.isInSystemMacro(CC)) 12877 return; 12878 12879 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12880 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12881 /* pruneControlFlow */ true); 12882 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12883 } 12884 12885 if (TargetRange.Width > SourceTypeRange.Width) { 12886 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12887 if (UO->getOpcode() == UO_Minus) 12888 if (Source->isUnsignedIntegerType()) { 12889 if (Target->isUnsignedIntegerType()) 12890 return DiagnoseImpCast(S, E, T, CC, 12891 diag::warn_impcast_high_order_zero_bits); 12892 if (Target->isSignedIntegerType()) 12893 return DiagnoseImpCast(S, E, T, CC, 12894 diag::warn_impcast_nonnegative_result); 12895 } 12896 } 12897 12898 if (TargetRange.Width == LikelySourceRange.Width && 12899 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12900 Source->isSignedIntegerType()) { 12901 // Warn when doing a signed to signed conversion, warn if the positive 12902 // source value is exactly the width of the target type, which will 12903 // cause a negative value to be stored. 12904 12905 Expr::EvalResult Result; 12906 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12907 !S.SourceMgr.isInSystemMacro(CC)) { 12908 llvm::APSInt Value = Result.Val.getInt(); 12909 if (isSameWidthConstantConversion(S, E, T, CC)) { 12910 std::string PrettySourceValue = toString(Value, 10); 12911 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12912 12913 S.DiagRuntimeBehavior( 12914 E->getExprLoc(), E, 12915 S.PDiag(diag::warn_impcast_integer_precision_constant) 12916 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12917 << E->getSourceRange() << SourceRange(CC)); 12918 return; 12919 } 12920 } 12921 12922 // Fall through for non-constants to give a sign conversion warning. 12923 } 12924 12925 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12926 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12927 LikelySourceRange.Width == TargetRange.Width)) { 12928 if (S.SourceMgr.isInSystemMacro(CC)) 12929 return; 12930 12931 unsigned DiagID = diag::warn_impcast_integer_sign; 12932 12933 // Traditionally, gcc has warned about this under -Wsign-compare. 12934 // We also want to warn about it in -Wconversion. 12935 // So if -Wconversion is off, use a completely identical diagnostic 12936 // in the sign-compare group. 12937 // The conditional-checking code will 12938 if (ICContext) { 12939 DiagID = diag::warn_impcast_integer_sign_conditional; 12940 *ICContext = true; 12941 } 12942 12943 return DiagnoseImpCast(S, E, T, CC, DiagID); 12944 } 12945 12946 // Diagnose conversions between different enumeration types. 12947 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12948 // type, to give us better diagnostics. 12949 QualType SourceType = E->getType(); 12950 if (!S.getLangOpts().CPlusPlus) { 12951 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12952 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12953 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12954 SourceType = S.Context.getTypeDeclType(Enum); 12955 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12956 } 12957 } 12958 12959 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12960 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12961 if (SourceEnum->getDecl()->hasNameForLinkage() && 12962 TargetEnum->getDecl()->hasNameForLinkage() && 12963 SourceEnum != TargetEnum) { 12964 if (S.SourceMgr.isInSystemMacro(CC)) 12965 return; 12966 12967 return DiagnoseImpCast(S, E, SourceType, T, CC, 12968 diag::warn_impcast_different_enum_types); 12969 } 12970 } 12971 12972 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12973 SourceLocation CC, QualType T); 12974 12975 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12976 SourceLocation CC, bool &ICContext) { 12977 E = E->IgnoreParenImpCasts(); 12978 12979 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12980 return CheckConditionalOperator(S, CO, CC, T); 12981 12982 AnalyzeImplicitConversions(S, E, CC); 12983 if (E->getType() != T) 12984 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12985 } 12986 12987 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12988 SourceLocation CC, QualType T) { 12989 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12990 12991 Expr *TrueExpr = E->getTrueExpr(); 12992 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12993 TrueExpr = BCO->getCommon(); 12994 12995 bool Suspicious = false; 12996 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12997 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12998 12999 if (T->isBooleanType()) 13000 DiagnoseIntInBoolContext(S, E); 13001 13002 // If -Wconversion would have warned about either of the candidates 13003 // for a signedness conversion to the context type... 13004 if (!Suspicious) return; 13005 13006 // ...but it's currently ignored... 13007 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13008 return; 13009 13010 // ...then check whether it would have warned about either of the 13011 // candidates for a signedness conversion to the condition type. 13012 if (E->getType() == T) return; 13013 13014 Suspicious = false; 13015 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13016 E->getType(), CC, &Suspicious); 13017 if (!Suspicious) 13018 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13019 E->getType(), CC, &Suspicious); 13020 } 13021 13022 /// Check conversion of given expression to boolean. 13023 /// Input argument E is a logical expression. 13024 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13025 if (S.getLangOpts().Bool) 13026 return; 13027 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13028 return; 13029 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13030 } 13031 13032 namespace { 13033 struct AnalyzeImplicitConversionsWorkItem { 13034 Expr *E; 13035 SourceLocation CC; 13036 bool IsListInit; 13037 }; 13038 } 13039 13040 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13041 /// that should be visited are added to WorkList. 13042 static void AnalyzeImplicitConversions( 13043 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13044 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13045 Expr *OrigE = Item.E; 13046 SourceLocation CC = Item.CC; 13047 13048 QualType T = OrigE->getType(); 13049 Expr *E = OrigE->IgnoreParenImpCasts(); 13050 13051 // Propagate whether we are in a C++ list initialization expression. 13052 // If so, we do not issue warnings for implicit int-float conversion 13053 // precision loss, because C++11 narrowing already handles it. 13054 bool IsListInit = Item.IsListInit || 13055 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13056 13057 if (E->isTypeDependent() || E->isValueDependent()) 13058 return; 13059 13060 Expr *SourceExpr = E; 13061 // Examine, but don't traverse into the source expression of an 13062 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13063 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13064 // evaluate it in the context of checking the specific conversion to T though. 13065 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13066 if (auto *Src = OVE->getSourceExpr()) 13067 SourceExpr = Src; 13068 13069 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13070 if (UO->getOpcode() == UO_Not && 13071 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13072 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13073 << OrigE->getSourceRange() << T->isBooleanType() 13074 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13075 13076 // For conditional operators, we analyze the arguments as if they 13077 // were being fed directly into the output. 13078 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13079 CheckConditionalOperator(S, CO, CC, T); 13080 return; 13081 } 13082 13083 // Check implicit argument conversions for function calls. 13084 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13085 CheckImplicitArgumentConversions(S, Call, CC); 13086 13087 // Go ahead and check any implicit conversions we might have skipped. 13088 // The non-canonical typecheck is just an optimization; 13089 // CheckImplicitConversion will filter out dead implicit conversions. 13090 if (SourceExpr->getType() != T) 13091 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13092 13093 // Now continue drilling into this expression. 13094 13095 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13096 // The bound subexpressions in a PseudoObjectExpr are not reachable 13097 // as transitive children. 13098 // FIXME: Use a more uniform representation for this. 13099 for (auto *SE : POE->semantics()) 13100 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13101 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13102 } 13103 13104 // Skip past explicit casts. 13105 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13106 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13107 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13108 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13109 WorkList.push_back({E, CC, IsListInit}); 13110 return; 13111 } 13112 13113 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13114 // Do a somewhat different check with comparison operators. 13115 if (BO->isComparisonOp()) 13116 return AnalyzeComparison(S, BO); 13117 13118 // And with simple assignments. 13119 if (BO->getOpcode() == BO_Assign) 13120 return AnalyzeAssignment(S, BO); 13121 // And with compound assignments. 13122 if (BO->isAssignmentOp()) 13123 return AnalyzeCompoundAssignment(S, BO); 13124 } 13125 13126 // These break the otherwise-useful invariant below. Fortunately, 13127 // we don't really need to recurse into them, because any internal 13128 // expressions should have been analyzed already when they were 13129 // built into statements. 13130 if (isa<StmtExpr>(E)) return; 13131 13132 // Don't descend into unevaluated contexts. 13133 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13134 13135 // Now just recurse over the expression's children. 13136 CC = E->getExprLoc(); 13137 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13138 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13139 for (Stmt *SubStmt : E->children()) { 13140 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13141 if (!ChildExpr) 13142 continue; 13143 13144 if (IsLogicalAndOperator && 13145 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13146 // Ignore checking string literals that are in logical and operators. 13147 // This is a common pattern for asserts. 13148 continue; 13149 WorkList.push_back({ChildExpr, CC, IsListInit}); 13150 } 13151 13152 if (BO && BO->isLogicalOp()) { 13153 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13154 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13155 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13156 13157 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13158 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13159 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13160 } 13161 13162 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13163 if (U->getOpcode() == UO_LNot) { 13164 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13165 } else if (U->getOpcode() != UO_AddrOf) { 13166 if (U->getSubExpr()->getType()->isAtomicType()) 13167 S.Diag(U->getSubExpr()->getBeginLoc(), 13168 diag::warn_atomic_implicit_seq_cst); 13169 } 13170 } 13171 } 13172 13173 /// AnalyzeImplicitConversions - Find and report any interesting 13174 /// implicit conversions in the given expression. There are a couple 13175 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13176 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13177 bool IsListInit/*= false*/) { 13178 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13179 WorkList.push_back({OrigE, CC, IsListInit}); 13180 while (!WorkList.empty()) 13181 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13182 } 13183 13184 /// Diagnose integer type and any valid implicit conversion to it. 13185 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13186 // Taking into account implicit conversions, 13187 // allow any integer. 13188 if (!E->getType()->isIntegerType()) { 13189 S.Diag(E->getBeginLoc(), 13190 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13191 return true; 13192 } 13193 // Potentially emit standard warnings for implicit conversions if enabled 13194 // using -Wconversion. 13195 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13196 return false; 13197 } 13198 13199 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13200 // Returns true when emitting a warning about taking the address of a reference. 13201 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13202 const PartialDiagnostic &PD) { 13203 E = E->IgnoreParenImpCasts(); 13204 13205 const FunctionDecl *FD = nullptr; 13206 13207 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13208 if (!DRE->getDecl()->getType()->isReferenceType()) 13209 return false; 13210 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13211 if (!M->getMemberDecl()->getType()->isReferenceType()) 13212 return false; 13213 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13214 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13215 return false; 13216 FD = Call->getDirectCallee(); 13217 } else { 13218 return false; 13219 } 13220 13221 SemaRef.Diag(E->getExprLoc(), PD); 13222 13223 // If possible, point to location of function. 13224 if (FD) { 13225 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13226 } 13227 13228 return true; 13229 } 13230 13231 // Returns true if the SourceLocation is expanded from any macro body. 13232 // Returns false if the SourceLocation is invalid, is from not in a macro 13233 // expansion, or is from expanded from a top-level macro argument. 13234 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13235 if (Loc.isInvalid()) 13236 return false; 13237 13238 while (Loc.isMacroID()) { 13239 if (SM.isMacroBodyExpansion(Loc)) 13240 return true; 13241 Loc = SM.getImmediateMacroCallerLoc(Loc); 13242 } 13243 13244 return false; 13245 } 13246 13247 /// Diagnose pointers that are always non-null. 13248 /// \param E the expression containing the pointer 13249 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13250 /// compared to a null pointer 13251 /// \param IsEqual True when the comparison is equal to a null pointer 13252 /// \param Range Extra SourceRange to highlight in the diagnostic 13253 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13254 Expr::NullPointerConstantKind NullKind, 13255 bool IsEqual, SourceRange Range) { 13256 if (!E) 13257 return; 13258 13259 // Don't warn inside macros. 13260 if (E->getExprLoc().isMacroID()) { 13261 const SourceManager &SM = getSourceManager(); 13262 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13263 IsInAnyMacroBody(SM, Range.getBegin())) 13264 return; 13265 } 13266 E = E->IgnoreImpCasts(); 13267 13268 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13269 13270 if (isa<CXXThisExpr>(E)) { 13271 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13272 : diag::warn_this_bool_conversion; 13273 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13274 return; 13275 } 13276 13277 bool IsAddressOf = false; 13278 13279 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13280 if (UO->getOpcode() != UO_AddrOf) 13281 return; 13282 IsAddressOf = true; 13283 E = UO->getSubExpr(); 13284 } 13285 13286 if (IsAddressOf) { 13287 unsigned DiagID = IsCompare 13288 ? diag::warn_address_of_reference_null_compare 13289 : diag::warn_address_of_reference_bool_conversion; 13290 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13291 << IsEqual; 13292 if (CheckForReference(*this, E, PD)) { 13293 return; 13294 } 13295 } 13296 13297 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13298 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13299 std::string Str; 13300 llvm::raw_string_ostream S(Str); 13301 E->printPretty(S, nullptr, getPrintingPolicy()); 13302 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13303 : diag::warn_cast_nonnull_to_bool; 13304 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13305 << E->getSourceRange() << Range << IsEqual; 13306 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13307 }; 13308 13309 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13310 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13311 if (auto *Callee = Call->getDirectCallee()) { 13312 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13313 ComplainAboutNonnullParamOrCall(A); 13314 return; 13315 } 13316 } 13317 } 13318 13319 // Expect to find a single Decl. Skip anything more complicated. 13320 ValueDecl *D = nullptr; 13321 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13322 D = R->getDecl(); 13323 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13324 D = M->getMemberDecl(); 13325 } 13326 13327 // Weak Decls can be null. 13328 if (!D || D->isWeak()) 13329 return; 13330 13331 // Check for parameter decl with nonnull attribute 13332 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13333 if (getCurFunction() && 13334 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13335 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13336 ComplainAboutNonnullParamOrCall(A); 13337 return; 13338 } 13339 13340 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13341 // Skip function template not specialized yet. 13342 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13343 return; 13344 auto ParamIter = llvm::find(FD->parameters(), PV); 13345 assert(ParamIter != FD->param_end()); 13346 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13347 13348 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13349 if (!NonNull->args_size()) { 13350 ComplainAboutNonnullParamOrCall(NonNull); 13351 return; 13352 } 13353 13354 for (const ParamIdx &ArgNo : NonNull->args()) { 13355 if (ArgNo.getASTIndex() == ParamNo) { 13356 ComplainAboutNonnullParamOrCall(NonNull); 13357 return; 13358 } 13359 } 13360 } 13361 } 13362 } 13363 } 13364 13365 QualType T = D->getType(); 13366 const bool IsArray = T->isArrayType(); 13367 const bool IsFunction = T->isFunctionType(); 13368 13369 // Address of function is used to silence the function warning. 13370 if (IsAddressOf && IsFunction) { 13371 return; 13372 } 13373 13374 // Found nothing. 13375 if (!IsAddressOf && !IsFunction && !IsArray) 13376 return; 13377 13378 // Pretty print the expression for the diagnostic. 13379 std::string Str; 13380 llvm::raw_string_ostream S(Str); 13381 E->printPretty(S, nullptr, getPrintingPolicy()); 13382 13383 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13384 : diag::warn_impcast_pointer_to_bool; 13385 enum { 13386 AddressOf, 13387 FunctionPointer, 13388 ArrayPointer 13389 } DiagType; 13390 if (IsAddressOf) 13391 DiagType = AddressOf; 13392 else if (IsFunction) 13393 DiagType = FunctionPointer; 13394 else if (IsArray) 13395 DiagType = ArrayPointer; 13396 else 13397 llvm_unreachable("Could not determine diagnostic."); 13398 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13399 << Range << IsEqual; 13400 13401 if (!IsFunction) 13402 return; 13403 13404 // Suggest '&' to silence the function warning. 13405 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13406 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13407 13408 // Check to see if '()' fixit should be emitted. 13409 QualType ReturnType; 13410 UnresolvedSet<4> NonTemplateOverloads; 13411 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13412 if (ReturnType.isNull()) 13413 return; 13414 13415 if (IsCompare) { 13416 // There are two cases here. If there is null constant, the only suggest 13417 // for a pointer return type. If the null is 0, then suggest if the return 13418 // type is a pointer or an integer type. 13419 if (!ReturnType->isPointerType()) { 13420 if (NullKind == Expr::NPCK_ZeroExpression || 13421 NullKind == Expr::NPCK_ZeroLiteral) { 13422 if (!ReturnType->isIntegerType()) 13423 return; 13424 } else { 13425 return; 13426 } 13427 } 13428 } else { // !IsCompare 13429 // For function to bool, only suggest if the function pointer has bool 13430 // return type. 13431 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13432 return; 13433 } 13434 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13435 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13436 } 13437 13438 /// Diagnoses "dangerous" implicit conversions within the given 13439 /// expression (which is a full expression). Implements -Wconversion 13440 /// and -Wsign-compare. 13441 /// 13442 /// \param CC the "context" location of the implicit conversion, i.e. 13443 /// the most location of the syntactic entity requiring the implicit 13444 /// conversion 13445 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13446 // Don't diagnose in unevaluated contexts. 13447 if (isUnevaluatedContext()) 13448 return; 13449 13450 // Don't diagnose for value- or type-dependent expressions. 13451 if (E->isTypeDependent() || E->isValueDependent()) 13452 return; 13453 13454 // Check for array bounds violations in cases where the check isn't triggered 13455 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13456 // ArraySubscriptExpr is on the RHS of a variable initialization. 13457 CheckArrayAccess(E); 13458 13459 // This is not the right CC for (e.g.) a variable initialization. 13460 AnalyzeImplicitConversions(*this, E, CC); 13461 } 13462 13463 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13464 /// Input argument E is a logical expression. 13465 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13466 ::CheckBoolLikeConversion(*this, E, CC); 13467 } 13468 13469 /// Diagnose when expression is an integer constant expression and its evaluation 13470 /// results in integer overflow 13471 void Sema::CheckForIntOverflow (Expr *E) { 13472 // Use a work list to deal with nested struct initializers. 13473 SmallVector<Expr *, 2> Exprs(1, E); 13474 13475 do { 13476 Expr *OriginalE = Exprs.pop_back_val(); 13477 Expr *E = OriginalE->IgnoreParenCasts(); 13478 13479 if (isa<BinaryOperator>(E)) { 13480 E->EvaluateForOverflow(Context); 13481 continue; 13482 } 13483 13484 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13485 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13486 else if (isa<ObjCBoxedExpr>(OriginalE)) 13487 E->EvaluateForOverflow(Context); 13488 else if (auto Call = dyn_cast<CallExpr>(E)) 13489 Exprs.append(Call->arg_begin(), Call->arg_end()); 13490 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13491 Exprs.append(Message->arg_begin(), Message->arg_end()); 13492 } while (!Exprs.empty()); 13493 } 13494 13495 namespace { 13496 13497 /// Visitor for expressions which looks for unsequenced operations on the 13498 /// same object. 13499 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13500 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13501 13502 /// A tree of sequenced regions within an expression. Two regions are 13503 /// unsequenced if one is an ancestor or a descendent of the other. When we 13504 /// finish processing an expression with sequencing, such as a comma 13505 /// expression, we fold its tree nodes into its parent, since they are 13506 /// unsequenced with respect to nodes we will visit later. 13507 class SequenceTree { 13508 struct Value { 13509 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13510 unsigned Parent : 31; 13511 unsigned Merged : 1; 13512 }; 13513 SmallVector<Value, 8> Values; 13514 13515 public: 13516 /// A region within an expression which may be sequenced with respect 13517 /// to some other region. 13518 class Seq { 13519 friend class SequenceTree; 13520 13521 unsigned Index; 13522 13523 explicit Seq(unsigned N) : Index(N) {} 13524 13525 public: 13526 Seq() : Index(0) {} 13527 }; 13528 13529 SequenceTree() { Values.push_back(Value(0)); } 13530 Seq root() const { return Seq(0); } 13531 13532 /// Create a new sequence of operations, which is an unsequenced 13533 /// subset of \p Parent. This sequence of operations is sequenced with 13534 /// respect to other children of \p Parent. 13535 Seq allocate(Seq Parent) { 13536 Values.push_back(Value(Parent.Index)); 13537 return Seq(Values.size() - 1); 13538 } 13539 13540 /// Merge a sequence of operations into its parent. 13541 void merge(Seq S) { 13542 Values[S.Index].Merged = true; 13543 } 13544 13545 /// Determine whether two operations are unsequenced. This operation 13546 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13547 /// should have been merged into its parent as appropriate. 13548 bool isUnsequenced(Seq Cur, Seq Old) { 13549 unsigned C = representative(Cur.Index); 13550 unsigned Target = representative(Old.Index); 13551 while (C >= Target) { 13552 if (C == Target) 13553 return true; 13554 C = Values[C].Parent; 13555 } 13556 return false; 13557 } 13558 13559 private: 13560 /// Pick a representative for a sequence. 13561 unsigned representative(unsigned K) { 13562 if (Values[K].Merged) 13563 // Perform path compression as we go. 13564 return Values[K].Parent = representative(Values[K].Parent); 13565 return K; 13566 } 13567 }; 13568 13569 /// An object for which we can track unsequenced uses. 13570 using Object = const NamedDecl *; 13571 13572 /// Different flavors of object usage which we track. We only track the 13573 /// least-sequenced usage of each kind. 13574 enum UsageKind { 13575 /// A read of an object. Multiple unsequenced reads are OK. 13576 UK_Use, 13577 13578 /// A modification of an object which is sequenced before the value 13579 /// computation of the expression, such as ++n in C++. 13580 UK_ModAsValue, 13581 13582 /// A modification of an object which is not sequenced before the value 13583 /// computation of the expression, such as n++. 13584 UK_ModAsSideEffect, 13585 13586 UK_Count = UK_ModAsSideEffect + 1 13587 }; 13588 13589 /// Bundle together a sequencing region and the expression corresponding 13590 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13591 struct Usage { 13592 const Expr *UsageExpr; 13593 SequenceTree::Seq Seq; 13594 13595 Usage() : UsageExpr(nullptr), Seq() {} 13596 }; 13597 13598 struct UsageInfo { 13599 Usage Uses[UK_Count]; 13600 13601 /// Have we issued a diagnostic for this object already? 13602 bool Diagnosed; 13603 13604 UsageInfo() : Uses(), Diagnosed(false) {} 13605 }; 13606 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13607 13608 Sema &SemaRef; 13609 13610 /// Sequenced regions within the expression. 13611 SequenceTree Tree; 13612 13613 /// Declaration modifications and references which we have seen. 13614 UsageInfoMap UsageMap; 13615 13616 /// The region we are currently within. 13617 SequenceTree::Seq Region; 13618 13619 /// Filled in with declarations which were modified as a side-effect 13620 /// (that is, post-increment operations). 13621 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13622 13623 /// Expressions to check later. We defer checking these to reduce 13624 /// stack usage. 13625 SmallVectorImpl<const Expr *> &WorkList; 13626 13627 /// RAII object wrapping the visitation of a sequenced subexpression of an 13628 /// expression. At the end of this process, the side-effects of the evaluation 13629 /// become sequenced with respect to the value computation of the result, so 13630 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13631 /// UK_ModAsValue. 13632 struct SequencedSubexpression { 13633 SequencedSubexpression(SequenceChecker &Self) 13634 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13635 Self.ModAsSideEffect = &ModAsSideEffect; 13636 } 13637 13638 ~SequencedSubexpression() { 13639 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13640 // Add a new usage with usage kind UK_ModAsValue, and then restore 13641 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13642 // the previous one was empty). 13643 UsageInfo &UI = Self.UsageMap[M.first]; 13644 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13645 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13646 SideEffectUsage = M.second; 13647 } 13648 Self.ModAsSideEffect = OldModAsSideEffect; 13649 } 13650 13651 SequenceChecker &Self; 13652 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13653 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13654 }; 13655 13656 /// RAII object wrapping the visitation of a subexpression which we might 13657 /// choose to evaluate as a constant. If any subexpression is evaluated and 13658 /// found to be non-constant, this allows us to suppress the evaluation of 13659 /// the outer expression. 13660 class EvaluationTracker { 13661 public: 13662 EvaluationTracker(SequenceChecker &Self) 13663 : Self(Self), Prev(Self.EvalTracker) { 13664 Self.EvalTracker = this; 13665 } 13666 13667 ~EvaluationTracker() { 13668 Self.EvalTracker = Prev; 13669 if (Prev) 13670 Prev->EvalOK &= EvalOK; 13671 } 13672 13673 bool evaluate(const Expr *E, bool &Result) { 13674 if (!EvalOK || E->isValueDependent()) 13675 return false; 13676 EvalOK = E->EvaluateAsBooleanCondition( 13677 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13678 return EvalOK; 13679 } 13680 13681 private: 13682 SequenceChecker &Self; 13683 EvaluationTracker *Prev; 13684 bool EvalOK = true; 13685 } *EvalTracker = nullptr; 13686 13687 /// Find the object which is produced by the specified expression, 13688 /// if any. 13689 Object getObject(const Expr *E, bool Mod) const { 13690 E = E->IgnoreParenCasts(); 13691 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13692 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13693 return getObject(UO->getSubExpr(), Mod); 13694 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13695 if (BO->getOpcode() == BO_Comma) 13696 return getObject(BO->getRHS(), Mod); 13697 if (Mod && BO->isAssignmentOp()) 13698 return getObject(BO->getLHS(), Mod); 13699 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13700 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13701 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13702 return ME->getMemberDecl(); 13703 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13704 // FIXME: If this is a reference, map through to its value. 13705 return DRE->getDecl(); 13706 return nullptr; 13707 } 13708 13709 /// Note that an object \p O was modified or used by an expression 13710 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13711 /// the object \p O as obtained via the \p UsageMap. 13712 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13713 // Get the old usage for the given object and usage kind. 13714 Usage &U = UI.Uses[UK]; 13715 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13716 // If we have a modification as side effect and are in a sequenced 13717 // subexpression, save the old Usage so that we can restore it later 13718 // in SequencedSubexpression::~SequencedSubexpression. 13719 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13720 ModAsSideEffect->push_back(std::make_pair(O, U)); 13721 // Then record the new usage with the current sequencing region. 13722 U.UsageExpr = UsageExpr; 13723 U.Seq = Region; 13724 } 13725 } 13726 13727 /// Check whether a modification or use of an object \p O in an expression 13728 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13729 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13730 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13731 /// usage and false we are checking for a mod-use unsequenced usage. 13732 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13733 UsageKind OtherKind, bool IsModMod) { 13734 if (UI.Diagnosed) 13735 return; 13736 13737 const Usage &U = UI.Uses[OtherKind]; 13738 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13739 return; 13740 13741 const Expr *Mod = U.UsageExpr; 13742 const Expr *ModOrUse = UsageExpr; 13743 if (OtherKind == UK_Use) 13744 std::swap(Mod, ModOrUse); 13745 13746 SemaRef.DiagRuntimeBehavior( 13747 Mod->getExprLoc(), {Mod, ModOrUse}, 13748 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13749 : diag::warn_unsequenced_mod_use) 13750 << O << SourceRange(ModOrUse->getExprLoc())); 13751 UI.Diagnosed = true; 13752 } 13753 13754 // A note on note{Pre, Post}{Use, Mod}: 13755 // 13756 // (It helps to follow the algorithm with an expression such as 13757 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13758 // operations before C++17 and both are well-defined in C++17). 13759 // 13760 // When visiting a node which uses/modify an object we first call notePreUse 13761 // or notePreMod before visiting its sub-expression(s). At this point the 13762 // children of the current node have not yet been visited and so the eventual 13763 // uses/modifications resulting from the children of the current node have not 13764 // been recorded yet. 13765 // 13766 // We then visit the children of the current node. After that notePostUse or 13767 // notePostMod is called. These will 1) detect an unsequenced modification 13768 // as side effect (as in "k++ + k") and 2) add a new usage with the 13769 // appropriate usage kind. 13770 // 13771 // We also have to be careful that some operation sequences modification as 13772 // side effect as well (for example: || or ,). To account for this we wrap 13773 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13774 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13775 // which record usages which are modifications as side effect, and then 13776 // downgrade them (or more accurately restore the previous usage which was a 13777 // modification as side effect) when exiting the scope of the sequenced 13778 // subexpression. 13779 13780 void notePreUse(Object O, const Expr *UseExpr) { 13781 UsageInfo &UI = UsageMap[O]; 13782 // Uses conflict with other modifications. 13783 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13784 } 13785 13786 void notePostUse(Object O, const Expr *UseExpr) { 13787 UsageInfo &UI = UsageMap[O]; 13788 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13789 /*IsModMod=*/false); 13790 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13791 } 13792 13793 void notePreMod(Object O, const Expr *ModExpr) { 13794 UsageInfo &UI = UsageMap[O]; 13795 // Modifications conflict with other modifications and with uses. 13796 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13797 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13798 } 13799 13800 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13801 UsageInfo &UI = UsageMap[O]; 13802 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13803 /*IsModMod=*/true); 13804 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13805 } 13806 13807 public: 13808 SequenceChecker(Sema &S, const Expr *E, 13809 SmallVectorImpl<const Expr *> &WorkList) 13810 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13811 Visit(E); 13812 // Silence a -Wunused-private-field since WorkList is now unused. 13813 // TODO: Evaluate if it can be used, and if not remove it. 13814 (void)this->WorkList; 13815 } 13816 13817 void VisitStmt(const Stmt *S) { 13818 // Skip all statements which aren't expressions for now. 13819 } 13820 13821 void VisitExpr(const Expr *E) { 13822 // By default, just recurse to evaluated subexpressions. 13823 Base::VisitStmt(E); 13824 } 13825 13826 void VisitCastExpr(const CastExpr *E) { 13827 Object O = Object(); 13828 if (E->getCastKind() == CK_LValueToRValue) 13829 O = getObject(E->getSubExpr(), false); 13830 13831 if (O) 13832 notePreUse(O, E); 13833 VisitExpr(E); 13834 if (O) 13835 notePostUse(O, E); 13836 } 13837 13838 void VisitSequencedExpressions(const Expr *SequencedBefore, 13839 const Expr *SequencedAfter) { 13840 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13841 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13842 SequenceTree::Seq OldRegion = Region; 13843 13844 { 13845 SequencedSubexpression SeqBefore(*this); 13846 Region = BeforeRegion; 13847 Visit(SequencedBefore); 13848 } 13849 13850 Region = AfterRegion; 13851 Visit(SequencedAfter); 13852 13853 Region = OldRegion; 13854 13855 Tree.merge(BeforeRegion); 13856 Tree.merge(AfterRegion); 13857 } 13858 13859 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13860 // C++17 [expr.sub]p1: 13861 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13862 // expression E1 is sequenced before the expression E2. 13863 if (SemaRef.getLangOpts().CPlusPlus17) 13864 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13865 else { 13866 Visit(ASE->getLHS()); 13867 Visit(ASE->getRHS()); 13868 } 13869 } 13870 13871 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13872 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13873 void VisitBinPtrMem(const BinaryOperator *BO) { 13874 // C++17 [expr.mptr.oper]p4: 13875 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13876 // the expression E1 is sequenced before the expression E2. 13877 if (SemaRef.getLangOpts().CPlusPlus17) 13878 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13879 else { 13880 Visit(BO->getLHS()); 13881 Visit(BO->getRHS()); 13882 } 13883 } 13884 13885 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13886 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13887 void VisitBinShlShr(const BinaryOperator *BO) { 13888 // C++17 [expr.shift]p4: 13889 // The expression E1 is sequenced before the expression E2. 13890 if (SemaRef.getLangOpts().CPlusPlus17) 13891 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13892 else { 13893 Visit(BO->getLHS()); 13894 Visit(BO->getRHS()); 13895 } 13896 } 13897 13898 void VisitBinComma(const BinaryOperator *BO) { 13899 // C++11 [expr.comma]p1: 13900 // Every value computation and side effect associated with the left 13901 // expression is sequenced before every value computation and side 13902 // effect associated with the right expression. 13903 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13904 } 13905 13906 void VisitBinAssign(const BinaryOperator *BO) { 13907 SequenceTree::Seq RHSRegion; 13908 SequenceTree::Seq LHSRegion; 13909 if (SemaRef.getLangOpts().CPlusPlus17) { 13910 RHSRegion = Tree.allocate(Region); 13911 LHSRegion = Tree.allocate(Region); 13912 } else { 13913 RHSRegion = Region; 13914 LHSRegion = Region; 13915 } 13916 SequenceTree::Seq OldRegion = Region; 13917 13918 // C++11 [expr.ass]p1: 13919 // [...] the assignment is sequenced after the value computation 13920 // of the right and left operands, [...] 13921 // 13922 // so check it before inspecting the operands and update the 13923 // map afterwards. 13924 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13925 if (O) 13926 notePreMod(O, BO); 13927 13928 if (SemaRef.getLangOpts().CPlusPlus17) { 13929 // C++17 [expr.ass]p1: 13930 // [...] The right operand is sequenced before the left operand. [...] 13931 { 13932 SequencedSubexpression SeqBefore(*this); 13933 Region = RHSRegion; 13934 Visit(BO->getRHS()); 13935 } 13936 13937 Region = LHSRegion; 13938 Visit(BO->getLHS()); 13939 13940 if (O && isa<CompoundAssignOperator>(BO)) 13941 notePostUse(O, BO); 13942 13943 } else { 13944 // C++11 does not specify any sequencing between the LHS and RHS. 13945 Region = LHSRegion; 13946 Visit(BO->getLHS()); 13947 13948 if (O && isa<CompoundAssignOperator>(BO)) 13949 notePostUse(O, BO); 13950 13951 Region = RHSRegion; 13952 Visit(BO->getRHS()); 13953 } 13954 13955 // C++11 [expr.ass]p1: 13956 // the assignment is sequenced [...] before the value computation of the 13957 // assignment expression. 13958 // C11 6.5.16/3 has no such rule. 13959 Region = OldRegion; 13960 if (O) 13961 notePostMod(O, BO, 13962 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13963 : UK_ModAsSideEffect); 13964 if (SemaRef.getLangOpts().CPlusPlus17) { 13965 Tree.merge(RHSRegion); 13966 Tree.merge(LHSRegion); 13967 } 13968 } 13969 13970 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13971 VisitBinAssign(CAO); 13972 } 13973 13974 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13975 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13976 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13977 Object O = getObject(UO->getSubExpr(), true); 13978 if (!O) 13979 return VisitExpr(UO); 13980 13981 notePreMod(O, UO); 13982 Visit(UO->getSubExpr()); 13983 // C++11 [expr.pre.incr]p1: 13984 // the expression ++x is equivalent to x+=1 13985 notePostMod(O, UO, 13986 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13987 : UK_ModAsSideEffect); 13988 } 13989 13990 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13991 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13992 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13993 Object O = getObject(UO->getSubExpr(), true); 13994 if (!O) 13995 return VisitExpr(UO); 13996 13997 notePreMod(O, UO); 13998 Visit(UO->getSubExpr()); 13999 notePostMod(O, UO, UK_ModAsSideEffect); 14000 } 14001 14002 void VisitBinLOr(const BinaryOperator *BO) { 14003 // C++11 [expr.log.or]p2: 14004 // If the second expression is evaluated, every value computation and 14005 // side effect associated with the first expression is sequenced before 14006 // every value computation and side effect associated with the 14007 // second expression. 14008 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14009 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14010 SequenceTree::Seq OldRegion = Region; 14011 14012 EvaluationTracker Eval(*this); 14013 { 14014 SequencedSubexpression Sequenced(*this); 14015 Region = LHSRegion; 14016 Visit(BO->getLHS()); 14017 } 14018 14019 // C++11 [expr.log.or]p1: 14020 // [...] the second operand is not evaluated if the first operand 14021 // evaluates to true. 14022 bool EvalResult = false; 14023 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14024 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14025 if (ShouldVisitRHS) { 14026 Region = RHSRegion; 14027 Visit(BO->getRHS()); 14028 } 14029 14030 Region = OldRegion; 14031 Tree.merge(LHSRegion); 14032 Tree.merge(RHSRegion); 14033 } 14034 14035 void VisitBinLAnd(const BinaryOperator *BO) { 14036 // C++11 [expr.log.and]p2: 14037 // If the second expression is evaluated, every value computation and 14038 // side effect associated with the first expression is sequenced before 14039 // every value computation and side effect associated with the 14040 // second expression. 14041 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14042 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14043 SequenceTree::Seq OldRegion = Region; 14044 14045 EvaluationTracker Eval(*this); 14046 { 14047 SequencedSubexpression Sequenced(*this); 14048 Region = LHSRegion; 14049 Visit(BO->getLHS()); 14050 } 14051 14052 // C++11 [expr.log.and]p1: 14053 // [...] the second operand is not evaluated if the first operand is false. 14054 bool EvalResult = false; 14055 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14056 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14057 if (ShouldVisitRHS) { 14058 Region = RHSRegion; 14059 Visit(BO->getRHS()); 14060 } 14061 14062 Region = OldRegion; 14063 Tree.merge(LHSRegion); 14064 Tree.merge(RHSRegion); 14065 } 14066 14067 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14068 // C++11 [expr.cond]p1: 14069 // [...] Every value computation and side effect associated with the first 14070 // expression is sequenced before every value computation and side effect 14071 // associated with the second or third expression. 14072 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14073 14074 // No sequencing is specified between the true and false expression. 14075 // However since exactly one of both is going to be evaluated we can 14076 // consider them to be sequenced. This is needed to avoid warning on 14077 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14078 // both the true and false expressions because we can't evaluate x. 14079 // This will still allow us to detect an expression like (pre C++17) 14080 // "(x ? y += 1 : y += 2) = y". 14081 // 14082 // We don't wrap the visitation of the true and false expression with 14083 // SequencedSubexpression because we don't want to downgrade modifications 14084 // as side effect in the true and false expressions after the visition 14085 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14086 // not warn between the two "y++", but we should warn between the "y++" 14087 // and the "y". 14088 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14089 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14090 SequenceTree::Seq OldRegion = Region; 14091 14092 EvaluationTracker Eval(*this); 14093 { 14094 SequencedSubexpression Sequenced(*this); 14095 Region = ConditionRegion; 14096 Visit(CO->getCond()); 14097 } 14098 14099 // C++11 [expr.cond]p1: 14100 // [...] The first expression is contextually converted to bool (Clause 4). 14101 // It is evaluated and if it is true, the result of the conditional 14102 // expression is the value of the second expression, otherwise that of the 14103 // third expression. Only one of the second and third expressions is 14104 // evaluated. [...] 14105 bool EvalResult = false; 14106 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14107 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14108 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14109 if (ShouldVisitTrueExpr) { 14110 Region = TrueRegion; 14111 Visit(CO->getTrueExpr()); 14112 } 14113 if (ShouldVisitFalseExpr) { 14114 Region = FalseRegion; 14115 Visit(CO->getFalseExpr()); 14116 } 14117 14118 Region = OldRegion; 14119 Tree.merge(ConditionRegion); 14120 Tree.merge(TrueRegion); 14121 Tree.merge(FalseRegion); 14122 } 14123 14124 void VisitCallExpr(const CallExpr *CE) { 14125 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14126 14127 if (CE->isUnevaluatedBuiltinCall(Context)) 14128 return; 14129 14130 // C++11 [intro.execution]p15: 14131 // When calling a function [...], every value computation and side effect 14132 // associated with any argument expression, or with the postfix expression 14133 // designating the called function, is sequenced before execution of every 14134 // expression or statement in the body of the function [and thus before 14135 // the value computation of its result]. 14136 SequencedSubexpression Sequenced(*this); 14137 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14138 // C++17 [expr.call]p5 14139 // The postfix-expression is sequenced before each expression in the 14140 // expression-list and any default argument. [...] 14141 SequenceTree::Seq CalleeRegion; 14142 SequenceTree::Seq OtherRegion; 14143 if (SemaRef.getLangOpts().CPlusPlus17) { 14144 CalleeRegion = Tree.allocate(Region); 14145 OtherRegion = Tree.allocate(Region); 14146 } else { 14147 CalleeRegion = Region; 14148 OtherRegion = Region; 14149 } 14150 SequenceTree::Seq OldRegion = Region; 14151 14152 // Visit the callee expression first. 14153 Region = CalleeRegion; 14154 if (SemaRef.getLangOpts().CPlusPlus17) { 14155 SequencedSubexpression Sequenced(*this); 14156 Visit(CE->getCallee()); 14157 } else { 14158 Visit(CE->getCallee()); 14159 } 14160 14161 // Then visit the argument expressions. 14162 Region = OtherRegion; 14163 for (const Expr *Argument : CE->arguments()) 14164 Visit(Argument); 14165 14166 Region = OldRegion; 14167 if (SemaRef.getLangOpts().CPlusPlus17) { 14168 Tree.merge(CalleeRegion); 14169 Tree.merge(OtherRegion); 14170 } 14171 }); 14172 } 14173 14174 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14175 // C++17 [over.match.oper]p2: 14176 // [...] the operator notation is first transformed to the equivalent 14177 // function-call notation as summarized in Table 12 (where @ denotes one 14178 // of the operators covered in the specified subclause). However, the 14179 // operands are sequenced in the order prescribed for the built-in 14180 // operator (Clause 8). 14181 // 14182 // From the above only overloaded binary operators and overloaded call 14183 // operators have sequencing rules in C++17 that we need to handle 14184 // separately. 14185 if (!SemaRef.getLangOpts().CPlusPlus17 || 14186 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14187 return VisitCallExpr(CXXOCE); 14188 14189 enum { 14190 NoSequencing, 14191 LHSBeforeRHS, 14192 RHSBeforeLHS, 14193 LHSBeforeRest 14194 } SequencingKind; 14195 switch (CXXOCE->getOperator()) { 14196 case OO_Equal: 14197 case OO_PlusEqual: 14198 case OO_MinusEqual: 14199 case OO_StarEqual: 14200 case OO_SlashEqual: 14201 case OO_PercentEqual: 14202 case OO_CaretEqual: 14203 case OO_AmpEqual: 14204 case OO_PipeEqual: 14205 case OO_LessLessEqual: 14206 case OO_GreaterGreaterEqual: 14207 SequencingKind = RHSBeforeLHS; 14208 break; 14209 14210 case OO_LessLess: 14211 case OO_GreaterGreater: 14212 case OO_AmpAmp: 14213 case OO_PipePipe: 14214 case OO_Comma: 14215 case OO_ArrowStar: 14216 case OO_Subscript: 14217 SequencingKind = LHSBeforeRHS; 14218 break; 14219 14220 case OO_Call: 14221 SequencingKind = LHSBeforeRest; 14222 break; 14223 14224 default: 14225 SequencingKind = NoSequencing; 14226 break; 14227 } 14228 14229 if (SequencingKind == NoSequencing) 14230 return VisitCallExpr(CXXOCE); 14231 14232 // This is a call, so all subexpressions are sequenced before the result. 14233 SequencedSubexpression Sequenced(*this); 14234 14235 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14236 assert(SemaRef.getLangOpts().CPlusPlus17 && 14237 "Should only get there with C++17 and above!"); 14238 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14239 "Should only get there with an overloaded binary operator" 14240 " or an overloaded call operator!"); 14241 14242 if (SequencingKind == LHSBeforeRest) { 14243 assert(CXXOCE->getOperator() == OO_Call && 14244 "We should only have an overloaded call operator here!"); 14245 14246 // This is very similar to VisitCallExpr, except that we only have the 14247 // C++17 case. The postfix-expression is the first argument of the 14248 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14249 // are in the following arguments. 14250 // 14251 // Note that we intentionally do not visit the callee expression since 14252 // it is just a decayed reference to a function. 14253 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14254 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14255 SequenceTree::Seq OldRegion = Region; 14256 14257 assert(CXXOCE->getNumArgs() >= 1 && 14258 "An overloaded call operator must have at least one argument" 14259 " for the postfix-expression!"); 14260 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14261 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14262 CXXOCE->getNumArgs() - 1); 14263 14264 // Visit the postfix-expression first. 14265 { 14266 Region = PostfixExprRegion; 14267 SequencedSubexpression Sequenced(*this); 14268 Visit(PostfixExpr); 14269 } 14270 14271 // Then visit the argument expressions. 14272 Region = ArgsRegion; 14273 for (const Expr *Arg : Args) 14274 Visit(Arg); 14275 14276 Region = OldRegion; 14277 Tree.merge(PostfixExprRegion); 14278 Tree.merge(ArgsRegion); 14279 } else { 14280 assert(CXXOCE->getNumArgs() == 2 && 14281 "Should only have two arguments here!"); 14282 assert((SequencingKind == LHSBeforeRHS || 14283 SequencingKind == RHSBeforeLHS) && 14284 "Unexpected sequencing kind!"); 14285 14286 // We do not visit the callee expression since it is just a decayed 14287 // reference to a function. 14288 const Expr *E1 = CXXOCE->getArg(0); 14289 const Expr *E2 = CXXOCE->getArg(1); 14290 if (SequencingKind == RHSBeforeLHS) 14291 std::swap(E1, E2); 14292 14293 return VisitSequencedExpressions(E1, E2); 14294 } 14295 }); 14296 } 14297 14298 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14299 // This is a call, so all subexpressions are sequenced before the result. 14300 SequencedSubexpression Sequenced(*this); 14301 14302 if (!CCE->isListInitialization()) 14303 return VisitExpr(CCE); 14304 14305 // In C++11, list initializations are sequenced. 14306 SmallVector<SequenceTree::Seq, 32> Elts; 14307 SequenceTree::Seq Parent = Region; 14308 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14309 E = CCE->arg_end(); 14310 I != E; ++I) { 14311 Region = Tree.allocate(Parent); 14312 Elts.push_back(Region); 14313 Visit(*I); 14314 } 14315 14316 // Forget that the initializers are sequenced. 14317 Region = Parent; 14318 for (unsigned I = 0; I < Elts.size(); ++I) 14319 Tree.merge(Elts[I]); 14320 } 14321 14322 void VisitInitListExpr(const InitListExpr *ILE) { 14323 if (!SemaRef.getLangOpts().CPlusPlus11) 14324 return VisitExpr(ILE); 14325 14326 // In C++11, list initializations are sequenced. 14327 SmallVector<SequenceTree::Seq, 32> Elts; 14328 SequenceTree::Seq Parent = Region; 14329 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14330 const Expr *E = ILE->getInit(I); 14331 if (!E) 14332 continue; 14333 Region = Tree.allocate(Parent); 14334 Elts.push_back(Region); 14335 Visit(E); 14336 } 14337 14338 // Forget that the initializers are sequenced. 14339 Region = Parent; 14340 for (unsigned I = 0; I < Elts.size(); ++I) 14341 Tree.merge(Elts[I]); 14342 } 14343 }; 14344 14345 } // namespace 14346 14347 void Sema::CheckUnsequencedOperations(const Expr *E) { 14348 SmallVector<const Expr *, 8> WorkList; 14349 WorkList.push_back(E); 14350 while (!WorkList.empty()) { 14351 const Expr *Item = WorkList.pop_back_val(); 14352 SequenceChecker(*this, Item, WorkList); 14353 } 14354 } 14355 14356 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14357 bool IsConstexpr) { 14358 llvm::SaveAndRestore<bool> ConstantContext( 14359 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14360 CheckImplicitConversions(E, CheckLoc); 14361 if (!E->isInstantiationDependent()) 14362 CheckUnsequencedOperations(E); 14363 if (!IsConstexpr && !E->isValueDependent()) 14364 CheckForIntOverflow(E); 14365 DiagnoseMisalignedMembers(); 14366 } 14367 14368 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14369 FieldDecl *BitField, 14370 Expr *Init) { 14371 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14372 } 14373 14374 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14375 SourceLocation Loc) { 14376 if (!PType->isVariablyModifiedType()) 14377 return; 14378 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14379 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14380 return; 14381 } 14382 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14383 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14384 return; 14385 } 14386 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14387 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14388 return; 14389 } 14390 14391 const ArrayType *AT = S.Context.getAsArrayType(PType); 14392 if (!AT) 14393 return; 14394 14395 if (AT->getSizeModifier() != ArrayType::Star) { 14396 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14397 return; 14398 } 14399 14400 S.Diag(Loc, diag::err_array_star_in_function_definition); 14401 } 14402 14403 /// CheckParmsForFunctionDef - Check that the parameters of the given 14404 /// function are appropriate for the definition of a function. This 14405 /// takes care of any checks that cannot be performed on the 14406 /// declaration itself, e.g., that the types of each of the function 14407 /// parameters are complete. 14408 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14409 bool CheckParameterNames) { 14410 bool HasInvalidParm = false; 14411 for (ParmVarDecl *Param : Parameters) { 14412 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14413 // function declarator that is part of a function definition of 14414 // that function shall not have incomplete type. 14415 // 14416 // This is also C++ [dcl.fct]p6. 14417 if (!Param->isInvalidDecl() && 14418 RequireCompleteType(Param->getLocation(), Param->getType(), 14419 diag::err_typecheck_decl_incomplete_type)) { 14420 Param->setInvalidDecl(); 14421 HasInvalidParm = true; 14422 } 14423 14424 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14425 // declaration of each parameter shall include an identifier. 14426 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14427 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14428 // Diagnose this as an extension in C17 and earlier. 14429 if (!getLangOpts().C2x) 14430 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14431 } 14432 14433 // C99 6.7.5.3p12: 14434 // If the function declarator is not part of a definition of that 14435 // function, parameters may have incomplete type and may use the [*] 14436 // notation in their sequences of declarator specifiers to specify 14437 // variable length array types. 14438 QualType PType = Param->getOriginalType(); 14439 // FIXME: This diagnostic should point the '[*]' if source-location 14440 // information is added for it. 14441 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14442 14443 // If the parameter is a c++ class type and it has to be destructed in the 14444 // callee function, declare the destructor so that it can be called by the 14445 // callee function. Do not perform any direct access check on the dtor here. 14446 if (!Param->isInvalidDecl()) { 14447 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14448 if (!ClassDecl->isInvalidDecl() && 14449 !ClassDecl->hasIrrelevantDestructor() && 14450 !ClassDecl->isDependentContext() && 14451 ClassDecl->isParamDestroyedInCallee()) { 14452 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14453 MarkFunctionReferenced(Param->getLocation(), Destructor); 14454 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14455 } 14456 } 14457 } 14458 14459 // Parameters with the pass_object_size attribute only need to be marked 14460 // constant at function definitions. Because we lack information about 14461 // whether we're on a declaration or definition when we're instantiating the 14462 // attribute, we need to check for constness here. 14463 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14464 if (!Param->getType().isConstQualified()) 14465 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14466 << Attr->getSpelling() << 1; 14467 14468 // Check for parameter names shadowing fields from the class. 14469 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14470 // The owning context for the parameter should be the function, but we 14471 // want to see if this function's declaration context is a record. 14472 DeclContext *DC = Param->getDeclContext(); 14473 if (DC && DC->isFunctionOrMethod()) { 14474 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14475 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14476 RD, /*DeclIsField*/ false); 14477 } 14478 } 14479 } 14480 14481 return HasInvalidParm; 14482 } 14483 14484 Optional<std::pair<CharUnits, CharUnits>> 14485 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14486 14487 /// Compute the alignment and offset of the base class object given the 14488 /// derived-to-base cast expression and the alignment and offset of the derived 14489 /// class object. 14490 static std::pair<CharUnits, CharUnits> 14491 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14492 CharUnits BaseAlignment, CharUnits Offset, 14493 ASTContext &Ctx) { 14494 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14495 ++PathI) { 14496 const CXXBaseSpecifier *Base = *PathI; 14497 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14498 if (Base->isVirtual()) { 14499 // The complete object may have a lower alignment than the non-virtual 14500 // alignment of the base, in which case the base may be misaligned. Choose 14501 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14502 // conservative lower bound of the complete object alignment. 14503 CharUnits NonVirtualAlignment = 14504 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14505 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14506 Offset = CharUnits::Zero(); 14507 } else { 14508 const ASTRecordLayout &RL = 14509 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14510 Offset += RL.getBaseClassOffset(BaseDecl); 14511 } 14512 DerivedType = Base->getType(); 14513 } 14514 14515 return std::make_pair(BaseAlignment, Offset); 14516 } 14517 14518 /// Compute the alignment and offset of a binary additive operator. 14519 static Optional<std::pair<CharUnits, CharUnits>> 14520 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14521 bool IsSub, ASTContext &Ctx) { 14522 QualType PointeeType = PtrE->getType()->getPointeeType(); 14523 14524 if (!PointeeType->isConstantSizeType()) 14525 return llvm::None; 14526 14527 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14528 14529 if (!P) 14530 return llvm::None; 14531 14532 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14533 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14534 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14535 if (IsSub) 14536 Offset = -Offset; 14537 return std::make_pair(P->first, P->second + Offset); 14538 } 14539 14540 // If the integer expression isn't a constant expression, compute the lower 14541 // bound of the alignment using the alignment and offset of the pointer 14542 // expression and the element size. 14543 return std::make_pair( 14544 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14545 CharUnits::Zero()); 14546 } 14547 14548 /// This helper function takes an lvalue expression and returns the alignment of 14549 /// a VarDecl and a constant offset from the VarDecl. 14550 Optional<std::pair<CharUnits, CharUnits>> 14551 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14552 E = E->IgnoreParens(); 14553 switch (E->getStmtClass()) { 14554 default: 14555 break; 14556 case Stmt::CStyleCastExprClass: 14557 case Stmt::CXXStaticCastExprClass: 14558 case Stmt::ImplicitCastExprClass: { 14559 auto *CE = cast<CastExpr>(E); 14560 const Expr *From = CE->getSubExpr(); 14561 switch (CE->getCastKind()) { 14562 default: 14563 break; 14564 case CK_NoOp: 14565 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14566 case CK_UncheckedDerivedToBase: 14567 case CK_DerivedToBase: { 14568 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14569 if (!P) 14570 break; 14571 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14572 P->second, Ctx); 14573 } 14574 } 14575 break; 14576 } 14577 case Stmt::ArraySubscriptExprClass: { 14578 auto *ASE = cast<ArraySubscriptExpr>(E); 14579 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14580 false, Ctx); 14581 } 14582 case Stmt::DeclRefExprClass: { 14583 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14584 // FIXME: If VD is captured by copy or is an escaping __block variable, 14585 // use the alignment of VD's type. 14586 if (!VD->getType()->isReferenceType()) 14587 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14588 if (VD->hasInit()) 14589 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14590 } 14591 break; 14592 } 14593 case Stmt::MemberExprClass: { 14594 auto *ME = cast<MemberExpr>(E); 14595 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14596 if (!FD || FD->getType()->isReferenceType() || 14597 FD->getParent()->isInvalidDecl()) 14598 break; 14599 Optional<std::pair<CharUnits, CharUnits>> P; 14600 if (ME->isArrow()) 14601 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14602 else 14603 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14604 if (!P) 14605 break; 14606 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14607 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14608 return std::make_pair(P->first, 14609 P->second + CharUnits::fromQuantity(Offset)); 14610 } 14611 case Stmt::UnaryOperatorClass: { 14612 auto *UO = cast<UnaryOperator>(E); 14613 switch (UO->getOpcode()) { 14614 default: 14615 break; 14616 case UO_Deref: 14617 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14618 } 14619 break; 14620 } 14621 case Stmt::BinaryOperatorClass: { 14622 auto *BO = cast<BinaryOperator>(E); 14623 auto Opcode = BO->getOpcode(); 14624 switch (Opcode) { 14625 default: 14626 break; 14627 case BO_Comma: 14628 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14629 } 14630 break; 14631 } 14632 } 14633 return llvm::None; 14634 } 14635 14636 /// This helper function takes a pointer expression and returns the alignment of 14637 /// a VarDecl and a constant offset from the VarDecl. 14638 Optional<std::pair<CharUnits, CharUnits>> 14639 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14640 E = E->IgnoreParens(); 14641 switch (E->getStmtClass()) { 14642 default: 14643 break; 14644 case Stmt::CStyleCastExprClass: 14645 case Stmt::CXXStaticCastExprClass: 14646 case Stmt::ImplicitCastExprClass: { 14647 auto *CE = cast<CastExpr>(E); 14648 const Expr *From = CE->getSubExpr(); 14649 switch (CE->getCastKind()) { 14650 default: 14651 break; 14652 case CK_NoOp: 14653 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14654 case CK_ArrayToPointerDecay: 14655 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14656 case CK_UncheckedDerivedToBase: 14657 case CK_DerivedToBase: { 14658 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14659 if (!P) 14660 break; 14661 return getDerivedToBaseAlignmentAndOffset( 14662 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14663 } 14664 } 14665 break; 14666 } 14667 case Stmt::CXXThisExprClass: { 14668 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14669 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14670 return std::make_pair(Alignment, CharUnits::Zero()); 14671 } 14672 case Stmt::UnaryOperatorClass: { 14673 auto *UO = cast<UnaryOperator>(E); 14674 if (UO->getOpcode() == UO_AddrOf) 14675 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14676 break; 14677 } 14678 case Stmt::BinaryOperatorClass: { 14679 auto *BO = cast<BinaryOperator>(E); 14680 auto Opcode = BO->getOpcode(); 14681 switch (Opcode) { 14682 default: 14683 break; 14684 case BO_Add: 14685 case BO_Sub: { 14686 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14687 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14688 std::swap(LHS, RHS); 14689 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14690 Ctx); 14691 } 14692 case BO_Comma: 14693 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14694 } 14695 break; 14696 } 14697 } 14698 return llvm::None; 14699 } 14700 14701 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14702 // See if we can compute the alignment of a VarDecl and an offset from it. 14703 Optional<std::pair<CharUnits, CharUnits>> P = 14704 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14705 14706 if (P) 14707 return P->first.alignmentAtOffset(P->second); 14708 14709 // If that failed, return the type's alignment. 14710 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14711 } 14712 14713 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14714 /// pointer cast increases the alignment requirements. 14715 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14716 // This is actually a lot of work to potentially be doing on every 14717 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14718 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14719 return; 14720 14721 // Ignore dependent types. 14722 if (T->isDependentType() || Op->getType()->isDependentType()) 14723 return; 14724 14725 // Require that the destination be a pointer type. 14726 const PointerType *DestPtr = T->getAs<PointerType>(); 14727 if (!DestPtr) return; 14728 14729 // If the destination has alignment 1, we're done. 14730 QualType DestPointee = DestPtr->getPointeeType(); 14731 if (DestPointee->isIncompleteType()) return; 14732 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14733 if (DestAlign.isOne()) return; 14734 14735 // Require that the source be a pointer type. 14736 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14737 if (!SrcPtr) return; 14738 QualType SrcPointee = SrcPtr->getPointeeType(); 14739 14740 // Explicitly allow casts from cv void*. We already implicitly 14741 // allowed casts to cv void*, since they have alignment 1. 14742 // Also allow casts involving incomplete types, which implicitly 14743 // includes 'void'. 14744 if (SrcPointee->isIncompleteType()) return; 14745 14746 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14747 14748 if (SrcAlign >= DestAlign) return; 14749 14750 Diag(TRange.getBegin(), diag::warn_cast_align) 14751 << Op->getType() << T 14752 << static_cast<unsigned>(SrcAlign.getQuantity()) 14753 << static_cast<unsigned>(DestAlign.getQuantity()) 14754 << TRange << Op->getSourceRange(); 14755 } 14756 14757 /// Check whether this array fits the idiom of a size-one tail padded 14758 /// array member of a struct. 14759 /// 14760 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14761 /// commonly used to emulate flexible arrays in C89 code. 14762 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14763 const NamedDecl *ND) { 14764 if (Size != 1 || !ND) return false; 14765 14766 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14767 if (!FD) return false; 14768 14769 // Don't consider sizes resulting from macro expansions or template argument 14770 // substitution to form C89 tail-padded arrays. 14771 14772 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14773 while (TInfo) { 14774 TypeLoc TL = TInfo->getTypeLoc(); 14775 // Look through typedefs. 14776 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14777 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14778 TInfo = TDL->getTypeSourceInfo(); 14779 continue; 14780 } 14781 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14782 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14783 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14784 return false; 14785 } 14786 break; 14787 } 14788 14789 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14790 if (!RD) return false; 14791 if (RD->isUnion()) return false; 14792 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14793 if (!CRD->isStandardLayout()) return false; 14794 } 14795 14796 // See if this is the last field decl in the record. 14797 const Decl *D = FD; 14798 while ((D = D->getNextDeclInContext())) 14799 if (isa<FieldDecl>(D)) 14800 return false; 14801 return true; 14802 } 14803 14804 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14805 const ArraySubscriptExpr *ASE, 14806 bool AllowOnePastEnd, bool IndexNegated) { 14807 // Already diagnosed by the constant evaluator. 14808 if (isConstantEvaluated()) 14809 return; 14810 14811 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14812 if (IndexExpr->isValueDependent()) 14813 return; 14814 14815 const Type *EffectiveType = 14816 BaseExpr->getType()->getPointeeOrArrayElementType(); 14817 BaseExpr = BaseExpr->IgnoreParenCasts(); 14818 const ConstantArrayType *ArrayTy = 14819 Context.getAsConstantArrayType(BaseExpr->getType()); 14820 14821 const Type *BaseType = 14822 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 14823 bool IsUnboundedArray = (BaseType == nullptr); 14824 if (EffectiveType->isDependentType() || 14825 (!IsUnboundedArray && BaseType->isDependentType())) 14826 return; 14827 14828 Expr::EvalResult Result; 14829 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14830 return; 14831 14832 llvm::APSInt index = Result.Val.getInt(); 14833 if (IndexNegated) { 14834 index.setIsUnsigned(false); 14835 index = -index; 14836 } 14837 14838 const NamedDecl *ND = nullptr; 14839 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14840 ND = DRE->getDecl(); 14841 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14842 ND = ME->getMemberDecl(); 14843 14844 if (IsUnboundedArray) { 14845 if (index.isUnsigned() || !index.isNegative()) { 14846 const auto &ASTC = getASTContext(); 14847 unsigned AddrBits = 14848 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 14849 EffectiveType->getCanonicalTypeInternal())); 14850 if (index.getBitWidth() < AddrBits) 14851 index = index.zext(AddrBits); 14852 Optional<CharUnits> ElemCharUnits = 14853 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 14854 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 14855 // pointer) bounds-checking isn't meaningful. 14856 if (!ElemCharUnits) 14857 return; 14858 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 14859 // If index has more active bits than address space, we already know 14860 // we have a bounds violation to warn about. Otherwise, compute 14861 // address of (index + 1)th element, and warn about bounds violation 14862 // only if that address exceeds address space. 14863 if (index.getActiveBits() <= AddrBits) { 14864 bool Overflow; 14865 llvm::APInt Product(index); 14866 Product += 1; 14867 Product = Product.umul_ov(ElemBytes, Overflow); 14868 if (!Overflow && Product.getActiveBits() <= AddrBits) 14869 return; 14870 } 14871 14872 // Need to compute max possible elements in address space, since that 14873 // is included in diag message. 14874 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 14875 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 14876 MaxElems += 1; 14877 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 14878 MaxElems = MaxElems.udiv(ElemBytes); 14879 14880 unsigned DiagID = 14881 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 14882 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 14883 14884 // Diag message shows element size in bits and in "bytes" (platform- 14885 // dependent CharUnits) 14886 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14887 PDiag(DiagID) 14888 << toString(index, 10, true) << AddrBits 14889 << (unsigned)ASTC.toBits(*ElemCharUnits) 14890 << toString(ElemBytes, 10, false) 14891 << toString(MaxElems, 10, false) 14892 << (unsigned)MaxElems.getLimitedValue(~0U) 14893 << IndexExpr->getSourceRange()); 14894 14895 if (!ND) { 14896 // Try harder to find a NamedDecl to point at in the note. 14897 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14898 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14899 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14900 ND = DRE->getDecl(); 14901 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14902 ND = ME->getMemberDecl(); 14903 } 14904 14905 if (ND) 14906 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14907 PDiag(diag::note_array_declared_here) << ND); 14908 } 14909 return; 14910 } 14911 14912 if (index.isUnsigned() || !index.isNegative()) { 14913 // It is possible that the type of the base expression after 14914 // IgnoreParenCasts is incomplete, even though the type of the base 14915 // expression before IgnoreParenCasts is complete (see PR39746 for an 14916 // example). In this case we have no information about whether the array 14917 // access exceeds the array bounds. However we can still diagnose an array 14918 // access which precedes the array bounds. 14919 if (BaseType->isIncompleteType()) 14920 return; 14921 14922 llvm::APInt size = ArrayTy->getSize(); 14923 if (!size.isStrictlyPositive()) 14924 return; 14925 14926 if (BaseType != EffectiveType) { 14927 // Make sure we're comparing apples to apples when comparing index to size 14928 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14929 uint64_t array_typesize = Context.getTypeSize(BaseType); 14930 // Handle ptrarith_typesize being zero, such as when casting to void* 14931 if (!ptrarith_typesize) ptrarith_typesize = 1; 14932 if (ptrarith_typesize != array_typesize) { 14933 // There's a cast to a different size type involved 14934 uint64_t ratio = array_typesize / ptrarith_typesize; 14935 // TODO: Be smarter about handling cases where array_typesize is not a 14936 // multiple of ptrarith_typesize 14937 if (ptrarith_typesize * ratio == array_typesize) 14938 size *= llvm::APInt(size.getBitWidth(), ratio); 14939 } 14940 } 14941 14942 if (size.getBitWidth() > index.getBitWidth()) 14943 index = index.zext(size.getBitWidth()); 14944 else if (size.getBitWidth() < index.getBitWidth()) 14945 size = size.zext(index.getBitWidth()); 14946 14947 // For array subscripting the index must be less than size, but for pointer 14948 // arithmetic also allow the index (offset) to be equal to size since 14949 // computing the next address after the end of the array is legal and 14950 // commonly done e.g. in C++ iterators and range-based for loops. 14951 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14952 return; 14953 14954 // Also don't warn for arrays of size 1 which are members of some 14955 // structure. These are often used to approximate flexible arrays in C89 14956 // code. 14957 if (IsTailPaddedMemberArray(*this, size, ND)) 14958 return; 14959 14960 // Suppress the warning if the subscript expression (as identified by the 14961 // ']' location) and the index expression are both from macro expansions 14962 // within a system header. 14963 if (ASE) { 14964 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14965 ASE->getRBracketLoc()); 14966 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14967 SourceLocation IndexLoc = 14968 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14969 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14970 return; 14971 } 14972 } 14973 14974 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 14975 : diag::warn_ptr_arith_exceeds_bounds; 14976 14977 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14978 PDiag(DiagID) << toString(index, 10, true) 14979 << toString(size, 10, true) 14980 << (unsigned)size.getLimitedValue(~0U) 14981 << IndexExpr->getSourceRange()); 14982 } else { 14983 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14984 if (!ASE) { 14985 DiagID = diag::warn_ptr_arith_precedes_bounds; 14986 if (index.isNegative()) index = -index; 14987 } 14988 14989 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14990 PDiag(DiagID) << toString(index, 10, true) 14991 << IndexExpr->getSourceRange()); 14992 } 14993 14994 if (!ND) { 14995 // Try harder to find a NamedDecl to point at in the note. 14996 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14997 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14998 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14999 ND = DRE->getDecl(); 15000 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15001 ND = ME->getMemberDecl(); 15002 } 15003 15004 if (ND) 15005 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15006 PDiag(diag::note_array_declared_here) << ND); 15007 } 15008 15009 void Sema::CheckArrayAccess(const Expr *expr) { 15010 int AllowOnePastEnd = 0; 15011 while (expr) { 15012 expr = expr->IgnoreParenImpCasts(); 15013 switch (expr->getStmtClass()) { 15014 case Stmt::ArraySubscriptExprClass: { 15015 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15016 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15017 AllowOnePastEnd > 0); 15018 expr = ASE->getBase(); 15019 break; 15020 } 15021 case Stmt::MemberExprClass: { 15022 expr = cast<MemberExpr>(expr)->getBase(); 15023 break; 15024 } 15025 case Stmt::OMPArraySectionExprClass: { 15026 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15027 if (ASE->getLowerBound()) 15028 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15029 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15030 return; 15031 } 15032 case Stmt::UnaryOperatorClass: { 15033 // Only unwrap the * and & unary operators 15034 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15035 expr = UO->getSubExpr(); 15036 switch (UO->getOpcode()) { 15037 case UO_AddrOf: 15038 AllowOnePastEnd++; 15039 break; 15040 case UO_Deref: 15041 AllowOnePastEnd--; 15042 break; 15043 default: 15044 return; 15045 } 15046 break; 15047 } 15048 case Stmt::ConditionalOperatorClass: { 15049 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15050 if (const Expr *lhs = cond->getLHS()) 15051 CheckArrayAccess(lhs); 15052 if (const Expr *rhs = cond->getRHS()) 15053 CheckArrayAccess(rhs); 15054 return; 15055 } 15056 case Stmt::CXXOperatorCallExprClass: { 15057 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15058 for (const auto *Arg : OCE->arguments()) 15059 CheckArrayAccess(Arg); 15060 return; 15061 } 15062 default: 15063 return; 15064 } 15065 } 15066 } 15067 15068 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15069 15070 namespace { 15071 15072 struct RetainCycleOwner { 15073 VarDecl *Variable = nullptr; 15074 SourceRange Range; 15075 SourceLocation Loc; 15076 bool Indirect = false; 15077 15078 RetainCycleOwner() = default; 15079 15080 void setLocsFrom(Expr *e) { 15081 Loc = e->getExprLoc(); 15082 Range = e->getSourceRange(); 15083 } 15084 }; 15085 15086 } // namespace 15087 15088 /// Consider whether capturing the given variable can possibly lead to 15089 /// a retain cycle. 15090 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15091 // In ARC, it's captured strongly iff the variable has __strong 15092 // lifetime. In MRR, it's captured strongly if the variable is 15093 // __block and has an appropriate type. 15094 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15095 return false; 15096 15097 owner.Variable = var; 15098 if (ref) 15099 owner.setLocsFrom(ref); 15100 return true; 15101 } 15102 15103 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15104 while (true) { 15105 e = e->IgnoreParens(); 15106 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15107 switch (cast->getCastKind()) { 15108 case CK_BitCast: 15109 case CK_LValueBitCast: 15110 case CK_LValueToRValue: 15111 case CK_ARCReclaimReturnedObject: 15112 e = cast->getSubExpr(); 15113 continue; 15114 15115 default: 15116 return false; 15117 } 15118 } 15119 15120 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15121 ObjCIvarDecl *ivar = ref->getDecl(); 15122 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15123 return false; 15124 15125 // Try to find a retain cycle in the base. 15126 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15127 return false; 15128 15129 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15130 owner.Indirect = true; 15131 return true; 15132 } 15133 15134 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15135 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15136 if (!var) return false; 15137 return considerVariable(var, ref, owner); 15138 } 15139 15140 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15141 if (member->isArrow()) return false; 15142 15143 // Don't count this as an indirect ownership. 15144 e = member->getBase(); 15145 continue; 15146 } 15147 15148 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15149 // Only pay attention to pseudo-objects on property references. 15150 ObjCPropertyRefExpr *pre 15151 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15152 ->IgnoreParens()); 15153 if (!pre) return false; 15154 if (pre->isImplicitProperty()) return false; 15155 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15156 if (!property->isRetaining() && 15157 !(property->getPropertyIvarDecl() && 15158 property->getPropertyIvarDecl()->getType() 15159 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15160 return false; 15161 15162 owner.Indirect = true; 15163 if (pre->isSuperReceiver()) { 15164 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15165 if (!owner.Variable) 15166 return false; 15167 owner.Loc = pre->getLocation(); 15168 owner.Range = pre->getSourceRange(); 15169 return true; 15170 } 15171 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15172 ->getSourceExpr()); 15173 continue; 15174 } 15175 15176 // Array ivars? 15177 15178 return false; 15179 } 15180 } 15181 15182 namespace { 15183 15184 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15185 ASTContext &Context; 15186 VarDecl *Variable; 15187 Expr *Capturer = nullptr; 15188 bool VarWillBeReased = false; 15189 15190 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15191 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15192 Context(Context), Variable(variable) {} 15193 15194 void VisitDeclRefExpr(DeclRefExpr *ref) { 15195 if (ref->getDecl() == Variable && !Capturer) 15196 Capturer = ref; 15197 } 15198 15199 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15200 if (Capturer) return; 15201 Visit(ref->getBase()); 15202 if (Capturer && ref->isFreeIvar()) 15203 Capturer = ref; 15204 } 15205 15206 void VisitBlockExpr(BlockExpr *block) { 15207 // Look inside nested blocks 15208 if (block->getBlockDecl()->capturesVariable(Variable)) 15209 Visit(block->getBlockDecl()->getBody()); 15210 } 15211 15212 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15213 if (Capturer) return; 15214 if (OVE->getSourceExpr()) 15215 Visit(OVE->getSourceExpr()); 15216 } 15217 15218 void VisitBinaryOperator(BinaryOperator *BinOp) { 15219 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15220 return; 15221 Expr *LHS = BinOp->getLHS(); 15222 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15223 if (DRE->getDecl() != Variable) 15224 return; 15225 if (Expr *RHS = BinOp->getRHS()) { 15226 RHS = RHS->IgnoreParenCasts(); 15227 Optional<llvm::APSInt> Value; 15228 VarWillBeReased = 15229 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15230 *Value == 0); 15231 } 15232 } 15233 } 15234 }; 15235 15236 } // namespace 15237 15238 /// Check whether the given argument is a block which captures a 15239 /// variable. 15240 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15241 assert(owner.Variable && owner.Loc.isValid()); 15242 15243 e = e->IgnoreParenCasts(); 15244 15245 // Look through [^{...} copy] and Block_copy(^{...}). 15246 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15247 Selector Cmd = ME->getSelector(); 15248 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15249 e = ME->getInstanceReceiver(); 15250 if (!e) 15251 return nullptr; 15252 e = e->IgnoreParenCasts(); 15253 } 15254 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15255 if (CE->getNumArgs() == 1) { 15256 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15257 if (Fn) { 15258 const IdentifierInfo *FnI = Fn->getIdentifier(); 15259 if (FnI && FnI->isStr("_Block_copy")) { 15260 e = CE->getArg(0)->IgnoreParenCasts(); 15261 } 15262 } 15263 } 15264 } 15265 15266 BlockExpr *block = dyn_cast<BlockExpr>(e); 15267 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15268 return nullptr; 15269 15270 FindCaptureVisitor visitor(S.Context, owner.Variable); 15271 visitor.Visit(block->getBlockDecl()->getBody()); 15272 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15273 } 15274 15275 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15276 RetainCycleOwner &owner) { 15277 assert(capturer); 15278 assert(owner.Variable && owner.Loc.isValid()); 15279 15280 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15281 << owner.Variable << capturer->getSourceRange(); 15282 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15283 << owner.Indirect << owner.Range; 15284 } 15285 15286 /// Check for a keyword selector that starts with the word 'add' or 15287 /// 'set'. 15288 static bool isSetterLikeSelector(Selector sel) { 15289 if (sel.isUnarySelector()) return false; 15290 15291 StringRef str = sel.getNameForSlot(0); 15292 while (!str.empty() && str.front() == '_') str = str.substr(1); 15293 if (str.startswith("set")) 15294 str = str.substr(3); 15295 else if (str.startswith("add")) { 15296 // Specially allow 'addOperationWithBlock:'. 15297 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15298 return false; 15299 str = str.substr(3); 15300 } 15301 else 15302 return false; 15303 15304 if (str.empty()) return true; 15305 return !isLowercase(str.front()); 15306 } 15307 15308 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15309 ObjCMessageExpr *Message) { 15310 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15311 Message->getReceiverInterface(), 15312 NSAPI::ClassId_NSMutableArray); 15313 if (!IsMutableArray) { 15314 return None; 15315 } 15316 15317 Selector Sel = Message->getSelector(); 15318 15319 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15320 S.NSAPIObj->getNSArrayMethodKind(Sel); 15321 if (!MKOpt) { 15322 return None; 15323 } 15324 15325 NSAPI::NSArrayMethodKind MK = *MKOpt; 15326 15327 switch (MK) { 15328 case NSAPI::NSMutableArr_addObject: 15329 case NSAPI::NSMutableArr_insertObjectAtIndex: 15330 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15331 return 0; 15332 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15333 return 1; 15334 15335 default: 15336 return None; 15337 } 15338 15339 return None; 15340 } 15341 15342 static 15343 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15344 ObjCMessageExpr *Message) { 15345 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15346 Message->getReceiverInterface(), 15347 NSAPI::ClassId_NSMutableDictionary); 15348 if (!IsMutableDictionary) { 15349 return None; 15350 } 15351 15352 Selector Sel = Message->getSelector(); 15353 15354 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15355 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15356 if (!MKOpt) { 15357 return None; 15358 } 15359 15360 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15361 15362 switch (MK) { 15363 case NSAPI::NSMutableDict_setObjectForKey: 15364 case NSAPI::NSMutableDict_setValueForKey: 15365 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15366 return 0; 15367 15368 default: 15369 return None; 15370 } 15371 15372 return None; 15373 } 15374 15375 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15376 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15377 Message->getReceiverInterface(), 15378 NSAPI::ClassId_NSMutableSet); 15379 15380 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15381 Message->getReceiverInterface(), 15382 NSAPI::ClassId_NSMutableOrderedSet); 15383 if (!IsMutableSet && !IsMutableOrderedSet) { 15384 return None; 15385 } 15386 15387 Selector Sel = Message->getSelector(); 15388 15389 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15390 if (!MKOpt) { 15391 return None; 15392 } 15393 15394 NSAPI::NSSetMethodKind MK = *MKOpt; 15395 15396 switch (MK) { 15397 case NSAPI::NSMutableSet_addObject: 15398 case NSAPI::NSOrderedSet_setObjectAtIndex: 15399 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15400 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15401 return 0; 15402 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15403 return 1; 15404 } 15405 15406 return None; 15407 } 15408 15409 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15410 if (!Message->isInstanceMessage()) { 15411 return; 15412 } 15413 15414 Optional<int> ArgOpt; 15415 15416 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15417 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15418 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15419 return; 15420 } 15421 15422 int ArgIndex = *ArgOpt; 15423 15424 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15425 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15426 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15427 } 15428 15429 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15430 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15431 if (ArgRE->isObjCSelfExpr()) { 15432 Diag(Message->getSourceRange().getBegin(), 15433 diag::warn_objc_circular_container) 15434 << ArgRE->getDecl() << StringRef("'super'"); 15435 } 15436 } 15437 } else { 15438 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15439 15440 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15441 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15442 } 15443 15444 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15445 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15446 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15447 ValueDecl *Decl = ReceiverRE->getDecl(); 15448 Diag(Message->getSourceRange().getBegin(), 15449 diag::warn_objc_circular_container) 15450 << Decl << Decl; 15451 if (!ArgRE->isObjCSelfExpr()) { 15452 Diag(Decl->getLocation(), 15453 diag::note_objc_circular_container_declared_here) 15454 << Decl; 15455 } 15456 } 15457 } 15458 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15459 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15460 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15461 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15462 Diag(Message->getSourceRange().getBegin(), 15463 diag::warn_objc_circular_container) 15464 << Decl << Decl; 15465 Diag(Decl->getLocation(), 15466 diag::note_objc_circular_container_declared_here) 15467 << Decl; 15468 } 15469 } 15470 } 15471 } 15472 } 15473 15474 /// Check a message send to see if it's likely to cause a retain cycle. 15475 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15476 // Only check instance methods whose selector looks like a setter. 15477 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15478 return; 15479 15480 // Try to find a variable that the receiver is strongly owned by. 15481 RetainCycleOwner owner; 15482 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15483 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15484 return; 15485 } else { 15486 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15487 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15488 owner.Loc = msg->getSuperLoc(); 15489 owner.Range = msg->getSuperLoc(); 15490 } 15491 15492 // Check whether the receiver is captured by any of the arguments. 15493 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15494 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15495 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15496 // noescape blocks should not be retained by the method. 15497 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15498 continue; 15499 return diagnoseRetainCycle(*this, capturer, owner); 15500 } 15501 } 15502 } 15503 15504 /// Check a property assign to see if it's likely to cause a retain cycle. 15505 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15506 RetainCycleOwner owner; 15507 if (!findRetainCycleOwner(*this, receiver, owner)) 15508 return; 15509 15510 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15511 diagnoseRetainCycle(*this, capturer, owner); 15512 } 15513 15514 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15515 RetainCycleOwner Owner; 15516 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15517 return; 15518 15519 // Because we don't have an expression for the variable, we have to set the 15520 // location explicitly here. 15521 Owner.Loc = Var->getLocation(); 15522 Owner.Range = Var->getSourceRange(); 15523 15524 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15525 diagnoseRetainCycle(*this, Capturer, Owner); 15526 } 15527 15528 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15529 Expr *RHS, bool isProperty) { 15530 // Check if RHS is an Objective-C object literal, which also can get 15531 // immediately zapped in a weak reference. Note that we explicitly 15532 // allow ObjCStringLiterals, since those are designed to never really die. 15533 RHS = RHS->IgnoreParenImpCasts(); 15534 15535 // This enum needs to match with the 'select' in 15536 // warn_objc_arc_literal_assign (off-by-1). 15537 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15538 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15539 return false; 15540 15541 S.Diag(Loc, diag::warn_arc_literal_assign) 15542 << (unsigned) Kind 15543 << (isProperty ? 0 : 1) 15544 << RHS->getSourceRange(); 15545 15546 return true; 15547 } 15548 15549 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15550 Qualifiers::ObjCLifetime LT, 15551 Expr *RHS, bool isProperty) { 15552 // Strip off any implicit cast added to get to the one ARC-specific. 15553 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15554 if (cast->getCastKind() == CK_ARCConsumeObject) { 15555 S.Diag(Loc, diag::warn_arc_retained_assign) 15556 << (LT == Qualifiers::OCL_ExplicitNone) 15557 << (isProperty ? 0 : 1) 15558 << RHS->getSourceRange(); 15559 return true; 15560 } 15561 RHS = cast->getSubExpr(); 15562 } 15563 15564 if (LT == Qualifiers::OCL_Weak && 15565 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15566 return true; 15567 15568 return false; 15569 } 15570 15571 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15572 QualType LHS, Expr *RHS) { 15573 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15574 15575 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15576 return false; 15577 15578 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15579 return true; 15580 15581 return false; 15582 } 15583 15584 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15585 Expr *LHS, Expr *RHS) { 15586 QualType LHSType; 15587 // PropertyRef on LHS type need be directly obtained from 15588 // its declaration as it has a PseudoType. 15589 ObjCPropertyRefExpr *PRE 15590 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15591 if (PRE && !PRE->isImplicitProperty()) { 15592 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15593 if (PD) 15594 LHSType = PD->getType(); 15595 } 15596 15597 if (LHSType.isNull()) 15598 LHSType = LHS->getType(); 15599 15600 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15601 15602 if (LT == Qualifiers::OCL_Weak) { 15603 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15604 getCurFunction()->markSafeWeakUse(LHS); 15605 } 15606 15607 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15608 return; 15609 15610 // FIXME. Check for other life times. 15611 if (LT != Qualifiers::OCL_None) 15612 return; 15613 15614 if (PRE) { 15615 if (PRE->isImplicitProperty()) 15616 return; 15617 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15618 if (!PD) 15619 return; 15620 15621 unsigned Attributes = PD->getPropertyAttributes(); 15622 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15623 // when 'assign' attribute was not explicitly specified 15624 // by user, ignore it and rely on property type itself 15625 // for lifetime info. 15626 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15627 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15628 LHSType->isObjCRetainableType()) 15629 return; 15630 15631 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15632 if (cast->getCastKind() == CK_ARCConsumeObject) { 15633 Diag(Loc, diag::warn_arc_retained_property_assign) 15634 << RHS->getSourceRange(); 15635 return; 15636 } 15637 RHS = cast->getSubExpr(); 15638 } 15639 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15640 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15641 return; 15642 } 15643 } 15644 } 15645 15646 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15647 15648 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15649 SourceLocation StmtLoc, 15650 const NullStmt *Body) { 15651 // Do not warn if the body is a macro that expands to nothing, e.g: 15652 // 15653 // #define CALL(x) 15654 // if (condition) 15655 // CALL(0); 15656 if (Body->hasLeadingEmptyMacro()) 15657 return false; 15658 15659 // Get line numbers of statement and body. 15660 bool StmtLineInvalid; 15661 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15662 &StmtLineInvalid); 15663 if (StmtLineInvalid) 15664 return false; 15665 15666 bool BodyLineInvalid; 15667 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15668 &BodyLineInvalid); 15669 if (BodyLineInvalid) 15670 return false; 15671 15672 // Warn if null statement and body are on the same line. 15673 if (StmtLine != BodyLine) 15674 return false; 15675 15676 return true; 15677 } 15678 15679 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15680 const Stmt *Body, 15681 unsigned DiagID) { 15682 // Since this is a syntactic check, don't emit diagnostic for template 15683 // instantiations, this just adds noise. 15684 if (CurrentInstantiationScope) 15685 return; 15686 15687 // The body should be a null statement. 15688 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15689 if (!NBody) 15690 return; 15691 15692 // Do the usual checks. 15693 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15694 return; 15695 15696 Diag(NBody->getSemiLoc(), DiagID); 15697 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15698 } 15699 15700 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15701 const Stmt *PossibleBody) { 15702 assert(!CurrentInstantiationScope); // Ensured by caller 15703 15704 SourceLocation StmtLoc; 15705 const Stmt *Body; 15706 unsigned DiagID; 15707 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15708 StmtLoc = FS->getRParenLoc(); 15709 Body = FS->getBody(); 15710 DiagID = diag::warn_empty_for_body; 15711 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15712 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15713 Body = WS->getBody(); 15714 DiagID = diag::warn_empty_while_body; 15715 } else 15716 return; // Neither `for' nor `while'. 15717 15718 // The body should be a null statement. 15719 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15720 if (!NBody) 15721 return; 15722 15723 // Skip expensive checks if diagnostic is disabled. 15724 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15725 return; 15726 15727 // Do the usual checks. 15728 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15729 return; 15730 15731 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15732 // noise level low, emit diagnostics only if for/while is followed by a 15733 // CompoundStmt, e.g.: 15734 // for (int i = 0; i < n; i++); 15735 // { 15736 // a(i); 15737 // } 15738 // or if for/while is followed by a statement with more indentation 15739 // than for/while itself: 15740 // for (int i = 0; i < n; i++); 15741 // a(i); 15742 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15743 if (!ProbableTypo) { 15744 bool BodyColInvalid; 15745 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15746 PossibleBody->getBeginLoc(), &BodyColInvalid); 15747 if (BodyColInvalid) 15748 return; 15749 15750 bool StmtColInvalid; 15751 unsigned StmtCol = 15752 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15753 if (StmtColInvalid) 15754 return; 15755 15756 if (BodyCol > StmtCol) 15757 ProbableTypo = true; 15758 } 15759 15760 if (ProbableTypo) { 15761 Diag(NBody->getSemiLoc(), DiagID); 15762 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15763 } 15764 } 15765 15766 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15767 15768 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15769 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15770 SourceLocation OpLoc) { 15771 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15772 return; 15773 15774 if (inTemplateInstantiation()) 15775 return; 15776 15777 // Strip parens and casts away. 15778 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15779 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15780 15781 // Check for a call expression 15782 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15783 if (!CE || CE->getNumArgs() != 1) 15784 return; 15785 15786 // Check for a call to std::move 15787 if (!CE->isCallToStdMove()) 15788 return; 15789 15790 // Get argument from std::move 15791 RHSExpr = CE->getArg(0); 15792 15793 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15794 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15795 15796 // Two DeclRefExpr's, check that the decls are the same. 15797 if (LHSDeclRef && RHSDeclRef) { 15798 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15799 return; 15800 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15801 RHSDeclRef->getDecl()->getCanonicalDecl()) 15802 return; 15803 15804 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15805 << LHSExpr->getSourceRange() 15806 << RHSExpr->getSourceRange(); 15807 return; 15808 } 15809 15810 // Member variables require a different approach to check for self moves. 15811 // MemberExpr's are the same if every nested MemberExpr refers to the same 15812 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15813 // the base Expr's are CXXThisExpr's. 15814 const Expr *LHSBase = LHSExpr; 15815 const Expr *RHSBase = RHSExpr; 15816 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15817 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15818 if (!LHSME || !RHSME) 15819 return; 15820 15821 while (LHSME && RHSME) { 15822 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15823 RHSME->getMemberDecl()->getCanonicalDecl()) 15824 return; 15825 15826 LHSBase = LHSME->getBase(); 15827 RHSBase = RHSME->getBase(); 15828 LHSME = dyn_cast<MemberExpr>(LHSBase); 15829 RHSME = dyn_cast<MemberExpr>(RHSBase); 15830 } 15831 15832 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15833 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15834 if (LHSDeclRef && RHSDeclRef) { 15835 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15836 return; 15837 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15838 RHSDeclRef->getDecl()->getCanonicalDecl()) 15839 return; 15840 15841 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15842 << LHSExpr->getSourceRange() 15843 << RHSExpr->getSourceRange(); 15844 return; 15845 } 15846 15847 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15848 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15849 << LHSExpr->getSourceRange() 15850 << RHSExpr->getSourceRange(); 15851 } 15852 15853 //===--- Layout compatibility ----------------------------------------------// 15854 15855 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15856 15857 /// Check if two enumeration types are layout-compatible. 15858 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15859 // C++11 [dcl.enum] p8: 15860 // Two enumeration types are layout-compatible if they have the same 15861 // underlying type. 15862 return ED1->isComplete() && ED2->isComplete() && 15863 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15864 } 15865 15866 /// Check if two fields are layout-compatible. 15867 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15868 FieldDecl *Field2) { 15869 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15870 return false; 15871 15872 if (Field1->isBitField() != Field2->isBitField()) 15873 return false; 15874 15875 if (Field1->isBitField()) { 15876 // Make sure that the bit-fields are the same length. 15877 unsigned Bits1 = Field1->getBitWidthValue(C); 15878 unsigned Bits2 = Field2->getBitWidthValue(C); 15879 15880 if (Bits1 != Bits2) 15881 return false; 15882 } 15883 15884 return true; 15885 } 15886 15887 /// Check if two standard-layout structs are layout-compatible. 15888 /// (C++11 [class.mem] p17) 15889 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15890 RecordDecl *RD2) { 15891 // If both records are C++ classes, check that base classes match. 15892 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15893 // If one of records is a CXXRecordDecl we are in C++ mode, 15894 // thus the other one is a CXXRecordDecl, too. 15895 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15896 // Check number of base classes. 15897 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15898 return false; 15899 15900 // Check the base classes. 15901 for (CXXRecordDecl::base_class_const_iterator 15902 Base1 = D1CXX->bases_begin(), 15903 BaseEnd1 = D1CXX->bases_end(), 15904 Base2 = D2CXX->bases_begin(); 15905 Base1 != BaseEnd1; 15906 ++Base1, ++Base2) { 15907 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15908 return false; 15909 } 15910 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15911 // If only RD2 is a C++ class, it should have zero base classes. 15912 if (D2CXX->getNumBases() > 0) 15913 return false; 15914 } 15915 15916 // Check the fields. 15917 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15918 Field2End = RD2->field_end(), 15919 Field1 = RD1->field_begin(), 15920 Field1End = RD1->field_end(); 15921 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15922 if (!isLayoutCompatible(C, *Field1, *Field2)) 15923 return false; 15924 } 15925 if (Field1 != Field1End || Field2 != Field2End) 15926 return false; 15927 15928 return true; 15929 } 15930 15931 /// Check if two standard-layout unions are layout-compatible. 15932 /// (C++11 [class.mem] p18) 15933 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15934 RecordDecl *RD2) { 15935 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15936 for (auto *Field2 : RD2->fields()) 15937 UnmatchedFields.insert(Field2); 15938 15939 for (auto *Field1 : RD1->fields()) { 15940 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15941 I = UnmatchedFields.begin(), 15942 E = UnmatchedFields.end(); 15943 15944 for ( ; I != E; ++I) { 15945 if (isLayoutCompatible(C, Field1, *I)) { 15946 bool Result = UnmatchedFields.erase(*I); 15947 (void) Result; 15948 assert(Result); 15949 break; 15950 } 15951 } 15952 if (I == E) 15953 return false; 15954 } 15955 15956 return UnmatchedFields.empty(); 15957 } 15958 15959 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15960 RecordDecl *RD2) { 15961 if (RD1->isUnion() != RD2->isUnion()) 15962 return false; 15963 15964 if (RD1->isUnion()) 15965 return isLayoutCompatibleUnion(C, RD1, RD2); 15966 else 15967 return isLayoutCompatibleStruct(C, RD1, RD2); 15968 } 15969 15970 /// Check if two types are layout-compatible in C++11 sense. 15971 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15972 if (T1.isNull() || T2.isNull()) 15973 return false; 15974 15975 // C++11 [basic.types] p11: 15976 // If two types T1 and T2 are the same type, then T1 and T2 are 15977 // layout-compatible types. 15978 if (C.hasSameType(T1, T2)) 15979 return true; 15980 15981 T1 = T1.getCanonicalType().getUnqualifiedType(); 15982 T2 = T2.getCanonicalType().getUnqualifiedType(); 15983 15984 const Type::TypeClass TC1 = T1->getTypeClass(); 15985 const Type::TypeClass TC2 = T2->getTypeClass(); 15986 15987 if (TC1 != TC2) 15988 return false; 15989 15990 if (TC1 == Type::Enum) { 15991 return isLayoutCompatible(C, 15992 cast<EnumType>(T1)->getDecl(), 15993 cast<EnumType>(T2)->getDecl()); 15994 } else if (TC1 == Type::Record) { 15995 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15996 return false; 15997 15998 return isLayoutCompatible(C, 15999 cast<RecordType>(T1)->getDecl(), 16000 cast<RecordType>(T2)->getDecl()); 16001 } 16002 16003 return false; 16004 } 16005 16006 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16007 16008 /// Given a type tag expression find the type tag itself. 16009 /// 16010 /// \param TypeExpr Type tag expression, as it appears in user's code. 16011 /// 16012 /// \param VD Declaration of an identifier that appears in a type tag. 16013 /// 16014 /// \param MagicValue Type tag magic value. 16015 /// 16016 /// \param isConstantEvaluated whether the evalaution should be performed in 16017 16018 /// constant context. 16019 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16020 const ValueDecl **VD, uint64_t *MagicValue, 16021 bool isConstantEvaluated) { 16022 while(true) { 16023 if (!TypeExpr) 16024 return false; 16025 16026 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16027 16028 switch (TypeExpr->getStmtClass()) { 16029 case Stmt::UnaryOperatorClass: { 16030 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16031 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16032 TypeExpr = UO->getSubExpr(); 16033 continue; 16034 } 16035 return false; 16036 } 16037 16038 case Stmt::DeclRefExprClass: { 16039 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16040 *VD = DRE->getDecl(); 16041 return true; 16042 } 16043 16044 case Stmt::IntegerLiteralClass: { 16045 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16046 llvm::APInt MagicValueAPInt = IL->getValue(); 16047 if (MagicValueAPInt.getActiveBits() <= 64) { 16048 *MagicValue = MagicValueAPInt.getZExtValue(); 16049 return true; 16050 } else 16051 return false; 16052 } 16053 16054 case Stmt::BinaryConditionalOperatorClass: 16055 case Stmt::ConditionalOperatorClass: { 16056 const AbstractConditionalOperator *ACO = 16057 cast<AbstractConditionalOperator>(TypeExpr); 16058 bool Result; 16059 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16060 isConstantEvaluated)) { 16061 if (Result) 16062 TypeExpr = ACO->getTrueExpr(); 16063 else 16064 TypeExpr = ACO->getFalseExpr(); 16065 continue; 16066 } 16067 return false; 16068 } 16069 16070 case Stmt::BinaryOperatorClass: { 16071 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16072 if (BO->getOpcode() == BO_Comma) { 16073 TypeExpr = BO->getRHS(); 16074 continue; 16075 } 16076 return false; 16077 } 16078 16079 default: 16080 return false; 16081 } 16082 } 16083 } 16084 16085 /// Retrieve the C type corresponding to type tag TypeExpr. 16086 /// 16087 /// \param TypeExpr Expression that specifies a type tag. 16088 /// 16089 /// \param MagicValues Registered magic values. 16090 /// 16091 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16092 /// kind. 16093 /// 16094 /// \param TypeInfo Information about the corresponding C type. 16095 /// 16096 /// \param isConstantEvaluated whether the evalaution should be performed in 16097 /// constant context. 16098 /// 16099 /// \returns true if the corresponding C type was found. 16100 static bool GetMatchingCType( 16101 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16102 const ASTContext &Ctx, 16103 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16104 *MagicValues, 16105 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16106 bool isConstantEvaluated) { 16107 FoundWrongKind = false; 16108 16109 // Variable declaration that has type_tag_for_datatype attribute. 16110 const ValueDecl *VD = nullptr; 16111 16112 uint64_t MagicValue; 16113 16114 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16115 return false; 16116 16117 if (VD) { 16118 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16119 if (I->getArgumentKind() != ArgumentKind) { 16120 FoundWrongKind = true; 16121 return false; 16122 } 16123 TypeInfo.Type = I->getMatchingCType(); 16124 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16125 TypeInfo.MustBeNull = I->getMustBeNull(); 16126 return true; 16127 } 16128 return false; 16129 } 16130 16131 if (!MagicValues) 16132 return false; 16133 16134 llvm::DenseMap<Sema::TypeTagMagicValue, 16135 Sema::TypeTagData>::const_iterator I = 16136 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16137 if (I == MagicValues->end()) 16138 return false; 16139 16140 TypeInfo = I->second; 16141 return true; 16142 } 16143 16144 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16145 uint64_t MagicValue, QualType Type, 16146 bool LayoutCompatible, 16147 bool MustBeNull) { 16148 if (!TypeTagForDatatypeMagicValues) 16149 TypeTagForDatatypeMagicValues.reset( 16150 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16151 16152 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16153 (*TypeTagForDatatypeMagicValues)[Magic] = 16154 TypeTagData(Type, LayoutCompatible, MustBeNull); 16155 } 16156 16157 static bool IsSameCharType(QualType T1, QualType T2) { 16158 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16159 if (!BT1) 16160 return false; 16161 16162 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16163 if (!BT2) 16164 return false; 16165 16166 BuiltinType::Kind T1Kind = BT1->getKind(); 16167 BuiltinType::Kind T2Kind = BT2->getKind(); 16168 16169 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16170 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16171 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16172 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16173 } 16174 16175 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16176 const ArrayRef<const Expr *> ExprArgs, 16177 SourceLocation CallSiteLoc) { 16178 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16179 bool IsPointerAttr = Attr->getIsPointer(); 16180 16181 // Retrieve the argument representing the 'type_tag'. 16182 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16183 if (TypeTagIdxAST >= ExprArgs.size()) { 16184 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16185 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16186 return; 16187 } 16188 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16189 bool FoundWrongKind; 16190 TypeTagData TypeInfo; 16191 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16192 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16193 TypeInfo, isConstantEvaluated())) { 16194 if (FoundWrongKind) 16195 Diag(TypeTagExpr->getExprLoc(), 16196 diag::warn_type_tag_for_datatype_wrong_kind) 16197 << TypeTagExpr->getSourceRange(); 16198 return; 16199 } 16200 16201 // Retrieve the argument representing the 'arg_idx'. 16202 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16203 if (ArgumentIdxAST >= ExprArgs.size()) { 16204 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16205 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16206 return; 16207 } 16208 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16209 if (IsPointerAttr) { 16210 // Skip implicit cast of pointer to `void *' (as a function argument). 16211 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16212 if (ICE->getType()->isVoidPointerType() && 16213 ICE->getCastKind() == CK_BitCast) 16214 ArgumentExpr = ICE->getSubExpr(); 16215 } 16216 QualType ArgumentType = ArgumentExpr->getType(); 16217 16218 // Passing a `void*' pointer shouldn't trigger a warning. 16219 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16220 return; 16221 16222 if (TypeInfo.MustBeNull) { 16223 // Type tag with matching void type requires a null pointer. 16224 if (!ArgumentExpr->isNullPointerConstant(Context, 16225 Expr::NPC_ValueDependentIsNotNull)) { 16226 Diag(ArgumentExpr->getExprLoc(), 16227 diag::warn_type_safety_null_pointer_required) 16228 << ArgumentKind->getName() 16229 << ArgumentExpr->getSourceRange() 16230 << TypeTagExpr->getSourceRange(); 16231 } 16232 return; 16233 } 16234 16235 QualType RequiredType = TypeInfo.Type; 16236 if (IsPointerAttr) 16237 RequiredType = Context.getPointerType(RequiredType); 16238 16239 bool mismatch = false; 16240 if (!TypeInfo.LayoutCompatible) { 16241 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16242 16243 // C++11 [basic.fundamental] p1: 16244 // Plain char, signed char, and unsigned char are three distinct types. 16245 // 16246 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16247 // char' depending on the current char signedness mode. 16248 if (mismatch) 16249 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16250 RequiredType->getPointeeType())) || 16251 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16252 mismatch = false; 16253 } else 16254 if (IsPointerAttr) 16255 mismatch = !isLayoutCompatible(Context, 16256 ArgumentType->getPointeeType(), 16257 RequiredType->getPointeeType()); 16258 else 16259 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16260 16261 if (mismatch) 16262 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16263 << ArgumentType << ArgumentKind 16264 << TypeInfo.LayoutCompatible << RequiredType 16265 << ArgumentExpr->getSourceRange() 16266 << TypeTagExpr->getSourceRange(); 16267 } 16268 16269 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16270 CharUnits Alignment) { 16271 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16272 } 16273 16274 void Sema::DiagnoseMisalignedMembers() { 16275 for (MisalignedMember &m : MisalignedMembers) { 16276 const NamedDecl *ND = m.RD; 16277 if (ND->getName().empty()) { 16278 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16279 ND = TD; 16280 } 16281 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16282 << m.MD << ND << m.E->getSourceRange(); 16283 } 16284 MisalignedMembers.clear(); 16285 } 16286 16287 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16288 E = E->IgnoreParens(); 16289 if (!T->isPointerType() && !T->isIntegerType()) 16290 return; 16291 if (isa<UnaryOperator>(E) && 16292 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16293 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16294 if (isa<MemberExpr>(Op)) { 16295 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16296 if (MA != MisalignedMembers.end() && 16297 (T->isIntegerType() || 16298 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16299 Context.getTypeAlignInChars( 16300 T->getPointeeType()) <= MA->Alignment)))) 16301 MisalignedMembers.erase(MA); 16302 } 16303 } 16304 } 16305 16306 void Sema::RefersToMemberWithReducedAlignment( 16307 Expr *E, 16308 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16309 Action) { 16310 const auto *ME = dyn_cast<MemberExpr>(E); 16311 if (!ME) 16312 return; 16313 16314 // No need to check expressions with an __unaligned-qualified type. 16315 if (E->getType().getQualifiers().hasUnaligned()) 16316 return; 16317 16318 // For a chain of MemberExpr like "a.b.c.d" this list 16319 // will keep FieldDecl's like [d, c, b]. 16320 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16321 const MemberExpr *TopME = nullptr; 16322 bool AnyIsPacked = false; 16323 do { 16324 QualType BaseType = ME->getBase()->getType(); 16325 if (BaseType->isDependentType()) 16326 return; 16327 if (ME->isArrow()) 16328 BaseType = BaseType->getPointeeType(); 16329 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16330 if (RD->isInvalidDecl()) 16331 return; 16332 16333 ValueDecl *MD = ME->getMemberDecl(); 16334 auto *FD = dyn_cast<FieldDecl>(MD); 16335 // We do not care about non-data members. 16336 if (!FD || FD->isInvalidDecl()) 16337 return; 16338 16339 AnyIsPacked = 16340 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16341 ReverseMemberChain.push_back(FD); 16342 16343 TopME = ME; 16344 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16345 } while (ME); 16346 assert(TopME && "We did not compute a topmost MemberExpr!"); 16347 16348 // Not the scope of this diagnostic. 16349 if (!AnyIsPacked) 16350 return; 16351 16352 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16353 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16354 // TODO: The innermost base of the member expression may be too complicated. 16355 // For now, just disregard these cases. This is left for future 16356 // improvement. 16357 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16358 return; 16359 16360 // Alignment expected by the whole expression. 16361 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16362 16363 // No need to do anything else with this case. 16364 if (ExpectedAlignment.isOne()) 16365 return; 16366 16367 // Synthesize offset of the whole access. 16368 CharUnits Offset; 16369 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16370 I++) { 16371 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16372 } 16373 16374 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16375 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16376 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16377 16378 // The base expression of the innermost MemberExpr may give 16379 // stronger guarantees than the class containing the member. 16380 if (DRE && !TopME->isArrow()) { 16381 const ValueDecl *VD = DRE->getDecl(); 16382 if (!VD->getType()->isReferenceType()) 16383 CompleteObjectAlignment = 16384 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16385 } 16386 16387 // Check if the synthesized offset fulfills the alignment. 16388 if (Offset % ExpectedAlignment != 0 || 16389 // It may fulfill the offset it but the effective alignment may still be 16390 // lower than the expected expression alignment. 16391 CompleteObjectAlignment < ExpectedAlignment) { 16392 // If this happens, we want to determine a sensible culprit of this. 16393 // Intuitively, watching the chain of member expressions from right to 16394 // left, we start with the required alignment (as required by the field 16395 // type) but some packed attribute in that chain has reduced the alignment. 16396 // It may happen that another packed structure increases it again. But if 16397 // we are here such increase has not been enough. So pointing the first 16398 // FieldDecl that either is packed or else its RecordDecl is, 16399 // seems reasonable. 16400 FieldDecl *FD = nullptr; 16401 CharUnits Alignment; 16402 for (FieldDecl *FDI : ReverseMemberChain) { 16403 if (FDI->hasAttr<PackedAttr>() || 16404 FDI->getParent()->hasAttr<PackedAttr>()) { 16405 FD = FDI; 16406 Alignment = std::min( 16407 Context.getTypeAlignInChars(FD->getType()), 16408 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16409 break; 16410 } 16411 } 16412 assert(FD && "We did not find a packed FieldDecl!"); 16413 Action(E, FD->getParent(), FD, Alignment); 16414 } 16415 } 16416 16417 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16418 using namespace std::placeholders; 16419 16420 RefersToMemberWithReducedAlignment( 16421 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16422 _2, _3, _4)); 16423 } 16424 16425 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16426 ExprResult CallResult) { 16427 if (checkArgCount(*this, TheCall, 1)) 16428 return ExprError(); 16429 16430 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16431 if (MatrixArg.isInvalid()) 16432 return MatrixArg; 16433 Expr *Matrix = MatrixArg.get(); 16434 16435 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16436 if (!MType) { 16437 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16438 return ExprError(); 16439 } 16440 16441 // Create returned matrix type by swapping rows and columns of the argument 16442 // matrix type. 16443 QualType ResultType = Context.getConstantMatrixType( 16444 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16445 16446 // Change the return type to the type of the returned matrix. 16447 TheCall->setType(ResultType); 16448 16449 // Update call argument to use the possibly converted matrix argument. 16450 TheCall->setArg(0, Matrix); 16451 return CallResult; 16452 } 16453 16454 // Get and verify the matrix dimensions. 16455 static llvm::Optional<unsigned> 16456 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16457 SourceLocation ErrorPos; 16458 Optional<llvm::APSInt> Value = 16459 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16460 if (!Value) { 16461 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16462 << Name; 16463 return {}; 16464 } 16465 uint64_t Dim = Value->getZExtValue(); 16466 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16467 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16468 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16469 return {}; 16470 } 16471 return Dim; 16472 } 16473 16474 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16475 ExprResult CallResult) { 16476 if (!getLangOpts().MatrixTypes) { 16477 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16478 return ExprError(); 16479 } 16480 16481 if (checkArgCount(*this, TheCall, 4)) 16482 return ExprError(); 16483 16484 unsigned PtrArgIdx = 0; 16485 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16486 Expr *RowsExpr = TheCall->getArg(1); 16487 Expr *ColumnsExpr = TheCall->getArg(2); 16488 Expr *StrideExpr = TheCall->getArg(3); 16489 16490 bool ArgError = false; 16491 16492 // Check pointer argument. 16493 { 16494 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16495 if (PtrConv.isInvalid()) 16496 return PtrConv; 16497 PtrExpr = PtrConv.get(); 16498 TheCall->setArg(0, PtrExpr); 16499 if (PtrExpr->isTypeDependent()) { 16500 TheCall->setType(Context.DependentTy); 16501 return TheCall; 16502 } 16503 } 16504 16505 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16506 QualType ElementTy; 16507 if (!PtrTy) { 16508 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16509 << PtrArgIdx + 1; 16510 ArgError = true; 16511 } else { 16512 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16513 16514 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16515 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16516 << PtrArgIdx + 1; 16517 ArgError = true; 16518 } 16519 } 16520 16521 // Apply default Lvalue conversions and convert the expression to size_t. 16522 auto ApplyArgumentConversions = [this](Expr *E) { 16523 ExprResult Conv = DefaultLvalueConversion(E); 16524 if (Conv.isInvalid()) 16525 return Conv; 16526 16527 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16528 }; 16529 16530 // Apply conversion to row and column expressions. 16531 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16532 if (!RowsConv.isInvalid()) { 16533 RowsExpr = RowsConv.get(); 16534 TheCall->setArg(1, RowsExpr); 16535 } else 16536 RowsExpr = nullptr; 16537 16538 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16539 if (!ColumnsConv.isInvalid()) { 16540 ColumnsExpr = ColumnsConv.get(); 16541 TheCall->setArg(2, ColumnsExpr); 16542 } else 16543 ColumnsExpr = nullptr; 16544 16545 // If any any part of the result matrix type is still pending, just use 16546 // Context.DependentTy, until all parts are resolved. 16547 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16548 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16549 TheCall->setType(Context.DependentTy); 16550 return CallResult; 16551 } 16552 16553 // Check row and column dimenions. 16554 llvm::Optional<unsigned> MaybeRows; 16555 if (RowsExpr) 16556 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16557 16558 llvm::Optional<unsigned> MaybeColumns; 16559 if (ColumnsExpr) 16560 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16561 16562 // Check stride argument. 16563 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16564 if (StrideConv.isInvalid()) 16565 return ExprError(); 16566 StrideExpr = StrideConv.get(); 16567 TheCall->setArg(3, StrideExpr); 16568 16569 if (MaybeRows) { 16570 if (Optional<llvm::APSInt> Value = 16571 StrideExpr->getIntegerConstantExpr(Context)) { 16572 uint64_t Stride = Value->getZExtValue(); 16573 if (Stride < *MaybeRows) { 16574 Diag(StrideExpr->getBeginLoc(), 16575 diag::err_builtin_matrix_stride_too_small); 16576 ArgError = true; 16577 } 16578 } 16579 } 16580 16581 if (ArgError || !MaybeRows || !MaybeColumns) 16582 return ExprError(); 16583 16584 TheCall->setType( 16585 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16586 return CallResult; 16587 } 16588 16589 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16590 ExprResult CallResult) { 16591 if (checkArgCount(*this, TheCall, 3)) 16592 return ExprError(); 16593 16594 unsigned PtrArgIdx = 1; 16595 Expr *MatrixExpr = TheCall->getArg(0); 16596 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16597 Expr *StrideExpr = TheCall->getArg(2); 16598 16599 bool ArgError = false; 16600 16601 { 16602 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16603 if (MatrixConv.isInvalid()) 16604 return MatrixConv; 16605 MatrixExpr = MatrixConv.get(); 16606 TheCall->setArg(0, MatrixExpr); 16607 } 16608 if (MatrixExpr->isTypeDependent()) { 16609 TheCall->setType(Context.DependentTy); 16610 return TheCall; 16611 } 16612 16613 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16614 if (!MatrixTy) { 16615 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16616 ArgError = true; 16617 } 16618 16619 { 16620 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16621 if (PtrConv.isInvalid()) 16622 return PtrConv; 16623 PtrExpr = PtrConv.get(); 16624 TheCall->setArg(1, PtrExpr); 16625 if (PtrExpr->isTypeDependent()) { 16626 TheCall->setType(Context.DependentTy); 16627 return TheCall; 16628 } 16629 } 16630 16631 // Check pointer argument. 16632 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16633 if (!PtrTy) { 16634 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16635 << PtrArgIdx + 1; 16636 ArgError = true; 16637 } else { 16638 QualType ElementTy = PtrTy->getPointeeType(); 16639 if (ElementTy.isConstQualified()) { 16640 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16641 ArgError = true; 16642 } 16643 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16644 if (MatrixTy && 16645 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16646 Diag(PtrExpr->getBeginLoc(), 16647 diag::err_builtin_matrix_pointer_arg_mismatch) 16648 << ElementTy << MatrixTy->getElementType(); 16649 ArgError = true; 16650 } 16651 } 16652 16653 // Apply default Lvalue conversions and convert the stride expression to 16654 // size_t. 16655 { 16656 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16657 if (StrideConv.isInvalid()) 16658 return StrideConv; 16659 16660 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16661 if (StrideConv.isInvalid()) 16662 return StrideConv; 16663 StrideExpr = StrideConv.get(); 16664 TheCall->setArg(2, StrideExpr); 16665 } 16666 16667 // Check stride argument. 16668 if (MatrixTy) { 16669 if (Optional<llvm::APSInt> Value = 16670 StrideExpr->getIntegerConstantExpr(Context)) { 16671 uint64_t Stride = Value->getZExtValue(); 16672 if (Stride < MatrixTy->getNumRows()) { 16673 Diag(StrideExpr->getBeginLoc(), 16674 diag::err_builtin_matrix_stride_too_small); 16675 ArgError = true; 16676 } 16677 } 16678 } 16679 16680 if (ArgError) 16681 return ExprError(); 16682 16683 return CallResult; 16684 } 16685 16686 /// \brief Enforce the bounds of a TCB 16687 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16688 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16689 /// and enforce_tcb_leaf attributes. 16690 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16691 const FunctionDecl *Callee) { 16692 const FunctionDecl *Caller = getCurFunctionDecl(); 16693 16694 // Calls to builtins are not enforced. 16695 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16696 Callee->getBuiltinID() != 0) 16697 return; 16698 16699 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16700 // all TCBs the callee is a part of. 16701 llvm::StringSet<> CalleeTCBs; 16702 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16703 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16704 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16705 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16706 16707 // Go through the TCBs the caller is a part of and emit warnings if Caller 16708 // is in a TCB that the Callee is not. 16709 for_each( 16710 Caller->specific_attrs<EnforceTCBAttr>(), 16711 [&](const auto *A) { 16712 StringRef CallerTCB = A->getTCBName(); 16713 if (CalleeTCBs.count(CallerTCB) == 0) { 16714 this->Diag(TheCall->getExprLoc(), 16715 diag::warn_tcb_enforcement_violation) << Callee 16716 << CallerTCB; 16717 } 16718 }); 16719 } 16720